From 21bbb4af001c04b72440fd4dc94f33163b2558f4 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:39:24 +0000 Subject: [PATCH 01/20] fix(rtx): preprocess geometry on the GPU Keep derived data device-resident and reject failed preparation before tracing. Preserve curve connectivity. --- devices/rtx/apps/tests/api/CMakeLists.txt | 41 ++ devices/rtx/apps/tests/api/DeviceTestArray.h | 83 ++++ .../rtx/apps/tests/api/ReceiverTestSupport.h | 128 ++++++ .../tests/api/TestCudaPreparationFailure.cpp | 313 ++++++++++++++ .../api/TestDeviceGeometryVisibility.cpp | 398 +++++++++++++++++ .../api/TestEmissiveCylinderConeLight.cpp | 259 +++++------ .../tests/api/TestEmissiveSphereLight.cpp | 212 ++++----- .../api/TestFramePublicationRecovery.cpp | 226 ++++++++++ .../apps/tests/api/TestGeneratedTangents.cpp | 22 +- .../api/TestGeometryPreprocessingFailure.cpp | 154 +++++++ .../tests/api/TestSharedGeometryLifecycle.cpp | 310 +++++++++++++ devices/rtx/device/CMakeLists.txt | 1 + devices/rtx/device/VisRTXDevice.cpp | 5 + devices/rtx/device/array/Array.cpp | 28 +- devices/rtx/device/frame/Frame.cu | 25 ++ devices/rtx/device/geometry/Cone.cpp | 132 ++---- devices/rtx/device/geometry/Cone.h | 10 +- devices/rtx/device/geometry/Curve.cpp | 49 ++- devices/rtx/device/geometry/Curve.h | 9 +- devices/rtx/device/geometry/Cylinder.cpp | 137 ++---- devices/rtx/device/geometry/Cylinder.h | 10 +- devices/rtx/device/geometry/Geometry.cpp | 24 ++ devices/rtx/device/geometry/Geometry.h | 15 +- devices/rtx/device/geometry/Isosurface.cpp | 2 + devices/rtx/device/geometry/Neural.cpp | 2 + devices/rtx/device/geometry/Preprocessing.cu | 408 ++++++++++++++++++ devices/rtx/device/geometry/Preprocessing.h | 95 ++++ devices/rtx/device/geometry/Quad.cpp | 41 +- devices/rtx/device/geometry/Quad.h | 3 +- devices/rtx/device/geometry/SDF.cpp | 99 ++--- devices/rtx/device/geometry/SDF.h | 6 +- devices/rtx/device/geometry/Sphere.cu | 131 ++---- devices/rtx/device/geometry/Sphere.h | 9 +- devices/rtx/device/geometry/Triangle.cpp | 51 +-- devices/rtx/device/geometry/Triangle.h | 8 +- devices/rtx/device/optix_visrtx.h | 5 + .../rtx/device/utility/MemoryAllocation.cpp | 17 +- devices/rtx/device/utility/MemoryAllocation.h | 4 +- devices/rtx/device/world/Group.cpp | 48 ++- devices/rtx/device/world/Group.h | 5 +- devices/rtx/device/world/World.cpp | 64 +-- devices/rtx/device/world/World.h | 4 +- 42 files changed, 2781 insertions(+), 812 deletions(-) create mode 100644 devices/rtx/apps/tests/api/DeviceTestArray.h create mode 100644 devices/rtx/apps/tests/api/ReceiverTestSupport.h create mode 100644 devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp create mode 100644 devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp create mode 100644 devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp create mode 100644 devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp create mode 100644 devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp create mode 100644 devices/rtx/device/geometry/Preprocessing.cu create mode 100644 devices/rtx/device/geometry/Preprocessing.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 04d6bff2b..dc0fdf02d 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -80,12 +80,51 @@ target_link_libraries(TestSampleAddressing PRIVATE CUDA::cudart) set_tests_properties(TestSampleAddressing PROPERTIES TIMEOUT 120) make_test(TestPowerLightPickEnv) make_test(TestEmissiveGeometryLight) +make_test(TestSharedGeometryLifecycle) +target_link_libraries(TestSharedGeometryLifecycle PRIVATE CUDA::cudart) +make_test(TestGeometryPreprocessingFailure) +target_link_libraries(TestGeometryPreprocessingFailure PRIVATE CUDA::cudart) +add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure --bounds) +# CUDA API interposition needs ELF dynamic symbols; static cudart calls cannot +# be intercepted. Configure with -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared to run. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") + make_test(TestFramePublicationRecovery) + target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) + make_test(TestCudaPreparationFailure) + target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestIsosurfacePreparationRecovery + COMMAND TestCudaPreparationFailure isosurface) + foreach(geometry sphere sphere-indexed) + add_test(NAME TestSpherePreparationRecovery_${geometry} + COMMAND TestCudaPreparationFailure ${geometry}) + endforeach() + foreach(failure allocation copy work-sync copy-sync) + add_test(NAME TestArrayPrivatizationFailure_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() +endif() +make_test(TestDeviceGeometryVisibility) +target_link_libraries(TestDeviceGeometryVisibility PRIVATE CUDA::cudart) +add_test(NAME TestSharedGeometryInputs COMMAND TestDeviceGeometryVisibility --shared-inputs) +add_test(NAME TestDeviceArrayRetirement COMMAND TestDeviceGeometryVisibility --retire) +add_test(NAME TestDeviceSdfExpansion COMMAND TestDeviceGeometryVisibility sdf-expanded) +foreach(type triangle sphere curve sdf cone cylinder) + add_test(NAME TestDeviceGeometryVisibility_${type} COMMAND TestDeviceGeometryVisibility ${type}) +endforeach() make_test(TestQuadLightSide) make_test(TestVisibleAreaLight) make_test(TestEmissiveSphereLight) +target_link_libraries(TestEmissiveSphereLight PRIVATE CUDA::cudart) +# Sampling radiometry retains host anchors and all-device integration; +# individual input roles use deterministic bounds/visibility above. make_test(TestEmissiveInstanceScale) make_test(TestEmissiveSphereInstanceScale) make_test(TestEmissiveCylinderConeLight) +target_link_libraries(TestEmissiveCylinderConeLight PRIVATE CUDA::cudart) +# Each family keeps independent identity/nonuniform-transform references; +# cap residency is isolated at identity, with all-device coverage also scaled. # These interleave attribute-driven emission cases, and MDL does not support # attributes — native-PBR only. (Textured emission itself works on the MDL # wrapper too; TestEmissiveMaterialParity covers it in that config.) @@ -96,6 +135,8 @@ endif() make_test(TestPbrSpecularDefault) make_test(TestNormalMapDecode) make_test(TestGeneratedTangents) +target_link_libraries(TestGeneratedTangents PRIVATE CUDA::cudart) +add_test(NAME TestDeviceGeneratedTangents COMMAND TestGeneratedTangents --device) make_test(TestShadingNormalGrazing) if (VISRTX_USE_MDL_FOR_PHYSICALLY_BASED) # Its closed-form reference models the backend's diffuse lobe. diff --git a/devices/rtx/apps/tests/api/DeviceTestArray.h b/devices/rtx/apps/tests/api/DeviceTestArray.h new file mode 100644 index 000000000..a4ad3788b --- /dev/null +++ b/devices/rtx/apps/tests/api/DeviceTestArray.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include + +// Capture device allocations so early PUBLIC release exercises array ownership. +// Ordinary inputs use their full range. Tests of logical slicing opt into +// padding explicitly; residency alone does not imply a nonzero range. +template +static void setTestArray(ANARIDevice device, + anari::Geometry geometry, + const char *name, + const Container &values, + bool onDevice, + size_t offset = 0) +{ + using T = typename Container::value_type; + std::vector padded(values.size() + 2 * offset); + std::copy(values.begin(), values.end(), padded.begin() + offset); + anari::Array1D array; + if (onDevice) { + void *ptr = nullptr; + if (cudaMalloc(&ptr, padded.size() * sizeof(T)) != cudaSuccess + || cudaMemcpy(ptr, + padded.data(), + padded.size() * sizeof(T), + cudaMemcpyHostToDevice) + != cudaSuccess) + std::exit(2); + array = anariNewArray1D( + device, + ptr, + [](const void *, const void *memory) { + cudaFree(const_cast(memory)); + }, + nullptr, + anari::ANARITypeFor::value, + padded.size()); + } else { + array = + anari::newArray1D(device, anari::ANARITypeFor::value, padded.size()); + std::copy(padded.begin(), padded.end(), anari::map(device, array)); + anari::unmap(device, array); + } + anari::setParameter(device, array, "begin", uint64_t(offset)); + anari::setParameter(device, array, "end", uint64_t(offset + values.size())); + anari::commitParameters(device, array); + anari::setAndReleaseParameter(device, geometry, name, array); +} diff --git a/devices/rtx/apps/tests/api/ReceiverTestSupport.h b/devices/rtx/apps/tests/api/ReceiverTestSupport.h new file mode 100644 index 000000000..a9e189fab --- /dev/null +++ b/devices/rtx/apps/tests/api/ReceiverTestSupport.h @@ -0,0 +1,128 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#pragma once + +// Reuse the existing public-object ownership and checked mapping support. Fog +// scenes and receiver scenes otherwise keep their own independent fixtures. +#include "RendererFogSupport.h" + +#include + +namespace visrtx::test { + +using fogtest::exitOnErrorStatus; +using fogtest::FrameMapping; +using fogtest::ObjectOwner; +using Vec4 = std::array; +using Size = std::array; + +// Fixed diffuse XZ receiver at y=0. The caller owns the returned Surface. +inline anari::Surface receiverFloor( + anari::Device device, float reflectance = 0.6f) +{ + const std::array, 4> pos = { + std::array{-6.f, 0.f, -6.f}, + std::array{6.f, 0.f, -6.f}, + std::array{6.f, 0.f, 6.f}, + std::array{-6.f, 0.f, 6.f}}; + const std::array, 2> idx = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + + auto geom = anari::newObject(device, "triangle"); + anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); + anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); + anari::commitParameters(device, geom); + + auto mat = anari::newObject(device, "physicallyBased"); + anari::setParameter(device, + mat, + "baseColor", + std::array{reflectance, reflectance, reflectance}); + anari::setParameter(device, mat, "metallic", 0.f); + anari::setParameter(device, mat, "roughness", 1.f); + anari::commitParameters(device, mat); + + auto surface = anari::newObject(device); + anari::setAndReleaseParameter(device, surface, "geometry", geom); + anari::setAndReleaseParameter(device, surface, "material", mat); + anari::commitParameters(device, surface); + return surface; +} + +/* Fixed receiver view shared by the geometry-light radiometry tests. The + * caller keeps its World reference; the returned Frame owns camera/Renderer. + * This deliberately does not construct emitters, references or a scene graph. + */ +inline anari::Frame receiverFrame(anari::Device device, + anari::World world, + Size size, + const char *rendererSubtype, + int pixelSamples) +{ + auto camera = anari::newObject(device, "perspective"); + const ObjectOwner cameraOwner(device, camera); + anari::setParameter( + device, camera, "position", std::array{0.f, 0.5f, -3.f}); + anari::setParameter( + device, camera, "direction", std::array{0.f, -0.15f, 1.f}); + anari::setParameter( + device, camera, "up", std::array{0.f, 1.f, 0.f}); + anari::setParameter(device, camera, "aspect", size[0] / float(size[1])); + anari::commitParameters(device, camera); + + auto renderer = anari::newObject(device, rendererSubtype); + const ObjectOwner rendererOwner(device, renderer); + anari::setParameter(device, renderer, "background", Vec4{0.f, 0.f, 0.f, 1.f}); + anari::setParameter(device, renderer, "ambientRadiance", 0.f); + anari::setParameter(device, renderer, "pixelSamples", pixelSamples); + anari::setParameter(device, renderer, "fireflyFilterMode", "none"); + anari::commitParameters(device, renderer); + + auto frame = anari::newObject(device); + ObjectOwner frameOwner(device, frame); + anari::setParameter(device, frame, "size", size); + anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(device, frame, "world", world); + anari::setParameter(device, frame, "camera", camera); + anari::setParameter(device, frame, "renderer", renderer); + anari::commitParameters(device, frame); + frameOwner.release(); + return frame; +} + +/* Half-open pixel bounds stay at the assertion site: they define the measured + * physical receiver, not a configurable scene or an implicit tolerance. + */ +struct PixelRegion +{ + unsigned xBegin, xEnd, yBegin, yEnd; +}; + +inline double meanLuminance(const Vec4 *pixels, Size size, PixelRegion region) +{ + if (region.xBegin >= region.xEnd || region.xEnd > size[0] + || region.yBegin >= region.yEnd || region.yEnd > size[1]) + throw std::runtime_error("Invalid receiver measurement region"); + double sum = 0.; + for (unsigned y = region.yBegin; y < region.yEnd; ++y) + for (unsigned x = region.xBegin; x < region.xEnd; ++x) { + const auto &p = pixels[std::size_t(y) * size[0] + x]; + sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + } + return sum + / (std::size_t(region.xEnd - region.xBegin) + * (region.yEnd - region.yBegin)); +} + +inline double receiverLuminance( + anari::Device device, anari::Frame frame, Size size, PixelRegion region) +{ + anari::render(device, frame); + anari::wait(device, frame); + const FrameMapping mapping(device, frame, "channel.color"); + return meanLuminance( + mapping.checkedData(size[0], size[1], ANARI_FLOAT32_VEC4), size, region); +} + +} // namespace visrtx::test diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp new file mode 100644 index 000000000..e4b68726a --- /dev/null +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// ELF interposition injects recoverable CUDA API errors without poisoning the +// real CUDA context. This test requires a shared CUDA runtime, not production +// failure-injection switches in the device. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +enum class Failure +{ + NONE, + ALLOCATION, + COPY, + WORK_SYNC, + COPY_SYNC +}; +Failure failure = Failure::NONE; +size_t allocationBytes = 0; +int injections = 0; +int errors = 0; +std::atomic completions{0}; + +bool inject(Failure kind) +{ + if (failure != kind) + return false; + failure = Failure::NONE; + ++injections; + return true; +} + +template +T next(const char *name) +{ + auto result = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!result) { + fprintf(stderr, "missing CUDA symbol %s\n", name); + std::abort(); + } + return result; +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} +} // namespace + +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (bytes == allocationBytes && inject(Failure::ALLOCATION)) { + // Use the real runtime: returning an enum alone does not set CUDA + // last-error state, and misses contamination of the next preparation. + *ptr = nullptr; + return next("cudaMalloc")(ptr, size_t(-1)); + } + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaMemcpy( + void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) +{ + if (kind == cudaMemcpyDeviceToDevice && inject(Failure::COPY)) + return cudaErrorInvalidValue; + return next("cudaMemcpy")(dst, src, bytes, kind); +} + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + // Drain real work even when simulating a failed completion report. + const auto result = + next("cudaStreamSynchronize")(stream); + if ((stream && inject(Failure::WORK_SYNC)) + || (!stream && inject(Failure::COPY_SYNC))) + return cudaErrorUnknown; + return result; +} + +int main(int argc, char **argv) +{ + const bool isosurfaceFailure = + argc > 1 && std::strcmp(argv[1], "isosurface") == 0; + const bool sphereFailure = argc > 1 + && (std::strcmp(argv[1], "sphere") == 0 + || std::strcmp(argv[1], "sphere-indexed") == 0); + const bool curveFailure = argc == 1 || isosurfaceFailure || sphereFailure; + auto d = makeVisRTXDevice(status); + using vec3 = std::array; + const std::array vertices = { + {{-1, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {1, 1, 0}, {-1, 2, 0}, {1, 2, 0}}}; + void *deviceVertices = nullptr; + if (cudaMalloc(&deviceVertices, sizeof(vertices)) != cudaSuccess + || cudaMemcpy(deviceVertices, + vertices.data(), + sizeof(vertices), + cudaMemcpyHostToDevice) + != cudaSuccess) + return 1; + auto array = anariNewArray1D( + d, deviceVertices, nullptr, nullptr, ANARI_FLOAT32_VEC3, vertices.size()); + auto geometry = anari::newObject(d, + isosurfaceFailure ? "isosurface" + : sphereFailure ? "sphere" + : "curve"); + if (sphereFailure && std::strcmp(argv[1], "sphere-indexed") == 0) { + const std::array indices{5, 1, 3}; + anari::setParameterArray1D( + d, geometry, "primitive.index", indices.data(), indices.size()); + } + if (isosurfaceFailure) { + std::array values{}; + for (size_t i = 0; i < values.size(); ++i) + values[i] = float(i / 64); + auto field = anari::newObject(d, "structuredRegular"); + auto data = anari::newArray3D(d, values.data(), 8, 8, 8); + anari::setAndReleaseParameter(d, field, "data", data); + anari::setParameter(d, field, "origin", vec3{0, 0, 0}); + anari::setParameter(d, field, "spacing", vec3{1, 1, 1}); + anari::commitParameters(d, field); + anari::setAndReleaseParameter(d, geometry, "field", field); + anari::setParameter(d, geometry, "isovalue", 3.5f); + } else { + anari::setParameter(d, geometry, "vertex.position", array); + anari::setParameter(d, geometry, "radius", 0.1f); + } + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + std::vector surfaces{surface}; + anari::Geometry sibling = nullptr; + if (curveFailure && !isosurfaceFailure && !sphereFailure) { + sibling = anari::newObject(d, "curve"); + anari::setParameterArray1D( + d, sibling, "vertex.position", vertices.data(), 4); + anari::setParameter(d, sibling, "radius", 0.1f); + anari::commitParameters(d, sibling); + auto siblingMaterial = anari::newObject(d, "matte"); + anari::commitParameters(d, siblingMaterial); + auto siblingSurface = anari::newObject(d); + anari::setParameter(d, siblingSurface, "geometry", sibling); + anari::setAndReleaseParameter( + d, siblingSurface, "material", siblingMaterial); + anari::commitParameters(d, siblingSurface); + surfaces.push_back(siblingSurface); + } + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + for (auto s : surfaces) + anari::release(d, s); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{8, 8}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + std::array bounds{}; + auto haveBounds = [&]() { + return anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + != 0; + }; + bool ok = errors == 0; + if (curveFailure) { + if (isosurfaceFailure) { + ok = haveBounds() && ok; + anari::setParameter(d, geometry, "isovalue", 2.5f); + anari::commitParameters(d, geometry); + } + if (sibling) { + anari::setParameter(d, sibling, "radius", 0.15f); + anari::commitParameters(d, sibling); + } + // Sphere AABBs (two vec3s each), or generated curve indices. + allocationBytes = sphereFailure + ? (std::strcmp(argv[1], "sphere-indexed") == 0 ? 3 : vertices.size()) + * 2 * sizeof(vec3) + : 3 * sizeof(unsigned); + failure = isosurfaceFailure ? Failure::WORK_SYNC : Failure::ALLOCATION; + ok = !haveBounds() && ok; + // The unaffected sibling must not inherit the first geometry's OOM. + // Recovery below must succeed without recommitting the sibling. + ok = injections == 1 && errors == 1 && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 0 && ok; + const int beforeErrors = errors; + anari::setParameter( + d, geometry, isosurfaceFailure ? "isovalue" : "radius", 0.2f); + anari::commitParameters(d, geometry); + ok = haveBounds() && errors == beforeErrors && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == beforeErrors && ok; + anari::release(d, array); + } else { + ok = haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == 0 && ok; + allocationBytes = sizeof(vertices); + if (std::strcmp(argv[1], "allocation") == 0) + failure = Failure::ALLOCATION; + else if (std::strcmp(argv[1], "copy") == 0) + failure = Failure::COPY; + else if (std::strcmp(argv[1], "work-sync") == 0) + failure = Failure::WORK_SYNC; + else if (std::strcmp(argv[1], "copy-sync") == 0) + failure = Failure::COPY_SYNC; + else + return 2; + anari::release(d, array); + ok = injections == 1 && errors > 0 && ok; + cudaFree(deviceVertices); + deviceVertices = nullptr; + ok = !haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && ok; + // No retry or device re-enable after the injected CUDA error is gone. + anari::setParameter(d, geometry, "radius", 0.3f); + anari::commitParameters(d, geometry); + ok = !haveBounds() && ok; + } + if (deviceVertices) + cudaFree(deviceVertices); + anari::release(d, frame); + anari::release(d, world); + anari::release(d, geometry); + if (sibling) + anari::release(d, sibling); + anari::release(d, d); + printf("%s injections=%d %s\n", + curveFailure ? "curve" : argv[1], + injections, + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp b/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp new file mode 100644 index 000000000..633e283aa --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static bool retireShared = false; +static bool expandedSdf = false; + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +static constexpr std::array QUAD_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"all-device", 3}}}; +static constexpr std::array CURVE_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-vertex-radii", 4}, + {"all-device", 7}}}; +static constexpr auto CONE_CASES = CURVE_CASES; +static constexpr auto TRIANGLE_CASES = QUAD_CASES; +static constexpr std::array SPHERE_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-vertex-radii", 4}, + {"all-device", 7}}}; +static constexpr std::array CYLINDER_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-primitive-radii", 4}, + {"all-device", 7}}}; +static constexpr std::array SDF_CASES = { + {{"host", 0}, {"device-primitive-bytes", 1}}}; +static constexpr std::array EXPANDED_SDF_CASES = { + {{"host", 0}, + {"device-primitive-bytes", 1}, + {"device-neighbors", 2}, + {"all-device", 3}}}; +// Indices and radii always use shared GPU storage in retirement mode. +static constexpr std::array RETIREMENT_CASES = { + {{"host-positions-shared-device-indices-radii", 0}, + {"device-positions-shared-device-indices-radii", 1}}}; + +template +static std::pair sharedArray( + ANARIDevice d, anari::Geometry g, const char *name, const Container &values) +{ + using T = typename Container::value_type; + void *ptr = nullptr; + if (cudaMalloc(&ptr, values.size() * sizeof(T)) != cudaSuccess + || cudaMemcpy(ptr, + values.data(), + values.size() * sizeof(T), + cudaMemcpyHostToDevice) + != cudaSuccess) + std::exit(2); + auto array = anariNewArray1D( + d, ptr, nullptr, nullptr, anari::ANARITypeFor::value, values.size()); + anari::setParameter(d, g, name, array); + return {array, ptr}; +} +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} + +struct Scene +{ + anari::World world; + anari::Frame frame; +}; +static Scene makeScene(ANARIDevice d, anari::Geometry g) +{ + auto material = anari::newObject(d, "matte"); + anari::setParameter(d, material, "color", vec3{1, 0, 0}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "baseColor"); + anari::setParameter(d, renderer, "background", vec4{0, 0, 0, 1}); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{64, 64}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + anari::commitParameters(d, frame); + return {world, frame}; +} + +// Exact bounds and a visible/cleared center pixel are independent oracles. +static bool validate(ANARIDevice d, + Scene scene, + const std::array &expected, + bool visible) +{ + anari::wait(d, scene.frame); + std::array bounds{}; + bool ok = anariGetProperty(d, + scene.world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + for (size_t i = 0; i < bounds.size(); ++i) + ok = std::isfinite(bounds[i]) && std::abs(bounds[i] - expected[i]) < 1e-4f + && ok; + auto fb = anari::map(d, scene.frame, "channel.color"); + const float red = fb.data ? fb.data[32 * 64 + 32][0] : NAN; + ok = std::isfinite(red) && (visible ? red > 0.5f : red < 0.01f) && ok; + anari::unmap(d, scene.frame, "channel.color"); + printf("bounds=[%g %g %g %g %g %g] center=%g %s\n", + bounds[0], + bounds[1], + bounds[2], + bounds[3], + bounds[4], + bounds[5], + red, + ok ? "PASS" : "FAIL"); + return ok; +} + +// Public API seam: exact geometric bounds and a visible center pixel are +// independent controls. 1e-4 absolute bounds tolerance permits OptiX rounding; +// moving the input by +2 in X must move the bounds and clear the center pixel. +static bool check(ANARIDevice d, + const char *type, + const ResidencyCase &residency, + float shift) +{ + const int device = residency.deviceInputs; + const char *scenario = + retireShared ? "retirement" : (expandedSdf ? "sdf-expanded" : type); + fprintf(stderr, "[case] %s/%s shift=%g\n", scenario, residency.name, shift); + auto g = anari::newObject(d, type); + std::vector> shared; + float xExtent = 0.5f, yExtent = 0.5f, zExtent = 0.f; + if (std::strcmp(type, "sphere") == 0) { + // The unused large sphere makes ignoring the index observable. + const std::array vertices = { + {{shift + 4.f, 4.f, 0}, {shift, 0, 0}}}; + const std::array indices = {1}; + const std::array radii = {1.f, 0.5f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + setTestArray(d, g, "vertex.radius", radii, device & 4, 1); + zExtent = 0.5f; + } else if (std::strcmp(type, "triangle") == 0) { + const std::array vertices = {{{shift + 4.f, 4.f, 0}, + {shift - 0.5f, -0.5f, 0}, + {shift + 0.5f, -0.5f, 0}, + {shift, 0.5f, 0}}}; + const std::array, 1> indices = {{{1, 2, 3}}}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + } else if (std::strcmp(type, "quad") == 0) { + const std::array vertices = {{{shift - 0.5f, -0.5f, 0}, + {shift + 0.5f, -0.5f, 0}, + {shift + 0.5f, 0.5f, 0}, + {shift - 0.5f, 0.5f, 0}}}; + const std::array, 1> indices = {{{0, 1, 2, 3}}}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + } else if (std::strcmp(type, "cone") == 0 + || std::strcmp(type, "cylinder") == 0) { + const bool cone = std::strcmp(type, "cone") == 0; + // Vertex 0 is deliberately unused. Selecting it instead of logical + // vertices 2 and 1 must fail both the bounds and visibility controls. + const std::array vertices = { + {{shift + 4.f, 4.f, 0}, {shift + 0.5f, 0, 0}, {shift - 0.5f, 0, 0}}}; + const std::array, 1> indices = {{{2, 1}}}; + const std::array vertexRadii = {0.75f, 0.25f, 0.125f}; + const std::array primitiveRadii = {0.25f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + if (cone) + setTestArray(d, g, "vertex.radius", vertexRadii, device & 4, 1); + else + setTestArray(d, g, "primitive.radius", primitiveRadii, device & 4, 1); + anari::setParameter(d, g, "caps", "both"); + // Conservative tube bounds: endpoints [-0.5,0.5], largest radius 0.25. + // This literal oracle is independent of device bound-generation code. + xExtent = 0.75f; + yExtent = zExtent = 0.25f; + } else if (std::strcmp(type, "curve") == 0) { + const std::array vertices = { + {{shift - 0.5f, 0, 0}, {shift + 0.5f, 0, 0}}}; + const std::array indices = {0}; + const std::array radii = {0.125f, 0.125f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + if (retireShared) { + shared.push_back(sharedArray(d, g, "primitive.index", indices)); + shared.push_back(sharedArray(d, g, "vertex.radius", radii)); + } else { + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + setTestArray(d, g, "vertex.radius", radii, device & 4, 1); + } + xExtent = 0.625f; + yExtent = zExtent = 0.125f; + } else { + // VISRTX_GEOMETRY_SDF documents N*72 raw bytes. Pack a sphere, without + // depending on device classes or their private preprocessing buffers. + std::array bytes{}; + const vec3 center = {shift, 0, 0}; + const float radius = 0.5f; + std::memcpy(bytes.data() + 20, center.data(), sizeof(center)); + std::memcpy(bytes.data() + 44, &radius, sizeof(radius)); + std::memcpy(bytes.data() + 48, &radius, sizeof(radius)); + if (expandedSdf) { + bytes[64] = 1; + const std::array neighbours = {0}; + setTestArray(d, g, "primitive.neighbor", neighbours, device & 2, 1); + anari::setParameter(d, g, "blendFactor", 0.5f); + anari::setParameter(d, g, "noiseFactor", 0.5f); + // 0.5 base + 0.5*0.5 blend + 0.5*0.5*0.1 noise. + xExtent = yExtent = 0.775f; + } + setTestArray(d, g, "primitive.sdf", bytes, device & 1, 1); + zExtent = xExtent; + } + anari::commitParameters(d, g); + const auto scene = makeScene(d, g); + anari::release(d, g); + const auto frame = scene.frame; + anari::render(d, frame); + if (retireShared) { + // Last PUBLIC release must finish outstanding consumers and rebind any + // aliases before the application is allowed to retire its shared storage. + for (auto entry : shared) { + anari::release(d, entry.first); + cudaFree(entry.second); + } + fprintf(stderr, + "[case] %s/%s shift=%g after shared storage retirement\n", + scenario, + residency.name, + shift); + anari::setParameter(d, frame, "accumulationVersion", uint64_t(2)); + anari::commitParameters(d, frame); + anari::render(d, frame); + } + const std::array expected = { + shift - xExtent, -yExtent, -zExtent, shift + xExtent, yExtent, zExtent}; + const bool ok = validate(d, scene, expected, shift == 0.f); + anari::release(d, frame); + anari::release(d, scene.world); + return ok; +} +// One array observed by two distinct geometries/worlds. Detaching one consumer +// must not detach the other or hide observer-only unmap updates. +static bool sharedInputs(ANARIDevice d) +{ + auto positions = anari::newArray1D(d, ANARI_FLOAT32_VEC3, 2); + const auto update = [&](float y) { + auto *p = anari::map(d, positions); + p[0] = {-0.5f, y, 0}; + p[1] = {0.5f, y, 0}; + anari::unmap(d, positions); + }; + update(0); + std::array geometries; + std::array scenes; + for (size_t i = 0; i < scenes.size(); ++i) { + auto g = anari::newObject(d, "curve"); + anari::setParameter(d, g, "vertex.position", positions); + anari::setParameter(d, g, "radius", 0.125f); + anari::commitParameters(d, g); + geometries[i] = g; + scenes[i] = makeScene(d, g); + } + const auto check = [&](size_t consumer, float y) { + fprintf(stderr, "[case] shared-input consumer=%zu y=%g\n", consumer, y); + anari::render(d, scenes[consumer].frame); + return validate(d, + scenes[consumer], + {-0.625f, y - 0.125f, -0.125f, 0.625f, y + 0.125f, 0.125f}, + y == 0); + }; + bool ok = check(0, 0); + ok = check(1, 0) && ok; + update(1); // no geometry/world recommit + ok = check(0, 1) && ok; + ok = check(1, 1) && ok; + const std::array replacement = {{{-0.5f, 0, 0}, {0.5f, 0, 0}}}; + setTestArray(d, geometries[0], "vertex.position", replacement, true); + anari::commitParameters(d, geometries[0]); + ok = check(0, 0) && ok; + ok = check(1, 1) && ok; + for (size_t i = 0; i < scenes.size(); ++i) { + anari::release(d, scenes[i].frame); + anari::release(d, scenes[i].world); + anari::release(d, geometries[i]); + } + anari::release(d, positions); + return ok; +} +int main(int argc, char **argv) +{ + retireShared = argc > 1 && std::strcmp(argv[1], "--retire") == 0; + expandedSdf = argc > 1 && std::strcmp(argv[1], "sdf-expanded") == 0; + const char *type = retireShared + ? "curve" + : (expandedSdf ? "sdf" : (argc > 1 ? argv[1] : "quad")); + auto d = makeVisRTXDevice(status); + bool ok = true; + const auto runCases = [&](const auto &cases) { + for (const auto &residency : cases) + for (float shift : {0.f, 2.f}) + ok = check(d, type, residency, shift) && ok; + }; + if (std::strcmp(type, "--shared-inputs") == 0) + ok = sharedInputs(d); + else if (retireShared) + runCases(RETIREMENT_CASES); + else if (expandedSdf) + runCases(EXPANDED_SDF_CASES); + else if (std::strcmp(type, "triangle") == 0) + runCases(TRIANGLE_CASES); + else if (std::strcmp(type, "sphere") == 0) + runCases(SPHERE_CASES); + else if (std::strcmp(type, "quad") == 0) + runCases(QUAD_CASES); + else if (std::strcmp(type, "curve") == 0) + runCases(CURVE_CASES); + else if (std::strcmp(type, "cone") == 0) + runCases(CONE_CASES); + else if (std::strcmp(type, "cylinder") == 0) + runCases(CYLINDER_CASES); + else + runCases(SDF_CASES); + anari::release(d, d); + return ok && errors == 0 ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp b/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp index c5f7269bb..fa6aaa1ad 100644 --- a/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp +++ b/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp @@ -64,31 +64,37 @@ #include #include #include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +// Bounds/visibility isolate positions, indices and radii. Caps affect +// sampling rather than conservative bounds, so retain their isolated oracle. +static constexpr std::array TUBE_CASES = { + {{"host-indexed", 0}, {"device-vertex-caps", 4}, {"all-device", 15}}}; using vec3 = std::array; using vec4 = std::array; using uvec3 = std::array; using mat4 = std::array; -static void statusFunc(const void *, - ANARIDevice, - ANARIObject source, - ANARIDataType, - ANARIStatusSeverity severity, - ANARIStatusCode, - const char *message) -{ - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) - fprintf(stderr, "[ERROR][%p] %s\n", source, message); -} - static constexpr std::array IMAGE_SIZE = {256, 256}; static constexpr int PIXEL_SAMPLES = 1024; static constexpr float EMISSIVE_RADIANCE = 8.f; -static constexpr int TESS = 128; // circumferential segments of the reference mesh +static constexpr double TOLERANCE = 0.03; +static bool equivalent(double actual, double reference) +{ + return std::isfinite(actual) && std::isfinite(reference) && actual > 0.0 + && reference > 0.0 + && std::abs(actual - reference) / reference <= TOLERANCE; +} +static constexpr int TESS = + 128; // circumferential segments of the reference mesh // One tapered tube (cylinder if r0==r1). Two parallel bars above the origin, // axes along X, offset in Z, so their walls face the floor. Above the top of @@ -169,35 +175,11 @@ static anari::Material makeEmissiveMaterial(ANARIDevice device) return mat; } -static anari::Surface makeFloor(ANARIDevice device) -{ - const std::array pos = {vec3{-6.f, 0.f, -6.f}, - vec3{6.f, 0.f, -6.f}, - vec3{6.f, 0.f, 6.f}, - vec3{-6.f, 0.f, 6.f}}; - const std::array idx = {uvec3{0, 1, 2}, uvec3{0, 2, 3}}; - - auto geom = anari::newObject(device, "triangle"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); - anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); - anari::commitParameters(device, geom); - - auto mat = anari::newObject(device, "physicallyBased"); - anari::setParameter(device, mat, "baseColor", vec3{0.5f, 0.5f, 0.5f}); - anari::setParameter(device, mat, "roughness", 1.f); - anari::commitParameters(device, mat); - - auto surface = anari::newObject(device); - anari::setAndReleaseParameter(device, surface, "geometry", geom); - anari::setAndReleaseParameter(device, surface, "material", mat); - anari::commitParameters(device, surface); - return surface; -} - // Capped, tessellated emissive triangle mesh of the given tubes: two rings of // TESS points per tube plus a center vertex for each ENABLED cap. Winding does -// not matter (emission is double-sided); the closed shell absorbs its own inward -// emission so it lights the exterior floor like a single-sided primitive. +// not matter (emission is double-sided); the closed shell absorbs its own +// inward emission so it lights the exterior floor like a single-sided +// primitive. static anari::Surface makeEmissiveTubeMesh( ANARIDevice device, const std::array &tubes) { @@ -257,7 +239,8 @@ static anari::Surface makeEmissiveTubeMesh( // Per-endpoint vertex.cap (0/1) for a soup tube set: endpoints of tube k are // vertices (2k, 2k+1). -static std::vector tubeVertexCaps(const std::array &tubes) +static std::vector tubeVertexCaps( + const std::array &tubes) { std::vector caps; for (const auto &t : tubes) { @@ -267,7 +250,8 @@ static std::vector tubeVertexCaps(const std::array &tube return caps; } -static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) +static anari::Surface makeEmissiveCylinderPrim( + ANARIDevice device, int deviceInputs, bool indexed) { std::vector pos; std::vector radii; // per primitive @@ -279,12 +263,13 @@ static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) const auto caps = tubeVertexCaps(CYLINDERS); auto geom = anari::newObject(device, "cylinder"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "primitive.radius", radii.data(), radii.size()); - anari::setParameterArray1D( - device, geom, "vertex.cap", caps.data(), caps.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs & 1); + setTestArray(device, geom, "primitive.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "vertex.cap", caps, deviceInputs & 4); + if (indexed) { + const std::array, 2> indices = {{{0, 1}, {2, 3}}}; + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 8); + } anari::commitParameters(device, geom); auto surface = anari::newObject(device); @@ -295,7 +280,8 @@ static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) return surface; } -static anari::Surface makeEmissiveConePrim(ANARIDevice device) +static anari::Surface makeEmissiveConePrim( + ANARIDevice device, int deviceInputs, bool indexed) { std::vector pos; std::vector radii; // per vertex @@ -308,12 +294,13 @@ static anari::Surface makeEmissiveConePrim(ANARIDevice device) const auto caps = tubeVertexCaps(CONES); auto geom = anari::newObject(device, "cone"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "vertex.radius", radii.data(), radii.size()); - anari::setParameterArray1D( - device, geom, "vertex.cap", caps.data(), caps.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs & 1); + setTestArray(device, geom, "vertex.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "vertex.cap", caps, deviceInputs & 4); + if (indexed) { + const std::array, 2> indices = {{{0, 1}, {2, 3}}}; + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 8); + } anari::commitParameters(device, geom); auto surface = anari::newObject(device); @@ -342,128 +329,90 @@ static anari::Instance instanceOf( return inst; } -static std::vector render(ANARIDevice device, +static double render(ANARIDevice device, const std::function &emitter, bool scaled) { const std::array instances = { - instanceOf(device, makeFloor(device), false), + instanceOf(device, visrtx::test::receiverFloor(device, 0.5f), false), instanceOf(device, emitter(device), scaled)}; auto world = anari::newObject(device); + const visrtx::test::ObjectOwner worldOwner(device, world); anari::setParameterArray1D( device, world, "instance", instances.data(), instances.size()); for (auto i : instances) anari::release(device, i); anari::commitParameters(device, world); - auto camera = anari::newObject(device, "perspective"); - anari::setParameter(device, camera, "position", vec3{0.f, 0.5f, -3.f}); - anari::setParameter(device, camera, "direction", vec3{0.f, -0.15f, 1.f}); - anari::setParameter(device, camera, "up", vec3{0.f, 1.f, 0.f}); - anari::setParameter( - device, camera, "aspect", IMAGE_SIZE[0] / float(IMAGE_SIZE[1])); - anari::commitParameters(device, camera); - - auto renderer = anari::newObject(device, "quality"); - anari::setParameter(device, renderer, "background", vec4{0.f, 0.f, 0.f, 1.f}); - anari::setParameter(device, renderer, "ambientRadiance", 0.f); - anari::setParameter(device, renderer, "pixelSamples", PIXEL_SAMPLES); - anari::setParameter(device, renderer, "fireflyFilterMode", "none"); - anari::commitParameters(device, renderer); - - auto frame = anari::newObject(device); - anari::setParameter(device, frame, "size", IMAGE_SIZE); - anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); - anari::setAndReleaseParameter(device, frame, "world", world); - anari::setAndReleaseParameter(device, frame, "camera", camera); - anari::setAndReleaseParameter(device, frame, "renderer", renderer); - anari::commitParameters(device, frame); - - anari::render(device, frame); - anari::wait(device, frame); - - auto fb = anari::map(device, frame, "channel.color"); - std::vector out(fb.data, fb.data + size_t(fb.width) * fb.height); - anari::unmap(device, frame, "channel.color"); - anari::release(device, frame); - return out; -} - -// Mean linear luminance over the lit floor region (lower-center of the frame, -// ANARI's bottom-left framebuffer origin). -static double poolMeanLuminance(const std::vector &fb) -{ - double sum = 0.0; - uint64_t n = 0; - for (uint32_t y = IMAGE_SIZE[1] / 8; y < IMAGE_SIZE[1] / 2; ++y) { - for (uint32_t x = 3 * IMAGE_SIZE[0] / 8; x < 5 * IMAGE_SIZE[0] / 8; ++x) { - const vec4 &p = fb[y * IMAGE_SIZE[0] + x]; - sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - ++n; - } - } - return n ? sum / double(n) : 0.0; + auto frame = visrtx::test::receiverFrame( + device, world, IMAGE_SIZE, "quality", PIXEL_SAMPLES); + const visrtx::test::ObjectOwner frameOwner(device, frame); + // Bottom-left origin; only the floor's cast pool, never the emitters. + return visrtx::test::receiverLuminance(device, + frame, + IMAGE_SIZE, + {3 * IMAGE_SIZE[0] / 8, + 5 * IMAGE_SIZE[0] / 8, + IMAGE_SIZE[1] / 8, + IMAGE_SIZE[1] / 2}); } -static bool checkEquivalent( - ANARIDevice device, const char *name, - const std::function &prim, - const std::function &mesh, +static bool checkFamily(ANARIDevice device, + const char *name, + const std::array &tubes, + const std::function &prim, bool scaled) { - const double p = poolMeanLuminance(render(device, prim, scaled)); - const double m = poolMeanLuminance(render(device, mesh, scaled)); - const double relErr = m > 0.0 ? std::abs(p - m) / m : (p > 0 ? 1.0 : 0.0); - printf("%s%s: primitive=%f mesh=%f relErr=%f\n", - name, - scaled ? " (scaled)" : "", - p, - m, - relErr); - if (p <= 0.0 || m <= 0.0) { - fprintf(stderr, "FAIL: %s floor pool unlit\n", name); - return false; + const char *transform = scaled ? "nonuniform-scale" : "identity"; + // Keep an independent tessellated reference for each family and transform. + fprintf(stderr, "[case] %s/%s/reference\n", name, transform); + const double mesh = render( + device, + [&](ANARIDevice d) { return makeEmissiveTubeMesh(d, tubes); }, + scaled); + bool ok = std::isfinite(mesh) && mesh > 0.0; + + const auto check = + [&](const char *residency, int deviceInputs, bool indexed) { + fprintf(stderr, "[case] %s/%s/%s\n", name, transform, residency); + const double actual = render( + device, + [&](ANARIDevice d) { return prim(d, deviceInputs, indexed); }, + scaled); + // Keep the original 3% MC/faceting allowance. + const bool matches = equivalent(actual, mesh); + printf("%s/%s/%s primitive=%f reference=%f relErr=%g tolerance=%g %s\n", + name, + transform, + residency, + actual, + mesh, + std::abs(actual - mesh) / mesh, + TOLERANCE, + matches ? "PASS" : "FAIL"); + ok = matches && ok; + }; + check("host-implicit-indices", 0, false); + for (const auto &residency : TUBE_CASES) { + // Residency roles are isolated at identity; the all-device case also + // witnesses their integration with the nonuniform area Jacobian. + if (!scaled || residency.deviceInputs == 15) + check(residency.name, residency.deviceInputs, true); } - // 3% absorbs MC noise at 1024 spp plus the reference mesh's small (<0.1% area) - // faceting; observed relErr is well under 1%. - constexpr double TOLERANCE = 0.03; - if (relErr > TOLERANCE) { - fprintf(stderr, - "FAIL: %s%s geometry light not equivalent to tessellated mesh (relErr=%f > %f)\n", - name, - scaled ? " (scaled)" : "", - relErr, - TOLERANCE); - return false; - } - return true; + return ok; } int main() { - auto device = makeVisRTXDevice(statusFunc); - - const auto cylMesh = [](ANARIDevice d) { - return makeEmissiveTubeMesh(d, CYLINDERS); - }; - const auto coneMesh = [](ANARIDevice d) { - return makeEmissiveTubeMesh(d, CONES); - }; - + auto device = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); bool ok = true; for (bool scaled : {false, true}) { - ok = checkEquivalent( - device, "cylinder", makeEmissiveCylinderPrim, cylMesh, scaled) - && ok; - ok = checkEquivalent(device, "cone", makeEmissiveConePrim, coneMesh, scaled) + ok = checkFamily( + device, "cylinder", CYLINDERS, makeEmissiveCylinderPrim, scaled) && ok; + ok = checkFamily(device, "cone", CONES, makeEmissiveConePrim, scaled) && ok; } - anari::release(device, device); - - if (!ok) - return 1; - printf("emissive cylinder/cone geometry light equivalence passed\n"); - return 0; + return ok ? 0 : 1; } diff --git a/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp b/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp index 52d295e17..6f54d078a 100644 --- a/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp +++ b/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp @@ -33,11 +33,11 @@ // (PhysicallyBased, constant `emissive`) must illuminate a floor the same as an // ANARI sphere light (the "point" subtype with radius) of matching radiance, // radius, and placement. Validates the sphere sampler's radiometry and that -// hit-side MIS does not bias (NEE + BSDF-hit deposit sum to the analytic light's -// contribution). The emitter sits above the top of frame so only its cast pool -// on the floor is measured — the emissive sphere's own glow (which the analytic -// light has no counterpart for) never enters the region. Rendered with 'quality' -// into a linear float buffer, firefly filter off. +// hit-side MIS does not bias (NEE + BSDF-hit deposit sum to the analytic +// light's contribution). The emitter sits above the top of frame so only its +// cast pool on the floor is measured — the emissive sphere's own glow (which +// the analytic light has no counterpart for) never enters the region. Rendered +// with 'quality' into a linear float buffer, firefly filter off. // anari_cpp #define ANARI_EXTENSION_UTILITY_IMPL @@ -52,70 +52,58 @@ #include #include #include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +// Bounds/visibility isolate input roles; radiometry checks the sampler. +static constexpr std::array SPHERE_CASES = { + {{"host-indexed", 0}, {"all-device", 7}}}; using uvec2 = std::array; using vec3 = std::array; using vec4 = std::array; -static void statusFunc(const void *, - ANARIDevice, - ANARIObject source, - ANARIDataType, - ANARIStatusSeverity severity, - ANARIStatusCode, - const char *message) -{ - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) - fprintf(stderr, "[ERROR][%p] %s\n", source, message); -} - static constexpr uvec2 IMAGE_SIZE = {256, 256}; static constexpr int PIXEL_SAMPLES = 512; static constexpr float EMISSIVE_RADIANCE = 8.f; +static constexpr double TOLERANCE = 0.05; + +static bool equivalent(double actual, double reference) +{ + return std::isfinite(actual) && std::isfinite(reference) && actual > 0.0 + && reference > 0.0 + && std::abs(actual - reference) / reference <= TOLERANCE; +} // Emitter footprint: a small sphere centered above the origin, above frame. static constexpr vec3 SPHERE_CENTER = {0.f, 1.5f, 0.f}; static constexpr float SPHERE_RADIUS = 0.4f; -// Add a floor (large diffuse XZ quad at y=0) to the world. -static anari::Surface makeFloor(ANARIDevice device) -{ - const std::array pos = {vec3{-6.f, 0.f, -6.f}, - vec3{6.f, 0.f, -6.f}, - vec3{6.f, 0.f, 6.f}, - vec3{-6.f, 0.f, 6.f}}; - const std::array, 2> idx = { - std::array{0, 1, 2}, std::array{0, 2, 3}}; - - auto geom = anari::newObject(device, "triangle"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); - anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); - anari::commitParameters(device, geom); - - auto mat = anari::newObject(device, "physicallyBased"); - anari::setParameter(device, mat, "baseColor", vec3{0.6f, 0.6f, 0.6f}); - anari::setParameter(device, mat, "metallic", 0.f); - anari::setParameter(device, mat, "roughness", 1.f); - anari::commitParameters(device, mat); - - auto surface = anari::newObject(device); - anari::setAndReleaseParameter(device, surface, "geometry", geom); - anari::setAndReleaseParameter(device, surface, "material", mat); - anari::commitParameters(device, surface); - return surface; -} - // Emissive sphere geometry at the emitter footprint. -static anari::Surface makeEmissiveSphere(ANARIDevice device) +static anari::Surface makeEmissiveSphere( + ANARIDevice device, int deviceInputs, bool indexed) { const std::array pos = {SPHERE_CENTER}; auto geom = anari::newObject(device, "sphere"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 1); - anari::setParameter(device, geom, "radius", SPHERE_RADIUS); + if (indexed) { + const std::array positions = {vec3{0.f, 20.f, 0.f}, SPHERE_CENTER}; + const std::array radii = {0.01f, SPHERE_RADIUS}; + const std::array indices = {1}; + setTestArray(device, geom, "vertex.position", positions, deviceInputs & 1); + setTestArray(device, geom, "vertex.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 4); + anari::setParameter(device, geom, "radius", 0.01f); + } else { + anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 1); + anari::setParameter(device, geom, "radius", SPHERE_RADIUS); + } anari::commitParameters(device, geom); auto mat = anari::newObject(device, "physicallyBased"); @@ -149,17 +137,21 @@ static anari::Light makeSphereLight(ANARIDevice device) } // Render the floor lit by either the emissive sphere (useMesh) or the ANARI -// sphere light, and return the linear framebuffer. -static std::vector render(ANARIDevice device, bool useMesh) +// sphere light, measuring linear luminance without copying the framebuffer. +static double render(ANARIDevice device, + bool useMesh, + int deviceInputs = 0, + bool indexed = false) { - std::vector surfaces = {makeFloor(device)}; + std::vector surfaces = {visrtx::test::receiverFloor(device)}; std::vector lights; if (useMesh) - surfaces.push_back(makeEmissiveSphere(device)); + surfaces.push_back(makeEmissiveSphere(device, deviceInputs, indexed)); else lights.push_back(makeSphereLight(device)); auto world = anari::newObject(device); + const visrtx::test::ObjectOwner worldOwner(device, world); anari::setParameterArray1D( device, world, "surface", surfaces.data(), surfaces.size()); if (!lights.empty()) @@ -171,85 +163,45 @@ static std::vector render(ANARIDevice device, bool useMesh) anari::release(device, l); anari::commitParameters(device, world); - // Look across the floor toward +Z; the emitter at y=1.5 sits above the frame, - // so only its cast pool on the floor is visible. - auto camera = anari::newObject(device, "perspective"); - anari::setParameter(device, camera, "position", vec3{0.f, 0.5f, -3.f}); - anari::setParameter(device, camera, "direction", vec3{0.f, -0.15f, 1.f}); - anari::setParameter(device, camera, "up", vec3{0.f, 1.f, 0.f}); - anari::setParameter( - device, camera, "aspect", IMAGE_SIZE[0] / float(IMAGE_SIZE[1])); - anari::commitParameters(device, camera); - - auto renderer = anari::newObject(device, "quality"); - anari::setParameter(device, renderer, "background", vec4{0.f, 0.f, 0.f, 1.f}); - anari::setParameter(device, renderer, "ambientRadiance", 0.f); - anari::setParameter(device, renderer, "pixelSamples", PIXEL_SAMPLES); - anari::setParameter(device, renderer, "fireflyFilterMode", "none"); - anari::commitParameters(device, renderer); - - auto frame = anari::newObject(device); - anari::setParameter(device, frame, "size", IMAGE_SIZE); - anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); - anari::setAndReleaseParameter(device, frame, "world", world); - anari::setAndReleaseParameter(device, frame, "camera", camera); - anari::setAndReleaseParameter(device, frame, "renderer", renderer); - anari::commitParameters(device, frame); - - anari::render(device, frame); - anari::wait(device, frame); - - auto fb = anari::map(device, frame, "channel.color"); - std::vector out(fb.data, fb.data + size_t(fb.width) * fb.height); - anari::unmap(device, frame, "channel.color"); - anari::release(device, frame); - return out; -} - -// Mean linear luminance over the lit floor region (lower-center of the frame, -// ANARI's bottom-left framebuffer origin). -static double poolMeanLuminance(const std::vector &fb) -{ - double sum = 0.0; - uint64_t n = 0; - for (uint32_t y = IMAGE_SIZE[1] / 8; y < IMAGE_SIZE[1] / 2; ++y) { - for (uint32_t x = 3 * IMAGE_SIZE[0] / 8; x < 5 * IMAGE_SIZE[0] / 8; ++x) { - const vec4 &p = fb[y * IMAGE_SIZE[0] + x]; - sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - ++n; - } - } - return n ? sum / double(n) : 0.0; + auto frame = visrtx::test::receiverFrame( + device, world, IMAGE_SIZE, "quality", PIXEL_SAMPLES); + const visrtx::test::ObjectOwner frameOwner(device, frame); + // Bottom-left origin; only the floor's cast pool, never the emitter. + return visrtx::test::receiverLuminance(device, + frame, + IMAGE_SIZE, + {3 * IMAGE_SIZE[0] / 8, + 5 * IMAGE_SIZE[0] / 8, + IMAGE_SIZE[1] / 8, + IMAGE_SIZE[1] / 2}); } int main() { - auto device = makeVisRTXDevice(statusFunc); - - const double mesh = poolMeanLuminance(render(device, true)); - const double light = poolMeanLuminance(render(device, false)); + auto device = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); + + fprintf(stderr, "[case] sphere/reference\n"); + const double light = render(device, false); + bool ok = std::isfinite(light) && light > 0.0; + + const auto check = [&](const char *name, int deviceInputs, bool indexed) { + fprintf(stderr, "[case] sphere/%s\n", name); + const double mesh = render(device, true, deviceInputs, indexed); + // The unchanged 5% allowance covers MC noise at 512 spp. + const bool matches = equivalent(mesh, light); + printf("sphere/%s mesh=%f reference=%f relErr=%g tolerance=%g %s\n", + name, + mesh, + light, + std::abs(mesh - light) / light, + TOLERANCE, + matches ? "PASS" : "FAIL"); + ok = matches && ok; + }; + check("host-scalar-radius", 0, false); + for (const auto &residency : SPHERE_CASES) + check(residency.name, residency.deviceInputs, true); anari::release(device, device); - - const double relErr = - light > 0.0 ? std::abs(mesh - light) / light : (mesh > 0 ? 1.0 : 0.0); - printf("emissiveSphere=%f sphereLight=%f relErr=%f\n", mesh, light, relErr); - - // Both estimators must converge to the same floor irradiance. A generous 5% - // absorbs residual MC noise at 512 spp; a broken radiometry or double-count - // shifts it by far more. - if (mesh <= 0.0 || light <= 0.0) { - fprintf(stderr, "FAIL: floor pool unlit (mesh=%f light=%f)\n", mesh, light); - return 1; - } - constexpr double TOLERANCE = 0.05; - if (relErr > TOLERANCE) { - fprintf(stderr, - "FAIL: emissive sphere geometry light not equivalent to sphere light (relErr=%f > %f)\n", - relErr, - TOLERANCE); - return 1; - } - printf("emissive sphere geometry light equivalence passed\n"); - return 0; + return ok ? 0 : 1; } diff --git a/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp b/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp new file mode 100644 index 000000000..3e3fa43fc --- /dev/null +++ b/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Recoverable publication errors must not consume a checkerboard tile. ELF +// interposition requires the shared CUDA runtime, just like preparation tests. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using vec3 = std::array; +using vec4 = std::array; +bool failPublication = false; +int injections = 0; +int errors = 0; +int publicationErrors = 0; +std::atomic completions{0}; + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + if (std::strstr(message, "GPU publication failure")) + ++publicationErrors; + std::fprintf(stderr, "%s\n", message); + } +} + +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +bool run(bool checkerboard, bool reset) +{ + const int initialErrors = errors; + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject(d, "quad"); + const std::array vertices = { + vec3{-10, -10, 0}, vec3{10, -10, 0}, vec3{10, 10, 0}, vec3{-10, 10, 0}}; + anari::setParameterArray1D( + d, geometry, "vertex.position", vertices.data(), vertices.size()); + anari::setParameter(d, geometry, "color", vec4{0.8f, 0.4f, 0.2f, 1.f}); + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setAndReleaseParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "orthographic"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + // Debug is deterministic and has a finite sample limit of one. Orthographic + // rays make facing modulation constant, so every tile must match exactly. + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "geometry.color"); + anari::setParameter(d, renderer, "checkerboarding", checkerboard); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{8, 8}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "world", world); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "accumulationVersion", uint64_t(1)); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + auto render = [&] { + anari::render(d, frame); + anari::wait(d, frame); + }; + auto samples = [&] { + int n = -1; + anariGetProperty( + d, frame, "numSamples", ANARI_INT32, &n, sizeof(n), ANARI_WAIT); + return n; + }; + auto pixels = [&] { + auto fb = anari::map(d, frame, "channel.color"); + std::vector result; + if (fb.data) + result.assign(fb.data, fb.data + 64); + anari::unmap(d, frame, "channel.color"); + return result; + }; + const int tiles = checkerboard ? 4 : 1; + // Resolve the frame's initial reset before the manual-version reset, then + // obtain a complete reference cycle (extra calls stop at the sample limit). + render(); + for (int i = 0; i < tiles; ++i) + render(); + const auto reference = pixels(); + bool ok = samples() == 1 && reference.size() == 64 && errors == initialErrors; + for (const auto &pixel : reference) + ok = pixel[0] > 0.7f && pixel[1] > 0.3f && ok; + if (!ok) + std::fprintf(stderr, + "reference failed: samples=%d pixels=%zu errors=%d\n", + samples(), + reference.size(), + errors - initialErrors); + + anari::setParameter(d, frame, "accumulationVersion", uint64_t(2)); + anari::commitParameters(d, frame); + if (!reset) + render(); // Start a checkerboard cycle, then reject its second tile. + const int before = completions; + const int beforeInjections = injections; + const int beforePublicationErrors = publicationErrors; + failPublication = true; + render(); + ok = injections == beforeInjections + 1 + && publicationErrors == beforePublicationErrors + 1 + && errors == initialErrors + 1 && completions == before && samples() == 0 + && ok; + // No recommit: recovery must restart every tile, not skip the rejected one. + for (int i = 0; i < tiles; ++i) { + render(); + const bool stepOk = + completions == before + i + 1 && samples() == (i + 1 == tiles ? 1 : 0); + if (!stepOk) + std::fprintf(stderr, + "retry %d: completions=%d samples=%d\n", + i, + int(completions) - before, + samples()); + ok = stepOk && ok; + } + const auto recovered = pixels(); + ok = recovered.size() == reference.size() && ok; + if (recovered.size() == reference.size()) + for (size_t i = 0; i < reference.size(); ++i) + for (int c = 0; c < 4; ++c) + ok = std::isfinite(recovered[i][c]) + && std::abs(recovered[i][c] - reference[i][c]) < 1e-5f && ok; + if (!ok) + std::fprintf(stderr, "recovery failed before sample-limit check\n"); + render(); // The finite sample limit must suppress only this extra call. + ok = completions == before + tiles && samples() == 1 + && errors == initialErrors + 1 && ok; + anari::release(d, frame); + anari::release(d, d); + std::printf("publication recovery checkerboard=%d reset=%d %s\n", + checkerboard, + reset, + ok ? "PASS" : "FAIL"); + return ok; +} +} // namespace + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + auto real = reinterpret_cast( + dlsym(RTLD_NEXT, "cudaStreamSynchronize")); + if (!real) + std::abort(); + const auto error = real(stream); + if (!stream && failPublication) { + failPublication = false; + ++injections; + return cudaErrorUnknown; + } + return error; +} + +int main() +{ + bool ok = run(true, false); + ok = run(true, true) && ok; + ok = run(false, true) && ok; + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp b/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp index 28ff414c9..337cd841c 100644 --- a/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp +++ b/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp @@ -53,6 +53,9 @@ #include #include #include +#include "DeviceTestArray.h" + +static bool deviceInputs = false; using uvec2 = std::array; using uvec3 = std::array; @@ -69,11 +72,10 @@ static void statusFunc(const void *, ANARIStatusCode, const char *message) { - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) + if (severity <= ANARI_SEVERITY_ERROR) { fprintf(stderr, "[ERROR][%p] %s\n", source, message); + std::exit(1); + } } static constexpr uvec2 IMAGE_SIZE = {256, 256}; @@ -200,13 +202,10 @@ static anari::Geometry makeQuads(ANARIDevice device, Frame frame) } auto geom = anari::newObject(device, "quad"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "primitive.index", idx.data(), idx.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs); + setTestArray(device, geom, "primitive.index", idx, deviceInputs); anari::setParameterArray1D(device, geom, "vertex.normal", n.data(), n.size()); - anari::setParameterArray1D( - device, geom, "vertex.attribute0", uv.data(), uv.size()); + setTestArray(device, geom, "vertex.attribute0", uv, deviceInputs); if (frame == Frame::AUTHORED || frame == Frame::ROTATED) anari::setParameterArray1D( device, geom, "vertex.tangent", t.data(), t.size()); @@ -320,8 +319,9 @@ static double maxTileRelErr( return worst; } -int main() +int main(int argc, char **) { + deviceInputs = argc > 1; auto device = makeVisRTXDevice(statusFunc); const std::array subtypes = {"physicallyBased", diff --git a/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp new file mode 100644 index 000000000..cd9118d30 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} +static std::atomic completions{0}; +static void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +// Numeric failure is recoverable without poisoning CUDA. Test first preparation +// and failure after a good generation, via public samples/callback/bounds APIs. +int main(int argc, char **argv) +{ + const bool boundsFailure = argc > 1; + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject( + d, boundsFailure ? "cylinder" : "sphere"); + const std::array positions = {{{-0.25f, 0, 0}, {0.25f, 0, 0}}}; + setTestArray(d, geometry, "vertex.position", positions, true); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "interactive"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{32, 32}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + bool ok = true; + int previousSamples = 0; + for (int step = 0; step < 4; ++step) { + const bool invalid = step % 2 == 0; + const std::array radii = {invalid + ? (boundsFailure ? std::numeric_limits::infinity() : 1e20f) + : 0.25f, + 0.125f}; + setTestArray(d, + geometry, + boundsFailure ? "primitive.radius" : "vertex.radius", + radii, + true); + anari::commitParameters(d, geometry); + const int beforeErrors = errors; + const int beforeCompletions = completions; + anari::render(d, frame); + anari::wait(d, frame); + int samples = -1; + ok = anari::getProperty(d, frame, "numSamples", samples) && ok; + std::array bounds{}; + const bool haveBounds = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + if (invalid) + ok = ok && errors > beforeErrors && samples == previousSamples + && completions == beforeCompletions && !haveBounds; + else { + ok = ok && errors == beforeErrors && samples > 0 + && completions == beforeCompletions + 1 && haveBounds; + previousSamples = samples; + } + printf("%s step=%d samples=%d callbacks=%d errors=%d bounds=%d %s\n", + boundsFailure ? "bounds" : "area", + step, + samples, + int(completions), + errors, + haveBounds, + ok ? "PASS" : "FAIL"); + } + anari::release(d, frame); + anari::release(d, world); + anari::release(d, geometry); + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp b/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp new file mode 100644 index 000000000..9ae529df8 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +using vec3 = std::array; +using vec4 = std::array; +using Pools = std::array; +static constexpr unsigned WIDTH = 128, HEIGHT = 128; +// Fixed before inspecting results: match the existing 512-spp triangle/quad +// oracle's 5% allowance. Omitting one light must fail this same threshold. +// Zero-area phases allow only 1e-6. +static constexpr double REL_TOL = 0.05, BLACK_TOL = 1e-6; + +static std::array vertices(float halfWidth) +{ + return {{{-halfWidth, 1.5f, -0.5f}, + {halfWidth, 1.5f, -0.5f}, + {halfWidth, 1.5f, 0.5f}, + {-halfWidth, 1.5f, 0.5f}, + {-halfWidth, 1.5f, -0.25f}}}; +} +static void setTriangles(ANARIDevice d, + anari::Geometry g, + float halfWidth, + bool device = true, + bool soup = false) +{ + const auto positions = vertices(halfWidth); + // Unequal areas plus a zero-area triangle exercise the area/CDF sampler. + const std::array, 4> indices = { + {{0, 1, 4}, {1, 2, 4}, {2, 3, 4}, {4, 4, 4}}}; + if (soup) { + std::array expanded; + for (size_t i = 0; i < indices.size(); ++i) + for (size_t c = 0; c < 3; ++c) + expanded[3 * i + c] = positions[indices[i][c]]; + setTestArray(d, g, "vertex.position", expanded, device); + anari::unsetParameter(d, g, "primitive.index"); + } else { + setTestArray(d, g, "vertex.position", positions, device); + setTestArray(d, g, "primitive.index", indices, device); + } + anari::commitParameters(d, g); +} +static anari::Geometry geometry(ANARIDevice d, float halfWidth) +{ + auto g = anari::newObject(d, "triangle"); + setTriangles(d, g, halfWidth); + return g; +} +static anari::Surface surface(ANARIDevice d, anari::Geometry g) +{ + auto m = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, m, "baseColor", vec3{0, 0, 0}); + anari::setParameter(d, m, "emissive", vec3{8, 8, 8}); + anari::commitParameters(d, m); + auto s = anari::newObject(d); + anari::setParameter(d, s, "geometry", g); + anari::setAndReleaseParameter(d, s, "material", m); + anari::commitParameters(d, s); + return s; +} +static void translate(ANARIDevice d, anari::Instance instance, float x) +{ + const std::array matrix = { + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1}; + anari::setParameter( + d, instance, "transform", ANARI_FLOAT32_MAT4, matrix.data()); + anari::commitParameters(d, instance); +} +static anari::Instance instanceOf(ANARIDevice d, anari::Surface s, float x) +{ + auto group = anari::newObject(d); + anari::setParameterArray1D(d, group, "surface", &s, 1); + anari::commitParameters(d, group); + auto instance = anari::newObject(d, "transform"); + anari::setAndReleaseParameter(d, instance, "group", group); + translate(d, instance, x); + return instance; +} +static anari::World worldWithFloor(ANARIDevice d) +{ + auto w = anari::newObject(d); + auto floor = visrtx::test::receiverFloor(d); + anari::setParameterArray1D(d, w, "surface", &floor, 1); + anari::release(d, floor); + return w; +} +static anari::Frame frame(ANARIDevice d, anari::World world) +{ + return visrtx::test::receiverFrame( + d, world, {WIDTH, HEIGHT}, "interactive", 512); +} +static Pools render(ANARIDevice d, anari::Frame f) +{ + anari::render(d, f); + anari::wait(d, f); + const visrtx::test::FrameMapping mapping(d, f, "channel.color"); + const auto *pixels = mapping.checkedData(WIDTH, HEIGHT, ANARI_FLOAT32_VEC4); + Pools pools{}; + for (unsigned side = 0; side < 2; ++side) + pools[side] = visrtx::test::meanLuminance(pixels, + {WIDTH, HEIGHT}, + {WIDTH / 4 + side * WIDTH / 4, + WIDTH / 2 + side * WIDTH / 4, + HEIGHT / 8, + HEIGHT / 2}); + return pools; +} +// Independent oracle: two authored analytic quads, not copies of the geometry +// preprocessing implementation. A missing light must fail the same comparator. +static Pools reference(ANARIDevice d, + const std::array &widths, + const std::array &offsets, + bool omitRight = false) +{ + auto w = worldWithFloor(d); + const visrtx::test::ObjectOwner worldOwner(d, w); + std::vector lights; + for (unsigned i = 0; i < 2; ++i) { + if (widths[i] == 0 || (omitRight && i == 1)) + continue; + auto light = anari::newObject(d, "quad"); + anari::setParameter( + d, light, "position", vec3{offsets[i] - widths[i], 1.5f, -0.5f}); + anari::setParameter(d, light, "edge1", vec3{2 * widths[i], 0, 0}); + anari::setParameter(d, light, "edge2", vec3{0, 0, 1}); + anari::setParameter(d, light, "color", vec3{1, 1, 1}); + anari::setParameter(d, light, "intensity", 8.f); + anari::setParameter(d, light, "side", "both"); + anari::commitParameters(d, light); + lights.push_back(light); + } + if (!lights.empty()) + anari::setParameterArray1D(d, w, "light", lights.data(), lights.size()); + for (auto light : lights) + anari::release(d, light); + anari::commitParameters(d, w); + auto f = frame(d, w); + const visrtx::test::ObjectOwner frameOwner(d, f); + return render(d, f); +} +static bool matches(const Pools &actual, const Pools &expected) +{ + for (unsigned i = 0; i < 2; ++i) { + if (!std::isfinite(actual[i]) || !std::isfinite(expected[i])) + return false; + if (expected[i] > BLACK_TOL) { + if (std::abs(actual[i] - expected[i]) / expected[i] > REL_TOL) + return false; + } else if (std::abs(actual[i]) > BLACK_TOL) + return false; + } + return true; +} +static bool phase(ANARIDevice d, + anari::Frame f, + anari::World world, + const char *name, + const std::array &widths, + const std::array &offsets) +{ + fprintf(stderr, "[case] %s\n", name); + const auto actual = render(d, f); + uint32_t lights = 0; + const uint32_t expectedLights = + uint32_t(widths[0] > 0) + uint32_t(widths[1] > 0); + const bool countMatches = + anari::getProperty(d, world, "numLightInstances", lights) + && lights == expectedLights; + const auto expected = reference(d, widths, offsets); + const bool lit = widths[0] > 0 || widths[1] > 0; + bool ok = countMatches && matches(actual, expected); + if (lit) + for (double value : expected) + ok = ok && std::isfinite(value) && value > BLACK_TOL; + printf("%s actual=[%g,%g] analytic=[%g,%g] lights=%u %s\n", + name, + actual[0], + actual[1], + expected[0], + expected[1], + lights, + ok ? "PASS" : "FAIL"); + return ok; +} +int main() +{ + auto d = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); + auto g = geometry(d, 0.5f); + const std::array surfaces = {surface(d, g), surface(d, g)}; + std::array offsets = {-0.9f, 0.9f}; + const std::array instances = { + instanceOf(d, surfaces[0], offsets[0]), + instanceOf(d, surfaces[1], offsets[1])}; + auto w = worldWithFloor(d); + anari::setParameterArray1D( + d, w, "instance", instances.data(), instances.size()); + anari::commitParameters(d, w); + auto f = frame(d, w); + bool ok = true; + // Share the analytic oracle with lifecycle checks; finish with device-backed + // indexed triangles so the subsequent sequence exercises that path once. + for (bool device : {false, true}) + for (bool soup : {true, false}) { + setTriangles(d, g, 0.5f, device, soup); + const std::string name = std::string(device ? "device/" : "host/") + + (soup ? "triangle-soup" : "indexed-triangle"); + ok = phase(d, f, w, name.c_str(), {0.5f, 0.5f}, offsets) && ok; + } + const auto oracle = reference(d, {0.5f, 0.5f}, offsets); + const auto missing = reference(d, {0.5f, 0.5f}, offsets, true); + const bool validControl = std::isfinite(missing[0]) + && std::isfinite(missing[1]) && missing[0] > BLACK_TOL + && missing[1] > BLACK_TOL; + const bool controls = validControl && !matches(oracle, missing); + printf("missing-instance=[%g,%g] control=%s\n", + missing[0], + missing[1], + controls ? "PASS" : "FAIL"); + ok = controls && ok; + + // Shrink while the five-vertex/four-triangle area data is active. The same + // geometry keeps its buffer capacity, but must publish only two triangles. + // A changed footprint makes stale area weights/counts observable in both + // pools against independently authored analytic lights. + auto positions = anari::newArray1D(d, ANARI_FLOAT32_VEC3, 4); + auto update = [&](float halfWidth) { + const auto v = vertices(halfWidth); + std::copy_n(v.begin(), 4, anari::map(d, positions)); + anari::unmap(d, positions); + }; + update(0.375f); + const std::array, 2> indices = { + {{0, 1, 2}, {0, 2, 3}}}; + anari::setParameter(d, g, "vertex.position", positions); + setTestArray(d, g, "primitive.index", indices, true); + anari::commitParameters(d, g); + ok = phase(d, f, w, "shared active count shrink", {0.375f, 0.375f}, offsets) + && ok; + update(0.f); // no geometry/surface/group/instance recommit + ok = phase(d, f, w, "shared unmap to zero", {0, 0}, offsets) && ok; + update(0.5f); // recovery also requires no higher-object recommit + ok = phase(d, f, w, "shared unmap recovery", {0.5f, 0.5f}, offsets) && ok; + setTestArray(d, g, "vertex.position", vertices(0.25f), true); + anari::commitParameters(d, g); + ok = phase(d, f, w, "shared device replacement", {0.25f, 0.25f}, offsets) + && ok; + auto detached = geometry(d, 0.375f); + anari::setParameter(d, surfaces[1], "geometry", detached); + anari::commitParameters(d, surfaces[1]); + anari::release(d, detached); + ok = phase(d, f, w, "detach right surface", {0.25f, 0.375f}, offsets) && ok; + update(0.125f); + anari::setParameter(d, g, "vertex.position", positions); + anari::commitParameters(d, g); + ok = phase(d, f, w, "update remaining consumer", {0.125f, 0.375f}, offsets) + && ok; + offsets[1] = 1.25f; + translate(d, instances[1], offsets[1]); + ok = + phase(d, f, w, "move detached instance", {0.125f, 0.375f}, offsets) && ok; + anari::release(d, f); + anari::release(d, w); + for (auto i : instances) + anari::release(d, i); + for (auto s : surfaces) + anari::release(d, s); + anari::release(d, g); + anari::release(d, positions); + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 7ff4e446f..661459180 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -137,6 +137,7 @@ set(SOURCES frame/Frame.cu geometry/ComputeTangent.cu + geometry/Preprocessing.cu geometry/Cone.cpp geometry/Curve.cpp geometry/Cylinder.cpp diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 25d0429cb..6eeb69b85 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -455,6 +455,11 @@ VisRTXDevice::~VisRTXDevice() bool VisRTXDevice::initDevice() { + if (deviceState()->arrayPrivatizationFailed) { + reportMessage(ANARI_SEVERITY_ERROR, + "device disabled after array privatization failure; create a new device"); + return false; + } if (m_initStatus == DeviceInitStatus::SUCCESS) return true; else if (m_initStatus == DeviceInitStatus::FAILURE) { diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 74fc57da1..b0120301d 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -30,6 +30,7 @@ */ #include "Array.h" +#include "optix_visrtx.h" // std #include @@ -166,6 +167,12 @@ void Array::unmap() void Array::privatize() { + auto &state = *static_cast(deviceState()); + // Cleanup can release more public references after the original failure. + // Do not retry copies from application memory that may already be freed. + if (state.arrayPrivatizationFailed) + return; + bool changed = false; if (m_data.shared.host.isValid() && !m_data.shared.host.isOwner()) { reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, "making private copy of shared host array (type '%s') | refs: (%i:%i)", @@ -173,6 +180,7 @@ void Array::privatize() this->useCount(helium::RefType::PUBLIC), this->useCount(helium::RefType::INTERNAL)); m_data.shared.host.privatize(); + changed = true; } if (m_data.shared.device.isValid() && !m_data.shared.device.isOwner()) { reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, @@ -180,8 +188,26 @@ void Array::privatize() anari::toString(elementType()), this->useCount(helium::RefType::PUBLIC), this->useCount(helium::RefType::INTERNAL)); - m_data.shared.device.privatize(); + // Existing frames may still read the shared pointer. The application may + // free it as soon as this last PUBLIC release returns. + auto completion = cudaStreamSynchronize(state.stream); + if (completion == cudaSuccess) + completion = m_data.shared.device.privatize(); + if (completion != cudaSuccess) { + // Set before reporting: callbacks must not resume rendering or query + // bounds using cached aliases to the application-owned allocation. + state.arrayPrivatizationFailed = true; + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "array privatization failed; device disabled: %s", + cudaGetErrorString(completion)); + return; + } + changed = true; } + // Geometry may alias authored arrays directly: a new backing allocation is + // an observable pointer change even though the array's values did not change. + if (changed) + notifyChangeObservers(); } void Array::uploadArrayData() const diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index 702aee870..5657da455 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -425,6 +425,8 @@ __global__ void resolveVec3Channel(const vec3 *__restrict__ accum, Frame::Frame(DeviceGlobalState *d) : helium::BaseFrame(d), m_denoiser(d) { + // Preparation can reject the first render before newFrame() initializes it. + data().fb.frameID = 0; data().mdlAnimationTime = 0.f; cudaEventCreate(&m_eventStart); cudaEventCreate(&m_eventEnd); @@ -679,6 +681,12 @@ void Frame::renderFrame() instrument::rangePop(); // rebuild BVHs instrument::rangePop(); // update scene + if (m_world->preparationFailed()) { + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after geometry preprocessing failure"); + return; + } + bool wasDenoising = m_denoise; bool wasDenoisingUsingAlbedo = m_denoiseUsingAlbedo; bool wasDenoisingUsingNormal = m_denoiseUsingNormal; @@ -741,6 +749,23 @@ void Frame::renderFrame() upload(); instrument::rangePop(); // Frame::upload() + // Frame and Registry uploads are legacy default-stream copies. Complete + // that producer before work-stream tracing sees newly published geometry. + const auto publication = cudaStreamSynchronize(nullptr); + if (publication != cudaSuccess) { + // newFrame() already advanced the checkerboard phase and may have cleared + // accumulation buffers. Restart rather than consuming an unrendered tile + // or restoring counters over buffers whose previous contents are gone. + m_nextFrameReset = true; + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after GPU publication failure: %s", + cudaGetErrorString(publication)); + instrument::rangePop(); // render all frames + instrument::rangePop(); // Frame::renderFrame() + instrument::rangePop(); // frame + map + return; + } + instrument::rangePush("optixLaunch()"); OPTIX_CHECK(optixLaunch(m_renderer->pipeline(), state.stream, diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index 678d6c8b6..87e2d7ec0 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -68,8 +68,27 @@ void Cone::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } +PrimitiveInput Cone::primitiveInput() const +{ + PrimitiveInput input; + input.type = GeometryType::CONE; + input.count = m_index ? m_index->size() : m_vertex->size() / 2; + input.vertices = m_vertex->beginAs(AddressSpace::GPU); + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radii = + m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; + input.caps = m_vertexCaps ? m_vertexCaps->beginAs(AddressSpace::GPU) + : nullptr; + input.radius = 0.f; + input.capFlags = m_defaultCapFlags; + return input; +} + void Cone::finalize() { + if (!beginPreparation()) + return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cone geometry"); @@ -86,47 +105,9 @@ void Cone::finalize() "finalizing %s cone geometry", m_index ? "indexed" : "soup"); - std::vector implicitIndices; - Span indices; - - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - std::for_each( - implicitIndices.begin(), implicitIndices.end(), [&](uvec2 &i) { - i = idx; - idx += 2; - }); - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else { - indices = make_Span(m_index->beginAs(), m_index->size()); - } - - const float *radius = m_radius->beginAs(); - - m_aabbs.resize(indices.size()); - - const auto *posBegin = m_vertex->beginAs(); - std::transform( - indices.begin(), indices.end(), m_aabbs.begin(), [&](const uvec2 &c) { - const vec3 &v0 = posBegin[c.x]; - const vec3 &v1 = posBegin[c.y]; - const float r = glm::max(std::abs(radius[c.x]), std::abs(radius[c.y])); - return box3(glm::min(v0, v1) - r, glm::max(v0, v1) + r); - }); - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); - - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - m_epsilonScale = 0.f; - for (auto it = m_aabbs.begin(); it != m_aabbs.end(); ++it) { - const vec3 m = glm::max(glm::abs(it->lower), glm::abs(it->upper)); - m_epsilonScale = - std::max(m_epsilonScale, std::max(m.x, std::max(m.y, m.z))); - } + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs, m_epsilonScale)) + return; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a // surface has ever requested it (order-independent of the surface commit), @@ -136,66 +117,17 @@ void Cone::finalize() buildAreaData(); else { m_totalArea = 0.f; - m_primAreaCdf.clear(); + m_primAreaCdf.reset(); } - upload(); + if (!preparationFailed()) + upload(); } void Cone::buildAreaData() { - std::vector implicitIndices; - Span indices; - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - for (auto &i : implicitIndices) { - i = idx; - idx += 2; - } - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else - indices = make_Span(m_index->beginAs(), m_index->size()); - - const float *radius = m_radius->beginAs(); - const vec3 *pos = m_vertex->beginAs(); - const uint8_t *vcaps = m_vertexCaps ? m_vertexCaps->beginAs() : nullptr; - - const size_t n = indices.size(); - m_primAreaCdf.resize(n); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < n; ++i) { - const uvec2 c = indices[i]; - const double r0 = double(std::abs(radius[c.x])); - const double r1 = double(std::abs(radius[c.y])); - const double len = double(glm::length(pos[c.y] - pos[c.x])); - const bool cap0 = vcaps ? (vcaps[c.x] != 0) : (m_defaultCapFlags & CAP_FIRST); - const bool cap1 = vcaps ? (vcaps[c.y] != 0) : (m_defaultCapFlags & CAP_SECOND); - // A degenerate (zero-length) cone gets no pick mass; the sampler - // early-returns on it, so any mass here would be a wasted sample. - double area = 0.0; - if (len > 0.0) { - const double slant = std::sqrt(len * len + (r0 - r1) * (r0 - r1)); - area = double(kPi) * (r0 + r1) * slant; // lateral (frustum) - if (cap0) - area += double(kPi) * r0 * r0; - if (cap1) - area += double(kPi) * r1 * r1; - } - cumulative += area; - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - if (m_totalArea > 0.f) { - for (size_t i = 0; i < n; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; + m_areaDataValid = + m_preprocessing.areas(this, primitiveInput(), m_primAreaCdf, m_totalArea); } bool Cone::isAreaSamplingSupported() const @@ -209,7 +141,8 @@ void Cone::ensureAreaData() if (m_areaDataValid) return; buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device + if (m_areaDataValid) + upload(); } float Cone::totalArea() const @@ -227,7 +160,8 @@ void Cone::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = m_aabbs.size(); + buildInput.customPrimitiveArray.numPrimitives = + m_index ? m_index->size() : m_vertex->size() / 2; static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -256,8 +190,8 @@ GeometryGPUData Cone::gpuData() const populateAttributeDataSet(m_vertexAttributes, cone.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cone.primAreaCdf = m_primAreaCdf.dataDevice(); - cone.numPrimitives = uint32_t(m_primAreaCdf.size()); + cone.primAreaCdf = m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; + cone.numPrimitives = m_totalArea > 0.f ? uint32_t(primitiveInput().count) : 0; cone.totalArea = m_totalArea; return retval; diff --git a/devices/rtx/device/geometry/Cone.h b/devices/rtx/device/geometry/Cone.h index c04b8fe5f..4a2b9a146 100644 --- a/devices/rtx/device/geometry/Cone.h +++ b/devices/rtx/device/geometry/Cone.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -60,6 +60,7 @@ struct Cone : public Geometry private: GeometryGPUData gpuData() const override; void buildAreaData(); + PrimitiveInput primitiveInput() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -67,13 +68,14 @@ struct Cone : public Geometry helium::ChangeObserverPtr m_vertexCaps; GeometryAttributes m_vertexAttributes; - HostDeviceArray m_aabbs; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; uint8_t m_defaultCapFlags{0}; - // Geometry Light sampling data, built lazily by ensureAreaData(); see Triangle. - HostDeviceArray m_primAreaCdf; + // Geometry Light sampling data, built lazily by ensureAreaData(); see + // Triangle. + DeviceBuffer m_primAreaCdf; float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index bdb865014..d838dcfa5 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -53,6 +53,8 @@ void Curve::commitParameters() void Curve::finalize() { + if (!beginPreparation()) + return; if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on curve geometry"); @@ -64,10 +66,15 @@ void Curve::finalize() m_index ? "indexed" : "soup"); computeIndices(); + if (preparationFailed()) + return; computeRadii(); + if (preparationFailed() || !waitForPreparationInputs(this) + || !finishPreparation(this)) + return; m_vertexBufferPtr = (CUdeviceptr)m_vertexPosition->begin(AddressSpace::GPU); - m_radiusBufferPtr = (CUdeviceptr)m_generatedRadii.dataDevice(); + m_radiusBufferPtr = (CUdeviceptr)m_radii; upload(); } @@ -88,8 +95,8 @@ void Curve::populateBuildInput(OptixBuildInput &buildInput) const curveArray.widthBuffers = &m_radiusBufferPtr; curveArray.indexStrideInBytes = sizeof(uint32_t); - curveArray.numPrimitives = m_generatedIndices.size(); - curveArray.indexBuffer = (CUdeviceptr)m_generatedIndices.dataDevice(); + curveArray.numPrimitives = m_numPrimitives; + curveArray.indexBuffer = (CUdeviceptr)m_indices; curveArray.normalBuffers = 0; curveArray.normalStrideInBytes = 0; @@ -107,30 +114,22 @@ bool Curve::isValid() const void Curve::computeIndices() { - if (m_index) { - m_generatedIndices.resize(m_index->size()); - std::copy(m_index->beginAs(), - m_index->endAs(), - m_generatedIndices.begin()); - } else { - m_generatedIndices.resize(m_vertexPosition->size() / 2); - std::iota(m_generatedIndices.begin(), m_generatedIndices.end(), 0); - } - m_generatedIndices.upload(); + m_numPrimitives = m_index ? m_index->size() : m_vertexPosition->size() / 2; + if (m_index) + m_indices = m_index->beginAs(AddressSpace::GPU); + else if (generateCurveIndices(this, m_numPrimitives, m_generatedIndices)) + m_indices = m_generatedIndices.ptrAs(); } void Curve::computeRadii() { - if (m_vertexRadius) { - m_generatedRadii.resize(m_vertexRadius->totalCapacity()); - std::copy(m_vertexRadius->dataAs(), - m_vertexRadius->dataAs() + m_vertexRadius->totalCapacity(), - m_generatedRadii.begin()); - } else { - m_generatedRadii.resize(m_vertexPosition->size()); - std::fill(m_generatedRadii.begin(), m_generatedRadii.end(), m_globalRadius); - } - m_generatedRadii.upload(); + if (m_vertexRadius) + m_radii = m_vertexRadius->beginAs(AddressSpace::GPU); + else if (generateCurveRadii(this, + m_vertexPosition->size(), + m_globalRadius, + m_generatedRadii)) + m_radii = m_generatedRadii.ptrAs(); } GeometryGPUData Curve::gpuData() const @@ -140,8 +139,8 @@ GeometryGPUData Curve::gpuData() const auto &curve = retval.curve; curve.vertices = m_vertexPosition->beginAs(AddressSpace::GPU); - curve.indices = m_generatedIndices.dataDevice(); - curve.radii = m_generatedRadii.dataDevice(); + curve.indices = m_indices; + curve.radii = m_radii; populateAttributeDataSet(m_vertexAttributes, curve.vertexAttr); return retval; diff --git a/devices/rtx/device/geometry/Curve.h b/devices/rtx/device/geometry/Curve.h index 5683cf308..749915aba 100644 --- a/devices/rtx/device/geometry/Curve.h +++ b/devices/rtx/device/geometry/Curve.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -62,8 +62,11 @@ struct Curve : public Geometry float m_globalRadius; - HostDeviceArray m_generatedIndices; - HostDeviceArray m_generatedRadii; + DeviceBuffer m_generatedIndices; + DeviceBuffer m_generatedRadii; + const uint32_t *m_indices{nullptr}; + const float *m_radii{nullptr}; + size_t m_numPrimitives{0}; CUdeviceptr m_vertexBufferPtr{}; CUdeviceptr m_radiusBufferPtr{}; diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index a703f1654..014870b2e 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -69,8 +69,27 @@ void Cylinder::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } +PrimitiveInput Cylinder::primitiveInput() const +{ + PrimitiveInput input; + input.type = GeometryType::CYLINDER; + input.count = m_index ? m_index->size() : m_vertex->size() / 2; + input.vertices = m_vertex->beginAs(AddressSpace::GPU); + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radii = + m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; + input.caps = m_vertexCaps ? m_vertexCaps->beginAs(AddressSpace::GPU) + : nullptr; + input.radius = m_globalRadius; + input.capFlags = m_defaultCapFlags; + return input; +} + void Cylinder::finalize() { + if (!beginPreparation()) + return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cylinders geometry"); @@ -81,51 +100,9 @@ void Cylinder::finalize() "finalizing %s cylinder geometry", m_index ? "indexed" : "soup"); - std::vector implicitIndices; - Span indices; - - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - std::for_each( - implicitIndices.begin(), implicitIndices.end(), [&](uvec2 &i) { - i = idx; - idx += 2; - }); - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else { - indices = make_Span(m_index->beginAs(), m_index->size()); - } - - const float *radius = nullptr; - if (m_radius) - radius = m_radius->beginAs(); - - m_aabbs.resize(indices.size()); - - const auto *posBegin = m_vertex->beginAs(); - size_t cylinderID = 0; - std::transform( - indices.begin(), indices.end(), m_aabbs.begin(), [&](const uvec2 &c) { - const float r = - std::abs(radius ? radius[cylinderID++] : m_globalRadius); - const vec3 &v0 = posBegin[c.x]; - const vec3 &v1 = posBegin[c.y]; - return box3(glm::min(v0, v1) - r, glm::max(v0, v1) + r); - }); - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); - - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - m_epsilonScale = 0.f; - for (auto it = m_aabbs.begin(); it != m_aabbs.end(); ++it) { - const vec3 m = glm::max(glm::abs(it->lower), glm::abs(it->upper)); - m_epsilonScale = - std::max(m_epsilonScale, std::max(m.x, std::max(m.y, m.z))); - } + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs, m_epsilonScale)) + return; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a // surface has ever requested it (order-independent of the surface commit), @@ -135,65 +112,17 @@ void Cylinder::finalize() buildAreaData(); else { m_totalArea = 0.f; - m_primAreaCdf.clear(); + m_primAreaCdf.reset(); } - upload(); + if (!preparationFailed()) + upload(); } void Cylinder::buildAreaData() { - std::vector implicitIndices; - Span indices; - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - for (auto &i : implicitIndices) { - i = idx; - idx += 2; - } - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else - indices = make_Span(m_index->beginAs(), m_index->size()); - - const float *radius = m_radius ? m_radius->beginAs() : nullptr; - const vec3 *pos = m_vertex->beginAs(); - const uint8_t *vcaps = m_vertexCaps ? m_vertexCaps->beginAs() : nullptr; - - const size_t n = indices.size(); - m_primAreaCdf.resize(n); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < n; ++i) { - const uvec2 c = indices[i]; - const float r = std::abs(radius ? radius[i] : m_globalRadius); - const double len = double(glm::length(pos[c.y] - pos[c.x])); - const bool cap0 = vcaps ? (vcaps[c.x] != 0) : (m_defaultCapFlags & CAP_FIRST); - const bool cap1 = vcaps ? (vcaps[c.y] != 0) : (m_defaultCapFlags & CAP_SECOND); - // A degenerate (zero-length or zero-radius) cylinder gets no pick mass; the - // sampler early-returns on it, so any mass here would be a wasted sample. - double area = 0.0; - if (len > 0.0 && r > 0.0f) { - area = 2.0 * double(kPi) * double(r) * len; // lateral - const double capArea = double(kPi) * double(r) * double(r); - if (cap0) - area += capArea; - if (cap1) - area += capArea; - } - cumulative += area; - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - if (m_totalArea > 0.f) { - for (size_t i = 0; i < n; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; + m_areaDataValid = + m_preprocessing.areas(this, primitiveInput(), m_primAreaCdf, m_totalArea); } bool Cylinder::isAreaSamplingSupported() const @@ -207,7 +136,8 @@ void Cylinder::ensureAreaData() if (m_areaDataValid) return; buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device + if (m_areaDataValid) + upload(); } float Cylinder::totalArea() const @@ -225,7 +155,8 @@ void Cylinder::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = m_aabbs.size(); + buildInput.customPrimitiveArray.numPrimitives = + m_index ? m_index->size() : m_vertex->size() / 2; static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -252,8 +183,10 @@ GeometryGPUData Cylinder::gpuData() const populateAttributeDataSet(m_vertexAttributes, cylinder.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cylinder.primAreaCdf = m_primAreaCdf.dataDevice(); - cylinder.numPrimitives = uint32_t(m_primAreaCdf.size()); + cylinder.primAreaCdf = + m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; + cylinder.numPrimitives = + m_totalArea > 0.f ? uint32_t(primitiveInput().count) : 0; cylinder.totalArea = m_totalArea; return retval; diff --git a/devices/rtx/device/geometry/Cylinder.h b/devices/rtx/device/geometry/Cylinder.h index 2b66e29e1..eb1aa190d 100644 --- a/devices/rtx/device/geometry/Cylinder.h +++ b/devices/rtx/device/geometry/Cylinder.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -60,6 +60,7 @@ struct Cylinder : public Geometry private: GeometryGPUData gpuData() const override; void buildAreaData(); + PrimitiveInput primitiveInput() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -67,15 +68,16 @@ struct Cylinder : public Geometry helium::ChangeObserverPtr m_vertexCaps; GeometryAttributes m_vertexAttributes; - HostDeviceArray m_aabbs; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; float m_globalRadius{1.f}; uint8_t m_defaultCapFlags{0}; - // Geometry Light sampling data, built lazily by ensureAreaData(); see Triangle. - HostDeviceArray m_primAreaCdf; + // Geometry Light sampling data, built lazily by ensureAreaData(); see + // Triangle. + DeviceBuffer m_primAreaCdf; float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index a00502c1f..b9e3f7ccb 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -113,6 +113,12 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { + // Array observers can re-finalize without a parameter commit, but parameter + // replacement can release the last reference to an aliased device array. + // Complete earlier consumers before subclasses replace those references. + m_inputRetirementFailed = !checkPreparation(this, + cudaStreamSynchronize(deviceState()->stream), + "retiring previous geometry inputs"); commitAttributes("primitive.", m_primitiveAttributes); auto getUniformAttribute = @@ -143,6 +149,24 @@ bool Geometry::isAreaSamplingSupported() const return false; } +bool Geometry::beginPreparation() +{ + if (m_inputRetirementFailed) + return false; + m_preparationFailed = false; + return true; +} + +bool Geometry::preparationFailed() const +{ + return m_preparationFailed; +} + +void Geometry::setPreparationFailed(bool failed) +{ + m_preparationFailed = failed; +} + void Geometry::ensureAreaData() {} float Geometry::totalArea() const diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index c0a0f7a47..71d002ebb 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -31,6 +31,7 @@ #pragma once +#include "Preprocessing.h" #include "RegisteredObject.h" #include "array/Array1D.h" #include "gpu/gpu_objects.h" @@ -77,13 +78,18 @@ struct Geometry : public RegisteredObject virtual int optixGeometryType() const = 0; // Geometry Light area sampling. Only types that can be sampled by area as an - // Emissive Surface override these (Stage 1: Triangle). ensureAreaData() builds - // the per-primitive area CDF; totalArea() is the object-space emitting area. + // Emissive Surface override these (Stage 1: Triangle). ensureAreaData() + // builds the per-primitive area CDF; totalArea() is the object-space emitting + // area. virtual bool isAreaSamplingSupported() const; virtual void ensureAreaData(); virtual float totalArea() const; + bool preparationFailed() const; + void setPreparationFailed(bool failed); + protected: + bool beginPreparation(); GeometryGPUData gpuData() const override = 0; void commitAttributes(const char *prefix, GeometryAttributes &attrs); @@ -96,6 +102,11 @@ struct Geometry : public RegisteredObject // Set by analytic-primitive subtypes in finalize(); see // GeometryGPUData::epsilonScale. float m_epsilonScale{0.f}; + Preprocessing m_preprocessing; + + private: + bool m_preparationFailed{false}; + bool m_inputRetirementFailed{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Isosurface.cpp b/devices/rtx/device/geometry/Isosurface.cpp index 725703155..eadf2ff3c 100644 --- a/devices/rtx/device/geometry/Isosurface.cpp +++ b/devices/rtx/device/geometry/Isosurface.cpp @@ -56,6 +56,8 @@ void Isosurface::commitParameters() void Isosurface::finalize() { + if (!beginPreparation()) + return; m_numBricks = 0; m_isovaluesDev = nullptr; m_numIsovalues = 0; diff --git a/devices/rtx/device/geometry/Neural.cpp b/devices/rtx/device/geometry/Neural.cpp index 114a0a0fd..b41c01a89 100644 --- a/devices/rtx/device/geometry/Neural.cpp +++ b/devices/rtx/device/geometry/Neural.cpp @@ -29,6 +29,8 @@ void Neural::commitParameters() void Neural::finalize() { + if (!beginPreparation()) + return; Geometry::finalize(); m_aabbs.resize(1); m_aabbs.dataHost()[0] = m_aabb; diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu new file mode 100644 index 000000000..e3eb900fe --- /dev/null +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "Geometry.h" +#include "Preprocessing.h" +#include "gpu/intersectPrimitives.h" + +#include +#include +#include + +namespace visrtx { +namespace { +struct Result +{ + float value; + uint32_t invalid; +}; + +VISRTX_GLOBAL void primitiveAreas( + PrimitiveInput in, double *areas, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + double area; + if (in.type == GeometryType::SPHERE) { + const auto *indices = static_cast(in.indices); + const uint32_t v = indices ? indices[i] : uint32_t(i); + const float r = glm::abs(in.radii ? in.radii[v] : in.radius); + area = 4.0 * double(kPi) * double(r) * double(r); + } else if (in.type == GeometryType::CONE + || in.type == GeometryType::CYLINDER) { + const auto *indices = static_cast(in.indices); + const uvec2 c = indices ? indices[i] : uvec2(2 * i, 2 * i + 1); + const bool cone = in.type == GeometryType::CONE; + const double r0 = + double(glm::abs(in.radii ? in.radii[cone ? c.x : i] : in.radius)); + const double r1 = cone ? double(glm::abs(in.radii[c.y])) : r0; + const double len = double(glm::length(in.vertices[c.y] - in.vertices[c.x])); + const bool cap0 = in.caps ? in.caps[c.x] != 0 : in.capFlags & CAP_FIRST; + const bool cap1 = in.caps ? in.caps[c.y] != 0 : in.capFlags & CAP_SECOND; + area = 0.0; + if (len > 0.0 && (cone || r0 > 0.0)) { + area = cone + ? double(kPi) * (r0 + r1) * sqrt(len * len + (r0 - r1) * (r0 - r1)) + : 2.0 * double(kPi) * r0 * len; + if (cap0) + area += double(kPi) * r0 * r0; + if (cap1) + area += double(kPi) * r1 * r1; + } + } else { + const auto *indices = static_cast(in.indices); + const uvec3 t = indices ? indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); + area = 0.5 + * glm::length(glm::cross(in.vertices[t.y] - in.vertices[t.x], + in.vertices[t.z] - in.vertices[t.x])); + } + if (!isfinite(area) || area < 0.0) + atomicOr(&result->invalid, 1u); + areas[i] = area; +} + +VISRTX_GLOBAL void normalizeAreas( + const double *prefix, size_t n, float *cdf, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= n) + return; + const double total = prefix[n - 1]; + const float area = float(total); + if (!isfinite(prefix[i]) || prefix[i] < 0.0 || !isfinite(area) + || (total > 0.0 && area == 0.f)) + atomicOr(&result->invalid, 1u); + cdf[i] = total > 0.0 ? (i + 1 == n ? 1.f : float(prefix[i] / total)) : 0.f; + if (i == 0) + result->value = area; +} +// Encode numeric failure in the scalar readback; cone/cylinder bounds have +// already returned their status word for this generation. +VISRTX_GLOBAL void publishArea(Result *result) +{ + if (result->invalid) + result->value = __int_as_float(0x7fffffff); +} + +VISRTX_DEVICE box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) +{ + const float disp = g.userParams.x; // displacement amplitude padding + const float r0 = glm::max(0.f, g.r0); + const float r1 = glm::max(0.f, g.r1); + + switch (static_cast(g.type)) { + case SDFType::SPHERE: + case SDFType::CUT_SPHERE: + return box3(g.p0 - (r0 + disp), g.p0 + (r0 + disp)); + + case SDFType::TORUS: + return box3(g.p0 - (r0 + r1 + disp), g.p0 + (r0 + r1 + disp)); + + case SDFType::ELLIPSOID: + // p1 stores radii vector for the ellipsoid + return box3(g.p0 - (g.p1 + disp), g.p0 + (g.p1 + disp)); + + case SDFType::PILL: + case SDFType::CONE_PILL: + case SDFType::CONE_PILL_SIGMOID: + case SDFType::CONE: + case SDFType::VESICA: + default: { + const float maxR = glm::max(r0, r1) + disp; + return box3(glm::min(g.p0, g.p1) - maxR, glm::max(g.p0, g.p1) + maxR); + } + } +} + +VISRTX_GLOBAL void primitiveBounds( + PrimitiveInput in, box3 *bounds, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + if (in.type == GeometryType::SDF) { + const SDFPrimitive &g = in.sdf[i]; + box3 b = computeSDFPrimitiveAABB(g); + float padding = in.noiseFactor * glm::max(0.f, g.r0) * 0.1f; + if (g.numNeighbours > 0) { + const float r0 = glm::max(0.f, g.r0); + const float r1 = glm::max(0.f, g.r1 >= 0.f ? g.r1 : g.r0); + padding += + glm::mix(glm::min(r0, r1), glm::max(r0, r1), in.blendLerpFactor) + * in.blendFactor; + } + b.lower -= padding; + b.upper += padding; + bounds[i] = b; + for (int axis = 0; axis < 3; ++axis) { + if (!isfinite(b.lower[axis]) || !isfinite(b.upper[axis])) + atomicOr(&result->invalid, 1u); + } + return; + } + const bool sphere = in.type == GeometryType::SPHERE; + const auto *indices = static_cast(in.indices); + const auto *sphereIndices = static_cast(in.indices); + const size_t center = sphere ? (sphereIndices ? sphereIndices[i] : i) : 0; + const uvec2 c = sphere ? uvec2(center) + : indices ? indices[i] + : uvec2(2 * i, 2 * i + 1); + const bool cone = in.type == GeometryType::CONE; + const float r = cone + ? glm::max(glm::abs(in.radii[c.x]), glm::abs(in.radii[c.y])) + : glm::abs(in.radii ? in.radii[sphere ? center : i] : in.radius); + const vec3 v0 = in.vertices[c.x], v1 = in.vertices[c.y]; + const box3 b(glm::min(v0, v1) - r, glm::max(v0, v1) + r); + bounds[i] = b; + const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); + const float scale = glm::max(m.x, glm::max(m.y, m.z)); + if (!isfinite(r) || !isfinite(v0.x) || !isfinite(v0.y) || !isfinite(v0.z) + || !isfinite(v1.x) || !isfinite(v1.y) || !isfinite(v1.z) + || !isfinite(scale)) + atomicOr(&result->invalid, 1u); + else + atomicMax( + reinterpret_cast(&result->value), __float_as_uint(scale)); +} +VISRTX_GLOBAL void quadIndices(const uvec4 *indices, size_t n, uvec3 *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= n) + return; + const uvec4 q = indices ? indices[i] : uvec4(4 * i) + uvec4(0, 1, 2, 3); + out[2 * i] = uvec3(q.x, q.y, q.w); + out[2 * i + 1] = uvec3(q.z, q.w, q.y); +} + +VISRTX_GLOBAL void curveIndices(size_t n, uint32_t *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) + out[i] = uint32_t(i); +} + +VISRTX_GLOBAL void curveRadii(size_t n, float radius, float *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) + out[i] = radius; +} +} // namespace + +bool generateQuadIndices( + Geometry *g, const uvec4 *indices, size_t n, DeviceBuffer &out) +{ + if (!waitForPreparationInputs(g)) + return false; + if (!reservePreparation(g, out, 2 * n * sizeof(uvec3))) + return false; + if (n) + quadIndices<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( + indices, n, out.ptrAs()); + return finishPreparation(g); +} + +bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) +{ + if (!waitForPreparationInputs(g)) + return false; + if (!reservePreparation(g, out, n * sizeof(uint32_t))) + return false; + if (n) + curveIndices<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( + n, out.ptrAs()); + return checkPreparation(g, cudaGetLastError(), "curve indices"); +} + +bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) +{ + if (!waitForPreparationInputs(g)) + return false; + if (!reservePreparation(g, out, n * sizeof(float))) + return false; + if (n) + curveRadii<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( + n, radius, out.ptrAs()); + return checkPreparation(g, cudaGetLastError(), "curve radii"); +} + +bool checkPreparation(Geometry *g, cudaError_t error, const char *operation) +{ + if (error == cudaSuccess) + return true; + g->setPreparationFailed(true); + // A failed dispatch/readback can follow successful queued kernels. Drain + // their stream before callers can retry, resize, or retire owned storage. + cudaStreamSynchronize(g->deviceState()->stream); + g->reportMessage(ANARI_SEVERITY_ERROR, + "geometry preprocessing failed during %s: %s", + operation, + cudaGetErrorString(error)); + return false; +} + +bool reservePreparation(Geometry *g, DeviceBuffer &buffer, size_t bytes) +{ + // Failed allocations can retain their requested capacity without storage. + // Clear it so a later preparation can retry the same-sized allocation. + if (!buffer) + buffer.reset(); + buffer.reserve(bytes); + // Consume the runtime error even when missing storage identifies allocation + // failure. Otherwise the next successful allocation inherits this error. + const auto error = cudaGetLastError(); + return checkPreparation(g, + error != cudaSuccess ? error + : bytes && (!buffer || buffer.bytes() < bytes) + ? cudaErrorMemoryAllocation + : cudaSuccess, + "allocating device storage"); +} + +bool waitForPreparationInputs(Geometry *g) +{ + // Legacy Array uploads use synchronous cudaMemcpy on the default stream. + // Pageable H2D may return after staging, not DMA completion: make that + // producer dependency explicit before launching on the device work stream. + return checkPreparation( + g, cudaStreamSynchronize(nullptr), "input upload completion"); +} + +bool finishPreparation(Geometry *g) +{ + // Also establishes an explicit boundary for legacy default-stream consumers. + return checkPreparation(g, cudaGetLastError(), "launch") + && checkPreparation(g, + cudaStreamSynchronize(g->deviceState()->stream), + "execution completion"); +} + +bool Preprocessing::bounds( + Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs, float &scale) +{ + if (!waitForPreparationInputs(g)) + return false; + const auto stream = g->deviceState()->stream; + scale = 0.f; + if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) + || !reservePreparation(g, m_result, sizeof(Result)) + || !checkPreparation(g, + cudaMemsetAsync(m_result.ptr(), 0, sizeof(Result), stream), + "clearing bounds status")) + return false; + if (in.count) + primitiveBounds<<<(in.count + 255) / 256, 256, 0, stream>>>( + in, aabbs.ptrAs(), m_result.ptrAs()); + Result host{}; + const bool sdf = in.type == GeometryType::SDF; + if (!checkPreparation(g, cudaGetLastError(), "bounds evaluation") + || !checkPreparation(g, + cudaMemcpyAsync(sdf ? static_cast(&host.invalid) : &host, + sdf ? static_cast(&m_result.ptrAs()->invalid) + : m_result.ptr(), + sdf ? sizeof(host.invalid) : sizeof(host), + cudaMemcpyDeviceToHost, + stream), + "bounds summary") + || !finishPreparation(g)) + return false; + if (host.invalid) + return checkPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); + scale = host.value; + return true; +} + +bool Preprocessing::areas( + Geometry *g, const PrimitiveInput &in, DeviceBuffer &cdf, float &total) +{ + if (!waitForPreparationInputs(g)) + return false; + total = 0.f; + if (in.count == 0) { + cdf.reset(); + return true; + } + if (in.count > size_t(std::numeric_limits::max())) + return checkPreparation(g, cudaErrorInvalidValue, "primitive count"); + const auto stream = g->deviceState()->stream; + size_t scratchBytes = 0; + if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) + || !reservePreparation(g, cdf, in.count * sizeof(float)) + || !reservePreparation(g, m_result, sizeof(Result)) + || !checkPreparation(g, + cudaMemsetAsync(m_result.ptr(), 0, sizeof(Result), stream), + "clearing area status")) + return false; + auto *prefix = m_prefix.ptrAs(); + auto *result = m_result.ptrAs(); + primitiveAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( + in, prefix, result); + if (!checkPreparation(g, cudaGetLastError(), "area evaluation") + || !checkPreparation(g, + cub::DeviceScan::InclusiveSum( + nullptr, scratchBytes, prefix, prefix, int(in.count), stream), + "scan workspace query") + || !reservePreparation(g, m_scratch, scratchBytes) + || !checkPreparation(g, + cub::DeviceScan::InclusiveSum(m_scratch.ptr(), + scratchBytes, + prefix, + prefix, + int(in.count), + stream), + "area scan")) + return false; + normalizeAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( + prefix, in.count, cdf.ptrAs(), result); + if (!checkPreparation(g, cudaGetLastError(), "CDF normalization")) + return false; + publishArea<<<1, 1, 0, stream>>>(result); + Result host{}; + if (!checkPreparation(g, cudaGetLastError(), "area publication") + || !checkPreparation(g, + cudaMemcpyAsync(&host.value, + &result->value, + sizeof(host.value), + cudaMemcpyDeviceToHost, + stream), + "area readback") + || !finishPreparation(g)) + return false; + if (!std::isfinite(host.value)) + return checkPreparation( + g, cudaErrorInvalidValue, "non-publishable primitive area"); + total = host.value; + if (total == 0.f) + cdf.reset(); + return true; +} +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h new file mode 100644 index 000000000..8c6f5f7dc --- /dev/null +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "gpu/gpu_objects.h" +#include "utility/DeviceBuffer.h" + +namespace visrtx { +struct Geometry; + +// GPU views use logical array beginnings, never application allocation bases. +struct PrimitiveInput +{ + GeometryType type{GeometryType::TRIANGLE}; + size_t count{0}; + const vec3 *vertices{nullptr}; + const void *indices{nullptr}; + const float *radii{nullptr}; + const uint8_t *caps{nullptr}; + float radius{0.f}; + uint8_t capFlags{0}; + const SDFPrimitive *sdf{nullptr}; + float blendFactor{1.f}; + float blendLerpFactor{0.5f}; + float noiseFactor{0.f}; +}; + +// Per-geometry reusable workspace. Only the compact result crosses to the host. +struct Preprocessing +{ + Preprocessing() = default; + Preprocessing(const Preprocessing &) = delete; + Preprocessing &operator=(const Preprocessing &) = delete; + Preprocessing(Preprocessing &&) = delete; + Preprocessing &operator=(Preprocessing &&) = delete; + + bool areas(Geometry *geometry, + const PrimitiveInput &input, + DeviceBuffer &cdf, + float &total); + bool bounds(Geometry *geometry, + const PrimitiveInput &input, + DeviceBuffer &aabbs, + float &scale); + + private: + DeviceBuffer m_prefix; + DeviceBuffer m_scratch; + DeviceBuffer m_result; +}; + +bool checkPreparation( + Geometry *geometry, cudaError_t error, const char *operation); +bool reservePreparation(Geometry *geometry, DeviceBuffer &buffer, size_t bytes); +bool waitForPreparationInputs(Geometry *geometry); +bool finishPreparation(Geometry *geometry); +bool generateQuadIndices(Geometry *geometry, + const uvec4 *indices, + size_t count, + DeviceBuffer &output); +bool generateCurveIndices( + Geometry *geometry, size_t count, DeviceBuffer &output); +bool generateCurveRadii( + Geometry *geometry, size_t count, float radius, DeviceBuffer &output); + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 515227e95..5dcc6bfbd 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -51,6 +51,8 @@ void Quad::commitParameters() void Quad::finalize() { + if (!beginPreparation()) + return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on quad geometry"); @@ -69,6 +71,8 @@ void Quad::finalize() m_index ? "indexed" : "soup"); generateIndices(); + if (preparationFailed()) + return; if (m_vertexTangent && m_vertex->size() != m_vertexTangent->size()) { reportMessage(ANARI_SEVERITY_WARNING, @@ -102,8 +106,8 @@ void Quad::populateBuildInput(OptixBuildInput &buildInput) const buildInput.triangleArray.indexFormat = OPTIX_INDICES_FORMAT_UNSIGNED_INT3; buildInput.triangleArray.indexStrideInBytes = sizeof(uvec3); - buildInput.triangleArray.numIndexTriplets = m_indices.size(); - buildInput.triangleArray.indexBuffer = (CUdeviceptr)m_indices.dataDevice(); + buildInput.triangleArray.numIndexTriplets = m_numTriangles; + buildInput.triangleArray.indexBuffer = (CUdeviceptr)m_indices.ptrAs(); static uint32_t buildInputFlags[1] = {0}; @@ -123,7 +127,7 @@ GeometryGPUData Quad::gpuData() const auto &quad = retval.quad; quad.vertices = m_vertex->beginAs(AddressSpace::GPU); - quad.indices = m_indices.dataDevice(); + quad.indices = m_indices.ptrAs(); quad.vertexNormals = m_vertexNormal ? m_vertexNormal->beginAs(AddressSpace::GPU) : nullptr; @@ -137,27 +141,12 @@ GeometryGPUData Quad::gpuData() const void Quad::generateIndices() { - if (m_index) { - size_t numIndices = 2 * m_index->size(); - m_indices.resize(numIndices); - auto *indicesIn = (const uvec4 *)m_index->dataAs(AddressSpace::HOST); - auto *indicesOut = m_indices.dataHost(); - for (size_t i = 0; i < m_index->size(); i++) { - auto idx = indicesIn[i]; - indicesOut[2 * i + 0] = uvec3(idx.x, idx.y, idx.w); - indicesOut[2 * i + 1] = uvec3(idx.z, idx.w, idx.y); - } - } else { - size_t numQuad = m_vertex->size() / 4; - m_indices.resize(2 * numQuad); - auto *indicesOut = m_indices.dataHost(); - for (size_t i = 0; i < numQuad; i++) { - indicesOut[2 * i + 0] = uvec3(4 * i) + uvec3(0, 1, 3); - indicesOut[2 * i + 1] = uvec3(4 * i) + uvec3(2, 3, 1); - } - } - - m_indices.upload(); + const size_t n = m_index ? m_index->size() : m_vertex->size() / 4; + m_numTriangles = 2 * n; + generateQuadIndices(this, + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr, + n, + m_indices); } void Quad::generateTangents() @@ -169,8 +158,8 @@ void Quad::generateTangents() // is always per vertex. TangentGenerationInput input; input.positions = m_vertex.get(); - input.indices = m_indices.dataDevice(); - input.numTriangles = m_indices.size(); + input.indices = m_indices.ptrAs(); + input.numTriangles = m_numTriangles; input.normals = m_vertexNormal.ptr; input.uvs = uvs; diff --git a/devices/rtx/device/geometry/Quad.h b/devices/rtx/device/geometry/Quad.h index 85dc950ec..c2d09b349 100644 --- a/devices/rtx/device/geometry/Quad.h +++ b/devices/rtx/device/geometry/Quad.h @@ -55,7 +55,8 @@ struct Quad : public Geometry void generateIndices(); void generateTangents(); - HostDeviceArray m_indices; + DeviceBuffer m_indices; + size_t m_numTriangles{0}; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_vertex; diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index a7bdd2493..75960d618 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -42,37 +42,6 @@ static_assert(offsetof(visrtx::SDFPrimitive, neighboursIndex) == 56, namespace visrtx { -// Compute a conservative AABB for an SDF primitive on the host (CPU). -static box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) -{ - const float disp = g.userParams.x; // displacement amplitude padding - const float r0 = glm::max(0.f, g.r0); - const float r1 = glm::max(0.f, g.r1); - - switch (static_cast(g.type)) { - case SDFType::SPHERE: - case SDFType::CUT_SPHERE: - return box3(g.p0 - (r0 + disp), g.p0 + (r0 + disp)); - - case SDFType::TORUS: - return box3(g.p0 - (r0 + r1 + disp), g.p0 + (r0 + r1 + disp)); - - case SDFType::ELLIPSOID: - // p1 stores radii vector for the ellipsoid - return box3(g.p0 - (g.p1 + disp), g.p0 + (g.p1 + disp)); - - case SDFType::PILL: - case SDFType::CONE_PILL: - case SDFType::CONE_PILL_SIGMOID: - case SDFType::CONE: - case SDFType::VESICA: - default: { - const float maxR = glm::max(r0, r1) + disp; - return box3(glm::min(g.p0, g.p1) - maxR, glm::max(g.p0, g.p1) + maxR); - } - } -} - SDF::SDF(DeviceGlobalState *d) : Geometry(d), m_sdf(this), m_neighbour(this) {} SDF::~SDF() = default; @@ -94,6 +63,8 @@ void SDF::commitParameters() void SDF::finalize() { + if (!beginPreparation()) + return; if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'primitive.sdf' on sdf geometry"); @@ -108,41 +79,34 @@ void SDF::finalize() "finalizing sdf geometry with %zu primitives", m_numPrimitives); - const auto *geometries = - reinterpret_cast(m_sdf->data()); - - m_aabbs.resize(m_numPrimitives); - auto *aabbsHost = m_aabbs.dataHost(); - for (size_t i = 0; i < m_numPrimitives; i++) { - aabbsHost[i] = computeSDFPrimitiveAABB(geometries[i]); - - // Expand AABB by the smooth-min blend radius so OptiX fires the - // intersection test for rays passing through the blending zone at - // junctions between adjacent primitives. Without this, blend zones that - // lie outside the tight per-primitive AABB produce holes in the geometry. - if (geometries[i].numNeighbours > 0) { - const float r0 = glm::max(0.f, geometries[i].r0); - const float r1 = glm::max( - 0.f, geometries[i].r1 >= 0.f ? geometries[i].r1 : geometries[i].r0); - const float k = - glm::mix(glm::min(r0, r1), glm::max(r0, r1), m_blendLerpFactor) - * m_blendFactor; - aabbsHost[i].lower -= k; - aabbsHost[i].upper += k; - } - - // Expand AABB for noise displacement. The noise can pull the surface - // outward by up to amplitude = noiseFactor * r0 * 0.1. - if (m_noiseFactor > 0.f) { - const float noiseAmplitude = - m_noiseFactor * glm::max(0.f, geometries[i].r0) * 0.1f; - aabbsHost[i].lower -= noiseAmplitude; - aabbsHost[i].upper += noiseAmplitude; - } - } - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); + PrimitiveInput input; + input.type = GeometryType::SDF; + input.count = m_numPrimitives; + const void *source = m_sdf->begin(AddressSpace::GPU); + if (!waitForPreparationInputs(this)) + return; + if (reinterpret_cast(source) % alignof(SDFPrimitive) != 0) { + const size_t bytes = m_numPrimitives * sizeof(SDFPrimitive); + if (!reservePreparation(this, m_alignedPrimitives, bytes) + || !checkPreparation(this, + cudaMemcpyAsync(m_alignedPrimitives.ptr(), + source, + bytes, + cudaMemcpyDeviceToDevice, + deviceState()->stream), + "aligning SDF input")) + return; + m_primitives = m_alignedPrimitives.ptrAs(); + } else + m_primitives = static_cast(source); + input.sdf = m_primitives; + input.blendFactor = m_blendFactor; + input.blendLerpFactor = m_blendLerpFactor; + input.noiseFactor = m_noiseFactor; + float unusedScale = 0.f; + if (!m_preprocessing.bounds(this, input, m_aabbs, unusedScale)) + return; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); upload(); } @@ -175,8 +139,7 @@ GeometryGPUData SDF::gpuData() const retval.type = GeometryType::SDF; auto &sdf = retval.sdf; - sdf.geometries = - reinterpret_cast(m_sdf->data(AddressSpace::GPU)); + sdf.geometries = m_primitives; sdf.neighbours = m_neighbour ? m_neighbour->beginAs(AddressSpace::GPU) : nullptr; sdf.numGeometries = static_cast(m_numPrimitives); diff --git a/devices/rtx/device/geometry/SDF.h b/devices/rtx/device/geometry/SDF.h index d5ee1bc10..a81286e92 100644 --- a/devices/rtx/device/geometry/SDF.h +++ b/devices/rtx/device/geometry/SDF.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -78,7 +78,9 @@ struct SDF : public Geometry float m_distanceFromCamera{100.f}; float m_noiseFactor{0.f}; - HostDeviceArray m_aabbs; + DeviceBuffer m_alignedPrimitives; + const SDFPrimitive *m_primitives{nullptr}; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; size_t m_numPrimitives{0}; }; diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index 66f5db3a3..f87aab5f1 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -30,12 +30,6 @@ */ #include "Sphere.h" -// thrust -#include -#include -#include -#include -#include namespace visrtx { @@ -57,6 +51,8 @@ void Sphere::commitParameters() void Sphere::finalize() { + if (!beginPreparation()) + return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on sphere geometry"); @@ -70,105 +66,48 @@ void Sphere::finalize() // Calculate bounds // m_numSpheres = m_index ? m_index->size() : m_vertex->size(); - m_aabbs.reserve(m_numSpheres * sizeof(box3)); - - const float globalRadius = m_globalRadius; - const float *radii = nullptr; - if (m_vertexRadius) - radii = m_vertexRadius->beginAs(AddressSpace::GPU); - - const auto *vertices = m_vertex->beginAs(AddressSpace::GPU); - - auto &state = *deviceState(); - - if (m_index) { - auto *begin = m_index->beginAs(AddressSpace::GPU); - auto *end = m_index->endAs(AddressSpace::GPU); - thrust::transform(thrust::cuda::par.on(state.stream), - begin, - end, - thrust::device_pointer_cast((box3 *)m_aabbs.ptr()), - [=] __device__(uint32_t i) { - const auto &v = vertices[i]; - const float r = glm::abs(radii ? radii[i] : globalRadius); - return box3(v - r, v + r); - }); - } else { - DeviceBuffer index; - index.reserve(m_numSpheres * sizeof(uint32_t)); - auto idx_begin = - thrust::device_pointer_cast((uint32_t *)index.ptr()); - auto idx_end = idx_begin + m_numSpheres; - thrust::sequence(thrust::cuda::par.on(state.stream), idx_begin, idx_end); - thrust::transform(thrust::cuda::par.on(state.stream), - idx_begin, - idx_end, - thrust::device_pointer_cast((box3 *)m_aabbs.ptr()), - [=] __device__(uint32_t i) { - const auto &v = vertices[i]; - const float r = glm::abs(radii ? radii[i] : globalRadius); - return box3(v - r, v + r); - }); - } - + PrimitiveInput input; + input.type = GeometryType::SPHERE; + input.count = m_numSpheres; + input.vertices = m_vertex->beginAs(AddressSpace::GPU); + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radii = m_vertexRadius + ? m_vertexRadius->beginAs(AddressSpace::GPU) + : nullptr; + input.radius = m_globalRadius; + if (!m_preprocessing.bounds(this, input, m_aabbs, m_epsilonScale)) + return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - auto aabbsBegin = thrust::device_pointer_cast((box3 *)m_aabbs.ptr()); - m_epsilonScale = thrust::transform_reduce( - thrust::cuda::par.on(state.stream), - aabbsBegin, - aabbsBegin + m_numSpheres, - [] __device__(const box3 &b) -> float { - const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); - return glm::max(m.x, glm::max(m.y, m.z)); - }, - 0.f, - thrust::maximum()); - - // Radii may have changed. Rebuild the Geometry Light CDF if a surface has ever - // requested it (order-independent of the surface commit), else drop stale data. + // Radii may have changed. Rebuild the Geometry Light CDF if a surface has + // ever requested it (order-independent of the surface commit), else drop + // stale data. m_areaDataValid = false; if (m_areaDataWanted) buildAreaData(); else { m_totalArea = 0.f; - m_primAreaCdf.clear(); + m_primAreaCdf.reset(); } - upload(); + if (!preparationFailed()) + upload(); } void Sphere::buildAreaData() { - const float *radii = - m_vertexRadius ? m_vertexRadius->beginAs(AddressSpace::HOST) : nullptr; - const uint32_t *indices = - m_index ? m_index->beginAs(AddressSpace::HOST) : nullptr; - - m_primAreaCdf.resize(m_numSpheres); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < m_numSpheres; ++i) { - const uint32_t vi = indices ? indices[i] : uint32_t(i); - const float r = glm::abs(radii ? radii[vi] : m_globalRadius); - cumulative += 4.0 * double(kPi) * double(r) * double(r); - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - // Normalize to a cumulative CDF ending at 1. A degenerate (zero-area) set - // leaves totalArea 0; callers gate on that. - if (m_totalArea > 0.f) { - for (size_t i = 0; i < m_numSpheres; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; + PrimitiveInput input; + input.type = GeometryType::SPHERE; + input.count = m_numSpheres; + input.radii = m_vertexRadius + ? m_vertexRadius->beginAs(AddressSpace::GPU) + : nullptr; + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radius = m_globalRadius; + m_areaDataValid = + m_preprocessing.areas(this, input, m_primAreaCdf, m_totalArea); } bool Sphere::isAreaSamplingSupported() const @@ -182,7 +121,8 @@ void Sphere::ensureAreaData() if (m_areaDataValid) return; buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device + if (m_areaDataValid) + upload(); } float Sphere::totalArea() const @@ -225,8 +165,9 @@ GeometryGPUData Sphere::gpuData() const populateAttributeDataSet(m_vertexAttributes, sphere.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - sphere.primAreaCdf = m_primAreaCdf.dataDevice(); - sphere.numPrimitives = uint32_t(m_primAreaCdf.size()); + sphere.primAreaCdf = + m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; + sphere.numPrimitives = m_totalArea > 0.f ? uint32_t(m_numSpheres) : 0; sphere.totalArea = m_totalArea; return retval; diff --git a/devices/rtx/device/geometry/Sphere.h b/devices/rtx/device/geometry/Sphere.h index 0d00ddca2..bcf07355f 100644 --- a/devices/rtx/device/geometry/Sphere.h +++ b/devices/rtx/device/geometry/Sphere.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -74,9 +74,10 @@ struct Sphere : public Geometry float m_globalRadius{1.f}; // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. m_areaDataWanted - // persists across recommits so a re-finalize rebuilds it order-independently. - HostDeviceArray m_primAreaCdf; + // the normalized cumulative object-space area over primitives. + // m_areaDataWanted persists across recommits so a re-finalize rebuilds it + // order-independently. + DeviceBuffer m_primAreaCdf; float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index 8b25db02f..0ebddc73c 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -76,6 +76,8 @@ void Triangle::commitParameters() void Triangle::finalize() { + if (!beginPreparation()) + return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on triangle geometry"); @@ -146,42 +148,22 @@ void Triangle::finalize() buildAreaData(); else { m_totalArea = 0.f; - m_primAreaCdf.clear(); + m_primAreaCdf.reset(); } - upload(); + if (!preparationFailed()) + upload(); } void Triangle::buildAreaData() { - const size_t numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; - const vec3 *vertices = m_vertex->beginAs(AddressSpace::HOST); - const uvec3 *indices = - m_index ? m_index->beginAs(AddressSpace::HOST) : nullptr; - - m_primAreaCdf.resize(numTriangles); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < numTriangles; ++i) { - const uvec3 tri = indices ? indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); - const vec3 &v0 = vertices[tri.x]; - const vec3 &v1 = vertices[tri.y]; - const vec3 &v2 = vertices[tri.z]; - cumulative += 0.5 * glm::length(glm::cross(v1 - v0, v2 - v0)); - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - // Normalize to a cumulative CDF ending at 1. A degenerate (zero-area) mesh - // leaves totalArea 0; callers gate on that. - if (m_totalArea > 0.f) { - for (size_t i = 0; i < numTriangles; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; + PrimitiveInput input; + input.count = m_index ? m_index->size() : m_vertex->size() / 3; + input.vertices = m_vertex->beginAs(AddressSpace::GPU); + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + m_areaDataValid = + m_preprocessing.areas(this, input, m_primAreaCdf, m_totalArea); } bool Triangle::isAreaSamplingSupported() const @@ -195,7 +177,8 @@ void Triangle::ensureAreaData() if (m_areaDataValid) return; buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device + if (m_areaDataValid) + upload(); // republish only successfully prepared sampling data } float Triangle::totalArea() const @@ -264,8 +247,10 @@ GeometryGPUData Triangle::gpuData() const tri.cullBackfaces = m_cullBackfaces; // Geometry Light sampling data; null/zero until ensureAreaData() runs. - tri.primAreaCdf = m_primAreaCdf.dataDevice(); - tri.numPrimitives = uint32_t(m_primAreaCdf.size()); + tri.primAreaCdf = m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; + tri.numPrimitives = m_totalArea > 0.f + ? uint32_t(m_index ? m_index->size() : m_vertex->size() / 3) + : 0; tri.totalArea = m_totalArea; return retval; diff --git a/devices/rtx/device/geometry/Triangle.h b/devices/rtx/device/geometry/Triangle.h index 9ef1161b8..ffc527d1c 100644 --- a/devices/rtx/device/geometry/Triangle.h +++ b/devices/rtx/device/geometry/Triangle.h @@ -35,7 +35,6 @@ #include "Geometry.h" #include "array/Array1D.h" #include "utility/DeviceBuffer.h" -#include "utility/HostDeviceArray.h" namespace visrtx { @@ -92,9 +91,10 @@ struct Triangle : public Geometry bool m_cullBackfaces{false}; // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. m_areaDataWanted - // persists across recommits so a re-finalize rebuilds it order-independently. - HostDeviceArray m_primAreaCdf; + // the normalized cumulative object-space area over primitives. + // m_areaDataWanted persists across recommits so a re-finalize rebuilds it + // order-independently. + DeviceBuffer m_primAreaCdf; float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index ffeaf323b..761bdf84e 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -52,6 +52,7 @@ #include "utility/TaskExecutor.h" #endif // defined(USE_MDL) // std +#include #include #include #include @@ -166,6 +167,10 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState { anari::Device anariDevice{nullptr}; + // A failed last-public-release copy leaves application memory unavailable. + // Cached GPU pointers cannot be repaired safely: only cleanup is permitted. + std::atomic arrayPrivatizationFailed{false}; + CUcontext cudaContext; CUstream stream; cudaDeviceProp deviceProps; diff --git a/devices/rtx/device/utility/MemoryAllocation.cpp b/devices/rtx/device/utility/MemoryAllocation.cpp index d10aba51e..eb18ca941 100644 --- a/devices/rtx/device/utility/MemoryAllocation.cpp +++ b/devices/rtx/device/utility/MemoryAllocation.cpp @@ -223,16 +223,25 @@ CudaMemoryAllocation::CudaMemoryAllocation(const HostMemoryAllocation &o) { (*this) = o; } -void CudaMemoryAllocation::privatize() +cudaError_t CudaMemoryAllocation::privatize() { if (!isValid() || isOwner()) - return; + return cudaSuccess; void *dst = nullptr; - cudaMalloc(&dst, bytes()); - cudaMemcpy(dst, ptr(), bytes(), cudaMemcpyDeviceToDevice); + auto error = cudaMalloc(&dst, bytes()); + if (error != cudaSuccess) + return error; + error = cudaMemcpy(dst, ptr(), bytes(), cudaMemcpyDeviceToDevice); + if (error == cudaSuccess) + error = cudaStreamSynchronize(nullptr); + if (error != cudaSuccess) { + cudaFree(dst); + return error; + } freeMemory(); m_ptr = dst; m_owner = true; + return cudaSuccess; } CudaMemoryAllocation::CudaMemoryAllocation(CudaMemoryAllocation &&o) diff --git a/devices/rtx/device/utility/MemoryAllocation.h b/devices/rtx/device/utility/MemoryAllocation.h index 8bcad0891..522349113 100644 --- a/devices/rtx/device/utility/MemoryAllocation.h +++ b/devices/rtx/device/utility/MemoryAllocation.h @@ -33,6 +33,8 @@ // anari #include +// CUDA +#include namespace visrtx { @@ -99,7 +101,7 @@ struct CudaMemoryAllocation CudaMemoryAllocation &operator=(const HostMemoryAllocation &o); CudaMemoryAllocation(const HostMemoryAllocation &o); - void privatize(); // if !isOwner(), then make internal copy + cudaError_t privatize(); // publish an internal copy only after completion // Movable, not copyable // CudaMemoryAllocation(CudaMemoryAllocation &&); diff --git a/devices/rtx/device/world/Group.cpp b/devices/rtx/device/world/Group.cpp index 0f991a0a7..a07f25784 100644 --- a/devices/rtx/device/world/Group.cpp +++ b/devices/rtx/device/world/Group.cpp @@ -73,7 +73,11 @@ bool Group::getProperty(const std::string_view &name, deviceState()->commitBuffer.flush(); rebuildSurfaceBVHs(); rebuildVolumeBVH(); + if (preparationFailed()) + return false; } + if (preparationFailed()) + return false; auto bounds = m_triangleBounds; bounds.extend(m_curveBounds); bounds.extend(m_userBounds); @@ -205,8 +209,24 @@ const std::vector &Group::surfacesUser() const return m_surfacesUser; } +bool Group::preparationFailed() const +{ + if (!m_surfaceData) + return false; + auto surfaces = make_Span( + (Surface **)m_surfaceData->handlesBegin(), m_surfaceData->totalSize()); + for (auto *s : surfaces) { + if (s && s->isVisible() && s->geometry() + && s->geometry()->preparationFailed()) + return true; + } + return false; +} + void Group::rebuildSurfaceBVHs() { + if (preparationFailed()) + return; const auto &state = *deviceState(); if (state.objectUpdates.lastSurfaceBLASChange < m_objectUpdates.lastSurfaceBVHBuilt) @@ -221,9 +241,21 @@ void Group::rebuildSurfaceBVHs() m_traversableCurve = {}; m_traversableUser = {}; + // populateBuildInput can trigger a first upload of an authored index array. + // Establish its default-stream producer edge before any BLAS consumes it. + auto triangles = createOBI(m_surfacesTriangle); + auto curves = createOBI(m_surfacesCurve); + auto users = createOBI(m_surfacesUser); + Surface *first = !m_surfacesTriangle.empty() ? m_surfacesTriangle.front() + : !m_surfacesCurve.empty() ? m_surfacesCurve.front() + : !m_surfacesUser.empty() ? m_surfacesUser.front() + : nullptr; + if (first && !waitForPreparationInputs(first->geometry())) + return; + if (!m_surfacesTriangle.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building triangle BVH"); - buildOptixBVH(createOBI(m_surfacesTriangle), + buildOptixBVH(std::move(triangles), m_bvhTriangle, m_traversableTriangle, m_triangleBounds, @@ -235,11 +267,8 @@ void Group::rebuildSurfaceBVHs() if (!m_surfacesCurve.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building curve BVH"); - buildOptixBVH(createOBI(m_surfacesCurve), - m_bvhCurve, - m_traversableCurve, - m_curveBounds, - this); + buildOptixBVH( + std::move(curves), m_bvhCurve, m_traversableCurve, m_curveBounds, this); } else { reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping curve BVH build"); @@ -247,11 +276,8 @@ void Group::rebuildSurfaceBVHs() if (!m_surfacesUser.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building user BVH"); - buildOptixBVH(createOBI(m_surfacesUser), - m_bvhUser, - m_traversableUser, - m_userBounds, - this); + buildOptixBVH( + std::move(users), m_bvhUser, m_traversableUser, m_userBounds, this); } else { reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping user BVH build"); diff --git a/devices/rtx/device/world/Group.h b/devices/rtx/device/world/Group.h index 3dc6073e6..5d18ab43d 100644 --- a/devices/rtx/device/world/Group.h +++ b/devices/rtx/device/world/Group.h @@ -76,10 +76,11 @@ struct Group : public Object // Triangle surfaces, the Stage 1 candidates for Geometry Light synthesis. const std::vector &surfacesTriangle() const; - // Custom-primitive surfaces (spheres, cylinders, cones, …); the area-samplable - // ones (Stage 1.5: Sphere) are also Geometry Light candidates. + // Custom-primitive surfaces (spheres, cylinders, cones, …); the + // area-samplable ones (Stage 1.5: Sphere) are also Geometry Light candidates. const std::vector &surfacesUser() const; + bool preparationFailed() const; void rebuildSurfaceBVHs(); void rebuildVolumeBVH(); void rebuildLights(); diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index b89950378..0b275b7c0 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -42,9 +42,9 @@ #include "utility/AnariTypeHelpers.h" #include "world/Group.h" -#include #include #include +#include #include #ifdef USE_MDL @@ -125,6 +125,8 @@ bool World::getProperty(const std::string_view &name, deviceState()->commitBuffer.flush(); rebuildWorld(); } + if (preparationFailed()) + return false; auto bounds = m_surfaceBounds; bounds.extend(m_volumeBounds); std::memcpy(ptr, &bounds, sizeof(bounds)); @@ -140,6 +142,8 @@ bool World::getProperty(const std::string_view &name, deviceState()->commitBuffer.flush(); rebuildWorld(); } + if (preparationFailed()) + return false; const auto count = uint32_t(m_instanceLightGPUData.size()); std::memcpy(ptr, &count, sizeof(count)); return true; @@ -247,6 +251,15 @@ WorldGPUData World::gpuData() const return retval; } +bool World::preparationFailed() const +{ + for (auto *instance : m_instances) { + if (instance->group()->preparationFailed()) + return true; + } + return false; +} + void World::rebuildWorld() { const auto &state = *deviceState(); @@ -259,6 +272,8 @@ void World::rebuildWorld() m_objectUpdates.lastTLASBuild = 0; // BLAS changed, so need to build TLAS rebuildBLASs(); } + if (preparationFailed()) + return; if (m_objectUpdates.lastTLASBuild <= state.objectUpdates.lastTLASChange) { m_surfaceBounds = box3(); @@ -272,6 +287,8 @@ void World::rebuildWorld() // is deliberately NOT computed here -- it is scaled by the scene radius, // which only exists once the TLAS has been built. See buildLightPickCdf(). buildInstanceLightGPUData(); + if (preparationFailed()) + return; buildLightProxies(); populateOptixInstances(); @@ -501,8 +518,7 @@ void World::buildInstanceSurfaceGPUData() const mat4 o2wMat4 = mat4(inst->xfm(t)); const mat3x4 o2w = glm::transpose(mat4x3(o2wMat4)); - const mat3x4 w2o = - glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); + const mat3x4 w2o = glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); auto assignXfm = [&](InstanceSurfaceGPUData &g) { g.objectToWorld = o2w; @@ -519,20 +535,18 @@ void World::buildInstanceSurfaceGPUData() ++instID; } if (group->containsCurveGeometry()) { - sd[instID] = - makeInstanceGPUData(group->surfaceCurveGPUIndices().data(), - inst->uniformAttributes(), - id, - t); + sd[instID] = makeInstanceGPUData(group->surfaceCurveGPUIndices().data(), + inst->uniformAttributes(), + id, + t); assignXfm(sd[instID]); ++instID; } if (group->containsUserGeometry()) { - sd[instID] = - makeInstanceGPUData(group->surfaceUserGPUIndices().data(), - inst->uniformAttributes(), - id, - t); + sd[instID] = makeInstanceGPUData(group->surfaceUserGPUIndices().data(), + inst->uniformAttributes(), + id, + t); assignXfm(sd[instID]); ++instID; } @@ -557,8 +571,7 @@ void World::buildInstanceVolumeGPUData() const mat4 o2wMat4 = mat4(inst->xfm(t)); const mat3x4 o2w = glm::transpose(mat4x3(o2wMat4)); - const mat3x4 w2o = - glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); + const mat3x4 w2o = glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); InstanceVolumeGPUData g; g.objectToWorld = o2w; @@ -588,8 +601,8 @@ void World::synthesizeGeometryLights() { // Configure or drop each candidate surface's Geometry Light from current // material + geometry state. Runs over triangle and user (custom-primitive, - // e.g. sphere) surfaces; isSampleableEmitter gates out non-area-samplable ones. - // Object-space, so done once per group; the fill pass instances it per + // e.g. sphere) surfaces; isSampleableEmitter gates out non-area-samplable + // ones. Object-space, so done once per group; the fill pass instances it per // transform like an authored light. The light carries the material's mean // radiance (Pick Power); the sampler evaluates the material at the sampled // point when its emission is not constant. @@ -597,6 +610,8 @@ void World::synthesizeGeometryLights() if (surface->isSampleableEmitter()) { auto *geometry = surface->geometry(); geometry->ensureAreaData(); + if (geometry->preparationFailed()) + return; const float area = geometry->totalArea(); if (area > 0.0f) { surface->ensureGeometryLight()->configure(geometry->index(), @@ -624,6 +639,8 @@ void World::synthesizeGeometryLights() void World::buildInstanceLightGPUData() { synthesizeGeometryLights(); + if (preparationFailed()) + return; // Calculate total lights (authored + synthesized Geometry Lights) size_t totalLights = 0; @@ -667,10 +684,10 @@ void World::buildInstanceLightGPUData() size_t lightIndex = 0; size_t hdriIndex = 0; - // Mirrors buildInstanceSurfaceGPUData's instID: surface instances are laid out - // per (instance, transform) as [triangle?][curve?][user?]. Tracking the same - // cursor here recovers each Geometry Light's surface-instance index without a - // side table. + // Mirrors buildInstanceSurfaceGPUData's instID: surface instances are laid + // out per (instance, transform) as [triangle?][curve?][user?]. Tracking the + // same cursor here recovers each Geometry Light's surface-instance index + // without a side table. size_t surfaceInstanceCursor = 0; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { @@ -798,9 +815,8 @@ void World::buildLightPickCdf() // // Fall back to unit radius so an empty scene still weights the infinite // lights nonzero. - m_sceneRadius = empty(m_illuminatedBounds) - ? 1.0f - : 0.5f + m_sceneRadius = empty(m_illuminatedBounds) ? 1.0f + : 0.5f * glm::length(m_illuminatedBounds.upper - m_illuminatedBounds.lower); if (!(m_sceneRadius > 0.0f) || !std::isfinite(m_sceneRadius)) m_sceneRadius = 1.0f; diff --git a/devices/rtx/device/world/World.h b/devices/rtx/device/world/World.h index 4f96cc9d7..abc8158b7 100644 --- a/devices/rtx/device/world/World.h +++ b/devices/rtx/device/world/World.h @@ -57,6 +57,7 @@ struct World : public Object WorldGPUData gpuData() const; + bool preparationFailed() const; void rebuildWorld(); private: @@ -153,7 +154,8 @@ struct World : public Object // Power-proportional Light Pick, rebuilt with the light instances. HostDeviceArray m_lightPickCdf; - // Per-slot discrete pick probability (power_i/total), parallel to m_lightPickCdf. + // Per-slot discrete pick probability (power_i/total), parallel to + // m_lightPickCdf. HostDeviceArray m_lightPickDelta; float m_totalLightPower{0.f}; float m_hdriPower{0.f}; From c00aa31f6a0d2f757d28ed5d9ca246329242390d Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:35:13 +0000 Subject: [PATCH 02/20] perf(rtx): reuse preparation for geometry-wide attribute updates --- devices/rtx/apps/tests/api/CMakeLists.txt | 2 + .../api/TestGeometryPreparationReuse.cpp | 346 ++++++++++++++++++ .../api/TestGeometryPreprocessingFailure.cpp | 16 +- devices/rtx/device/geometry/Cone.cpp | 6 +- devices/rtx/device/geometry/Curve.cpp | 3 +- devices/rtx/device/geometry/Cylinder.cpp | 7 +- devices/rtx/device/geometry/Geometry.cpp | 74 +++- devices/rtx/device/geometry/Geometry.h | 23 +- devices/rtx/device/geometry/Quad.cpp | 6 +- devices/rtx/device/geometry/SDF.cpp | 10 +- devices/rtx/device/geometry/Sphere.cu | 3 +- devices/rtx/device/geometry/Triangle.cpp | 13 +- .../rtx/docs/geometry-preparation-reuse.md | 96 +++++ 13 files changed, 593 insertions(+), 12 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp create mode 100644 devices/rtx/docs/geometry-preparation-reuse.md diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index dc0fdf02d..df7f5960f 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -80,6 +80,8 @@ target_link_libraries(TestSampleAddressing PRIVATE CUDA::cudart) set_tests_properties(TestSampleAddressing PROPERTIES TIMEOUT 120) make_test(TestPowerLightPickEnv) make_test(TestEmissiveGeometryLight) +make_test(TestGeometryPreparationReuse) +target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) target_link_libraries(TestSharedGeometryLifecycle PRIVATE CUDA::cudart) make_test(TestGeometryPreprocessingFailure) diff --git a/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp b/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp new file mode 100644 index 000000000..46ebaa8c0 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0, preparations = 0, builds = 0; +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType type, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } + // Diagnostic counts verify that metadata publication does not silently run + // the expensive path. Images/bounds independently verify observable results. + if (type == ANARI_GEOMETRY && std::strstr(message, "finalizing ")) + ++preparations; + if (std::strstr(message, "visrtx::Group building ") + || std::strstr(message, "visrtx::World building surface BVH")) + ++builds; +} + +static bool run(ANARIDevice d, const std::string &type, bool device) +{ + auto geometry = anari::newObject(d, type.c_str()); + std::vector positions; + if (type == "triangle") + positions = {{-1, -1, 0}, {1, -1, 0}, {0, 1, 0}}; + else if (type == "quad") + positions = {{-1, -1, 0}, {1, -1, 0}, {1, 1, 0}, {-1, 1, 0}}; + else if (type == "sphere") + positions = {{0, 0, 0}}; + else + positions = {{-0.5f, 0, 0}, {0.5f, 0, 0}}; + const bool sdf = type == "sdf"; + const size_t count = sdf ? 72 : positions.size(); + const auto elementType = sdf ? ANARI_UINT8 : ANARI_FLOAT32_VEC3; + const size_t bytes = sdf ? count : count * sizeof(vec3); + std::vector inputs(2 * bytes); + if (sdf) { + const float radius = 0.5f; + std::memcpy(inputs.data() + 44, &radius, sizeof(radius)); + std::memcpy(inputs.data() + 48, &radius, sizeof(radius)); + std::memcpy(inputs.data() + bytes, inputs.data(), bytes); + const float shift = 2.f; + std::memcpy(inputs.data() + bytes + 20, &shift, sizeof(shift)); + } else { + std::memcpy(inputs.data(), positions.data(), bytes); + for (auto &v : positions) + v[0] += 2.f; + std::memcpy(inputs.data() + bytes, positions.data(), bytes); + } + void *external = nullptr; + anari::Array1D array; + if (device) { + if (cudaMalloc(&external, inputs.size()) != cudaSuccess + || cudaMemcpy( + external, inputs.data(), inputs.size(), cudaMemcpyHostToDevice) + != cudaSuccess) + return false; + array = + anariNewArray1D(d, external, nullptr, nullptr, elementType, 2 * count); + } else { + array = anari::newArray1D(d, elementType, 2 * count); + std::memcpy(anariMapArray(d, array), inputs.data(), inputs.size()); + anariUnmapArray(d, array); + } + anari::setParameter(d, array, "end", uint64_t(count)); + anari::commitParameters(d, array); + const char *inputName = sdf ? "primitive.sdf" : "vertex.position"; + anari::setParameter(d, geometry, inputName, array); + anari::setParameter(d, geometry, "radius", 0.25f); + if (type == "cone") { + const std::array radii = {0.25f, 0.25f}; + anari::setParameterArray1D(d, geometry, "vertex.radius", radii.data(), 2); + } + anari::setParameter(d, geometry, "attribute0", vec4{0.2f, 0.4f, 0.8f, 1}); + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "physicallyBased"); + // Area-samplable types prepare their CDF as well as bounds on first use. + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "geometry.attribute0"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{32, 32}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(d, frame, "world", world); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setParameter(d, frame, "renderer", renderer); + anari::commitParameters(d, frame); + auto render = [&]() { + anari::render(d, frame); + anari::wait(d, frame); + auto fb = anari::map(d, frame, "channel.color"); + vec3 result{}; + if (!fb.data) { + ++errors; + return result; + } + const auto pixel = fb.data[16 * 32 + 16]; + for (int i = 0; i < 3; ++i) + result[i] = pixel[i]; + anari::unmap(d, frame, "channel.color"); + return result; + }; + auto bounds = [&]() { + std::array result{}; + if (!anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + result.data(), + sizeof(result), + ANARI_WAIT)) + ++errors; + return result; + }; + auto close = [](vec3 actual, vec3 expected) { + for (int i = 0; i < 3; ++i) + if (!std::isfinite(actual[i]) + || std::abs(actual[i] - expected[i]) > 1e-4f) + return false; + return true; + }; + // Debug output includes geometric facing modulation. Obtain its reference + // from initial full preparation, then require identical + // preparation-preserving output. + const auto reference = render(); + const auto originalBounds = bounds(); + bool ok = errors == 0 && reference[0] > 0.1f && reference[2] > 0.6f; + anari::unsetParameter(d, geometry, "attribute0"); + anari::commitParameters(d, geometry); + ok = close(render(), {0, 0, 0}) && ok; + for (const char *attribute : + {"attribute0", "attribute1", "attribute2", "attribute3", "color"}) { + const std::string method = std::string("geometry.") + attribute; + anari::setParameter(d, renderer, "method", method.c_str()); + anari::commitParameters(d, renderer); + const int beforePrep = preparations, beforeBuild = builds; + anari::setParameter(d, geometry, attribute, vec4{0.2f, 0.4f, 0.8f, 1}); + anari::commitParameters(d, geometry); + // Staging a geometric edit after commit must not leak into its snapshot. + anari::unsetParameter(d, geometry, inputName); + const auto actual = render(); + const bool setOk = close(actual, reference) && bounds() == originalBounds + && preparations == beforePrep && builds == beforeBuild; + if (!setOk) + fprintf(stderr, + "%s %s set pixel=%g,%g,%g prep=%d build=%d\n", + type.c_str(), + attribute, + actual[0], + actual[1], + actual[2], + preparations - beforePrep, + builds - beforeBuild); + ok = setOk && ok; + anari::setParameter(d, geometry, inputName, array); + anari::unsetParameter(d, geometry, attribute); + anari::commitParameters(d, geometry); + const auto unset = render(); + const bool unsetOk = close(unset, {0, 0, 0}) && preparations == beforePrep + && builds == beforeBuild; + if (!unsetOk) + fprintf(stderr, + "%s %s unset pixel=%g,%g,%g prep=%d build=%d\n", + type.c_str(), + attribute, + unset[0], + unset[1], + unset[2], + preparations - beforePrep, + builds - beforeBuild); + ok = unsetOk && ok; + } + { + // Scalar/string parameters are part of the preparation identity too. + const int beforePrep = preparations, beforeBuild = builds; + const bool round = + type == "sphere" || type == "curve" || type == "cylinder"; + auto change = [&](bool changed) { + if (round) + anari::setParameter(d, geometry, "radius", changed ? 0.35f : 0.25f); + else if (type == "cone") + anari::setParameter(d, geometry, "caps", changed ? "both" : "none"); + else if (sdf) + anari::setParameter(d, geometry, "epsilon", changed ? 1e-4f : 1e-5f); + else + anari::setParameter(d, geometry, "cullBackfaces", changed); + anari::commitParameters(d, geometry); + }; + change(true); + const auto changedBounds = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + if (round) + ok = changedBounds[0] < originalBounds[0] - 0.05f + && changedBounds[3] > originalBounds[3] + 0.05f && ok; + change(false); + const auto restored = bounds(); + for (int i = 0; i < 6; ++i) + ok = std::isfinite(restored[i]) + && std::abs(restored[i] - originalBounds[i]) < 1e-4f && ok; + } + if (!device) { + // An in-place unmap changes values without changing the handle or GPU + // address. Coalescing it with a geometry-wide attribute commit must still + // prepare. + const int beforePrep = preparations, beforeBuild = builds; + auto *mapped = static_cast(anariMapArray(d, array)); + if (sdf) { + const float shift = 0.25f; + std::memcpy(mapped + 20, &shift, sizeof(shift)); + } else { + for (size_t i = 0; i < count; ++i) { + vec3 position; + std::memcpy(position.data(), mapped + i * sizeof(vec3), sizeof(vec3)); + position[0] += 0.25f; + std::memcpy(mapped + i * sizeof(vec3), position.data(), sizeof(vec3)); + } + } + anariUnmapArray(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{0.1f, 0.2f, 0.3f, 1}); + anari::commitParameters(d, geometry); + const auto moved = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + for (int i = 0; i < 6; ++i) + ok = std::isfinite(moved[i]) + && std::abs(moved[i] - originalBounds[i] - (i % 3 == 0 ? 0.25f : 0.f)) + < 1e-4f + && ok; + std::memcpy(anariMapArray(d, array), inputs.data(), inputs.size()); + anariUnmapArray(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{0, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = bounds() == originalBounds && ok; + } + // Coalesced range and geometry-wide attribute commits must prepare the new + // logical input. + int beforePrep = preparations, beforeBuild = builds; + anari::setParameter(d, array, "begin", uint64_t(count)); + anari::setParameter(d, array, "end", uint64_t(2 * count)); + anari::commitParameters(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + const auto shifted = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + for (int i = 0; i < 6; ++i) + ok = std::isfinite(shifted[i]) + && std::abs(shifted[i] - originalBounds[i] - (i % 3 == 0 ? 2.f : 0.f)) + < 1e-4f + && ok; + // Last-public release changes backing pointers, but not values or ranges. + // Coalesce it with a geometry-wide attribute commit to exercise pointer-only + // invalidation. + beforePrep = preparations; + beforeBuild = builds; + anari::release(d, array); + if (external) + cudaFree(external); + anari::setParameter(d, geometry, "attribute0", vec4{0, 1, 0, 1}); + anari::commitParameters(d, geometry); + ok = bounds() == shifted && ok; + if (device) + ok = preparations > beforePrep && builds > beforeBuild && ok; + render(); + ok = errors == 0 && ok; + printf("preparation-preserving updates %s device=%d %s\n", + type.c_str(), + device, + ok ? "PASS" : "FAIL"); + anari::release(d, frame); + anari::release(d, renderer); + anari::release(d, world); + anari::release(d, geometry); + return ok; +} + +int main() +{ + auto d = makeVisRTXDevice(status); + bool ok = true; + for (const char *type : + {"triangle", "quad", "sphere", "curve", "cone", "cylinder", "sdf"}) + for (bool device : {false, true}) + ok = run(d, type, device) && ok; + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp index cd9118d30..9f3cab41b 100644 --- a/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp +++ b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp @@ -129,10 +129,22 @@ int main(int argc, char **argv) bounds.data(), sizeof(bounds), ANARI_WAIT); - if (invalid) + if (invalid) { ok = ok && errors > beforeErrors && samples == previousSamples && completions == beforeCompletions && !haveBounds; - else { + // Geometry-wide attributes must not rehabilitate a failed generation. + anari::setParameter( + d, geometry, "attribute0", vec4{float(step), 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = !anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + && ok; + } else { ok = ok && errors == beforeErrors && samples > 0 && completions == beforeCompletions + 1 && haveBounds; previousSamples = samples; diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index 87e2d7ec0..a26d2f373 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -87,7 +87,11 @@ PrimitiveInput Cone::primitiveInput() const void Cone::finalize() { - if (!beginPreparation()) + if (!beginPreparation({"primitive.index", + "vertex.position", + "vertex.radius", + "vertex.cap", + "caps"})) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index d838dcfa5..6814ba190 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -53,7 +53,8 @@ void Curve::commitParameters() void Curve::finalize() { - if (!beginPreparation()) + if (!beginPreparation( + {"primitive.index", "vertex.position", "vertex.radius", "radius"})) return; if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index 014870b2e..e6d84822e 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -88,7 +88,12 @@ PrimitiveInput Cylinder::primitiveInput() const void Cylinder::finalize() { - if (!beginPreparation()) + if (!beginPreparation({"primitive.index", + "vertex.position", + "primitive.radius", + "vertex.cap", + "caps", + "radius"})) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index b9e3f7ccb..45b3a4424 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -141,7 +141,8 @@ void Geometry::commitParameters() void Geometry::markFinalized() { Object::markFinalized(); - deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); + if (!m_preparationPreserved) + deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); } bool Geometry::isAreaSamplingSupported() const @@ -149,10 +150,79 @@ bool Geometry::isAreaSamplingSupported() const return false; } -bool Geometry::beginPreparation() +bool Geometry::PreparationParameter::operator==( + const PreparationParameter &other) const { + return parameterIndex == other.parameterIndex && value == other.value + && updated == other.updated && finalized == other.finalized + && modified == other.modified && devicePointer == other.devicePointer; +} + +void Geometry::upload() +{ + RegisteredObject::upload(); + m_hasPreparedData = !preparationFailed() && isValid(); +} + +bool Geometry::beginPreparation(std::initializer_list parameters) +{ + m_preparationPreserved = false; if (m_inputRetirementFailed) return false; + + std::vector current; + if (parameters.size() != 0) { + current.reserve(m_preparedParameters.size()); + size_t parameterIndex = 0; + auto append = [&](const char *name) { + PreparationParameter parameter; + parameter.parameterIndex = parameterIndex++; + parameter.value = getParamDirect(name); // committed snapshot, not staging + if (!parameter.value.valid()) + return; // Keep only present values, retaining their parameter identity. + if (anari::isObject(parameter.value.type())) { + auto *object = parameter.value.getObject(); + if (object) { + parameter.updated = object->lastUpdated(); + parameter.finalized = object->lastFinalized(); + if (auto *array = dynamic_cast(object)) { + parameter.modified = array->lastDataModified(); + // Privatization can change backing pointers without changing values + // or the array timestamp. Never reuse cached aliases in that case. + parameter.devicePointer = array->dataGPU(); + } + } + } + current.push_back(std::move(parameter)); + }; + for (const char *name : {"primitive.attribute0", + "primitive.attribute1", + "primitive.attribute2", + "primitive.attribute3", + "primitive.color", + "primitive.id", + "vertex.attribute0", + "vertex.attribute1", + "vertex.attribute2", + "vertex.attribute3", + "vertex.color"}) + append(name); + for (const char *name : parameters) + append(name); + + // Observer-only updates always take the preparation path. A geometry-wide + // attribute edit coalesced with an array change cannot hide that change; + // the versions/pointers above still invalidate preparation reuse. + if (m_hasPreparedData && !preparationFailed() && isValid() + && lastCommitted() > lastFinalized() + && current == m_preparedParameters) { + m_preparationPreserved = true; + upload(); + return false; + } + } + m_preparedParameters = std::move(current); + m_hasPreparedData = false; m_preparationFailed = false; return true; } diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index 71d002ebb..deea52d2f 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -36,7 +36,9 @@ #include "array/Array1D.h" #include "gpu/gpu_objects.h" // std +#include #include +#include namespace visrtx { @@ -73,6 +75,7 @@ struct Geometry : public RegisteredObject void commitParameters() override; void markFinalized() override; + void upload(); virtual void populateBuildInput(OptixBuildInput &) const = 0; virtual int optixGeometryType() const = 0; @@ -89,7 +92,11 @@ struct Geometry : public RegisteredObject void setPreparationFailed(bool failed); protected: - bool beginPreparation(); + // Opt-in preparation reuse: list every subtype parameter except the five + // geometry-wide attributes. The base adds primitive and vertex arrays. + // Returns false after preparation reuse and registry publication, or if + // preparation cannot start. + bool beginPreparation(std::initializer_list parameters = {}); GeometryGPUData gpuData() const override = 0; void commitAttributes(const char *prefix, GeometryAttributes &attrs); @@ -105,6 +112,20 @@ struct Geometry : public RegisteredObject Preprocessing m_preprocessing; private: + struct PreparationParameter + { + size_t parameterIndex{0}; + helium::AnariAny value; + helium::TimeStamp updated{0}; + helium::TimeStamp finalized{0}; + helium::TimeStamp modified{0}; + const void *devicePointer{nullptr}; + + bool operator==(const PreparationParameter &other) const; + }; + std::vector m_preparedParameters; + bool m_hasPreparedData{false}; + bool m_preparationPreserved{false}; bool m_preparationFailed{false}; bool m_inputRetirementFailed{false}; }; diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 5dcc6bfbd..1cbb4d5e2 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -51,7 +51,11 @@ void Quad::commitParameters() void Quad::finalize() { - if (!beginPreparation()) + if (!beginPreparation({"primitive.index", + "vertex.position", + "vertex.normal", + "vertex.tangent", + "cullBackfaces"})) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index 75960d618..3921466f3 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -63,7 +63,15 @@ void SDF::commitParameters() void SDF::finalize() { - if (!beginPreparation()) + if (!beginPreparation({"primitive.sdf", + "primitive.neighbor", + "epsilon", + "nbMarchIterations", + "blendFactor", + "blendLerpFactor", + "omega", + "distanceFromCamera", + "noiseFactor"})) return; if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index f87aab5f1..8cf884685 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -51,7 +51,8 @@ void Sphere::commitParameters() void Sphere::finalize() { - if (!beginPreparation()) + if (!beginPreparation( + {"primitive.index", "vertex.position", "vertex.radius", "radius"})) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index 0ebddc73c..5bc8c3922 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -76,7 +76,18 @@ void Triangle::commitParameters() void Triangle::finalize() { - if (!beginPreparation()) + if (!beginPreparation({"primitive.index", + "vertex.position", + "vertex.normal", + "faceVarying.normal", + "vertex.tangent", + "faceVarying.tangent", + "cullBackfaces", + "faceVarying.attribute0", + "faceVarying.attribute1", + "faceVarying.attribute2", + "faceVarying.attribute3", + "faceVarying.color"})) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md new file mode 100644 index 000000000..4daa88786 --- /dev/null +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -0,0 +1,96 @@ +# Preparation-preserving geometry updates + +## Terminology + +A **geometry-wide attribute** supplies one value for the entire geometry: +`attribute0`–`attribute3` or `color`, rather than a per-vertex or per-primitive +attribute array. The storage/shading representation may still call these values +*uniform attributes*; that term describes their scope, not an update strategy. + +A **preparation-preserving update** reuses successfully prepared geometry because +its preparation inputs are unchanged. Geometry-wide attribute edits can take +this path, but not if coalesced with an input change or applied to a failed +preparation. A scalar parameter such as `radius` is still a preparation input. + +## Scope + +Triangle, quad, sphere, curve, cone, cylinder, and SDF geometries opt into a +preparation-preserving finalization path. Changing only geometry-wide attributes +republishes the geometry registry slot without regenerating tangents, indices, +radii, bounds, or area CDFs, and without invalidating the surface BLAS timestamp. +Normal object-finalization timestamps still advance, so automatic accumulation +reset remains intact. No stream or synchronization policy is changed; the +existing input-retirement check still runs on a parameter commit. + +This is deliberately not general fine-grained invalidation. Any changed +preparation input takes the existing full preparation path, including shading +arrays and scalar/string parameters that could be narrowed further later. +Isosurfaces, optional neural geometry, and unknown geometries retain their +existing full-preparation behavior; they do not opt in. + +## Reuse contract + +`Geometry::beginPreparation(parameters)` is the opt-in seam. A subtype must list +**every consumed parameter except geometry-wide attributes**, including inputs +read lazily by tangent generation or `gpuData()`. These are the subtype's +preparation inputs. The base adds primitive and vertex +attribute arrays and primitive IDs. When adding a subtype parameter, update its +list or keep that subtype on the default conservative path. + +The helper compares committed parameter values, not live staging iterators. +For referenced arrays it also records object update/finalization timestamps, +data modification timestamp, and device backing pointer. Consequently: + +- Changed handles, values, logical ranges, or backing pointers invalidate reuse. +- A geometry-wide attribute commit coalesced with an array unmap or + privatization cannot hide it. +- Observer-only finalization always follows the full preparation path. +- Missing/invalid initial data and previously failed preparation cannot reuse + uninitialized or failed derived state. +- Reuse becomes eligible only after a valid, successful geometry upload. + +Only present parameters occupy snapshot storage. The cached `AnariAny` values +retain internal references to the current input objects until replacement or +geometry destruction; they do not copy authored data. This also prevents cached +parameter identity from becoming a dangling object pointer. The extra reference +lifetime is intentional; old snapshot references are dropped on the next full +preparation after the existing retirement check. + +Geometry-wide attribute values are excluded because they do not change geometric +area or bounds. +Geometry Light synthesis uses the material's emission estimate, while sampled +attribute-driven radiance reads the updated geometry registry data at rendering +time. Material changes continue to use their existing light-set invalidation. + +## Correctness checks + +`TestGeometryPreparationReuse` exercises seven types with host and shared-device +inputs. It verifies all five geometry-wide attributes and their removal against +the initial full-preparation rendering, stable bounds, and no preparation/BVH-build diagnostic +messages. Debug rendering modulates attributes by geometric facing, so the initial +full-preparation image is the exact per-shape reference, with a separate nonzero +control. Scalar/string edits, array ranges, in-place host unmaps, and device-array +privatization act as positive controls requiring preparation and BVH rebuilding. + +The test also stages an input removal **after** a geometry-wide attribute commit: +that uncommitted edit must not leak into the committed update. Emissive materials request area data +where supported. Existing numeric-failure tests additionally verify that a +geometry-wide attribute commit cannot rehabilitate a failed generation. + +## Local performance checks + +Use the [benchmark skill](../../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) +to compare against a revision before the optimization with matched builds. +Measure `small-recommit` for bounds/BVH readiness and add +`--extra-case reuse-render:32:64:recommit:1` for registry publication and a +completed render. Keep replacement and unchanged-frame cases as guards. +The [benchmark guide](geometry-preprocessing-performance.md) defines the timed +boundaries and local result interpretation; no historical baseline is required. + +## Remaining work + +Broader array/shading invalidation precision, avoiding retirement waits when no +ownership changes, batched readback/dispatch, and fine-grained area-vs-bounds +invalidation are separate improvements. This change does not repack or download +inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs +are prepared on the GPU before their derived data is published. From 49d1a6d570154d1ee89bd540ba5a55732e572916 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:43:41 +0000 Subject: [PATCH 03/20] perf(rtx): add local preprocessing comparisons --- .../benchmark-geometry-preprocessing/SKILL.md | 87 ++++++ devices/rtx/AGENTS.md | 4 + .../apps/tests/api/BenchmarkCudaOrdering.cu | 90 ++++++ .../api/BenchmarkGeometryPreprocessing.cpp | 294 ++++++++++++++++++ devices/rtx/apps/tests/api/CMakeLists.txt | 5 + .../apps/tests/api/benchmark_preprocessing.py | 105 +++++++ .../geometry-preprocessing-performance.md | 101 ++++++ 7 files changed, 686 insertions(+) create mode 100644 .agents/skills/benchmark-geometry-preprocessing/SKILL.md create mode 100644 devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu create mode 100644 devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp create mode 100644 devices/rtx/apps/tests/api/benchmark_preprocessing.py create mode 100644 devices/rtx/docs/geometry-preprocessing-performance.md diff --git a/.agents/skills/benchmark-geometry-preprocessing/SKILL.md b/.agents/skills/benchmark-geometry-preprocessing/SKILL.md new file mode 100644 index 000000000..8cd3c0fc0 --- /dev/null +++ b/.agents/skills/benchmark-geometry-preprocessing/SKILL.md @@ -0,0 +1,87 @@ +--- +name: benchmark-geometry-preprocessing +description: Compare local before/after performance for RTX geometry preparation, preprocessing, BVH readiness or preparation-preserving updates. Use when assessing whether a development change improves end-to-end latency. +--- + +# Local geometry-preprocessing comparison + +Produce a terminal before/after comparison and a short assessment of whether the +change helps its intended workload. Results are local development feedback; +historical performance tracking is a separate CI concern. Run affected correctness +tests independently of timing. + +Repository paths below are relative to the checkout root. Timing definitions, +custom workload examples and optional profiling commands live in +`devices/rtx/docs/geometry-preprocessing-performance.md`; read it before choosing +workloads or interpreting numbers. + +## 1. Identify before and after + +Use the user's control revision; ask if unspecified. Keep the candidate intact +and create a separate control workspace using the checkout's VCS (`jj workspace +add` in a jj workspace, otherwise `git worktree add`). Record the control revision +and candidate revision/working-copy state in the local report. + +## 2. Build matched libraries + +Use identical compiler, CUDA, OptiX, architecture, build configuration, optional +components and library suffix on both sides. Prefer the host's existing build +recipe. A minimal single-configuration starting point, with dependencies already +available, is: + +```bash +cmake -S SOURCE -B BUILD -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DVISRTX_BUILD_GL_DEVICE=OFF -DVISRTX_ENABLE_MDL_SUPPORT=OFF \ + -DVISRTX_ENABLE_MATERIALX_SUPPORT=OFF -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared +``` + +Enable `VISRTX_BUILD_TESTS` in the candidate and build +`BenchmarkGeometryPreprocessing`; build `anari_library_visrtx` in the control. +One candidate executable runs against either ABI-compatible library, so the +control need not contain benchmark sources. If their ABIs differ, establish a +compatible harness/build pair before comparing. + +Locate the executable and directories containing the built shared libraries. +For multi-configuration builds include the configuration directory. Check both +loader resolutions, substituting each library directory: + +```bash +LD_LIBRARY_PATH=LIBRARY_DIR ldd BENCHMARK +``` + +Proceed only when each resolves the intended device library and a real CUDA +driver, not a toolkit link-time stub. Keep the remaining runtime environment the +same on both sides. + +## 3. Compare + +Start with the default cases, or a focused case when the user requests one: + +```bash +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK CONTROL_LIBRARY_DIR CANDIDATE_LIBRARY_DIR +``` + +Use `--help` for workload selection, geometry, device inputs and run budget. +The tool prints warm medians, trial ranges and candidate/control ratios. +A trailing JSON path before the options retains raw results in local scratch; +no output file is required. A nonzero exit or incomplete run is a failed +comparison. Resolve the failure rather than reporting its partial timing. + +## 4. Assess and stop + +Report the selected workloads, before/after medians, trial ranges and ratios. +Describe what improved, regressed or remains inconclusive, and the geometry/input +and rendering paths actually measured. Overlapping ranges warrant a focused +rerun with more trials if the distinction matters; they neither prove equality +nor establish a statistically significant effect. Avoid universal percentage +thresholds for noise on an uncontrolled host. + +For an apparent regression, rerun that case before drawing a conclusion. For a +claimed work-elimination speedup, use the optional trace recipe to check work +counts. Pair synchronization or memory-lifetime changes with relevant failure +and retirement tests; use Compute Sanitizer when those risks warrant it. + +Finish with a concise local assessment and any remaining uncertainty. Keep raw +results and captures outside the repository; this workflow does not create +versioned baselines, performance-history tables or CI acceptance thresholds. diff --git a/devices/rtx/AGENTS.md b/devices/rtx/AGENTS.md index e597deaa1..1a18e3f7f 100644 --- a/devices/rtx/AGENTS.md +++ b/devices/rtx/AGENTS.md @@ -12,6 +12,10 @@ The `devices/rtx/` subdirectory contains the OptiX-based GPU ray-tracing ANARI d - [`CONTEXT-MAP.md`](./CONTEXT-MAP.md) — bounded contexts and how they relate; each context has its own `CONTEXT.md` glossary ([Frontend](./device/CONTEXT.md), [Render Pipeline](./device/renderer/CONTEXT.md), [World](./device/world/CONTEXT.md), [MDL](./libmdl/CONTEXT.md)). Use these terms in code and docs. - [`docs/adr/`](./docs/adr/) — architecture decision records. Scan the directory and read the relevant one before "fixing" a design it locks in. +## Measuring geometry preparation + +Use the [`benchmark-geometry-preprocessing`](../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) skill for local before/after checks of geometry preparation or preparation-reuse performance. Timing contracts: [`docs/geometry-preprocessing-performance.md`](./docs/geometry-preprocessing-performance.md). Keep one-off results in local scratch; historical tracking belongs in a separate CI workflow. + ## Build Built as part of the repository build — see the repo-root [AGENTS.md](../../AGENTS.md). `CMAKE_PREFIX_PATH` must locate the ANARI-SDK and OptiX. diff --git a/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu b/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu new file mode 100644 index 000000000..d0569f264 --- /dev/null +++ b/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Manual semantics probe, not a timing assertion. Uses the same legacy-default +// stream compilation mode as the device. Never change production ordering based +// only on this probe: pageable copies and readbacks impose additional edges. +#include +#include +#include +#include +#include + +static void check(cudaError_t error) +{ + if (error != cudaSuccess) { + fprintf(stderr, "%s\n", cudaGetErrorString(error)); + std::exit(1); + } +} + +__global__ void delay(unsigned long long cycles) +{ + const auto start = clock64(); + while (clock64() - start < cycles) { + } +} + +int main() +{ + int clockRate = 0; + check(cudaDeviceGetAttribute(&clockRate, cudaDevAttrClockRate, 0)); + // clockRate is kHz: about 30 ms, not a precision timing source. + const auto cycles = 30ull * clockRate; + check(cudaFree(nullptr)); + for (unsigned flags : + {unsigned(cudaStreamDefault), unsigned(cudaStreamNonBlocking)}) { + cudaStream_t stream; + cudaEvent_t done; + check(cudaStreamCreateWithFlags(&stream, flags)); + check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming)); + for (bool producerDefault : {true, false}) { + delay<<<1, 1, 0, producerDefault ? nullptr : stream>>>(cycles); + check(cudaGetLastError()); + // Record completion of an otherwise empty consumer stream. With legacy + // NULL-stream ordering this event cannot pass the blocking producer. + check(cudaEventRecord(done, producerDefault ? stream : nullptr)); + const auto start = std::chrono::steady_clock::now(); + check(cudaEventSynchronize(done)); + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + printf("flags=%s producer=%s consumer=%s consumer_wait_ms=%.3f\n", + flags == cudaStreamDefault ? "blocking" : "nonblocking", + producerDefault ? "default" : "work", + producerDefault ? "work" : "default", + ms); + check(cudaDeviceSynchronize()); + } + check(cudaEventDestroy(done)); + check(cudaStreamDestroy(stream)); + } +} diff --git a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp new file mode 100644 index 000000000..a1270c532 --- /dev/null +++ b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Manual evidence tool, deliberately not a wall-clock CTest assertion. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static std::atomic completions{0}; +static void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} +int main(int argc, char **argv) +{ + if (argc < 5 || argc > 10) { + fprintf(stderr, + "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged] [frames:0=bounds] [emissive:0|1]\n", + argv[0]); + return 2; + } + const std::string type = argv[1]; + const size_t n = std::stoull(argv[2]); + const bool device = std::atoi(argv[3]) != 0; + const int repeats = std::atoi(argv[4]); + const int sharedSurfaces = argc >= 6 ? std::atoi(argv[5]) : 1; + const int distinctGeometries = argc >= 7 ? std::atoi(argv[6]) : 1; + const std::string mode = argc >= 8 ? argv[7] : "recommit"; + const int numFrames = argc >= 9 ? std::atoi(argv[8]) : 0; + const bool emissive = argc >= 10 ? std::atoi(argv[9]) != 0 : true; + if (!n || repeats < 2 || sharedSurfaces < 1 || distinctGeometries < 1 + || numFrames < 0 + || (mode != "recommit" && mode != "replace" && mode != "unchanged") + || (type != "triangle" && type != "sphere" && type != "cone" + && type != "cylinder" && type != "quad" && type != "curve" + && type != "sdf")) + return 2; + auto d = makeVisRTXDevice(status); + const auto setupStart = std::chrono::steady_clock::now(); + std::vector geometries; + std::vector positions; + std::vector radii; + std::vector sphereIndices; + std::vector> tubeIndices; + std::vector> triIndices; + std::vector> quadIndices; + std::vector sdf; + for (size_t i = 0; i < n; ++i) { + const float x = float(i % 256) * 0.04f, y = float(i / 256) * 0.04f; + const unsigned base = unsigned(positions.size()); + if (type == "triangle" || type == "quad") { + positions.push_back({x, y, 0}); + positions.push_back({x + 0.02f, y, 0}); + positions.push_back({x + 0.02f, y + 0.02f, 0}); + if (type == "quad") { + positions.push_back({x, y + 0.02f, 0}); + quadIndices.push_back({base, base + 1, base + 2, base + 3}); + } else + triIndices.push_back({base, base + 1, base + 2}); + } else if (type == "sphere") { + positions.push_back({x, y, 0}); + radii.push_back(0.01f); + sphereIndices.push_back(base); + } else if (type == "sdf") { + const size_t offset = sdf.size(); + sdf.resize(offset + 72); + const vec3 center = {x, y, 0}; + const float radius = 0.01f; + std::memcpy(sdf.data() + offset + 20, center.data(), sizeof(center)); + std::memcpy(sdf.data() + offset + 44, &radius, sizeof(radius)); + std::memcpy(sdf.data() + offset + 48, &radius, sizeof(radius)); + } else { + positions.push_back({x, y, 0}); + positions.push_back({x + 0.02f, y, 0}); + tubeIndices.push_back({base, base + 1}); + radii.push_back(0.01f); + if (type != "cylinder") + radii.push_back(0.005f); + } + } + auto setInputs = [&](anari::Geometry geometry) { + if (type == "sdf") + setTestArray(d, geometry, "primitive.sdf", sdf, device, 0); + else + setTestArray(d, geometry, "vertex.position", positions, device, 0); + if (type == "triangle") + setTestArray(d, geometry, "primitive.index", triIndices, device, 0); + if (type == "quad") + setTestArray(d, geometry, "primitive.index", quadIndices, device, 0); + if (type == "sphere") + setTestArray(d, geometry, "primitive.index", sphereIndices, device, 0); + if (type == "cone" || type == "cylinder") + setTestArray(d, geometry, "primitive.index", tubeIndices, device, 0); + if (type != "curve" && !radii.empty()) + setTestArray(d, + geometry, + type == "cylinder" ? "primitive.radius" : "vertex.radius", + radii, + device, + 0); + if (type == "curve") + anari::setParameter(d, geometry, "radius", 0.01f); + anari::commitParameters(d, geometry); + }; + for (int i = 0; i < distinctGeometries; ++i) { + auto geometry = anari::newObject(d, type.c_str()); + setInputs(geometry); + geometries.push_back(geometry); + } + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter( + d, material, "emissive", emissive ? vec3{1, 1, 1} : vec3{0, 0, 0}); + anari::commitParameters(d, material); + std::vector surfaces; + for (auto geometry : geometries) + for (int i = 0; i < sharedSurfaces; ++i) { + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + surfaces.push_back(surface); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + for (auto surface : surfaces) + anari::release(d, surface); + anari::commitParameters(d, world); + std::vector frames; + for (int i = 0; i < numFrames; ++i) { + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "interactive"); + anari::setParameter(d, renderer, "sampleLimit", 0); + anari::setParameter(d, renderer, "pixelSamples", 1); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{64, 64}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::commitParameters(d, frame); + frames.push_back(frame); + } + // Bounds-only measures GPU-ready acceleration structures; render mode also + // includes registry publication and completed tracing. No pre-query in render + // mode: it would move update work outside the submission measurement. + double warm = 0; + for (int iteration = 0; iteration < repeats; ++iteration) { + const auto start = std::chrono::steady_clock::now(); + if (iteration > 0) { + for (auto geometry : geometries) { + if (mode == "replace") + setInputs(geometry); // Include allocation, staging, and H2D costs. + else if (mode == "recommit") { + anari::setParameter( + d, geometry, "attribute0", vec4{float(iteration), 0, 0, 0}); + anari::commitParameters(d, geometry); + } + } + } + for (auto frame : frames) + anari::render(d, frame); + const auto submitted = std::chrono::steady_clock::now(); + for (auto frame : frames) + anari::wait(d, frame); + std::array bounds{}; + const bool ok = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + const auto completed = std::chrono::steady_clock::now(); + const double ms = + std::chrono::duration(completed - start).count(); + if (!ok || errors || completions != (iteration + 1) * numFrames) + return 1; + // Validation is outside the timed interval. Never accept a skipped frame + // or non-finite output as a faster completed render. + for (auto frame : frames) { + int samples = 0; + if (!anari::getProperty(d, frame, "numSamples", samples) || samples < 1) { + fprintf( + stderr, "unexpected samples=%d iteration=%d\n", samples, iteration); + return 1; + } + auto pixels = anari::map(d, frame, "channel.color"); + if (!pixels.data) + return 1; + for (size_t i = 0; i < size_t(pixels.width) * pixels.height; ++i) + for (float value : pixels.data[i]) + if (!std::isfinite(value)) + return 1; + anari::unmap(d, frame, "channel.color"); + } + for (float value : bounds) + if (!std::isfinite(value)) + return 1; + printf("sample iteration=%d ms=%.6f submit_ms=%.6f\n", + iteration, + ms, + std::chrono::duration(submitted - start).count()); + if (iteration == 0) { + printf("first_ms=%.6f setup_to_ready_ms=%.6f\n", + ms, + std::chrono::duration(completed - setupStart) + .count()); + } else + warm += ms; + } + printf("mode=%s geometries=%d shared_surfaces=%d frames=%d emissive=%d\n", + mode.c_str(), + distinctGeometries, + sharedSurfaces, + numFrames, + emissive); + printf("type=%s count=%zu device=%d warm_rebuild_ms=%.6f repeats=%d\n", + type.c_str(), + n, + device, + warm / (repeats - 1), + repeats); + for (auto frame : frames) + anari::release(d, frame); + anari::release(d, world); + for (auto geometry : geometries) + anari::release(d, geometry); + anari::release(d, d); + return 0; +} diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index df7f5960f..6c4380380 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -80,6 +80,11 @@ target_link_libraries(TestSampleAddressing PRIVATE CUDA::cudart) set_tests_properties(TestSampleAddressing PROPERTIES TIMEOUT 120) make_test(TestPowerLightPickEnv) make_test(TestEmissiveGeometryLight) +add_executable(BenchmarkCudaOrdering BenchmarkCudaOrdering.cu) +target_link_libraries(BenchmarkCudaOrdering PRIVATE CUDA::cudart) +set_target_properties(BenchmarkCudaOrdering PROPERTIES CUDA_ARCHITECTURES "${CMAKE_CUDA_ARCHITECTURES}") +add_executable(BenchmarkGeometryPreprocessing BenchmarkGeometryPreprocessing.cpp) +target_link_libraries(BenchmarkGeometryPreprocessing PRIVATE anari_library_visrtx anari::anari_static CUDA::cudart) make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) diff --git a/devices/rtx/apps/tests/api/benchmark_preprocessing.py b/devices/rtx/apps/tests/api/benchmark_preprocessing.py new file mode 100644 index 000000000..d8d91c72a --- /dev/null +++ b/devices/rtx/apps/tests/api/benchmark_preprocessing.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Compare local before/after geometry-preparation latency (not a CI assertion). + +Run one harness against two ABI-compatible device libraries. Only the device +library path is injected; the environment must resolve a real CUDA driver. +Each trial is a fresh process; iteration zero is excluded from warm statistics. +Optional JSON output is local scratch, not a versioned performance baseline. +""" +import argparse +import json +import math +import os +from pathlib import Path +import re +import statistics +import subprocess + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument("executable") +p.add_argument("base_library_dir", help="before/control device library directory") +p.add_argument("branch_library_dir", help="after/candidate device library directory") +p.add_argument("output", type=Path, nargs="?", help="optional local JSON results path") +p.add_argument("--trials", type=int, default=3) +p.add_argument("--repeats", type=int, default=21) +p.add_argument("--geometry", default="cylinder", + choices=["triangle", "quad", "sphere", "curve", "cone", "cylinder", "sdf"]) +p.add_argument("--device", action="store_true", + help="use device-backed inputs; both libraries must support them") +p.add_argument("--case", action="append", default=[], metavar="NAME", + help="run only the named default case; repeatable") +p.add_argument("--extra-case", action="append", default=[], + metavar="NAME:COUNT:GEOMETRIES:MODE:FRAMES", + help="append a custom case; repeatable") +a = p.parse_args() +if a.trials < 2 or a.repeats < 3: + p.error("need at least two trials and three repetitions") +# name, primitive count per geometry, distinct geometries, update mode, frames +cases = [ + ("small-recommit", 32, 64, "recommit", 0), + ("small-replace", 32, 64, "replace", 0), + ("large-replace", 262144, 1, "replace", 0), + ("unchanged-frame", 32, 64, "unchanged", 1), + ("two-frames-replace", 32, 64, "replace", 2), +] +if a.case: + known = {c[0] for c in cases} + unknown = [n for n in a.case if n not in known] + if unknown: + p.error(f"unknown case(s) {unknown}; known: {sorted(known)}") + cases = [c for c in cases if c[0] in a.case] +for spec in a.extra_case: + try: + name, count, geometries, mode, frames = spec.split(":") + case = (name, int(count), int(geometries), mode, int(frames)) + if (not name or case[1] < 1 or case[2] < 1 or case[4] < 0 + or mode not in {"recommit", "replace", "unchanged"} + or name in {c[0] for c in cases}): + raise ValueError() + cases.append(case) + except ValueError: + p.error(f"bad --extra-case {spec!r}; use a unique NAME, positive COUNT/GEOMETRIES, " + "recommit|replace|unchanged, and nonnegative FRAMES") +records = [] + + +def save(): + if a.output: + a.output.write_text(json.dumps(records, indent=2) + "\n") + + +print("Warm latency (ms): median of trial medians [min..max trial median]. " + "After/before < 1 is faster; ranges are not confidence intervals.", flush=True) +for name, count, geometries, mode, frames in cases: + for trial in range(a.trials): + order = ["base", "branch"] if trial % 2 == 0 else ["branch", "base"] + for revision in order: + env = os.environ.copy() + lib = a.base_library_dir if revision == "base" else a.branch_library_dir + env["LD_LIBRARY_PATH"] = os.pathsep.join( + filter(None, [lib, env.get("LD_LIBRARY_PATH")])) + command = [a.executable, a.geometry, str(count), str(int(a.device)), + str(a.repeats), "1", str(geometries), mode, str(frames), "1"] + run = subprocess.run(command, env=env, capture_output=True, text=True) + samples = [(int(i), float(ms)) for i, ms in re.findall( + r"sample iteration=(\d+) ms=([\d.]+)", run.stdout)] + record = dict(case=name, trial=trial, revision=revision, + command=command, library_dir=lib, returncode=run.returncode, + stdout=run.stdout, stderr=run.stderr) + records.append(record) + save() + if (run.returncode or len(samples) != a.repeats + or {i for i, ms in samples} != set(range(a.repeats)) + or any(not math.isfinite(ms) or ms < 0 for i, ms in samples)): + raise SystemExit(f"failed {name} {revision} (exit {run.returncode}):\n" + f"{run.stderr}\n{run.stdout}") + record["warm_median_ms"] = statistics.median(ms for i, ms in samples if i) + save() + medians = {rev: [r["warm_median_ms"] for r in records + if r["case"] == name and r["revision"] == rev] + for rev in ["base", "branch"]} + before, after = (statistics.median(medians[rev]) for rev in ["base", "branch"]) + ratio = f"{after / before:.3f}" if before else "n/a" + ranges = [f"{statistics.median(values):.4f} [{min(values):.4f}..{max(values):.4f}]" + for values in medians.values()] + print(f"{name}: before={ranges[0]} after={ranges[1]} after/before={ratio}", flush=True) diff --git a/devices/rtx/docs/geometry-preprocessing-performance.md b/devices/rtx/docs/geometry-preprocessing-performance.md new file mode 100644 index 000000000..1df5bf965 --- /dev/null +++ b/devices/rtx/docs/geometry-preprocessing-performance.md @@ -0,0 +1,101 @@ +# Local geometry-preprocessing benchmarks + +Use this tool to assess whether a development change improves end-to-end latency +on your machine. It is a manual before/after helper, not a performance regression +CTest or a historical baseline. Performance evolution tracking belongs in a +separate controlled CI job; this tool does not establish that infrastructure. + +## Quick comparison + +Build `BenchmarkGeometryPreprocessing` in the candidate and `anari_library_visrtx` +in a separate control workspace, with matching compiler, CUDA, OptiX, architecture, +optional-component settings and library suffix. The same benchmark executable +loads either ABI-compatible device library. The control needs no benchmark code. +Use the project [benchmark skill](../../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) +for workspace/build preparation and interpretation. + +```bash +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + CANDIDATE_BUILD/BenchmarkGeometryPreprocessing \ + CONTROL_LIBRARY_DIR CANDIDATE_LIBRARY_DIR +``` + +Pass the directories **containing the shared libraries**, not an install prefix. +For a multi-configuration build these may be `BUILD/RelWithDebInfo`. Verify with +`LD_LIBRARY_PATH=LIBRARY_DIR ldd BENCHMARK` that each side loads the intended +library and a real CUDA driver, rather than a toolkit link-time driver stub. + +The runner prints before/after warm medians, trial-median ranges, and ratios. +Defaults cover small recommits, small/large input replacement, unchanged rendering, +and two completed frames after replacement. It alternates order across fresh +process trials. Run `--help` for controls. Examples: + +```bash +# Focus on a preparation-reuse change. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB --case small-recommit + +# Include a completed frame and use another geometry family. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB --case unchanged-frame \ + --extra-case reuse-render:32:64:recommit:1 --geometry triangle + +# Longer comparison with optional local raw output. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB /tmp/preprocessing-comparison.json \ + --trials 6 --repeats 101 +``` + +The optional JSON contains commands, library paths, stdout/stderr and trial +medians. It is written incrementally: a failed command leaves partial results, +not a successful comparison. Keep results and profiler captures in local scratch. +Record revision IDs and environment alongside local results when needed to +interpret them; do not add one-off evidence files or result tables to the repo. + +## Workload and timing contract + +The executable can also run one workload directly: + +```text +BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ + [SHARED_SURFACES] [DISTINCT_GEOMETRIES] \ + [recommit|replace|unchanged] [FRAMES:0=bounds] [EMISSIVE:0|1] +``` + +- COUNT is primitives **per geometry**. The paired runner uses emissive geometry, + one surface per geometry and host inputs by default. `--device` requires device + input support on both revisions; unsupported input paths are not comparisons. +- `recommit` changes a geometry-wide attribute; `replace` replaces inputs, including + allocation, host staging, application H2D copy and parameter installation in + the measured interval; `unchanged` retains the initial inputs. +- FRAMES=0 ends at completed bounds/BVH readiness. FRAMES>0 includes submission + and completion of all frames, registry publication and tracing, then bounds. + Multiple frames share one device/world; this is not a concurrency benchmark. +- Initial setup is outside each iteration's timer. `setup_to_ready_ms` also + includes fixture generation and initial input setup, but not device creation. + Iteration zero is reported separately and excluded from warm statistics. +- The runner reports the median of per-process warm medians and their range. + Ranges are not confidence intervals. Thermal state, clocks and system load + affect results; rerun suspicious cases before attributing a delta to code. +- DEVICE=1 stages host fixtures to the GPU. It does not model an upstream GPU + producer or prove that real GPU-produced input needs an H2D copy. +- The harness checks finite bounds/images, sample counts and frame completion + outside the timed interval. These guard against skipped work, not radiometric + equivalence. Run the affected correctness tests separately. + +## Optional investigation + +Profile only when timing leaves an explanatory question: + +```bash +nsys profile --trace=cuda --sample=none -o /tmp/preprocessing-trace \ + env LD_LIBRARY_PATH=LIBRARY_DIR \ + BENCHMARK cylinder 32 0 6 1 64 recommit 1 1 +nsys stats --report cuda_api_sum,cuda_gpu_mem_size_sum /tmp/preprocessing-trace.nsys-rep +``` + +Compare work counts when claiming work elimination. Profiled whole-process totals +include initialization and teardown and are not comparable to unprofiled warm +latencies. `BenchmarkCudaOrdering` is an optional stream-ordering probe, not an +end-to-end timing or correctness test. Synchronization changes must still protect +input retirement, host readbacks and publication; timing cannot establish safety. From 9f9f13032dbaf8bba89861cbe7f20795f21efa67 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:29:44 +0000 Subject: [PATCH 04/20] perf(rtx): skip retirement waits for preparation-preserving updates --- .../api/BenchmarkGeometryPreprocessing.cpp | 38 +++++++++- .../tests/api/TestCudaPreparationFailure.cpp | 17 +++++ devices/rtx/device/geometry/Geometry.cpp | 76 ++++++++++++++----- devices/rtx/device/geometry/Geometry.h | 7 +- .../rtx/docs/geometry-preparation-reuse.md | 20 +++-- .../geometry-preprocessing-performance.md | 9 ++- 6 files changed, 138 insertions(+), 29 deletions(-) diff --git a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp index a1270c532..b148bec74 100644 --- a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp +++ b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp @@ -67,7 +67,7 @@ int main(int argc, char **argv) { if (argc < 5 || argc > 10) { fprintf(stderr, - "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged] [frames:0=bounds] [emissive:0|1]\n", + "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged|overlap] [frames:0=bounds] [emissive:0|1]\n", argv[0]); return 2; } @@ -82,7 +82,9 @@ int main(int argc, char **argv) const bool emissive = argc >= 10 ? std::atoi(argv[9]) != 0 : true; if (!n || repeats < 2 || sharedSurfaces < 1 || distinctGeometries < 1 || numFrames < 0 - || (mode != "recommit" && mode != "replace" && mode != "unchanged") + || (mode != "recommit" && mode != "replace" && mode != "unchanged" + && mode != "overlap") + || (mode == "overlap" && numFrames != 1) || (type != "triangle" && type != "sphere" && type != "cone" && type != "cylinder" && type != "quad" && type != "curve" && type != "sdf")) @@ -187,10 +189,13 @@ int main(int argc, char **argv) anari::commitParameters(d, camera); auto renderer = anari::newObject(d, "interactive"); anari::setParameter(d, renderer, "sampleLimit", 0); - anari::setParameter(d, renderer, "pixelSamples", 1); + anari::setParameter( + d, renderer, "pixelSamples", mode == "overlap" ? 32 : 1); anari::commitParameters(d, renderer); auto frame = anari::newObject(d); - anari::setParameter(d, frame, "size", std::array{64, 64}); + const unsigned resolution = mode == "overlap" ? 1024 : 64; + anari::setParameter( + d, frame, "size", std::array{resolution, resolution}); anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); anari::setParameter(d, frame, "world", world); ANARIFrameCompletionCallback callback = complete; @@ -224,6 +229,31 @@ int main(int argc, char **argv) for (auto frame : frames) anari::render(d, frame); const auto submitted = std::chrono::steady_clock::now(); + if (mode == "overlap") { + for (auto geometry : geometries) { + anari::setParameter( + d, geometry, "attribute0", vec4{float(iteration), 0, 0, 0}); + anari::commitParameters(d, geometry); + } + std::array overlapBounds{}; + const auto queryStart = std::chrono::steady_clock::now(); + if (!anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + overlapBounds.data(), + sizeof(overlapBounds), + ANARI_WAIT)) + return 1; + const auto queryEnd = std::chrono::steady_clock::now(); + for (float value : overlapBounds) + if (!std::isfinite(value)) + return 1; + printf("overlap iteration=%d query_ms=%.6f\n", + iteration, + std::chrono::duration(queryEnd - queryStart) + .count()); + } for (auto frame : frames) anari::wait(d, frame); std::array bounds{}; diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index e4b68726a..5969a9178 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -267,6 +267,23 @@ int main(int argc, char **argv) anari::render(d, frame); anari::wait(d, frame); ok = completions == 1 && errors == beforeErrors && ok; + if (sphereFailure) { + // Preparation-preserving bounds queries must not drain the work stream. + // Leave the injection armed, then change radius to require the fence. + failure = Failure::WORK_SYNC; + anari::setParameter( + d, geometry, "color", std::array{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = haveBounds() && injections == 1 && errors == beforeErrors && ok; + anari::setParameter(d, geometry, "radius", 0.3f); + anari::commitParameters(d, geometry); + ok = !haveBounds() && injections == 2 && errors > beforeErrors && ok; + const int retirementErrors = errors; + // Change the value to force a retry through deferred commit processing. + anari::setParameter(d, geometry, "radius", 0.4f); + anari::commitParameters(d, geometry); + ok = haveBounds() && errors == retirementErrors && ok; + } anari::release(d, array); } else { ok = haveBounds() && ok; diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 45b3a4424..11f4645fe 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -116,9 +116,10 @@ void Geometry::commitParameters() // Array observers can re-finalize without a parameter commit, but parameter // replacement can release the last reference to an aliased device array. // Complete earlier consumers before subclasses replace those references. - m_inputRetirementFailed = !checkPreparation(this, - cudaStreamSynchronize(deviceState()->stream), - "retiring previous geometry inputs"); + m_inputRetirementFailed = !canRetainPreparationInputs() + && !checkPreparation(this, + cudaStreamSynchronize(deviceState()->stream), + "retiring previous geometry inputs"); commitAttributes("primitive.", m_primitiveAttributes); auto getUniformAttribute = @@ -158,6 +159,41 @@ bool Geometry::PreparationParameter::operator==( && modified == other.modified && devicePointer == other.devicePointer; } +bool Geometry::canRetainPreparationInputs() const +{ + if (!m_hasPreparedData || preparationFailed() || m_inputRetirementFailed + || m_preparationParameterNames.empty()) + return false; + + // Inspect committed values only, before subclasses replace their references. + // Do not call dataGPU(): it can upload/replace storage. Pointer validation + // remains in beginPreparation(), after references have been retained safely. + size_t present = 0; + for (size_t i = 0; i < m_preparationParameterNames.size(); ++i) { + const auto value = getParamDirect(m_preparationParameterNames[i]); + if (!value.valid()) + continue; + if (present == m_preparedParameters.size()) + return false; + const auto &previous = m_preparedParameters[present++]; + if (previous.parameterIndex != i || !(previous.value == value)) + return false; + if (anari::isObject(value.type())) { + auto *object = value.getObject(); + if (object) { + if (previous.updated != object->lastUpdated() + || previous.finalized != object->lastFinalized()) + return false; + if (auto *array = dynamic_cast(object)) { + if (previous.modified != array->lastDataModified()) + return false; + } + } + } + } + return present == m_preparedParameters.size(); +} + void Geometry::upload() { RegisteredObject::upload(); @@ -172,9 +208,27 @@ bool Geometry::beginPreparation(std::initializer_list parameters) std::vector current; if (parameters.size() != 0) { + // Subtype declarations are fixed. Keep the lookup names across commits + // instead of allocating/copying their strings on every finalization. + if (m_preparationParameterNames.empty()) { + for (const char *name : {"primitive.attribute0", + "primitive.attribute1", + "primitive.attribute2", + "primitive.attribute3", + "primitive.color", + "primitive.id", + "vertex.attribute0", + "vertex.attribute1", + "vertex.attribute2", + "vertex.attribute3", + "vertex.color"}) + m_preparationParameterNames.emplace_back(name); + for (const char *name : parameters) + m_preparationParameterNames.emplace_back(name); + } current.reserve(m_preparedParameters.size()); size_t parameterIndex = 0; - auto append = [&](const char *name) { + auto append = [&](const std::string &name) { PreparationParameter parameter; parameter.parameterIndex = parameterIndex++; parameter.value = getParamDirect(name); // committed snapshot, not staging @@ -195,19 +249,7 @@ bool Geometry::beginPreparation(std::initializer_list parameters) } current.push_back(std::move(parameter)); }; - for (const char *name : {"primitive.attribute0", - "primitive.attribute1", - "primitive.attribute2", - "primitive.attribute3", - "primitive.color", - "primitive.id", - "vertex.attribute0", - "vertex.attribute1", - "vertex.attribute2", - "vertex.attribute3", - "vertex.color"}) - append(name); - for (const char *name : parameters) + for (const auto &name : m_preparationParameterNames) append(name); // Observer-only updates always take the preparation path. A geometry-wide diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index deea52d2f..4f9e7d504 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -38,6 +38,7 @@ // std #include #include +#include #include namespace visrtx { @@ -93,7 +94,8 @@ struct Geometry : public RegisteredObject protected: // Opt-in preparation reuse: list every subtype parameter except the five - // geometry-wide attributes. The base adds primitive and vertex arrays. + // geometry-wide attributes. This declaration must stay fixed for the subtype; + // lookup names are cached. The base adds primitive and vertex arrays. // Returns false after preparation reuse and registry publication, or if // preparation cannot start. bool beginPreparation(std::initializer_list parameters = {}); @@ -123,7 +125,10 @@ struct Geometry : public RegisteredObject bool operator==(const PreparationParameter &other) const; }; + bool canRetainPreparationInputs() const; + std::vector m_preparedParameters; + std::vector m_preparationParameterNames; bool m_hasPreparedData{false}; bool m_preparationPreserved{false}; bool m_preparationFailed{false}; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 4daa88786..fb842b5a2 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -19,8 +19,15 @@ preparation-preserving finalization path. Changing only geometry-wide attributes republishes the geometry registry slot without regenerating tangents, indices, radii, bounds, or area CDFs, and without invalidating the surface BLAS timestamp. Normal object-finalization timestamps still advance, so automatic accumulation -reset remains intact. No stream or synchronization policy is changed; the -existing input-retirement check still runs on a parameter commit. +reset remains intact. Before replacing parameter references, the input-retirement +check compares the declared committed preparation inputs and referenced-object +versions with the last successful preparation. Unchanged inputs skip the work- +stream wait; first preparation, changed inputs, failed preparation, and non-opt-in +types retain it. This check performs no GPU uploads. Parameter lookup names are +cached once per geometry rather than rebuilt on every finalization. Finalization +still revalidates values, object versions, and backing pointers before reusing +derived data: dependencies can be updated between commit and finalization, so the +earlier retirement verdict is not a reusable preparation verdict. This is deliberately not general fine-grained invalidation. Any changed preparation input takes the existing full preparation path, including shading @@ -35,7 +42,8 @@ existing full-preparation behavior; they do not opt in. read lazily by tangent generation or `gpuData()`. These are the subtype's preparation inputs. The base adds primitive and vertex attribute arrays and primitive IDs. When adding a subtype parameter, update its -list or keep that subtype on the default conservative path. +list or keep that subtype on the default conservative path. The declaration is +fixed per subtype; do not conditionally add/remove names based on current values. The helper compares committed parameter values, not live staging iterators. For referenced arrays it also records object update/finalization timestamps, @@ -54,7 +62,7 @@ retain internal references to the current input objects until replacement or geometry destruction; they do not copy authored data. This also prevents cached parameter identity from becoming a dangling object pointer. The extra reference lifetime is intentional; old snapshot references are dropped on the next full -preparation after the existing retirement check. +preparation after the retirement check. Geometry-wide attribute values are excluded because they do not change geometric area or bounds. @@ -89,8 +97,8 @@ boundaries and local result interpretation; no historical baseline is required. ## Remaining work -Broader array/shading invalidation precision, avoiding retirement waits when no -ownership changes, batched readback/dispatch, and fine-grained area-vs-bounds +Broader array/shading invalidation precision, reducing the extra CPU snapshot +comparison cost, batched readback/dispatch, and fine-grained area-vs-bounds invalidation are separate improvements. This change does not repack or download inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs are prepared on the GPU before their derived data is published. diff --git a/devices/rtx/docs/geometry-preprocessing-performance.md b/devices/rtx/docs/geometry-preprocessing-performance.md index 1df5bf965..fab99a0de 100644 --- a/devices/rtx/docs/geometry-preprocessing-performance.md +++ b/devices/rtx/docs/geometry-preprocessing-performance.md @@ -59,7 +59,7 @@ The executable can also run one workload directly: ```text BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ [SHARED_SURFACES] [DISTINCT_GEOMETRIES] \ - [recommit|replace|unchanged] [FRAMES:0=bounds] [EMISSIVE:0|1] + [recommit|replace|unchanged|overlap] [FRAMES:0=bounds] [EMISSIVE:0|1] ``` - COUNT is primitives **per geometry**. The paired runner uses emissive geometry, @@ -71,6 +71,13 @@ BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ - FRAMES=0 ends at completed bounds/BVH readiness. FRAMES>0 includes submission and completion of all frames, registry publication and tracing, then bounds. Multiple frames share one device/world; this is not a concurrency benchmark. +- `overlap` requires FRAMES=1 and uses a 1024x1024 frame with 32 pixel samples. + It submits rendering, commits geometry-wide attribute updates, then queries bounds before + waiting for the frame. `overlap ... query_ms` measures the bounds query alone; + `sample ... ms` still includes completed rendering. This isolates CPU blocking + on an outstanding frame, not a rendering-throughput improvement. Run it + directly (the paired runner does not summarize query latency): + `BENCHMARK cylinder 32 0 11 1 64 overlap 1 1`. - Initial setup is outside each iteration's timer. `setup_to_ready_ms` also includes fixture generation and initial input setup, but not device creation. Iteration zero is reported separately and excluded from warm statistics. From 3f6b4238f01ed7867e45eacea7af3bc6f84605ab Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:40:49 +0000 Subject: [PATCH 05/20] perf(rtx): isolate geometry and BVH preparation Use a nonblocking preparation stream with explicit producer dependencies. Replace device-wide BVH barriers with stream-local completion, and block publication after failed builds while allowing retry. Retain render-consumer retirement waits until storage generations can be tracked independently. --- devices/rtx/apps/tests/api/CMakeLists.txt | 9 +- .../tests/api/TestCudaPreparationFailure.cpp | 95 ++++++++- .../apps/tests/api/TestPreparationStream.cpp | 153 +++++++++++++++ devices/rtx/device/VisRTXDevice.cpp | 8 + devices/rtx/device/geometry/Geometry.cpp | 7 +- devices/rtx/device/geometry/Preprocessing.cu | 37 ++-- devices/rtx/device/geometry/SDF.cpp | 2 +- devices/rtx/device/optix_visrtx.cpp | 185 +++++++++++------- devices/rtx/device/optix_visrtx.h | 4 +- .../rtx/device/utility/PreparationStream.h | 108 ++++++++++ devices/rtx/device/world/Group.cpp | 66 ++++--- devices/rtx/device/world/Group.h | 4 + devices/rtx/device/world/World.cpp | 55 ++++-- devices/rtx/device/world/World.h | 1 + .../rtx/docs/geometry-preparation-reuse.md | 35 ++++ 15 files changed, 635 insertions(+), 134 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestPreparationStream.cpp create mode 100644 devices/rtx/device/utility/PreparationStream.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 6c4380380..95bdec1bb 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -85,6 +85,9 @@ target_link_libraries(BenchmarkCudaOrdering PRIVATE CUDA::cudart) set_target_properties(BenchmarkCudaOrdering PROPERTIES CUDA_ARCHITECTURES "${CMAKE_CUDA_ARCHITECTURES}") add_executable(BenchmarkGeometryPreprocessing BenchmarkGeometryPreprocessing.cpp) target_link_libraries(BenchmarkGeometryPreprocessing PRIVATE anari_library_visrtx anari::anari_static CUDA::cudart) +add_executable(TestPreparationStream TestPreparationStream.cpp) +target_link_libraries(TestPreparationStream PRIVATE CUDA::cudart Threads::Threads) +add_test(NAME TestPreparationStream COMMAND TestPreparationStream) make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) @@ -103,10 +106,14 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) add_test(NAME TestIsosurfacePreparationRecovery COMMAND TestCudaPreparationFailure isosurface) - foreach(geometry sphere sphere-indexed) + foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency) add_test(NAME TestSpherePreparationRecovery_${geometry} COMMAND TestCudaPreparationFailure ${geometry}) endforeach() + foreach(failure bvh-copy bvh-sync tlas-sync) + add_test(NAME TestBvhPreparationRecovery_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() foreach(failure allocation copy work-sync copy-sync) add_test(NAME TestArrayPrivatizationFailure_${failure} COMMAND TestCudaPreparationFailure ${failure}) diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 5969a9178..a3bdc6f7a 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -51,8 +51,15 @@ enum class Failure ALLOCATION, COPY, WORK_SYNC, - COPY_SYNC + COPY_SYNC, + PREPARATION_SYNC, + PREPARATION_DEPENDENCY, + BVH_SYNC, + BVH_COPY }; +cudaStream_t preparationStream = nullptr; +bool bvhReadback = false; +int bvhReadbacksToSkip = 0; Failure failure = Failure::NONE; size_t allocationBytes = 0; int injections = 0; @@ -117,13 +124,56 @@ extern "C" cudaError_t cudaMemcpy( return next("cudaMemcpy")(dst, src, bytes, kind); } +extern "C" cudaError_t cudaStreamCreateWithFlags( + cudaStream_t *stream, unsigned flags) +{ + const auto result = next( + "cudaStreamCreateWithFlags")(stream, flags); + if (result == cudaSuccess && (flags & cudaStreamNonBlocking)) + preparationStream = *stream; + return result; +} + +extern "C" cudaError_t cudaStreamWaitEvent( + cudaStream_t stream, cudaEvent_t event, unsigned flags) +{ + if (stream == preparationStream && inject(Failure::PREPARATION_DEPENDENCY)) + return cudaErrorInvalidValue; + return next("cudaStreamWaitEvent")( + stream, event, flags); +} + +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + if (stream == preparationStream && kind == cudaMemcpyDeviceToHost + && bytes == 6 * sizeof(float) + && (failure == Failure::BVH_COPY || failure == Failure::BVH_SYNC)) { + if (bvhReadbacksToSkip) + --bvhReadbacksToSkip; + else { + if (inject(Failure::BVH_COPY)) + return cudaErrorInvalidValue; + bvhReadback = true; + } + } + return next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); +} + extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) { // Drain real work even when simulating a failed completion report. const auto result = next("cudaStreamSynchronize")(stream); if ((stream && inject(Failure::WORK_SYNC)) - || (!stream && inject(Failure::COPY_SYNC))) + || (!stream && inject(Failure::COPY_SYNC)) + || (stream == preparationStream && inject(Failure::PREPARATION_SYNC)) + || (stream == preparationStream && bvhReadback + && inject(Failure::BVH_SYNC))) return cudaErrorUnknown; return result; } @@ -132,9 +182,11 @@ int main(int argc, char **argv) { const bool isosurfaceFailure = argc > 1 && std::strcmp(argv[1], "isosurface") == 0; - const bool sphereFailure = argc > 1 - && (std::strcmp(argv[1], "sphere") == 0 - || std::strcmp(argv[1], "sphere-indexed") == 0); + const bool sphereFailure = + argc > 1 && std::strncmp(argv[1], "sphere", 6) == 0; + const bool bvhFailure = argc > 1 + && (std::strncmp(argv[1], "bvh-", 4) == 0 + || std::strcmp(argv[1], "tlas-sync") == 0); const bool curveFailure = argc == 1 || isosurfaceFailure || sphereFailure; auto d = makeVisRTXDevice(status); using vec3 = std::array; @@ -236,7 +288,34 @@ int main(int argc, char **argv) != 0; }; bool ok = errors == 0; - if (curveFailure) { + if (bvhFailure) { + const auto injected = std::strcmp(argv[1], "bvh-copy") == 0 + ? Failure::BVH_COPY + : Failure::BVH_SYNC; + bvhReadbacksToSkip = std::strcmp(argv[1], "tlas-sync") == 0 ? 1 : 0; + failure = injected; + ok = !haveBounds() && injections == 1 && errors > 0 && ok; + ok = !anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_NO_WAIT) + && ok; + failure = injected; + bvhReadback = false; + bvhReadbacksToSkip = 0; + anari::render(d, frame); + anari::wait(d, frame); + ok = injections == 2 && completions == 0 && ok; + const int beforeErrors = errors; + ok = haveBounds() && errors == beforeErrors && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == beforeErrors && ok; + anari::release(d, array); + } else if (curveFailure) { if (isosurfaceFailure) { ok = haveBounds() && ok; anari::setParameter(d, geometry, "isovalue", 2.5f); @@ -252,6 +331,10 @@ int main(int argc, char **argv) * 2 * sizeof(vec3) : 3 * sizeof(unsigned); failure = isosurfaceFailure ? Failure::WORK_SYNC : Failure::ALLOCATION; + if (sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) + failure = Failure::PREPARATION_SYNC; + if (sphereFailure && std::strcmp(argv[1], "sphere-dependency") == 0) + failure = Failure::PREPARATION_DEPENDENCY; ok = !haveBounds() && ok; // The unaffected sibling must not inherit the first geometry's OOM. // Recovery below must succeed without recommitting the sibling. diff --git a/devices/rtx/apps/tests/api/TestPreparationStream.cpp b/devices/rtx/apps/tests/api/TestPreparationStream.cpp new file mode 100644 index 000000000..45fc7c95b --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationStream.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/utility/PreparationStream.h" + +namespace { +struct Gate +{ + std::atomic released{false}; + std::atomic timedOut{false}; + std::mutex mutex; + std::condition_variable condition; +}; + +void CUDART_CB block(void *data) +{ + auto &gate = *static_cast(data); + while (!gate.released.load()) + std::this_thread::yield(); +} + +bool check(cudaError_t error) +{ + if (error == cudaSuccess) + return true; + std::fprintf(stderr, "%s\n", cudaGetErrorString(error)); + return false; +} +} // namespace + +int main() +{ + visrtx::PreparationStream preparation; + cudaStream_t other{}; + cudaEvent_t done{}; + int *device = nullptr; + if (!check(preparation.initialize()) + || !check(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking)) + || !check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming)) + || !check( + cudaMalloc(reinterpret_cast(&device), 2 * sizeof(int)))) + return 1; + unsigned flags = 0; + bool ok = check(cudaStreamGetFlags(preparation.stream(), &flags)) + && (flags & cudaStreamNonBlocking); + + // Exercise both explicit and legacy-default producers, plus independence + // from an unrelated nonblocking stream. All allocations precede gated work. + for (int mode : {0, 1, 2}) { + const bool dependency = mode != 0; + const cudaStream_t producer = mode == 2 ? nullptr : other; + ok = + check(cudaMemsetAsync(device, 0, 2 * sizeof(int), preparation.stream())) + && check(preparation.finish()) && ok; + Gate gate; + // Watchdog is a deadlock escape, not a latency assertion. A stream-wide + // or device-wide accidental wait must fail rather than hang the suite. + std::thread watchdog([&] { + std::unique_lock lock(gate.mutex); + if (!gate.condition.wait_for(lock, std::chrono::seconds(5), [&] { + return gate.released.load(); + })) { + gate.timedOut = true; + gate.released = true; + } + }); + ok = check(cudaLaunchHostFunc(producer, block, &gate)) && ok; + int result = 0; + if (dependency) { + ok = check(cudaMemsetAsync(device, 0x2a, sizeof(int), producer)) && ok; + ok = check(preparation.waitFor(producer)) && ok; + } else { + // Importing the default stream must not join an unrelated nonblocking + // stream. The mode above separately tests a pending default producer. + ok = check(preparation.waitFor(nullptr)) && ok; + ok = check( + cudaMemsetAsync(device, 0x2a, sizeof(int), preparation.stream())) + && ok; + } + // A real consumer distinguishes importing producer data from merely + // waiting for the stream later during host readback. + ok = check(cudaMemcpyAsync(device + 1, + device, + sizeof(int), + cudaMemcpyDeviceToDevice, + preparation.stream())) + && ok; + // Keep readback after releasing the gate: a pageable D2H copy itself may + // block the host and would obscure what the stream dependency test proves. + ok = check(cudaEventRecord(done, preparation.stream())) && ok; + if (dependency) + ok = cudaEventQuery(done) == cudaErrorNotReady && ok; + else { + ok = check(preparation.finish()) && ok; + ok = cudaStreamQuery(other) == cudaErrorNotReady && ok; + } + { + std::lock_guard lock(gate.mutex); + gate.released = true; + } + gate.condition.notify_one(); + watchdog.join(); + ok = !gate.timedOut && check(preparation.finish()) && ok; + ok = check(cudaMemcpyAsync(&result, + device + 1, + sizeof(result), + cudaMemcpyDeviceToHost, + preparation.stream())) + && check(preparation.finish()) && result == 0x2a2a2a2a && ok; + ok = check(cudaStreamSynchronize(producer)) && ok; + } + cudaFree(device); + cudaEventDestroy(done); + cudaStreamDestroy(other); + preparation.reset(); + std::printf("preparation stream dependencies: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 6eeb69b85..4d947fb5a 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -448,6 +448,7 @@ VisRTXDevice::~VisRTXDevice() optixModuleDestroy(state.intersectionModules.customIntersectors); + state.preparation.reset(); optixDeviceContextDestroy(state.optixContext); cudaStreamDestroy(state.stream); @@ -850,6 +851,13 @@ DeviceInitStatus VisRTXDevice::initOptix() &builtinISOptions, &state.intersectionModules.curveIntersector)); + const auto preparationStatus = state.preparation.initialize(); + if (preparationStatus != cudaSuccess) { + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "could not initialize preparation stream: %s", + cudaGetErrorString(preparationStatus)); + return DeviceInitStatus::FAILURE; + } return DeviceInitStatus::SUCCESS; } diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 11f4645fe..d12da2cb5 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -266,7 +266,12 @@ bool Geometry::beginPreparation(std::initializer_list parameters) m_preparedParameters = std::move(current); m_hasPreparedData = false; m_preparationFailed = false; - return true; + // Full preparation can overwrite derived buffers read by earlier frames. + // Keep that dependency on the GPU; parameter-reference retirement above + // still requires a host wait before releasing old application storage. + return checkPreparation(this, + deviceState()->preparation.waitFor(deviceState()->stream), + "previous geometry consumers"); } bool Geometry::preparationFailed() const diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index e3eb900fe..58d51b011 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -226,7 +226,10 @@ bool generateQuadIndices( if (!reservePreparation(g, out, 2 * n * sizeof(uvec3))) return false; if (n) - quadIndices<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( + quadIndices<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparation.stream()>>>( indices, n, out.ptrAs()); return finishPreparation(g); } @@ -238,8 +241,10 @@ bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) if (!reservePreparation(g, out, n * sizeof(uint32_t))) return false; if (n) - curveIndices<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( - n, out.ptrAs()); + curveIndices<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparation.stream()>>>(n, out.ptrAs()); return checkPreparation(g, cudaGetLastError(), "curve indices"); } @@ -250,7 +255,10 @@ bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) if (!reservePreparation(g, out, n * sizeof(float))) return false; if (n) - curveRadii<<<(n + 255) / 256, 256, 0, g->deviceState()->stream>>>( + curveRadii<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparation.stream()>>>( n, radius, out.ptrAs()); return checkPreparation(g, cudaGetLastError(), "curve radii"); } @@ -261,7 +269,10 @@ bool checkPreparation(Geometry *g, cudaError_t error, const char *operation) return true; g->setPreparationFailed(true); // A failed dispatch/readback can follow successful queued kernels. Drain - // their stream before callers can retry, resize, or retire owned storage. + // preparation before retrying or freeing scratch. Keep the render-stream + // drain on this error path too: this helper also handles input retirement + // and dependency failures, which may precede a successful producer edge. + g->deviceState()->preparation.finish(); cudaStreamSynchronize(g->deviceState()->stream); g->reportMessage(ANARI_SEVERITY_ERROR, "geometry preprocessing failed during %s: %s", @@ -292,18 +303,18 @@ bool waitForPreparationInputs(Geometry *g) { // Legacy Array uploads use synchronous cudaMemcpy on the default stream. // Pageable H2D may return after staging, not DMA completion: make that - // producer dependency explicit before launching on the device work stream. - return checkPreparation( - g, cudaStreamSynchronize(nullptr), "input upload completion"); + // producer dependency explicit before launching on the preparation stream. + return checkPreparation(g, + g->deviceState()->preparation.waitFor(nullptr), + "input upload dependency"); } bool finishPreparation(Geometry *g) { // Also establishes an explicit boundary for legacy default-stream consumers. return checkPreparation(g, cudaGetLastError(), "launch") - && checkPreparation(g, - cudaStreamSynchronize(g->deviceState()->stream), - "execution completion"); + && checkPreparation( + g, g->deviceState()->preparation.finish(), "execution completion"); } bool Preprocessing::bounds( @@ -311,7 +322,7 @@ bool Preprocessing::bounds( { if (!waitForPreparationInputs(g)) return false; - const auto stream = g->deviceState()->stream; + const auto stream = g->deviceState()->preparation.stream(); scale = 0.f; if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) || !reservePreparation(g, m_result, sizeof(Result)) @@ -353,7 +364,7 @@ bool Preprocessing::areas( } if (in.count > size_t(std::numeric_limits::max())) return checkPreparation(g, cudaErrorInvalidValue, "primitive count"); - const auto stream = g->deviceState()->stream; + const auto stream = g->deviceState()->preparation.stream(); size_t scratchBytes = 0; if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) || !reservePreparation(g, cdf, in.count * sizeof(float)) diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index 3921466f3..f221a820f 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -101,7 +101,7 @@ void SDF::finalize() source, bytes, cudaMemcpyDeviceToDevice, - deviceState()->stream), + deviceState()->preparation.stream()), "aligning SDF input")) return; m_primitives = m_alignedPrimitives.ptrAs(); diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 8bba46cfd..31ab39147 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -40,7 +40,7 @@ namespace visrtx { -void buildOptixBVH(std::vector buildInput, +bool buildOptixBVH(std::vector buildInput, DeviceBuffer &bvh, OptixTraversableHandle &traversable, box3 &bounds, @@ -48,82 +48,127 @@ void buildOptixBVH(std::vector buildInput, { traversable = {}; bounds = {}; - if (buildInput.empty()) { obj->reportMessage(ANARI_SEVERITY_DEBUG, "skipping BVH build"); - return; + return true; } auto &state = *obj->deviceState(); - - // TLAS setup // - - OptixAccelBuildOptions accelOptions{}; - accelOptions.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION; - accelOptions.operation = OPTIX_BUILD_OPERATION_BUILD; - - OptixAccelBufferSizes tlasBufferSizes; - OPTIX_CHECK_OBJECT(optixAccelComputeMemoryUsage(state.optixContext, - &accelOptions, - buildInput.data(), - buildInput.size(), - &tlasBufferSizes), - obj); - - // Prepare compaction // - - DeviceBuffer compactedSizeBuffer; - compactedSizeBuffer.reserve(sizeof(uint64_t)); - - OptixAccelEmitDesc emitDesc[2]; - emitDesc[0].type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; - emitDesc[0].result = (CUdeviceptr)compactedSizeBuffer.ptr(); - - DeviceBuffer aabbBuffer; - aabbBuffer.reserve(sizeof(box3)); - - emitDesc[1].type = OPTIX_PROPERTY_TYPE_AABBS; - emitDesc[1].result = (CUdeviceptr)aabbBuffer.ptr(); - - // Execute BVH build // - - DeviceBuffer tempBuffer; - tempBuffer.reserve(tlasBufferSizes.tempSizeInBytes); - - DeviceBuffer outputBuffer; - outputBuffer.reserve(tlasBufferSizes.outputSizeInBytes); - - OPTIX_CHECK_OBJECT(optixAccelBuild(state.optixContext, - state.stream, - &accelOptions, - buildInput.data(), - buildInput.size(), - (CUdeviceptr)tempBuffer.ptr(), - tempBuffer.bytes(), - (CUdeviceptr)outputBuffer.ptr(), - outputBuffer.bytes(), - &traversable, - emitDesc, - 2), - obj); - CUDA_SYNC_CHECK_OBJECT(obj); - - aabbBuffer.download(&bounds); - - // Perform compaction // - - uint64_t compactedSize; - compactedSizeBuffer.download(&compactedSize, 1); - - bvh.reserve(compactedSize); - OPTIX_CHECK_OBJECT(optixAccelCompact(state.optixContext, - state.stream, - traversable, + auto &preparation = state.preparation; + const auto stream = preparation.stream(); + auto check = [&](cudaError_t error, const char *operation) { + if (error == cudaSuccess) + return true; + preparation.finish(); // Drain queued consumers before scratch is freed. + cudaGetLastError(); + obj->reportMessage(ANARI_SEVERITY_ERROR, + "BVH preparation failed during %s: %s", + operation, + cudaGetErrorString(error)); + return false; + }; + auto checkOptix = [&](OptixResult result, const char *operation) { + if (result == OPTIX_SUCCESS) + return true; + preparation.finish(); + obj->reportMessage(ANARI_SEVERITY_ERROR, + "BVH preparation failed during %s: %s", + operation, + optixGetErrorName(result)); + return false; + }; + auto reserve = [&](DeviceBuffer &buffer, size_t bytes) { + if (!buffer) + buffer.reset(); + buffer.reserve(bytes); + const auto error = cudaGetLastError(); + return check(error != cudaSuccess ? error + : bytes && (!buffer || buffer.bytes() < bytes) + ? cudaErrorMemoryAllocation + : cudaSuccess, + "allocating device storage"); + }; + + // Legacy producers include field/isosurface work on the render stream and + // authored arrays/instance uploads on the default stream. Previous rendering + // must also finish before the existing BVH storage can be reused. + if (!check(preparation.waitFor(state.stream), "previous BVH consumers") + || !check(preparation.waitFor(nullptr), "input upload dependency")) + return false; + + OptixAccelBuildOptions options{}; + options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION; + options.operation = OPTIX_BUILD_OPERATION_BUILD; + OptixAccelBufferSizes sizes{}; + if (!checkOptix(optixAccelComputeMemoryUsage(state.optixContext, + &options, + buildInput.data(), + buildInput.size(), + &sizes), + "memory requirements")) + return false; + + DeviceBuffer compactedSizeBuffer, aabbBuffer, tempBuffer, outputBuffer; + if (!reserve(compactedSizeBuffer, sizeof(uint64_t)) + || !reserve(aabbBuffer, sizeof(box3)) + || !reserve(tempBuffer, sizes.tempSizeInBytes) + || !reserve(outputBuffer, sizes.outputSizeInBytes)) + return false; + + OptixAccelEmitDesc emit[2]{}; + emit[0].type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; + emit[0].result = (CUdeviceptr)compactedSizeBuffer.ptr(); + emit[1].type = OPTIX_PROPERTY_TYPE_AABBS; + emit[1].result = (CUdeviceptr)aabbBuffer.ptr(); + OptixTraversableHandle built{}; + if (!checkOptix(optixAccelBuild(state.optixContext, + stream, + &options, + buildInput.data(), + buildInput.size(), + (CUdeviceptr)tempBuffer.ptr(), + tempBuffer.bytes(), + (CUdeviceptr)outputBuffer.ptr(), + outputBuffer.bytes(), + &built, + emit, + 2), + "build")) + return false; + + box3 builtBounds; + uint64_t compactedSize = 0; + if (!check(cudaMemcpyAsync(&builtBounds, + aabbBuffer.ptr(), + sizeof(box3), + cudaMemcpyDeviceToHost, + stream), + "bounds readback") + || !check(cudaMemcpyAsync(&compactedSize, + compactedSizeBuffer.ptr(), + sizeof(compactedSize), + cudaMemcpyDeviceToHost, + stream), + "compaction size readback") + || !check(preparation.finish(), "build completion")) + return false; + + if (!reserve(bvh, compactedSize) + || !checkOptix(optixAccelCompact(state.optixContext, + stream, + built, (CUdeviceptr)bvh.ptr(), bvh.bytes(), - &traversable), - obj); - CUDA_SYNC_CHECK_OBJECT(obj); + &built), + "compaction") + || !check(preparation.finish(), "compaction completion")) + return false; + + // Publication and scratch destruction happen only after this stream's work + // completes. Subsequent tracing needs no device-wide barrier. + traversable = built; + bounds = builtBounds; + return true; } /////////////////////////////////////////////////////////////////////////////// diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 761bdf84e..ec5d82826 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -33,6 +33,7 @@ #include "gpu/gpu_objects.h" #include "utility/DeviceObjectArray.h" +#include "utility/PreparationStream.h" // helium #include "helium/BaseGlobalDeviceState.h" @@ -173,6 +174,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUcontext cudaContext; CUstream stream; + PreparationStream preparation; cudaDeviceProp deviceProps; OptixDeviceContext optixContext; @@ -269,7 +271,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState ~DeviceGlobalState() override; }; -void buildOptixBVH(std::vector buildInput, +bool buildOptixBVH(std::vector buildInput, DeviceBuffer &bvh, OptixTraversableHandle &traversable, box3 &bounds, diff --git a/devices/rtx/device/utility/PreparationStream.h b/devices/rtx/device/utility/PreparationStream.h new file mode 100644 index 000000000..22c7b4db7 --- /dev/null +++ b/devices/rtx/device/utility/PreparationStream.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include + +namespace visrtx { + +// Serialized by the device's scene-update path. GPU dependencies do not block +// the host; finish() is reserved for host readback/publication and scratch +// reuse. +struct PreparationStream +{ + PreparationStream() = default; + ~PreparationStream(); + PreparationStream(const PreparationStream &) = delete; + PreparationStream &operator=(const PreparationStream &) = delete; + + cudaError_t initialize(); + void reset(); + cudaStream_t stream() const; + cudaError_t waitFor(cudaStream_t producer); + cudaError_t finish(); + + private: + cudaStream_t m_stream{nullptr}; + cudaEvent_t m_dependency{nullptr}; +}; + +// Inlined definitions //////////////////////////////////////////////////////// + +inline PreparationStream::~PreparationStream() +{ + reset(); +} + +inline cudaError_t PreparationStream::initialize() +{ + if (m_stream) + return cudaSuccess; + auto error = cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking); + if (error == cudaSuccess) + error = cudaEventCreateWithFlags(&m_dependency, cudaEventDisableTiming); + if (error != cudaSuccess) + reset(); + return error; +} + +inline void PreparationStream::reset() +{ + if (m_stream) + cudaStreamSynchronize(m_stream); + if (m_dependency) + cudaEventDestroy(m_dependency); + if (m_stream) + cudaStreamDestroy(m_stream); + m_dependency = nullptr; + m_stream = nullptr; +} + +inline cudaStream_t PreparationStream::stream() const +{ + return m_stream; +} + +inline cudaError_t PreparationStream::waitFor(cudaStream_t producer) +{ + auto error = cudaEventRecord(m_dependency, producer); + if (error == cudaSuccess) + error = cudaStreamWaitEvent(m_stream, m_dependency, 0); + return error; +} + +inline cudaError_t PreparationStream::finish() +{ + return cudaStreamSynchronize(m_stream); +} + +} // namespace visrtx diff --git a/devices/rtx/device/world/Group.cpp b/devices/rtx/device/world/Group.cpp index a07f25784..6fba61a90 100644 --- a/devices/rtx/device/world/Group.cpp +++ b/devices/rtx/device/world/Group.cpp @@ -210,6 +210,12 @@ const std::vector &Group::surfacesUser() const } bool Group::preparationFailed() const +{ + return m_surfaceBuildFailed || m_volumeBuildFailed + || geometryPreparationFailed(); +} + +bool Group::geometryPreparationFailed() const { if (!m_surfaceData) return false; @@ -225,13 +231,14 @@ bool Group::preparationFailed() const void Group::rebuildSurfaceBVHs() { - if (preparationFailed()) + if (geometryPreparationFailed()) return; const auto &state = *deviceState(); if (state.objectUpdates.lastSurfaceBLASChange < m_objectUpdates.lastSurfaceBVHBuilt) return; + m_surfaceBuildFailed = false; partitionValidGeometriesByType(); m_triangleBounds = box3(); @@ -241,25 +248,22 @@ void Group::rebuildSurfaceBVHs() m_traversableCurve = {}; m_traversableUser = {}; - // populateBuildInput can trigger a first upload of an authored index array. - // Establish its default-stream producer edge before any BLAS consumes it. + // populateBuildInput can upload authored indices. The BVH builder imports + // those default-stream producers before submitting the build. auto triangles = createOBI(m_surfacesTriangle); auto curves = createOBI(m_surfacesCurve); auto users = createOBI(m_surfacesUser); - Surface *first = !m_surfacesTriangle.empty() ? m_surfacesTriangle.front() - : !m_surfacesCurve.empty() ? m_surfacesCurve.front() - : !m_surfacesUser.empty() ? m_surfacesUser.front() - : nullptr; - if (first && !waitForPreparationInputs(first->geometry())) - return; if (!m_surfacesTriangle.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building triangle BVH"); - buildOptixBVH(std::move(triangles), - m_bvhTriangle, - m_traversableTriangle, - m_triangleBounds, - this); + if (!buildOptixBVH(std::move(triangles), + m_bvhTriangle, + m_traversableTriangle, + m_triangleBounds, + this)) { + m_surfaceBuildFailed = true; + return; + } } else { reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping triangle BVH build"); @@ -267,8 +271,14 @@ void Group::rebuildSurfaceBVHs() if (!m_surfacesCurve.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building curve BVH"); - buildOptixBVH( - std::move(curves), m_bvhCurve, m_traversableCurve, m_curveBounds, this); + if (!buildOptixBVH(std::move(curves), + m_bvhCurve, + m_traversableCurve, + m_curveBounds, + this)) { + m_surfaceBuildFailed = true; + return; + } } else { reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping curve BVH build"); @@ -276,8 +286,14 @@ void Group::rebuildSurfaceBVHs() if (!m_surfacesUser.empty()) { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building user BVH"); - buildOptixBVH( - std::move(users), m_bvhUser, m_traversableUser, m_userBounds, this); + if (!buildOptixBVH(std::move(users), + m_bvhUser, + m_traversableUser, + m_userBounds, + this)) { + m_surfaceBuildFailed = true; + return; + } } else { reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping user BVH build"); @@ -295,6 +311,7 @@ void Group::rebuildVolumeBVH() < m_objectUpdates.lastVolumeBVHBuilt) return; + m_volumeBuildFailed = false; partitionValidVolumes(); if (m_volumes.empty()) { m_volumeBounds = box3(); @@ -306,11 +323,14 @@ void Group::rebuildVolumeBVH() } reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building volume BVH"); - buildOptixBVH(createOBI(m_volumes), - m_bvhVolume, - m_traversableVolume, - m_volumeBounds, - this); + if (!buildOptixBVH(createOBI(m_volumes), + m_bvhVolume, + m_traversableVolume, + m_volumeBounds, + this)) { + m_volumeBuildFailed = true; + return; + } buildVolumeGPUData(); diff --git a/devices/rtx/device/world/Group.h b/devices/rtx/device/world/Group.h index 5d18ab43d..bfcfbff1d 100644 --- a/devices/rtx/device/world/Group.h +++ b/devices/rtx/device/world/Group.h @@ -86,6 +86,7 @@ struct Group : public Object void rebuildLights(); private: + bool geometryPreparationFailed() const; void partitionValidGeometriesByType(); void partitionValidVolumes(); void partitionValidLights(); @@ -122,6 +123,9 @@ struct Group : public Object // BVH // + bool m_surfaceBuildFailed{false}; + bool m_volumeBuildFailed{false}; + struct ObjectUpdates { helium::TimeStamp lastSurfaceBVHBuilt{0}; diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index 0b275b7c0..583352405 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -253,6 +253,8 @@ WorldGPUData World::gpuData() const bool World::preparationFailed() const { + if (m_bvhBuildFailed) + return true; for (auto *instance : m_instances) { if (instance->group()->preparationFailed()) return true; @@ -262,6 +264,9 @@ bool World::preparationFailed() const void World::rebuildWorld() { + if (m_bvhBuildFailed) + m_objectUpdates.lastTLASBuild = 0; + m_bvhBuildFailed = false; const auto &state = *deviceState(); const auto &updates = state.objectUpdates; @@ -290,16 +295,21 @@ void World::rebuildWorld() if (preparationFailed()) return; buildLightProxies(); + if (preparationFailed()) + return; populateOptixInstances(); reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building surface BVH over %zu instances", m_optixSurfaceInstances.size()); - buildOptixBVH(createOBI(m_optixSurfaceInstances), - m_bvhSurfaces, - m_traversableSurfaces, - m_surfaceBounds, - this); + if (!buildOptixBVH(createOBI(m_optixSurfaceInstances), + m_bvhSurfaces, + m_traversableSurfaces, + m_surfaceBounds, + this)) { + m_bvhBuildFailed = true; + return; + } reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::World building surface gpu data"); buildInstanceSurfaceGPUData(); @@ -307,11 +317,14 @@ void World::rebuildWorld() reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building volume BVH over %zu instances", m_optixVolumeInstances.size()); - buildOptixBVH(createOBI(m_optixVolumeInstances), - m_bvhVolumes, - m_traversableVolumes, - m_volumeBounds, - this); + if (!buildOptixBVH(createOBI(m_optixVolumeInstances), + m_bvhVolumes, + m_traversableVolumes, + m_volumeBounds, + this)) { + m_bvhBuildFailed = true; + return; + } reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::World building volume gpu data"); buildInstanceVolumeGPUData(); @@ -319,6 +332,8 @@ void World::rebuildWorld() // Both TLASs have reported their bounds, so the extent of the illuminated // scene can be resolved and the infinite lights weighted against it. buildIlluminatedBounds(); + if (preparationFailed()) + return; buildLightPickCdf(); reportMessage(ANARI_SEVERITY_DEBUG, @@ -454,7 +469,8 @@ void World::rebuildBLASs() group->rebuildLights(); }); - m_objectUpdates.lastBLASCheck = helium::newTimeStamp(); + if (!preparationFailed()) + m_objectUpdates.lastBLASCheck = helium::newTimeStamp(); } void World::buildInstanceSurfaceGPUData() @@ -788,12 +804,15 @@ void World::buildIlluminatedBounds() DeviceBuffer geometryBvh; OptixTraversableHandle geometryTraversable{}; box3 geometryBounds; - buildOptixBVH( - createOBI(m_optixSurfaceInstances, m_numGeometrySurfaceInstances), - geometryBvh, - geometryTraversable, - geometryBounds, - this); + if (!buildOptixBVH( + createOBI(m_optixSurfaceInstances, m_numGeometrySurfaceInstances), + geometryBvh, + geometryTraversable, + geometryBounds, + this)) { + m_bvhBuildFailed = true; + return; + } m_illuminatedBounds = geometryBounds; m_illuminatedBounds.extend(m_volumeBounds); @@ -1015,7 +1034,7 @@ void World::buildLightProxies() buildInput.customPrimitiveArray.numSbtRecords = 1; box3 proxyBounds; - buildOptixBVH({buildInput}, + m_bvhBuildFailed = !buildOptixBVH({buildInput}, m_bvhLightProxies, m_traversableLightProxies, proxyBounds, diff --git a/devices/rtx/device/world/World.h b/devices/rtx/device/world/World.h index abc8158b7..aab24abee 100644 --- a/devices/rtx/device/world/World.h +++ b/devices/rtx/device/world/World.h @@ -99,6 +99,7 @@ struct World : public Object size_t m_numUserInstances{0}; size_t m_numVolumeInstances{0}; + bool m_bvhBuildFailed{false}; box3 m_surfaceBounds; box3 m_volumeBounds; // m_surfaceBounds minus the light-proxy instance, unioned with the volumes. diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index fb842b5a2..6e687f8ac 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -95,6 +95,41 @@ completed render. Keep replacement and unchanged-frame cases as guards. The [benchmark guide](geometry-preprocessing-performance.md) defines the timed boundaries and local result interpretation; no historical baseline is required. +## Preparation stream and retirement + +Checked geometry preprocessing (bounds, area CDFs, generated quad/curve indices +and radii, and SDF alignment) and OptiX BVH build/compaction use one device-owned +nonblocking preparation stream. `utility/PreparationStream.h` owns its lifetime +and the event used to import producer dependencies. Scene-update submission is +serialized; each event wait captures the corresponding record before the event +is reused. + +- Full preparation imports prior render work before overwriting derived buffers. +- Legacy array uploads are imported through an event on the default stream. +- The BVH builder imports both render-stream producers (including legacy field + and isosurface work) and default-stream input uploads. Its build, readbacks, + and compaction execute on the preparation stream. +- Host bounds/area summaries and BVH publication still require preparation-stream + completion. BVH scratch survives through that completion; handles/bounds are + published only on success. Group/World failure state prevents failed builds + from being treated as ready and permits a later retry. +- Parameter-reference replacement and last-public-release privatization retain + host waits for old render consumers. Error handling drains participating work + before storage can be retired or retried. + +This is not concurrent in-place scene replacement. Legacy default-stream events +can include preceding work on blocking streams; tangent generation and field-grid +preparation retain their legacy synchronization, and `cudaMalloc`/`cudaFree` can +still serialize work. Removing those dependencies requires stream-aware upload +and allocation ownership. Overlapping replacement with active rendering also +requires separate storage generations and last-use tracking for all consumers, +including shared geometry and registries. + +`TestPreparationStream` checks explicit producer ordering and independence from +an unrelated nonblocking stream. The shared-cudart failure tests additionally +cover preparation dependency/completion failures and BLAS/TLAS readback/completion +failures, publication suppression, and retry. + ## Remaining work Broader array/shading invalidation precision, reducing the extra CPU snapshot From d60ca4d15c5f22cd7fa5fb19d9cfb186761b696a Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:04:54 +0000 Subject: [PATCH 06/20] perf(rtx): upload geometry arrays on preparation stream Batch declared host inputs before geometry finalization, preserving source lifetimes and marking uploads complete only after the batch succeeds. Remove default-stream dependencies from checked preprocessing kernels. Cover allocation, copy, completion and partial-batch failures plus retry and coalesced host-array updates. --- devices/rtx/apps/tests/api/CMakeLists.txt | 4 +- .../tests/api/TestCudaPreparationFailure.cpp | 68 +++++++++++++++++-- devices/rtx/device/array/Array.cpp | 40 +++++++++++ devices/rtx/device/array/Array.h | 5 ++ devices/rtx/device/geometry/Curve.cpp | 3 +- devices/rtx/device/geometry/Geometry.cpp | 32 ++++++++- devices/rtx/device/geometry/Preprocessing.cu | 20 ------ devices/rtx/device/geometry/Preprocessing.h | 3 +- devices/rtx/device/geometry/SDF.cpp | 2 - .../rtx/docs/geometry-preparation-reuse.md | 18 +++-- 10 files changed, 160 insertions(+), 35 deletions(-) diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 95bdec1bb..ffb1333a9 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -106,7 +106,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) add_test(NAME TestIsosurfacePreparationRecovery COMMAND TestCudaPreparationFailure isosurface) - foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency) + foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency + sphere-upload-allocation sphere-upload-copy sphere-upload-completion + sphere-upload-partial) add_test(NAME TestSpherePreparationRecovery_${geometry} COMMAND TestCudaPreparationFailure ${geometry}) endforeach() diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index a3bdc6f7a..5ce7ef2a6 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -55,8 +56,14 @@ enum class Failure PREPARATION_SYNC, PREPARATION_DEPENDENCY, BVH_SYNC, - BVH_COPY + BVH_COPY, + UPLOAD_COPY, + UPLOAD_SYNC }; +const void *uploadSource = nullptr; +int uploadCopies = 0; +bool uploadOnWrongStream = false; +bool uploadQueued = false; cudaStream_t preparationStream = nullptr; bool bvhReadback = false; int bvhReadbacksToSkip = 0; @@ -119,6 +126,10 @@ extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) extern "C" cudaError_t cudaMemcpy( void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) { + if (uploadSource && src == uploadSource && kind == cudaMemcpyHostToDevice) { + ++uploadCopies; + uploadOnWrongStream = true; + } if (kind == cudaMemcpyDeviceToDevice && inject(Failure::COPY)) return cudaErrorInvalidValue; return next("cudaMemcpy")(dst, src, bytes, kind); @@ -149,6 +160,13 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, cudaMemcpyKind kind, cudaStream_t stream) { + if (uploadSource && src == uploadSource && kind == cudaMemcpyHostToDevice) { + ++uploadCopies; + uploadOnWrongStream |= stream != preparationStream; + if (inject(Failure::UPLOAD_COPY)) + return cudaErrorInvalidValue; + uploadQueued = true; + } if (stream == preparationStream && kind == cudaMemcpyDeviceToHost && bytes == 6 * sizeof(float) && (failure == Failure::BVH_COPY || failure == Failure::BVH_SYNC)) { @@ -172,6 +190,8 @@ extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) if ((stream && inject(Failure::WORK_SYNC)) || (!stream && inject(Failure::COPY_SYNC)) || (stream == preparationStream && inject(Failure::PREPARATION_SYNC)) + || (stream == preparationStream && uploadQueued + && inject(Failure::UPLOAD_SYNC)) || (stream == preparationStream && bvhReadback && inject(Failure::BVH_SYNC))) return cudaErrorUnknown; @@ -184,13 +204,17 @@ int main(int argc, char **argv) argc > 1 && std::strcmp(argv[1], "isosurface") == 0; const bool sphereFailure = argc > 1 && std::strncmp(argv[1], "sphere", 6) == 0; + const bool sphereUpload = + argc > 1 && std::strncmp(argv[1], "sphere-upload-", 14) == 0; + const bool partialUpload = + sphereUpload && std::strcmp(argv[1], "sphere-upload-partial") == 0; const bool bvhFailure = argc > 1 && (std::strncmp(argv[1], "bvh-", 4) == 0 || std::strcmp(argv[1], "tlas-sync") == 0); const bool curveFailure = argc == 1 || isosurfaceFailure || sphereFailure; auto d = makeVisRTXDevice(status); using vec3 = std::array; - const std::array vertices = { + std::array vertices = { {{-1, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {1, 1, 0}, {-1, 2, 0}, {1, 2, 0}}}; void *deviceVertices = nullptr; if (cudaMalloc(&deviceVertices, sizeof(vertices)) != cudaSuccess @@ -200,12 +224,23 @@ int main(int argc, char **argv) cudaMemcpyHostToDevice) != cudaSuccess) return 1; - auto array = anariNewArray1D( - d, deviceVertices, nullptr, nullptr, ANARI_FLOAT32_VEC3, vertices.size()); + if (sphereUpload) + uploadSource = vertices.data(); + auto array = anariNewArray1D(d, + sphereUpload ? static_cast(vertices.data()) : deviceVertices, + nullptr, + nullptr, + ANARI_FLOAT32_VEC3, + vertices.size()); auto geometry = anari::newObject(d, isosurfaceFailure ? "isosurface" : sphereFailure ? "sphere" : "curve"); + if (partialUpload) { + const std::array radii{0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f}; + anari::setParameterArray1D( + d, geometry, "vertex.radius", radii.data(), radii.size()); + } if (sphereFailure && std::strcmp(argv[1], "sphere-indexed") == 0) { const std::array indices{5, 1, 3}; anari::setParameterArray1D( @@ -330,7 +365,14 @@ int main(int argc, char **argv) ? (std::strcmp(argv[1], "sphere-indexed") == 0 ? 3 : vertices.size()) * 2 * sizeof(vec3) : 3 * sizeof(unsigned); + if (sphereUpload) + allocationBytes = + partialUpload ? vertices.size() * sizeof(float) : sizeof(vertices); failure = isosurfaceFailure ? Failure::WORK_SYNC : Failure::ALLOCATION; + if (sphereUpload && std::strcmp(argv[1], "sphere-upload-copy") == 0) + failure = Failure::UPLOAD_COPY; + if (sphereUpload && std::strcmp(argv[1], "sphere-upload-completion") == 0) + failure = Failure::UPLOAD_SYNC; if (sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) failure = Failure::PREPARATION_SYNC; if (sphereFailure && std::strcmp(argv[1], "sphere-dependency") == 0) @@ -350,6 +392,24 @@ int main(int argc, char **argv) anari::render(d, frame); anari::wait(d, frame); ok = completions == 1 && errors == beforeErrors && ok; + if (sphereUpload) { + const int expected = + std::strcmp(argv[1], "sphere-upload-allocation") == 0 ? 1 : 2; + ok = uploadCopies == expected && !uploadOnWrongStream && ok; + auto *mapped = static_cast(anariMapArray(d, array)); + if (!mapped) + return 1; + mapped[0][0] -= 0.2f; + anariUnmapArray(d, array); + anari::setParameter( + d, geometry, "attribute0", std::array{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = haveBounds() && errors == beforeErrors + && uploadCopies == expected + 1 && !uploadOnWrongStream + && std::fabs(bounds[0] - (-1.2f - (partialUpload ? 0.1f : 0.2f))) + < 1e-4f + && ok; + } if (sphereFailure) { // Preparation-preserving bounds queries must not drain the work stream. // Leave the injection armed, then change radius to require the fence. diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index b0120301d..51cbcdd98 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -33,6 +33,7 @@ #include "optix_visrtx.h" // std #include +#include namespace visrtx { @@ -225,6 +226,45 @@ void Array::uploadArrayData() const markDataUploaded(); } +cudaError_t Array::enqueueUpload(cudaStream_t stream) const +{ + if (anari::isObject(elementType())) + return cudaErrorInvalidValue; // ObjectArray has its own handle translation. + if (!needToUploadData()) + return cudaSuccess; + + const HostMemoryAllocation *host = nullptr; + CudaMemoryAllocation *device = nullptr; + if (m_data.shared.host.isValid()) { + host = &m_data.shared.host; + device = &m_data.shared.device; + } else if (m_data.captured.host.isValid()) { + host = &m_data.captured.host; + device = &m_data.captured.device; + } else if (m_data.managed.host.isValid()) { + host = &m_data.managed.host; + device = &m_data.managed.device; + } else + return cudaSuccess; // Application-owned device inputs are already resident. + + if (!device->isValid()) { + CudaMemoryAllocation allocation(host->bytes()); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + return error; + if (!allocation) + return cudaErrorMemoryAllocation; + *device = std::move(allocation); + } + if (device->bytes() != host->bytes()) + return cudaErrorInvalidValue; + return cudaMemcpyAsync(device->ptr(), + host->ptr(), + host->bytes(), + cudaMemcpyHostToDevice, + stream); +} + ANARIDataType Array::elementType() const { return m_elementType; diff --git a/devices/rtx/device/array/Array.h b/devices/rtx/device/array/Array.h index 22e087649..9858c875a 100644 --- a/devices/rtx/device/array/Array.h +++ b/devices/rtx/device/array/Array.h @@ -82,6 +82,11 @@ struct Array : public UploadableArray void uploadArrayData() const override; + // Queue a pending host upload without marking it complete. Caller retains + // the array and orders prior GPU readers before this stream, then waits for + // completion before markDataUploaded() or exposing the pointer to consumers. + cudaError_t enqueueUpload(cudaStream_t stream) const; + // VisRTX interface // ANARIDataType elementType() const; diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index 6814ba190..a2ff4e9a6 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -70,8 +70,7 @@ void Curve::finalize() if (preparationFailed()) return; computeRadii(); - if (preparationFailed() || !waitForPreparationInputs(this) - || !finishPreparation(this)) + if (preparationFailed() || !finishPreparation(this)) return; m_vertexBufferPtr = (CUdeviceptr)m_vertexPosition->begin(AddressSpace::GPU); diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index d12da2cb5..2e3021e18 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -47,6 +47,7 @@ // std #include #include +#include // helium #include @@ -227,6 +228,9 @@ bool Geometry::beginPreparation(std::initializer_list parameters) m_preparationParameterNames.emplace_back(name); } current.reserve(m_preparedParameters.size()); + // Indices remain valid if current grows; its AnariAny values retain every + // source array until the batch completes (including on failure). + std::vector> pendingUploads; size_t parameterIndex = 0; auto append = [&](const std::string &name) { PreparationParameter parameter; @@ -243,7 +247,10 @@ bool Geometry::beginPreparation(std::initializer_list parameters) parameter.modified = array->lastDataModified(); // Privatization can change backing pointers without changing values // or the array timestamp. Never reuse cached aliases in that case. - parameter.devicePointer = array->dataGPU(); + if (array->needToUploadData() && array->dataHost()) + pendingUploads.emplace_back(current.size(), array); + else + parameter.devicePointer = array->dataGPU(); } } } @@ -252,6 +259,29 @@ bool Geometry::beginPreparation(std::initializer_list parameters) for (const auto &name : m_preparationParameterNames) append(name); + if (!pendingUploads.empty()) { + auto &state = *deviceState(); + if (!checkPreparation(this, + state.preparation.waitFor(state.stream), + "previous array consumers")) + return false; + for (const auto &[index, array] : pendingUploads) { + if (!checkPreparation(this, + array->enqueueUpload(state.preparation.stream()), + "geometry array upload")) + return false; + } + if (!checkPreparation(this, + state.preparation.finish(), + "geometry array upload completion")) + return false; + // Never mark a partial/failed batch uploaded: a later commit must retry. + for (const auto &[index, array] : pendingUploads) { + array->markDataUploaded(); + current[index].devicePointer = array->dataGPU(); + } + } + // Observer-only updates always take the preparation path. A geometry-wide // attribute edit coalesced with an array change cannot hide that change; // the versions/pointers above still invalidate preparation reuse. diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index 58d51b011..b63b7946b 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -221,8 +221,6 @@ VISRTX_GLOBAL void curveRadii(size_t n, float radius, float *out) bool generateQuadIndices( Geometry *g, const uvec4 *indices, size_t n, DeviceBuffer &out) { - if (!waitForPreparationInputs(g)) - return false; if (!reservePreparation(g, out, 2 * n * sizeof(uvec3))) return false; if (n) @@ -236,8 +234,6 @@ bool generateQuadIndices( bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) { - if (!waitForPreparationInputs(g)) - return false; if (!reservePreparation(g, out, n * sizeof(uint32_t))) return false; if (n) @@ -250,8 +246,6 @@ bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) { - if (!waitForPreparationInputs(g)) - return false; if (!reservePreparation(g, out, n * sizeof(float))) return false; if (n) @@ -299,16 +293,6 @@ bool reservePreparation(Geometry *g, DeviceBuffer &buffer, size_t bytes) "allocating device storage"); } -bool waitForPreparationInputs(Geometry *g) -{ - // Legacy Array uploads use synchronous cudaMemcpy on the default stream. - // Pageable H2D may return after staging, not DMA completion: make that - // producer dependency explicit before launching on the preparation stream. - return checkPreparation(g, - g->deviceState()->preparation.waitFor(nullptr), - "input upload dependency"); -} - bool finishPreparation(Geometry *g) { // Also establishes an explicit boundary for legacy default-stream consumers. @@ -320,8 +304,6 @@ bool finishPreparation(Geometry *g) bool Preprocessing::bounds( Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs, float &scale) { - if (!waitForPreparationInputs(g)) - return false; const auto stream = g->deviceState()->preparation.stream(); scale = 0.f; if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) @@ -355,8 +337,6 @@ bool Preprocessing::bounds( bool Preprocessing::areas( Geometry *g, const PrimitiveInput &in, DeviceBuffer &cdf, float &total) { - if (!waitForPreparationInputs(g)) - return false; total = 0.f; if (in.count == 0) { cdf.reset(); diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 8c6f5f7dc..d5772ec62 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -38,6 +38,8 @@ namespace visrtx { struct Geometry; // GPU views use logical array beginnings, never application allocation bases. +// Geometry::beginPreparation() completes authored host-array uploads before +// these views are consumed; kernels need no legacy default-stream dependency. struct PrimitiveInput { GeometryType type{GeometryType::TRIANGLE}; @@ -81,7 +83,6 @@ struct Preprocessing bool checkPreparation( Geometry *geometry, cudaError_t error, const char *operation); bool reservePreparation(Geometry *geometry, DeviceBuffer &buffer, size_t bytes); -bool waitForPreparationInputs(Geometry *geometry); bool finishPreparation(Geometry *geometry); bool generateQuadIndices(Geometry *geometry, const uvec4 *indices, diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index f221a820f..a73026230 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -91,8 +91,6 @@ void SDF::finalize() input.type = GeometryType::SDF; input.count = m_numPrimitives; const void *source = m_sdf->begin(AddressSpace::GPU); - if (!waitForPreparationInputs(this)) - return; if (reinterpret_cast(source) % alignof(SDFPrimitive) != 0) { const size_t bytes = m_numPrimitives * sizeof(SDFPrimitive); if (!reservePreparation(this, m_alignedPrimitives, bytes) diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 6e687f8ac..d8f45c943 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -105,7 +105,15 @@ serialized; each event wait captures the corresponding record before the event is reused. - Full preparation imports prior render work before overwriting derived buffers. -- Legacy array uploads are imported through an event on the default stream. +- For the seven opt-in geometry types, pending host uploads of declared arrays + are batched on the preparation stream before finalization. The committed + snapshot retains source arrays through completion. Uploaded timestamps and + device-pointer snapshots are published only after the whole batch succeeds; + partial failures remain dirty and are retried. Legacy consumers can safely + use the completed device copy afterward. +- These checked geometry kernels no longer import the default stream: authored + inputs are ready before they run. Other array consumers retain their existing + upload path. - The BVH builder imports both render-stream producers (including legacy field and isosurface work) and default-stream input uploads. Its build, readbacks, and compaction execute on the preparation stream. @@ -120,15 +128,17 @@ is reused. This is not concurrent in-place scene replacement. Legacy default-stream events can include preceding work on blocking streams; tangent generation and field-grid preparation retain their legacy synchronization, and `cudaMalloc`/`cudaFree` can -still serialize work. Removing those dependencies requires stream-aware upload -and allocation ownership. Overlapping replacement with active rendering also +still serialize work. Removing the remaining dependencies requires stream-aware +instance/registry uploads and allocation ownership. Overlapping replacement with active rendering also requires separate storage generations and last-use tracking for all consumers, including shared geometry and registries. `TestPreparationStream` checks explicit producer ordering and independence from an unrelated nonblocking stream. The shared-cudart failure tests additionally cover preparation dependency/completion failures and BLAS/TLAS readback/completion -failures, publication suppression, and retry. +failures, publication suppression, and retry. Host-upload cases also check copy +stream selection, allocation/copy/completion failures, partial-batch retry, and +an in-place unmap coalesced with a uniform commit. ## Remaining work From 62422dc6d073175038be9d08a2503bb40e6bd182 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:42:54 -0400 Subject: [PATCH 07/20] perf(rtx): batch instance and registry uploads Upload OptiX instances and finalized world tables on the preparation stream, and publish dirty registries as one checked batch before tracing. Keep stable registry snapshots across host-vector growth and preserve newer edits or failed batches for retry. Retain render-consumer ordering and legacy fences for producers not migrated yet. --- devices/rtx/apps/tests/api/CMakeLists.txt | 14 +++ .../tests/api/TestCudaPreparationFailure.cpp | 96 ++++++++++++++-- .../apps/tests/api/TestRegistrySnapshot.cpp | 104 ++++++++++++++++++ devices/rtx/device/RegisteredObject.h | 4 +- devices/rtx/device/frame/Frame.cu | 16 ++- devices/rtx/device/optix_visrtx.cpp | 27 +++++ devices/rtx/device/optix_visrtx.h | 3 + devices/rtx/device/utility/DeviceBuffer.h | 45 +++++++- .../rtx/device/utility/DeviceObjectArray.h | 82 ++++++++++---- devices/rtx/device/utility/HostDeviceArray.h | 34 ++++++ .../rtx/device/utility/PreparationStream.h | 21 ++++ devices/rtx/device/world/World.cpp | 55 +++++---- devices/rtx/device/world/World.h | 18 +++ .../rtx/docs/geometry-preparation-reuse.md | 26 ++++- 14 files changed, 482 insertions(+), 63 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index ffb1333a9..2c5760c55 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -88,6 +88,14 @@ target_link_libraries(BenchmarkGeometryPreprocessing PRIVATE anari_library_visrt add_executable(TestPreparationStream TestPreparationStream.cpp) target_link_libraries(TestPreparationStream PRIVATE CUDA::cudart Threads::Threads) add_test(NAME TestPreparationStream COMMAND TestPreparationStream) +add_executable(TestRegistrySnapshot TestRegistrySnapshot.cpp + ../../../device/utility/MemoryAllocation.cpp) +target_include_directories(TestRegistrySnapshot PRIVATE + ../../../device ../../../external/nanovdb/include ${OptiX_ROOT_DIR}/include) +target_link_libraries(TestRegistrySnapshot PRIVATE + CUDA::cudart anari::anari_static visrtx::glm) +target_compile_definitions(TestRegistrySnapshot PRIVATE GLM_ENABLE_EXPERIMENTAL) +add_test(NAME TestRegistrySnapshot COMMAND TestRegistrySnapshot) make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) @@ -103,6 +111,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) make_test(TestCudaPreparationFailure) target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + target_include_directories(TestCudaPreparationFailure PRIVATE ${OptiX_ROOT_DIR}/include) set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) add_test(NAME TestIsosurfacePreparationRecovery COMMAND TestCudaPreparationFailure isosurface) @@ -112,6 +121,11 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S add_test(NAME TestSpherePreparationRecovery_${geometry} COMMAND TestCudaPreparationFailure ${geometry}) endforeach() + foreach(failure registry-copy registry-sync registry-partial + instance-allocation instance-copy instance-sync world-copy world-sync) + add_test(NAME TestSceneUploadRecovery_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() foreach(failure bvh-copy bvh-sync tlas-sync) add_test(NAME TestBvhPreparationRecovery_${failure} COMMAND TestCudaPreparationFailure ${failure}) diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 5ce7ef2a6..b4c4c37e6 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -58,8 +59,14 @@ enum class Failure BVH_SYNC, BVH_COPY, UPLOAD_COPY, - UPLOAD_SYNC + UPLOAD_SYNC, + BATCH_COPY, + BATCH_SYNC }; +bool trackBatch = false; +bool batchQueued = false; +int batchCopiesToSkip = 0; +int batchCopies = 0; const void *uploadSource = nullptr; int uploadCopies = 0; bool uploadOnWrongStream = false; @@ -167,6 +174,20 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, return cudaErrorInvalidValue; uploadQueued = true; } + if (trackBatch && stream == preparationStream + && kind == cudaMemcpyHostToDevice) { + ++batchCopies; + if (batchCopiesToSkip) + --batchCopiesToSkip; + else { + if (inject(Failure::BATCH_COPY)) { + // Exercise real CUDA last-error state as well as the returned status. + return next("cudaMemcpyAsync")( + nullptr, src, bytes, kind, stream); + } + batchQueued = true; + } + } if (stream == preparationStream && kind == cudaMemcpyDeviceToHost && bytes == 6 * sizeof(float) && (failure == Failure::BVH_COPY || failure == Failure::BVH_SYNC)) { @@ -193,7 +214,9 @@ extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) || (stream == preparationStream && uploadQueued && inject(Failure::UPLOAD_SYNC)) || (stream == preparationStream && bvhReadback - && inject(Failure::BVH_SYNC))) + && inject(Failure::BVH_SYNC)) + || (stream == preparationStream && batchQueued + && inject(Failure::BATCH_SYNC))) return cudaErrorUnknown; return result; } @@ -211,6 +234,15 @@ int main(int argc, char **argv) const bool bvhFailure = argc > 1 && (std::strncmp(argv[1], "bvh-", 4) == 0 || std::strcmp(argv[1], "tlas-sync") == 0); + const bool registryFailure = + argc > 1 && std::strncmp(argv[1], "registry-", 9) == 0; + const bool registryPartial = + registryFailure && std::strcmp(argv[1], "registry-partial") == 0; + const bool instanceFailure = argc > 1 + && (std::strncmp(argv[1], "instance-", 9) == 0 + || std::strncmp(argv[1], "world-", 6) == 0); + const bool worldRecords = + instanceFailure && std::strncmp(argv[1], "world-", 6) == 0; const bool curveFailure = argc == 1 || isosurfaceFailure || sphereFailure; auto d = makeVisRTXDevice(status); using vec3 = std::array; @@ -286,6 +318,12 @@ int main(int argc, char **argv) anari::commitParameters(d, siblingSurface); surfaces.push_back(siblingSurface); } + if (registryPartial) { + sibling = anari::newObject(d, "curve"); + anari::setParameter(d, sibling, "vertex.position", array); + anari::setParameter(d, sibling, "radius", 0.1f); + anari::commitParameters(d, sibling); + } auto world = anari::newObject(d); anari::setParameterArray1D( d, world, "surface", surfaces.data(), surfaces.size()); @@ -296,7 +334,10 @@ int main(int argc, char **argv) anari::setParameter(d, camera, "position", vec3{0, 0, -3}); anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); anari::commitParameters(d, camera); - auto renderer = anari::newObject(d, "debug"); + auto renderer = anari::newObject( + d, registryFailure ? "interactive" : "debug"); + if (registryFailure) + anari::setParameter(d, renderer, "sampleLimit", 0); anari::commitParameters(d, renderer); auto frame = anari::newObject(d); anari::setParameter(d, frame, "size", std::array{8, 8}); @@ -323,10 +364,49 @@ int main(int argc, char **argv) != 0; }; bool ok = errors == 0; - if (bvhFailure) { - const auto injected = std::strcmp(argv[1], "bvh-copy") == 0 - ? Failure::BVH_COPY - : Failure::BVH_SYNC; + if (registryFailure) { + ok = haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == 0 && ok; + for (auto g : {geometry, sibling}) { + if (!g) + continue; + anari::setParameter(d, g, "color", std::array{1, 0, 0, 1}); + anari::commitParameters(d, g); + } + trackBatch = true; + batchCopiesToSkip = registryPartial ? 1 : 0; + failure = std::strcmp(argv[1], "registry-sync") == 0 ? Failure::BATCH_SYNC + : Failure::BATCH_COPY; + anari::render(d, frame); + anari::wait(d, frame); + ok = injections == 1 && errors > 0 && completions == 1 && ok; + const int beforeErrors = errors; + // No recommit: failed upload must retain all dirty slots, including the + // first successful copy in the partial-batch case. + anari::render(d, frame); + anari::wait(d, frame); + ok = errors == beforeErrors && completions == 2 + && batchCopies == (registryPartial ? 4 : 2) && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = errors == beforeErrors && completions == 3 + && batchCopies == (registryPartial ? 4 : 2) && ok; + anari::release(d, array); + } else if (bvhFailure || instanceFailure) { + auto injected = std::strcmp(argv[1], "bvh-copy") == 0 ? Failure::BVH_COPY + : Failure::BVH_SYNC; + if (instanceFailure) { + trackBatch = true; + batchCopiesToSkip = worldRecords ? 1 : 0; + injected = std::strstr(argv[1], "copy") ? Failure::BATCH_COPY + : Failure::BATCH_SYNC; + if (std::strcmp(argv[1], "instance-allocation") == 0) { + allocationBytes = sizeof(OptixInstance); + injected = Failure::ALLOCATION; + } + } bvhReadbacksToSkip = std::strcmp(argv[1], "tlas-sync") == 0 ? 1 : 0; failure = injected; ok = !haveBounds() && injections == 1 && errors > 0 && ok; @@ -341,6 +421,8 @@ int main(int argc, char **argv) failure = injected; bvhReadback = false; bvhReadbacksToSkip = 0; + batchCopiesToSkip = worldRecords ? 1 : 0; + batchQueued = false; anari::render(d, frame); anari::wait(d, frame); ok = injections == 2 && completions == 0 && ok; diff --git a/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp new file mode 100644 index 000000000..6e6eb7efd --- /dev/null +++ b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "gpu/gpu_objects.h" +#include "utility/DeviceObjectArray.h" +#include "utility/PreparationStream.h" + +int main() +{ + visrtx::PreparationStream preparation; + if (preparation.initialize() != cudaSuccess) + return 1; + visrtx::DeviceObjectArray registry; + int token = 0; + const auto first = registry.alloc(&token); + registry.set(first, 11); + if (preparation.upload(nullptr, registry) != cudaSuccess) + return 1; + registry.markUploaded(); + bool ok = !registry.dirty(); + + registry.set(first, 22); + if (registry.enqueueUpload(preparation.stream()) != cudaSuccess) + return 1; + // Model object creation/finalization between submission and completion: + // growing the live host vector must not invalidate the copy's source, and + // acknowledging that copy must not erase newer edits. + registry.set(first, 33); + visrtx::DeviceObjectIndex last = first; + for (int i = 0; i < 1024; ++i) + last = registry.alloc(&token); + registry.set(last, 44); + if (preparation.finish() != cudaSuccess) + return 1; + registry.markUploaded(); + ok = registry.dirty() && ok; + int value = 0; + ok = cudaMemcpy( + &value, registry.devicePtr(), sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 22 && ok; + + if (preparation.upload(nullptr, registry) != cudaSuccess) + return 1; + registry.markUploaded(); + ok = !registry.dirty() && ok; + ok = cudaMemcpy( + &value, registry.devicePtr(), sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 33 && ok; + ok = cudaMemcpy(&value, + registry.devicePtr() + last, + sizeof(value), + cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 44 && ok; + + visrtx::DeviceObjectArray uncommitted; + uncommitted.alloc(&token); + uncommitted.alloc(&token); + if (preparation.upload(nullptr, uncommitted) != cudaSuccess) + return 1; + uncommitted.markUploaded(); + uncommitted.set(0, 7); + if (preparation.upload(nullptr, uncommitted) != cudaSuccess) + return 1; + uncommitted.markUploaded(); + int pair[2]{}; + ok = cudaMemcpy( + pair, uncommitted.devicePtr(), sizeof(pair), cudaMemcpyDeviceToHost) + == cudaSuccess + && pair[0] == 7 && pair[1] == 0 && !uncommitted.dirty() && ok; + std::printf("registry snapshot: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/RegisteredObject.h b/devices/rtx/device/RegisteredObject.h index 3e7ac7b6e..34b106cc8 100644 --- a/devices/rtx/device/RegisteredObject.h +++ b/devices/rtx/device/RegisteredObject.h @@ -86,9 +86,7 @@ inline void RegisteredObject::finalize() template inline void RegisteredObject::upload() { - auto &data = m_registryArray->map(index()); - data = gpuData(); - m_registryArray->unmap(index()); + m_registryArray->set(index(), gpuData()); } template diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index 5657da455..db794e1da 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -730,6 +730,17 @@ void Frame::renderFrame() hd.fb.buffers.trimTopK = nullptr; } + const auto registryUpload = + state.registry.upload(state.preparation, state.stream); + if (registryUpload != cudaSuccess) { + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after registry upload failure: %s", + cudaGetErrorString(registryUpload)); + instrument::rangePop(); // frame setup + instrument::rangePop(); // Frame::renderFrame() + instrument::rangePop(); // frame + map + return; + } hd.registry.samplers = state.registry.samplers.devicePtr(); hd.registry.geometries = state.registry.geometries.devicePtr(); hd.registry.materials = state.registry.materials.devicePtr(); @@ -749,8 +760,9 @@ void Frame::renderFrame() upload(); instrument::rangePop(); // Frame::upload() - // Frame and Registry uploads are legacy default-stream copies. Complete - // that producer before work-stream tracing sees newly published geometry. + // Frame/renderer uploads still use legacy default-stream copies. Registries + // are already complete on the preparation stream; finish the remaining + // producers before tracing. const auto publication = cudaStreamSynchronize(nullptr); if (publication != cudaSuccess) { // newFrame() already advanced the checkerboard phase and may have cleared diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 31ab39147..396d578e5 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -181,6 +181,33 @@ DeviceGlobalState::DeviceGlobalState(ANARIDevice d) DeviceGlobalState::~DeviceGlobalState() = default; +cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( + PreparationStream &preparation, cudaStream_t renderStream) +{ + if (!(samplers.dirty() || geometries.dirty() || materials.dirty() + || surfaces.dirty() || lights.dirty() || fields.dirty() + || volumes.dirty())) + return cudaSuccess; + const auto error = preparation.upload(renderStream, + samplers, + geometries, + materials, + surfaces, + lights, + fields, + volumes); + if (error != cudaSuccess) + return error; + samplers.markUploaded(); + geometries.markUploaded(); + materials.markUploaded(); + surfaces.markUploaded(); + lights.markUploaded(); + fields.markUploaded(); + volumes.markUploaded(); + return cudaSuccess; +} + #ifdef USE_MDL namespace { diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index ec5d82826..9ba2f3e84 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -230,6 +230,9 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceObjectArray lights; DeviceObjectArray fields; DeviceObjectArray volumes; + + cudaError_t upload( + PreparationStream &preparation, cudaStream_t renderStream); } registry; // MDL diff --git a/devices/rtx/device/utility/DeviceBuffer.h b/devices/rtx/device/utility/DeviceBuffer.h index bb9dca153..9fc629763 100644 --- a/devices/rtx/device/utility/DeviceBuffer.h +++ b/devices/rtx/device/utility/DeviceBuffer.h @@ -33,6 +33,7 @@ #include "MemoryAllocation.h" // std +#include #include #include #include @@ -50,10 +51,20 @@ struct DeviceBuffer template void upload(const std::vector &v); + // Caller orders previous readers and retains src through stream completion. + template + cudaError_t enqueueUpload(const T *src, + size_t numElements, + cudaStream_t stream, + size_t byteOffsetStart = 0); + template void download(T *dst, size_t numElements = 1, size_t byteOffsetStart = 0); - HostMemoryAllocation hostCopy() const { return m_mem; } + HostMemoryAllocation hostCopy() const + { + return m_mem; + } template T *ptrAs() const; @@ -103,6 +114,38 @@ inline void DeviceBuffer::upload(const std::vector &v) upload(v.data(), v.size()); } +template +inline cudaError_t DeviceBuffer::enqueueUpload(const T *src, + size_t numElements, + cudaStream_t stream, + size_t byteOffsetStart) +{ + static_assert(std::is_trivially_copyable::value); + if (numElements == 0) + return cudaSuccess; + if (!src + || numElements + > (std::numeric_limits::max() - byteOffsetStart) / sizeof(T)) + return cudaErrorInvalidValue; + const auto copyBytes = bytesof(numElements); + const auto needed = copyBytes + byteOffsetStart; + if (!ptr()) + reset(); // A failed allocation may retain capacity without storage. + if (needed > bytes()) { + alloc(needed); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + return error; + } + if (!ptr() || bytes() < needed) + return cudaErrorMemoryAllocation; + return cudaMemcpyAsync(static_cast(ptr()) + byteOffsetStart, + src, + copyBytes, + cudaMemcpyHostToDevice, + stream); +} + template inline void DeviceBuffer::download( T *dst, size_t numElements, size_t byteOffsetStart) diff --git a/devices/rtx/device/utility/DeviceObjectArray.h b/devices/rtx/device/utility/DeviceObjectArray.h index 01a2e5d5f..438f2500b 100644 --- a/devices/rtx/device/utility/DeviceObjectArray.h +++ b/devices/rtx/device/utility/DeviceObjectArray.h @@ -52,14 +52,15 @@ struct DeviceObjectArray size_t size() const; bool empty() const; - T &map(DeviceObjectIndex idx); - void unmap(DeviceObjectIndex idx); + void set(DeviceObjectIndex idx, const T &value); void *hostObject(DeviceObjectIndex idx) const; - void upload(); + bool dirty() const; + cudaError_t enqueueUpload(cudaStream_t stream); + void markUploaded(); - const T *devicePtr(); + const T *devicePtr() const; private: bool m_fullReupload{true}; @@ -70,7 +71,13 @@ struct DeviceObjectArray std::stack> m_freeIndices; std::vector m_objectsToUpload; - std::mutex m_allocationMutex; + // Stable sources for asynchronous copies even if unrelated objects are + // created or finalized while the batch is in flight. + std::vector m_uploadSnapshot; + std::vector m_uploadIndices; + size_t m_updateVersion{0}; + size_t m_uploadVersion{0}; + mutable std::mutex m_allocationMutex; }; // Inlined definitions //////////////////////////////////////////////////////// @@ -96,6 +103,7 @@ inline DeviceObjectIndex DeviceObjectArray::alloc(void *hostObj) m_fullReupload = true; } + ++m_updateVersion; return i; } @@ -126,44 +134,74 @@ inline bool DeviceObjectArray::empty() const } template -inline T &DeviceObjectArray::map(DeviceObjectIndex idx) +inline void DeviceObjectArray::set(DeviceObjectIndex idx, const T &value) { - return *(m_objects.dataHost() + idx); + std::scoped_lock lock(m_allocationMutex); + m_objects.dataHost()[idx] = value; + m_objectsToUpload.push_back(idx); + ++m_updateVersion; } template -inline void DeviceObjectArray::unmap(DeviceObjectIndex idx) +inline void *DeviceObjectArray::hostObject(DeviceObjectIndex idx) const { - m_objectsToUpload.push_back(idx); + return m_hostObjects[idx]; } template -inline void *DeviceObjectArray::hostObject(DeviceObjectIndex idx) const +inline bool DeviceObjectArray::dirty() const { - return m_hostObjects[idx]; + std::scoped_lock lock(m_allocationMutex); + return !m_objectsToUpload.empty(); } template -inline void DeviceObjectArray::upload() +inline cudaError_t DeviceObjectArray::enqueueUpload(cudaStream_t stream) { - if (m_objectsToUpload.empty()) - return; - - if (m_fullReupload) - m_objects.upload(); - else { - for (auto i : m_objectsToUpload) - m_objects.upload(i, i + 1); + bool full = false; + { + std::scoped_lock lock(m_allocationMutex); + m_uploadVersion = m_updateVersion; + m_uploadIndices = m_objectsToUpload; + if (m_uploadIndices.empty()) + return cudaSuccess; + full = m_fullReupload; + if (full) + m_uploadSnapshot.assign(m_objects.begin(), m_objects.end()); + else { + m_uploadSnapshot.clear(); + m_uploadSnapshot.reserve(m_uploadIndices.size()); + for (auto i : m_uploadIndices) + m_uploadSnapshot.push_back(m_objects.dataHost()[i]); + } + } + // Do not hold the registry lock during CUDA calls/waits: completion + // callbacks may create objects. The snapshot outlives the entire batch. + if (full) + return m_objects.enqueueUploadFrom( + m_uploadSnapshot.data(), m_uploadSnapshot.size(), 0, stream); + for (size_t i = 0; i < m_uploadIndices.size(); ++i) { + const auto error = m_objects.enqueueUploadFrom( + &m_uploadSnapshot[i], 1, m_uploadIndices[i], stream); + if (error != cudaSuccess) + return error; } + return cudaSuccess; +} +template +inline void DeviceObjectArray::markUploaded() +{ + std::scoped_lock lock(m_allocationMutex); + if (m_uploadIndices.empty() || m_uploadVersion != m_updateVersion) + return; // Retain edits made after the snapshot for the next batch. m_objectsToUpload.clear(); m_fullReupload = false; } template -inline const T *DeviceObjectArray::devicePtr() +inline const T *DeviceObjectArray::devicePtr() const { - upload(); return m_objects.dataDevice(); } diff --git a/devices/rtx/device/utility/HostDeviceArray.h b/devices/rtx/device/utility/HostDeviceArray.h index 626bb0de0..7ca68dc54 100644 --- a/devices/rtx/device/utility/HostDeviceArray.h +++ b/devices/rtx/device/utility/HostDeviceArray.h @@ -56,6 +56,12 @@ struct HostDeviceArray void upload(); void download(); + cudaError_t enqueueUpload(cudaStream_t stream); + cudaError_t enqueueUploadFrom( + const T *source, size_t count, size_t startIndex, cudaStream_t stream); + cudaError_t enqueueUpload( + cudaStream_t stream, size_t startIndex, size_t endIndex); + Span hostSpan() const; Span deviceSpan() const; @@ -121,6 +127,34 @@ inline void HostDeviceArray::upload(size_t startIndex, size_t endIndex) } } +template +inline cudaError_t HostDeviceArray::enqueueUpload( + cudaStream_t stream, size_t startIndex, size_t endIndex) +{ + if (startIndex > endIndex || endIndex > size()) + return cudaErrorInvalidValue; + if (startIndex == endIndex) + return cudaSuccess; + return m_deviceBuffer.enqueueUpload(&m_hostArray[startIndex], + endIndex - startIndex, + stream, + startIndex * sizeof(T)); +} + +template +inline cudaError_t HostDeviceArray::enqueueUploadFrom( + const T *source, size_t count, size_t startIndex, cudaStream_t stream) +{ + return m_deviceBuffer.enqueueUpload( + source, count, stream, startIndex * sizeof(T)); +} + +template +inline cudaError_t HostDeviceArray::enqueueUpload(cudaStream_t stream) +{ + return enqueueUpload(stream, 0, size()); +} + template inline void HostDeviceArray::download(size_t startIndex, size_t endIndex) { diff --git a/devices/rtx/device/utility/PreparationStream.h b/devices/rtx/device/utility/PreparationStream.h index 22c7b4db7..e00722c59 100644 --- a/devices/rtx/device/utility/PreparationStream.h +++ b/devices/rtx/device/utility/PreparationStream.h @@ -51,6 +51,11 @@ struct PreparationStream cudaError_t waitFor(cudaStream_t producer); cudaError_t finish(); + // All sources must remain stable until this returns. Drain a partial batch + // on failure; callers acknowledge dirty state only after success. + template + cudaError_t upload(cudaStream_t previousConsumers, Arrays &...arrays); + private: cudaStream_t m_stream{nullptr}; cudaEvent_t m_dependency{nullptr}; @@ -105,4 +110,20 @@ inline cudaError_t PreparationStream::finish() return cudaStreamSynchronize(m_stream); } +template +inline cudaError_t PreparationStream::upload( + cudaStream_t previousConsumers, Arrays &...arrays) +{ + auto error = waitFor(previousConsumers); + auto enqueue = [&](auto &array) { + if (error == cudaSuccess) + error = array.enqueueUpload(m_stream); + }; + (enqueue(arrays), ...); + const auto completion = finish(); + if (error != cudaSuccess || completion != cudaSuccess) + cudaGetLastError(); // Keep a recoverable API error out of the next batch. + return error == cudaSuccess ? completion : error; +} + } // namespace visrtx diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index 583352405..95e2d0fef 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -299,6 +299,8 @@ void World::rebuildWorld() return; populateOptixInstances(); + if (preparationFailed()) + return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building surface BVH over %zu instances", m_optixSurfaceInstances.size()); @@ -335,6 +337,16 @@ void World::rebuildWorld() if (preparationFailed()) return; buildLightPickCdf(); + // These records are consumed only by tracing, not by the intervening BVH + // builds. Upload their final values together, including proxy flag edits. + if (!uploadArrays(m_instanceSurfaceGPUData, + m_instanceVolumeGPUData, + m_instanceLightGPUData, + m_instanceHdriLightGPUData, + m_lightProxyGPUData, + m_lightPickCdf, + m_lightPickDelta)) + return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World finished building world over %zu instances", @@ -374,8 +386,8 @@ void World::populateOptixInstances() m_numTriangleInstances + m_numCurveInstances + m_numUserInstances; m_optixSurfaceInstances.resize( - m_numGeometrySurfaceInstances + (hasLightProxies ? 1 : 0)); - m_optixVolumeInstances.resize(m_numVolumeInstances); + m_numGeometrySurfaceInstances + (hasLightProxies ? 1 : 0), false); + m_optixVolumeInstances.resize(m_numVolumeInstances, false); auto prepInstance = [](auto &i, int instID, @@ -454,8 +466,7 @@ void World::populateOptixInstances() instID++; } - m_optixSurfaceInstances.upload(); - m_optixVolumeInstances.upload(); + uploadArrays(m_optixSurfaceInstances, m_optixVolumeInstances); } void World::rebuildBLASs() @@ -476,7 +487,7 @@ void World::rebuildBLASs() void World::buildInstanceSurfaceGPUData() { m_instanceSurfaceGPUData.resize( - m_numTriangleInstances + m_numCurveInstances + m_numUserInstances); + m_numTriangleInstances + m_numCurveInstances + m_numUserInstances, false); auto makeInstanceGPUData = [](const DeviceObjectIndex *s, const UniformAttributes &ua, @@ -569,12 +580,12 @@ void World::buildInstanceSurfaceGPUData() } }); - m_instanceSurfaceGPUData.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } void World::buildInstanceVolumeGPUData() { - m_instanceVolumeGPUData.resize(m_numVolumeInstances); + m_instanceVolumeGPUData.resize(m_numVolumeInstances, false); int instID = 0; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { @@ -598,7 +609,7 @@ void World::buildInstanceVolumeGPUData() } }); - m_instanceVolumeGPUData.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } size_t World::countGeometryLights(Group *group) const @@ -690,10 +701,10 @@ void World::buildInstanceLightGPUData() totalHdriLights); // Allocate the instance-data, HDRI, and pick arrays. - m_instanceLightGPUData.resize(totalLights); - m_instanceHdriLightGPUData.resize(totalHdriLights); - m_lightPickCdf.resize(totalLights); - m_lightPickDelta.resize(totalLights); + m_instanceLightGPUData.resize(totalLights, false); + m_instanceHdriLightGPUData.resize(totalHdriLights, false); + m_lightPickCdf.resize(totalLights, false); + m_lightPickDelta.resize(totalLights, false); m_lightInstanceObjects.clear(); m_lightInstanceObjects.resize(totalLights, nullptr); @@ -763,8 +774,7 @@ void World::buildInstanceLightGPUData() // surface instance and emit silently wrong radiance — catch it here. assert(surfaceInstanceCursor == m_instanceSurfaceGPUData.size()); - m_instanceLightGPUData.upload(); - m_instanceHdriLightGPUData.upload(); + // Keep records host-side until proxy flags and Light Pick are finalized. } void World::buildIlluminatedBounds() @@ -890,8 +900,7 @@ void World::buildLightPickCdf() } } - m_lightPickCdf.upload(); - m_lightPickDelta.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } // An area light is flat, so its world AABB is degenerate along one axis @@ -1008,17 +1017,15 @@ void World::buildLightProxies() if (proxies.empty()) return; - // Re-upload: the hasAreaProxy flags were written after - // buildInstanceLightGPUData's own upload. - m_instanceLightGPUData.upload(); - - m_lightProxyGPUData.resize(proxies.size()); + // Tracing records (including hasAreaProxy) are uploaded once after the TLAS + // build; only the proxy AABBs are needed by the BLAS below. + m_lightProxyGPUData.resize(proxies.size(), false); std::copy(proxies.begin(), proxies.end(), m_lightProxyGPUData.dataHost()); - m_lightProxyGPUData.upload(); - m_lightProxyAabbs.resize(aabbs.size()); + m_lightProxyAabbs.resize(aabbs.size(), false); std::copy(aabbs.begin(), aabbs.end(), m_lightProxyAabbs.dataHost()); - m_lightProxyAabbs.upload(); + if (!uploadArrays(m_lightProxyAabbs)) + return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building light-proxy BLAS over %zu proxies", diff --git a/devices/rtx/device/world/World.h b/devices/rtx/device/world/World.h index aab24abee..0aaa84a89 100644 --- a/devices/rtx/device/world/World.h +++ b/devices/rtx/device/world/World.h @@ -61,6 +61,8 @@ struct World : public Object void rebuildWorld(); private: + template + bool uploadArrays(Arrays &...arrays); void populateOptixInstances(); void rebuildBLASs(); void buildInstanceSurfaceGPUData(); @@ -163,6 +165,22 @@ struct World : public Object float m_sceneRadius{0.f}; }; +template +inline bool World::uploadArrays(Arrays &...arrays) +{ + if ((arrays.empty() && ...)) + return true; + auto &state = *deviceState(); + const auto error = state.preparation.upload(state.stream, arrays...); + if (error == cudaSuccess) + return true; + m_bvhBuildFailed = true; + reportMessage(ANARI_SEVERITY_ERROR, + "world upload failed: %s", + cudaGetErrorString(error)); + return false; +} + } // namespace visrtx VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::World *, ANARI_WORLD); diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index d8f45c943..1ac767950 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -117,6 +117,16 @@ is reused. - The BVH builder imports both render-stream producers (including legacy field and isosurface work) and default-stream input uploads. Its build, readbacks, and compaction execute on the preparation stream. +- OptiX instance arrays and proxy AABBs are uploaded on the preparation stream + before their builds. World tracing tables (surface/volume/light records, proxy + records, and Light Pick arrays) are batched after their final CPU edits; proxy + flags no longer require a separate re-upload. +- All dirty object registries are uploaded in one preparation-stream batch before + tracing. Registry pointer access no longer performs implicit uploads. Stable + host snapshots survive object creation or edits during the batch; only dirty + slots are staged unless registry growth requires a full copy. Edits made after + a snapshot remain dirty for the next batch. No registry lock is held during + CUDA waits, so completion callbacks cannot be blocked by that lock. - Host bounds/area summaries and BVH publication still require preparation-stream completion. BVH scratch survives through that completion; handles/bounds are published only on success. Group/World failure state prevents failed builds @@ -128,8 +138,9 @@ is reused. This is not concurrent in-place scene replacement. Legacy default-stream events can include preceding work on blocking streams; tangent generation and field-grid preparation retain their legacy synchronization, and `cudaMalloc`/`cudaFree` can -still serialize work. Removing the remaining dependencies requires stream-aware -instance/registry uploads and allocation ownership. Overlapping replacement with active rendering also +still serialize work. Frame/renderer payloads and group index tables still use +legacy uploads. Removing those dependencies requires further producer migration +and allocation ownership changes. Overlapping replacement with active rendering also requires separate storage generations and last-use tracking for all consumers, including shared geometry and registries. @@ -138,12 +149,19 @@ an unrelated nonblocking stream. The shared-cudart failure tests additionally cover preparation dependency/completion failures and BLAS/TLAS readback/completion failures, publication suppression, and retry. Host-upload cases also check copy stream selection, allocation/copy/completion failures, partial-batch retry, and -an in-place unmap coalesced with a uniform commit. +an in-place unmap coalesced with a geometry-wide attribute commit. Scene-upload cases cover +instance allocation, instance/world copy and completion errors, registry copy +and completion errors, partial registry batches, and retry without recommitting +already-finalized objects. `TestRegistrySnapshot` verifies stable copy sources +across host-vector growth and preservation of newer dirty edits. ## Remaining work Broader array/shading invalidation precision, reducing the extra CPU snapshot comparison cost, batched readback/dispatch, and fine-grained area-vs-bounds -invalidation are separate improvements. This change does not repack or download +invalidation are separate improvements. Registry batching spans geometries, but +geometry input/bounds/area preparation still completes per geometry. Batching +that work across geometries requires splitting finalization into submission and +result collection while preserving source lifetimes and failure propagation. This change does not repack or download inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs are prepared on the GPU before their derived data is published. From e5dfc0ce8bebb3d90f8b4bf92633b95d9a3accb4 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:34:51 +0000 Subject: [PATCH 08/20] perf(rtx): batch geometry preparation readbacks Submit checked bounds and area readbacks into owned pinned storage, then collect and validate before BVH builds and geometry-light publication. Retain queued geometries and drain before storage reuse or retirement. Cover deferred lifetime, callback reentry, pinned allocation failure, batch completion errors, and pending shared-array retirement. --- devices/rtx/apps/tests/api/CMakeLists.txt | 9 +- .../tests/api/TestCudaPreparationFailure.cpp | 185 +++++++++++++++++- .../api/TestDeferredGeometryPreparation.cpp | 169 ++++++++++++++++ devices/rtx/device/VisRTXDevice.cpp | 7 + devices/rtx/device/array/Array.cpp | 4 + devices/rtx/device/geometry/Geometry.cpp | 30 ++- devices/rtx/device/geometry/Geometry.h | 10 +- devices/rtx/device/geometry/Preprocessing.cu | 93 ++++++--- devices/rtx/device/geometry/Preprocessing.h | 20 +- devices/rtx/device/geometry/SDF.cpp | 3 +- devices/rtx/device/optix_visrtx.cpp | 56 ++++++ devices/rtx/device/optix_visrtx.h | 12 ++ devices/rtx/device/world/Group.cpp | 2 + devices/rtx/device/world/World.cpp | 17 +- .../rtx/docs/geometry-preparation-reuse.md | 50 ++++- 15 files changed, 614 insertions(+), 53 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 2c5760c55..bc87cc008 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -96,6 +96,8 @@ target_link_libraries(TestRegistrySnapshot PRIVATE CUDA::cudart anari::anari_static visrtx::glm) target_compile_definitions(TestRegistrySnapshot PRIVATE GLM_ENABLE_EXPERIMENTAL) add_test(NAME TestRegistrySnapshot COMMAND TestRegistrySnapshot) +make_test(TestDeferredGeometryPreparation) +target_link_libraries(TestDeferredGeometryPreparation PRIVATE CUDA::cudart) make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) @@ -110,12 +112,15 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) make_test(TestCudaPreparationFailure) - target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) target_include_directories(TestCudaPreparationFailure PRIVATE ${OptiX_ROOT_DIR}/include) set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) add_test(NAME TestIsosurfacePreparationRecovery COMMAND TestCudaPreparationFailure isosurface) foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency + sphere-undrained-completion + sphere-readback-allocation sphere-batch-completion + sphere-batch-upload-completion sphere-upload-allocation sphere-upload-copy sphere-upload-completion sphere-upload-partial) add_test(NAME TestSpherePreparationRecovery_${geometry} @@ -130,7 +135,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S add_test(NAME TestBvhPreparationRecovery_${failure} COMMAND TestCudaPreparationFailure ${failure}) endforeach() - foreach(failure allocation copy work-sync copy-sync) + foreach(failure allocation copy work-sync copy-sync pending-retirement) add_test(NAME TestArrayPrivatizationFailure_${failure} COMMAND TestCudaPreparationFailure ${failure}) endforeach() diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index b4c4c37e6..e84e5914d 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -40,10 +40,14 @@ #include #include #include +#include #include +#include #include #include #include +#include +#include #include namespace { @@ -51,10 +55,12 @@ enum class Failure { NONE, ALLOCATION, + READBACK_ALLOCATION, COPY, WORK_SYNC, COPY_SYNC, PREPARATION_SYNC, + PREPARATION_EARLY_SYNC, PREPARATION_DEPENDENCY, BVH_SYNC, BVH_COPY, @@ -80,6 +86,39 @@ int injections = 0; int errors = 0; std::atomic completions{0}; +struct PendingCompletion +{ + cudaEvent_t done{}; + const void *scratch{nullptr}; + bool queued{false}; + bool failed{false}; + bool drained{false}; + bool pendingAtFailure{false}; + bool pendingAtDrain{false}; + bool prematureFree{false}; + bool prematureReport{false}; + bool retired{false}; + std::atomic released{false}; + std::atomic timedOut{false}; + std::mutex mutex; + std::condition_variable condition; +} pendingCompletion; + +void releasePendingWork() +{ + { + std::lock_guard lock(pendingCompletion.mutex); + pendingCompletion.released = true; + } + pendingCompletion.condition.notify_one(); +} + +void CUDART_CB blockPreparation(void *) +{ + while (!pendingCompletion.released.load()) + std::this_thread::yield(); +} + bool inject(Failure kind) { if (failure != kind) @@ -109,6 +148,8 @@ void status(const void *, const char *message) { if (severity <= ANARI_SEVERITY_ERROR) { + pendingCompletion.prematureReport |= + pendingCompletion.failed && !pendingCompletion.drained; ++errors; fprintf(stderr, "%s\n", message); } @@ -119,6 +160,15 @@ void complete(const void *, ANARIDevice, ANARIFrame) } } // namespace +extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) +{ + if (bytes == 16 && inject(Failure::READBACK_ALLOCATION)) { + *ptr = nullptr; + return cudaErrorMemoryAllocation; + } + return next("cudaMallocHost")(ptr, bytes); +} + extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) { if (bytes == allocationBytes && inject(Failure::ALLOCATION)) { @@ -130,6 +180,15 @@ extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) return next("cudaMalloc")(ptr, bytes); } +extern "C" cudaError_t cudaFree(void *ptr) +{ + if (ptr && ptr == pendingCompletion.scratch) { + pendingCompletion.retired = true; + pendingCompletion.prematureFree |= !pendingCompletion.drained; + } + return next("cudaFree")(ptr); +} + extern "C" cudaError_t cudaMemcpy( void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) { @@ -199,13 +258,49 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, bvhReadback = true; } } + if (failure == Failure::PREPARATION_EARLY_SYNC && stream == preparationStream + && kind == cudaMemcpyDeviceToHost + && bytes == sizeof(float) + sizeof(uint32_t) + && !pendingCompletion.queued) { + // The bounds summary is a float scale and uint32 status. Gate its pinned + // readback after kernel submission, with no subsequent allocation or + // pageable copy to supply a hidden wait. + auto error = cudaLaunchHostFunc(stream, blockPreparation, nullptr); + if (error != cudaSuccess) + return error; + pendingCompletion.queued = true; + pendingCompletion.scratch = src; + error = next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); + if (error == cudaSuccess) + error = cudaEventRecord(pendingCompletion.done, stream); + return error; + } return next("cudaMemcpyAsync")( dst, src, bytes, kind, stream); } extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) { - // Drain real work even when simulating a failed completion report. + if (stream == preparationStream && pendingCompletion.queued) { + if (inject(Failure::PREPARATION_EARLY_SYNC)) { + pendingCompletion.pendingAtFailure = + cudaEventQuery(pendingCompletion.done) == cudaErrorNotReady; + pendingCompletion.failed = true; + return cudaErrorUnknown; // Deliberately do NOT drain the real work. + } + if (pendingCompletion.failed && !pendingCompletion.drained) { + pendingCompletion.pendingAtDrain = + cudaEventQuery(pendingCompletion.done) == cudaErrorNotReady; + releasePendingWork(); // Only the fallback drain releases the producer. + const auto error = next( + "cudaStreamSynchronize")(stream); + pendingCompletion.drained = error == cudaSuccess + && cudaEventQuery(pendingCompletion.done) == cudaSuccess; + return error; + } + } + // Other cases simulate a failed completion report after draining real work. const auto result = next("cudaStreamSynchronize")(stream); if ((stream && inject(Failure::WORK_SYNC)) @@ -223,10 +318,18 @@ extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) int main(int argc, char **argv) { + const bool pendingRetirement = + argc > 1 && std::strcmp(argv[1], "pending-retirement") == 0; const bool isosurfaceFailure = argc > 1 && std::strcmp(argv[1], "isosurface") == 0; const bool sphereFailure = argc > 1 && std::strncmp(argv[1], "sphere", 6) == 0; + const bool earlyCompletion = + sphereFailure && std::strcmp(argv[1], "sphere-undrained-completion") == 0; + const bool batchCompletion = + sphereFailure && std::strncmp(argv[1], "sphere-batch-", 13) == 0; + const bool batchUploadCompletion = batchCompletion + && std::strcmp(argv[1], "sphere-batch-upload-completion") == 0; const bool sphereUpload = argc > 1 && std::strncmp(argv[1], "sphere-upload-", 14) == 0; const bool partialUpload = @@ -265,9 +368,9 @@ int main(int argc, char **argv) ANARI_FLOAT32_VEC3, vertices.size()); auto geometry = anari::newObject(d, - isosurfaceFailure ? "isosurface" - : sphereFailure ? "sphere" - : "curve"); + isosurfaceFailure ? "isosurface" + : (sphereFailure || pendingRetirement) ? "sphere" + : "curve"); if (partialUpload) { const std::array radii{0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f}; anari::setParameterArray1D( @@ -303,10 +406,15 @@ int main(int argc, char **argv) anari::commitParameters(d, surface); std::vector surfaces{surface}; anari::Geometry sibling = nullptr; - if (curveFailure && !isosurfaceFailure && !sphereFailure) { - sibling = anari::newObject(d, "curve"); - anari::setParameterArray1D( - d, sibling, "vertex.position", vertices.data(), 4); + if ((curveFailure && !isosurfaceFailure && !sphereFailure) + || batchCompletion) { + sibling = anari::newObject( + d, batchCompletion ? "sphere" : "curve"); + if (batchCompletion && !batchUploadCompletion) + anari::setParameter(d, sibling, "vertex.position", array); + else + anari::setParameterArray1D( + d, sibling, "vertex.position", vertices.data(), 4); anari::setParameter(d, sibling, "radius", 0.1f); anari::commitParameters(d, sibling); auto siblingMaterial = anari::newObject(d, "matte"); @@ -364,7 +472,22 @@ int main(int argc, char **argv) != 0; }; bool ok = errors == 0; - if (registryFailure) { + if (pendingRetirement) { + uint8_t valid = 0; + ok = + anariGetProperty( + d, geometry, "valid", ANARI_BOOL, &valid, sizeof(valid), ANARI_WAIT) + && valid && ok; + failure = Failure::PREPARATION_SYNC; + anari::release(d, array); + ok = injections == 1 && errors > 0 && ok; + cudaFree(deviceVertices); + deviceVertices = nullptr; + ok = !haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 0 && ok; + } else if (registryFailure) { ok = haveBounds() && ok; anari::render(d, frame); anari::wait(d, frame); @@ -455,11 +578,42 @@ int main(int argc, char **argv) failure = Failure::UPLOAD_COPY; if (sphereUpload && std::strcmp(argv[1], "sphere-upload-completion") == 0) failure = Failure::UPLOAD_SYNC; - if (sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) + if (sphereFailure + && std::strcmp(argv[1], "sphere-readback-allocation") == 0) + failure = Failure::READBACK_ALLOCATION; + if ((sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) + || batchCompletion) failure = Failure::PREPARATION_SYNC; if (sphereFailure && std::strcmp(argv[1], "sphere-dependency") == 0) failure = Failure::PREPARATION_DEPENDENCY; + std::thread watchdog; + if (earlyCompletion) { + if (cudaEventCreateWithFlags( + &pendingCompletion.done, cudaEventDisableTiming) + != cudaSuccess) + return 1; + failure = Failure::PREPARATION_EARLY_SYNC; + watchdog = std::thread([] { + std::unique_lock lock(pendingCompletion.mutex); + if (!pendingCompletion.condition.wait_for(lock, + std::chrono::seconds(5), + [] { return pendingCompletion.released.load(); })) { + pendingCompletion.timedOut = true; + pendingCompletion.released = true; + } + }); + } ok = !haveBounds() && ok; + if (earlyCompletion) { + // Cleanup cannot conceal a missing fallback drain. Snapshot its outcome + // before unblocking the gate ourselves and destroying any resources. + ok = pendingCompletion.queued && pendingCompletion.pendingAtFailure + && pendingCompletion.pendingAtDrain && pendingCompletion.drained + && !pendingCompletion.timedOut && !pendingCompletion.prematureFree + && !pendingCompletion.prematureReport && ok; + releasePendingWork(); + watchdog.join(); + } // The unaffected sibling must not inherit the first geometry's OOM. // Recovery below must succeed without recommitting the sibling. ok = injections == 1 && errors == 1 && ok; @@ -470,6 +624,13 @@ int main(int argc, char **argv) anari::setParameter( d, geometry, isosurfaceFailure ? "isovalue" : "radius", 0.2f); anari::commitParameters(d, geometry); + if (batchCompletion) { + // A completion error invalidates the whole pending batch, not just its + // first geometry. Repreparing only that geometry cannot publish a world. + ok = !haveBounds() && errors == beforeErrors && ok; + anari::setParameter(d, sibling, "radius", 0.25f); + anari::commitParameters(d, sibling); + } ok = haveBounds() && errors == beforeErrors && ok; anari::render(d, frame); anari::wait(d, frame); @@ -547,6 +708,10 @@ int main(int argc, char **argv) if (sibling) anari::release(d, sibling); anari::release(d, d); + if (earlyCompletion) { + ok = pendingCompletion.retired && !pendingCompletion.prematureFree && ok; + cudaEventDestroy(pendingCompletion.done); + } printf("%s injections=%d %s\n", curveFailure ? "curve" : argv[1], injections, diff --git a/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp new file mode 100644 index 000000000..71264f7b3 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int freed = 0; +int errors = 0; +int rejectedQueries = 0; +anari::World callbackWorld = nullptr; + +void releaseDevice(const void *, const void *memory) +{ + cudaFree(const_cast(memory)); + ++freed; +} + +void status(const void *, + ANARIDevice d, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity > ANARI_SEVERITY_ERROR) + return; + ++errors; + std::fprintf(stderr, "%s\n", message); + if (callbackWorld) { + std::array bounds{}; + if (!anariGetProperty(d, + callbackWorld, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT)) + ++rejectedQueries; + } +} + +bool position(anari::Device d, anari::Geometry geometry, float x) +{ + const std::array center{x, 0, 0}; + void *device = nullptr; + if (cudaMalloc(&device, sizeof(center)) != cudaSuccess + || cudaMemcpy( + device, center.data(), sizeof(center), cudaMemcpyHostToDevice) + != cudaSuccess) + return false; + auto array = + anariNewArray1D(d, device, releaseDevice, nullptr, ANARI_FLOAT32_VEC3, 1); + anariSetParameter(d, geometry, "vertex.position", ANARI_ARRAY1D, &array); + anariRelease(d, array); + anari::setParameter(d, geometry, "radius", 1.f); + anari::commitParameters(d, geometry); + return true; +} + +bool flushGeometry(anari::Device d, anari::Geometry geometry) +{ + uint8_t valid = 0; + return anariGetProperty(d, + geometry, + "valid", + ANARI_BOOL, + &valid, + sizeof(valid), + ANARI_WAIT) + && valid; +} +} // namespace + +int main() +{ + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject(d, "sphere"); + if (!position(d, geometry, 0.f)) + return 1; + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + + // Flush finalizers without requesting a BVH: readbacks remain queued. + bool ok = flushGeometry(d, geometry) && freed == 0; + ok = position(d, geometry, 4.f) && ok; + ok = flushGeometry(d, geometry) && freed == 1 && ok; + std::array bounds{}; + auto haveBounds = [&] { + return anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + != 0; + }; + ok = haveBounds() && std::fabs(bounds[0] - 3.f) < 1e-4f + && std::fabs(bounds[3] - 5.f) < 1e-4f && errors == 0 && ok; + + // A failed, unreferenced geometry must not poison an unrelated world. A + // status callback must not reenter collection and publish partial results. + auto invalid = anari::newObject(d, "sphere"); + ok = position(d, invalid, std::numeric_limits::quiet_NaN()) && ok; + ok = flushGeometry(d, invalid) && ok; + callbackWorld = world; + ok = haveBounds() && errors == 1 && rejectedQueries == 1 && ok; + callbackWorld = nullptr; + anari::release(d, invalid); + + // The pending queue owns a last-reference geometry until device teardown. + auto orphan = anari::newObject(d, "sphere"); + ok = position(d, orphan, 8.f) && flushGeometry(d, orphan) && ok; + anari::release(d, orphan); + anari::release(d, world); + anari::release(d, geometry); + ok = freed == 3 && ok; + anari::release(d, d); + ok = freed == 4 && errors == 1 && ok; + std::printf("deferred geometry: freed=%d errors=%d %s\n", + freed, + errors, + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 4d947fb5a..21d141783 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -346,6 +346,10 @@ int VisRTXDevice::getProperty(ANARIObject object, uint64_t size, uint32_t mask) { + // A status callback during collection must not flush/re-finalize geometry + // whose readbacks and registry publication are still being resolved. + if (deviceState()->collectingGeometryPreparations()) + return 0; if (!initDevice()) return 0; CUDADeviceScope ds(this); @@ -375,6 +379,8 @@ const void *VisRTXDevice::frameBufferMap(ANARIFrame f, void VisRTXDevice::renderFrame(ANARIFrame f) { + if (deviceState()->collectingGeometryPreparations()) + return; if (!initDevice()) return; CUDADeviceScope ds(this); @@ -426,6 +432,7 @@ VisRTXDevice::~VisRTXDevice() // material dying here releases its samplers into the registry, so the MDL // teardown below must come after (also what empties the registry before its // "not empty on destruction" check). + state.collectGeometryPreparations(); state.commitBuffer.clear(); #ifdef USE_MDL diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 51cbcdd98..a571abfce 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -192,6 +192,10 @@ void Array::privatize() // Existing frames may still read the shared pointer. The application may // free it as soon as this last PUBLIC release returns. auto completion = cudaStreamSynchronize(state.stream); + // Deferred preprocessing can still read this external allocation even + // when no frame is in flight. Retain it through that stream's completion. + if (completion == cudaSuccess && state.hasPendingGeometryPreparations()) + completion = state.finishGeometryPreparation(); if (completion == cudaSuccess) completion = m_data.shared.device.privatize(); if (completion != cudaSuccess) { diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 2e3021e18..64be4b2b4 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -114,6 +114,8 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { + if (m_preparationQueued) + deviceState()->collectGeometryPreparations(); // Array observers can re-finalize without a parameter commit, but parameter // replacement can release the last reference to an aliased device array. // Complete earlier consumers before subclasses replace those references. @@ -195,14 +197,40 @@ bool Geometry::canRetainPreparationInputs() const return present == m_preparedParameters.size(); } +void Geometry::deferPreparation() +{ + if (!m_preparationQueued) { + deviceState()->enqueueGeometryPreparation(this); + m_preparationQueued = true; + } +} + +void Geometry::completePreparation() +{ + m_preparationQueued = false; + if (!m_preprocessing.complete(this)) { + m_hasPreparedData = false; + return; + } + upload(); +} + void Geometry::upload() { + if (m_preprocessing.pending()) { + deferPreparation(); + return; + } RegisteredObject::upload(); m_hasPreparedData = !preparationFailed() && isValid(); } bool Geometry::beginPreparation(std::initializer_list parameters) { + // Observer-only finalization can arrive before a prior submission is + // collected. + if (m_preparationQueued) + deviceState()->collectGeometryPreparations(); m_preparationPreserved = false; if (m_inputRetirementFailed) return false; @@ -272,7 +300,7 @@ bool Geometry::beginPreparation(std::initializer_list parameters) return false; } if (!checkPreparation(this, - state.preparation.finish(), + state.finishGeometryPreparation(), "geometry array upload completion")) return false; // Never mark a partial/failed batch uploaded: a later commit must retry. diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index 4f9e7d504..330ce43c0 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -77,14 +77,15 @@ struct Geometry : public RegisteredObject void commitParameters() override; void markFinalized() override; void upload(); + void deferPreparation(); + void completePreparation(); virtual void populateBuildInput(OptixBuildInput &) const = 0; virtual int optixGeometryType() const = 0; - // Geometry Light area sampling. Only types that can be sampled by area as an - // Emissive Surface override these (Stage 1: Triangle). ensureAreaData() - // builds the per-primitive area CDF; totalArea() is the object-space emitting - // area. + // Geometry Light area sampling. ensureAreaData() submits a per-primitive + // CDF if needed. Collect device geometry preparations before reading + // totalArea(), the object-space emitting area, or publishing a registry. virtual bool isAreaSamplingSupported() const; virtual void ensureAreaData(); virtual float totalArea() const; @@ -133,6 +134,7 @@ struct Geometry : public RegisteredObject bool m_preparationPreserved{false}; bool m_preparationFailed{false}; bool m_inputRetirementFailed{false}; + bool m_preparationQueued{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index b63b7946b..e16a7f3bb 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -36,14 +36,11 @@ #include #include #include +#include namespace visrtx { namespace { -struct Result -{ - float value; - uint32_t invalid; -}; +using Result = PreparationResult; VISRTX_GLOBAL void primitiveAreas( PrimitiveInput in, double *areas, Result *result) @@ -106,7 +103,7 @@ VISRTX_GLOBAL void normalizeAreas( result->value = area; } // Encode numeric failure in the scalar readback; cone/cylinder bounds have -// already returned their status word for this generation. +// have a separate status readback for this generation. VISRTX_GLOBAL void publishArea(Result *result) { if (result->invalid) @@ -266,7 +263,7 @@ bool checkPreparation(Geometry *g, cudaError_t error, const char *operation) // preparation before retrying or freeing scratch. Keep the render-stream // drain on this error path too: this helper also handles input retirement // and dependency failures, which may precede a successful producer edge. - g->deviceState()->preparation.finish(); + g->deviceState()->finishGeometryPreparation(); cudaStreamSynchronize(g->deviceState()->stream); g->reportMessage(ANARI_SEVERITY_ERROR, "geometry preprocessing failed during %s: %s", @@ -297,8 +294,56 @@ bool finishPreparation(Geometry *g) { // Also establishes an explicit boundary for legacy default-stream consumers. return checkPreparation(g, cudaGetLastError(), "launch") - && checkPreparation( - g, g->deviceState()->preparation.finish(), "execution completion"); + && checkPreparation(g, + g->deviceState()->finishGeometryPreparation(), + "execution completion"); +} + +Preprocessing::~Preprocessing() +{ + if (m_readback) + cudaFreeHost(m_readback); +} + +bool Preprocessing::reserveReadback(Geometry *g) +{ + if (m_readback) + return true; + Result *readback = nullptr; + if (!checkPreparation(g, + cudaMallocHost( + reinterpret_cast(&readback), 2 * sizeof(Result)), + "allocating preparation readback")) + return false; + m_readback = readback; + return true; +} + +bool Preprocessing::pending() const +{ + return m_scale || m_total; +} + +bool Preprocessing::complete(Geometry *g) +{ + auto *scale = std::exchange(m_scale, nullptr); + auto *total = std::exchange(m_total, nullptr); + auto *cdf = std::exchange(m_cdf, nullptr); + if (g->preparationFailed()) + return false; + if (scale && m_readback[0].invalid) + return checkPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); + if (total && !std::isfinite(m_readback[1].value)) + return checkPreparation( + g, cudaErrorInvalidValue, "non-publishable primitive area"); + if (scale) + *scale = m_readback[0].value; + if (total) { + *total = m_readback[1].value; + if (*total == 0.f) + cdf->reset(); + } + return true; } bool Preprocessing::bounds( @@ -306,6 +351,11 @@ bool Preprocessing::bounds( { const auto stream = g->deviceState()->preparation.stream(); scale = 0.f; + if (!reserveReadback(g)) + return false; + g->deferPreparation(); + m_scale = &scale; + m_readback[0] = {}; if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) || !reservePreparation(g, m_result, sizeof(Result)) || !checkPreparation(g, @@ -315,7 +365,7 @@ bool Preprocessing::bounds( if (in.count) primitiveBounds<<<(in.count + 255) / 256, 256, 0, stream>>>( in, aabbs.ptrAs(), m_result.ptrAs()); - Result host{}; + auto &host = m_readback[0]; const bool sdf = in.type == GeometryType::SDF; if (!checkPreparation(g, cudaGetLastError(), "bounds evaluation") || !checkPreparation(g, @@ -325,12 +375,8 @@ bool Preprocessing::bounds( sdf ? sizeof(host.invalid) : sizeof(host), cudaMemcpyDeviceToHost, stream), - "bounds summary") - || !finishPreparation(g)) + "bounds summary")) return false; - if (host.invalid) - return checkPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); - scale = host.value; return true; } @@ -344,6 +390,12 @@ bool Preprocessing::areas( } if (in.count > size_t(std::numeric_limits::max())) return checkPreparation(g, cudaErrorInvalidValue, "primitive count"); + if (!reserveReadback(g)) + return false; + g->deferPreparation(); + m_total = &total; + m_cdf = &cdf; + m_readback[1] = {}; const auto stream = g->deviceState()->preparation.stream(); size_t scratchBytes = 0; if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) @@ -377,7 +429,7 @@ bool Preprocessing::areas( if (!checkPreparation(g, cudaGetLastError(), "CDF normalization")) return false; publishArea<<<1, 1, 0, stream>>>(result); - Result host{}; + auto &host = m_readback[1]; if (!checkPreparation(g, cudaGetLastError(), "area publication") || !checkPreparation(g, cudaMemcpyAsync(&host.value, @@ -385,15 +437,8 @@ bool Preprocessing::areas( sizeof(host.value), cudaMemcpyDeviceToHost, stream), - "area readback") - || !finishPreparation(g)) + "area readback")) return false; - if (!std::isfinite(host.value)) - return checkPreparation( - g, cudaErrorInvalidValue, "non-publishable primitive area"); - total = host.value; - if (total == 0.f) - cdf.reset(); return true; } } // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index d5772ec62..48c3e48be 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -56,15 +56,25 @@ struct PrimitiveInput float noiseFactor{0.f}; }; -// Per-geometry reusable workspace. Only the compact result crosses to the host. +struct PreparationResult +{ + float value; + uint32_t invalid; +}; + +// Per-geometry reusable workspace. Submission retains pinned readback storage; +// complete() publishes scalar results after the device's collection barrier. struct Preprocessing { Preprocessing() = default; + ~Preprocessing(); Preprocessing(const Preprocessing &) = delete; Preprocessing &operator=(const Preprocessing &) = delete; Preprocessing(Preprocessing &&) = delete; Preprocessing &operator=(Preprocessing &&) = delete; + // Success means submitted, not published. Output references must be owned + // by the retained geometry and remain valid until collection completes. bool areas(Geometry *geometry, const PrimitiveInput &input, DeviceBuffer &cdf, @@ -74,7 +84,15 @@ struct Preprocessing DeviceBuffer &aabbs, float &scale); + bool pending() const; + bool complete(Geometry *geometry); + private: + bool reserveReadback(Geometry *geometry); + PreparationResult *m_readback{nullptr}; + float *m_scale{nullptr}; + float *m_total{nullptr}; + DeviceBuffer *m_cdf{nullptr}; DeviceBuffer m_prefix; DeviceBuffer m_scratch; DeviceBuffer m_result; diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index a73026230..3be2b121e 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -109,8 +109,7 @@ void SDF::finalize() input.blendFactor = m_blendFactor; input.blendLerpFactor = m_blendLerpFactor; input.noiseFactor = m_noiseFactor; - float unusedScale = 0.f; - if (!m_preprocessing.bounds(this, input, m_aabbs, unusedScale)) + if (!m_preprocessing.bounds(this, input, m_aabbs, m_epsilonScale)) return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 396d578e5..1b477208f 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -30,7 +30,9 @@ */ #include "optix_visrtx.h" +#include #include "Object.h" +#include "geometry/Geometry.h" #ifdef USE_MDL #include @@ -181,6 +183,60 @@ DeviceGlobalState::DeviceGlobalState(ANARIDevice d) DeviceGlobalState::~DeviceGlobalState() = default; +void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) +{ + m_geometryPreparations.emplace_back(geometry); +} + +bool DeviceGlobalState::collectingGeometryPreparations() const +{ + return m_collectingGeometryPreparations; +} + +bool DeviceGlobalState::hasPendingGeometryPreparations() const +{ + return m_collectingGeometryPreparations || !m_geometryPreparations.empty(); +} + +cudaError_t DeviceGlobalState::finishGeometryPreparation() +{ + const auto error = preparation.finish(); + if (error != cudaSuccess) { + // An intervening upload/legacy consumer may wait before the collection + // point. Its stream-completion error affects all already queued results. + for (auto &geometry : m_geometryPreparations) + geometry->setPreparationFailed(true); + } + return error; +} + +bool DeviceGlobalState::collectGeometryPreparations() +{ + if (m_collectingGeometryPreparations) + return false; + if (m_geometryPreparations.empty()) + return true; + m_collectingGeometryPreparations = true; + auto collecting = nonstd::make_scope_exit( + [&] { m_collectingGeometryPreparations = false; }); + auto pending = std::move(m_geometryPreparations); + const auto error = preparation.finish(); + if (error != cudaSuccess) { + // A stream error invalidates every generation in this batch. Mark them + // before reporting, so callbacks cannot see a partially valid generation. + for (auto &geometry : pending) + geometry->setPreparationFailed(true); + checkPreparation(pending.front().ptr, error, "batch completion"); + } + for (auto &geometry : pending) + geometry->completePreparation(); + pending.clear(); + m_geometryPreparations.swap(pending); // Reuse queue capacity next batch. + // Failure is local to the affected geometries; unrelated worlds remain + // usable. + return true; +} + cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( PreparationStream &preparation, cudaStream_t renderStream) { diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 9ba2f3e84..b4e54b432 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -40,6 +40,7 @@ // anari #include // optix +#include #include #include #include @@ -156,6 +157,7 @@ VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::box3, ANARI_FLOAT32_BOX3); namespace visrtx { struct Object; +struct Geometry; struct MDL; struct ptx_blob @@ -272,6 +274,16 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceGlobalState(ANARIDevice d); ~DeviceGlobalState() override; + + void enqueueGeometryPreparation(Geometry *geometry); + bool collectGeometryPreparations(); + cudaError_t finishGeometryPreparation(); + bool collectingGeometryPreparations() const; + bool hasPendingGeometryPreparations() const; + + private: + std::vector> m_geometryPreparations; + bool m_collectingGeometryPreparations{false}; }; bool buildOptixBVH(std::vector buildInput, diff --git a/devices/rtx/device/world/Group.cpp b/devices/rtx/device/world/Group.cpp index 6fba61a90..f4a502e72 100644 --- a/devices/rtx/device/world/Group.cpp +++ b/devices/rtx/device/world/Group.cpp @@ -231,6 +231,8 @@ bool Group::geometryPreparationFailed() const void Group::rebuildSurfaceBVHs() { + if (!deviceState()->collectGeometryPreparations()) + return; if (geometryPreparationFailed()) return; const auto &state = *deviceState(); diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index 95e2d0fef..26db24ad5 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -264,6 +264,8 @@ bool World::preparationFailed() const void World::rebuildWorld() { + if (!deviceState()->collectGeometryPreparations()) + return; if (m_bvhBuildFailed) m_objectUpdates.lastTLASBuild = 0; m_bvhBuildFailed = false; @@ -636,7 +638,6 @@ void World::synthesizeGeometryLights() auto configure = [](Surface *surface) { if (surface->isSampleableEmitter()) { auto *geometry = surface->geometry(); - geometry->ensureAreaData(); if (geometry->preparationFailed()) return; const float area = geometry->totalArea(); @@ -652,15 +653,25 @@ void World::synthesizeGeometryLights() }; std::set visited; + std::vector candidates; for (auto *inst : m_instances) { auto *group = inst->group(); if (!visited.insert(group).second) continue; for (auto *surface : group->surfacesTriangle()) - configure(surface); + candidates.push_back(surface); for (auto *surface : group->surfacesUser()) - configure(surface); + candidates.push_back(surface); } + // Submit every newly requested CDF before collecting scalar areas. Shared + // geometry's validity flag prevents duplicate submissions across surfaces. + for (auto *surface : candidates) + if (surface->isSampleableEmitter()) + surface->geometry()->ensureAreaData(); + if (!deviceState()->collectGeometryPreparations()) + return; + for (auto *surface : candidates) + configure(surface); } void World::buildInstanceLightGPUData() diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 1ac767950..29a26f409 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -127,8 +127,9 @@ is reused. slots are staged unless registry growth requires a full copy. Edits made after a snapshot remain dirty for the next batch. No registry lock is held during CUDA waits, so completion callbacks cannot be blocked by that lock. -- Host bounds/area summaries and BVH publication still require preparation-stream - completion. BVH scratch survives through that completion; handles/bounds are +- Host bounds/area summaries are collected after batched submission (see below). + BVH publication still requires preparation-stream completion. BVH scratch + survives through that completion; handles/bounds are published only on success. Group/World failure state prevents failed builds from being treated as ready and permits a later retry. - Parameter-reference replacement and last-public-release privatization retain @@ -155,13 +156,50 @@ and completion errors, partial registry batches, and retry without recommitting already-finalized objects. `TestRegistrySnapshot` verifies stable copy sources across host-vector growth and preservation of newer dirty edits. +## Geometry submission and collection + +Checked bounds and area-CDF preparation submit kernels and asynchronous readbacks +into geometry-owned pinned storage. A successful submission is not publication: +scalar outputs, numeric validation, and geometry registry updates happen only +after collection. The device queue retains each submitted geometry, and thereby +its arrays and derived buffers, until those operations finish. + +Group/World rebuilds collect queued finalizations before constructing BVHs. Lazy +Geometry Light area requests are submitted for all candidate surfaces first, +then collected together before configuring lights. Shared geometry is queued +once. A numeric failure invalidates its geometry only; a stream-completion error +invalidates every pending generation, including errors observed by an intervening +upload or legacy completion wait. Failed generations cannot take preparation reuse. + +A recommit or observer-only re-finalization drains the geometry's previous queued +work before reusing its storage. Last-public-release privatization of shared CUDA +arrays also drains pending preparation readers, not just rendering. Device +teardown collects the queue before releasing objects or CUDA/OptiX resources. +Status callbacks cannot reenter device property queries or rendering while +collection is resolving results; those calls are refused instead of publishing +a partially collected scene. + +Pinned readback storage is reused per geometry. Pooling these small allocations +is a future scaling improvement. Host input upload batches still complete per +geometry to preserve their source lifetime and existing legacy consumers; +quad/curve generated-data completion, tangent generation, and field/isosurface +preparation retain their current synchronous paths. This does not introduce +independent scene generations or concurrent in-place replacement during tracing. + +`TestDeferredGeometryPreparation` covers recommitting a queued geometry, retained +captured-device inputs, last-reference queue ownership through teardown, unrelated +numeric failures, and collection-time callback reentry. Injection cases also +cover pinned-readback allocation failure, completion failure across multiple +queued geometries, an intervening upload completion failure, and shared CUDA +array retirement while preparation remains pending. + ## Remaining work Broader array/shading invalidation precision, reducing the extra CPU snapshot comparison cost, batched readback/dispatch, and fine-grained area-vs-bounds -invalidation are separate improvements. Registry batching spans geometries, but -geometry input/bounds/area preparation still completes per geometry. Batching -that work across geometries requires splitting finalization into submission and -result collection while preserving source lifetimes and failure propagation. This change does not repack or download +invalidation are separate improvements. Registry, bounds, and area-result +collection now span geometries. Batching the remaining host-input uploads and +legacy finalizers requires further producer migration while preserving source +lifetimes and failure propagation. This change does not repack or download inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs are prepared on the GPU before their derived data is published. From cf9eb365355830eb504889ac3270f1e964f9fce2 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:49:55 +0000 Subject: [PATCH 09/20] perf(rtx): pool pinned geometry readbacks Lease result slots from device-local pinned pages instead of allocating one pinned buffer per geometry. Cache pages for reuse and retain page ownership independently of the pool until every lease is returned. Cover page-growth failures, retry, move/reset, concurrent slot use, asynchronous DMA, and pool-before-lease teardown. --- devices/rtx/apps/tests/api/CMakeLists.txt | 5 + .../tests/api/TestCudaPreparationFailure.cpp | 8 +- .../tests/api/TestGeometryReadbackPool.cpp | 225 ++++++++++++++++++ devices/rtx/device/geometry/Preprocessing.cu | 12 +- devices/rtx/device/geometry/Preprocessing.h | 8 +- devices/rtx/device/geometry/ReadbackPool.h | 206 ++++++++++++++++ devices/rtx/device/optix_visrtx.h | 2 + .../rtx/docs/geometry-preparation-reuse.md | 23 +- 8 files changed, 469 insertions(+), 20 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp create mode 100644 devices/rtx/device/geometry/ReadbackPool.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index bc87cc008..96b9005a1 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -111,6 +111,11 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S make_test(TestFramePublicationRecovery) target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) + add_executable(TestGeometryReadbackPool TestGeometryReadbackPool.cpp) + target_link_libraries(TestGeometryReadbackPool PRIVATE + CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) + set_target_properties(TestGeometryReadbackPool PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestGeometryReadbackPool COMMAND TestGeometryReadbackPool) make_test(TestCudaPreparationFailure) target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) target_include_directories(TestCudaPreparationFailure PRIVATE ${OptiX_ROOT_DIR}/include) diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index e84e5914d..e9e7bbd33 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -49,6 +49,7 @@ #include #include #include +#include "../../../device/geometry/ReadbackPool.h" namespace { enum class Failure @@ -162,9 +163,12 @@ void complete(const void *, ANARIDevice, ANARIFrame) extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) { - if (bytes == 16 && inject(Failure::READBACK_ALLOCATION)) { + constexpr size_t readbackPageBytes = 2 + * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE + * sizeof(visrtx::PreparationResult); + if (bytes == readbackPageBytes && inject(Failure::READBACK_ALLOCATION)) { *ptr = nullptr; - return cudaErrorMemoryAllocation; + return next("cudaMallocHost")(ptr, size_t(-1)); } return next("cudaMallocHost")(ptr, bytes); } diff --git a/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp b/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp new file mode 100644 index 000000000..7e8f233a5 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/geometry/ReadbackPool.h" + +namespace { +std::atomic failNext{false}; +std::atomic attempts{0}; +std::atomic allocations{0}; +std::atomic frees{0}; + +template +T next(const char *name) +{ + auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!function) + std::abort(); + return function; +} +} // namespace + +extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) +{ + ++attempts; + if (failNext.exchange(false)) { + *ptr = nullptr; + return next("cudaMallocHost")(ptr, size_t(-1)); + } + const auto error = + next("cudaMallocHost")(ptr, bytes); + if (error == cudaSuccess) + ++allocations; + return error; +} + +extern "C" cudaError_t cudaFreeHost(void *ptr) +{ + const auto error = next("cudaFreeHost")(ptr); + if (error == cudaSuccess && ptr) + ++frees; + return error; +} + +int main(int argc, char **argv) +{ + if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "--no-failure") != 0)) + return 2; + const bool injectFailures = argc == 1; + using Pool = visrtx::GeometryReadbackPool; + bool ok = true; + { + Pool pool; + Pool::Lease failed; + if (injectFailures) { + failNext = true; + ok = pool.acquire(failed) != cudaSuccess + && cudaGetLastError() == cudaSuccess && !failed.data() + && allocations == 0 && ok; + } + + std::vector leases(Pool::SLOTS_PER_PAGE + 1); + for (size_t i = 0; i < leases.size(); ++i) { + if (injectFailures && i == Pool::SLOTS_PER_PAGE) { + failNext = true; + ok = pool.acquire(leases[i]) != cudaSuccess + && cudaGetLastError() == cudaSuccess && !leases[i].data() + && allocations == 1 && ok; + } + if (pool.acquire(leases[i]) != cudaSuccess) + return 1; + leases[i].data()[0] = {float(i), uint32_t(i)}; + leases[i].data()[1] = {-float(i), uint32_t(i + 1)}; + } + // Exercise independent asynchronous DMA targets on the same pinned page, + // including writes to one slot while the CPU initializes a later slot. + std::vector source(2 * leases.size()); + for (size_t i = 0; i < leases.size(); ++i) { + source[2 * i] = leases[i].data()[0]; + source[2 * i + 1] = leases[i].data()[1]; + } + void *device = nullptr; + cudaStream_t stream = nullptr; + const size_t bytes = source.size() * sizeof(source[0]); + if (cudaMalloc(&device, bytes) != cudaSuccess + || cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) + != cudaSuccess + || cudaMemcpyAsync( + device, source.data(), bytes, cudaMemcpyHostToDevice, stream) + != cudaSuccess) + return 1; + for (size_t i = 0; i < leases.size(); ++i) { + leases[i].data()[0] = {}; + leases[i].data()[1] = {}; + if (cudaMemcpyAsync(leases[i].data(), + static_cast(device) + 2 * i, + 2 * sizeof(source[0]), + cudaMemcpyDeviceToHost, + stream) + != cudaSuccess) + return 1; + } + if (cudaStreamSynchronize(stream) != cudaSuccess) + return 1; + cudaFree(device); + cudaStreamDestroy(stream); + std::unordered_set addresses; + for (size_t i = 0; i < leases.size(); ++i) { + addresses.insert(leases[i].data()); + ok = leases[i].data()[0].value == float(i) + && leases[i].data()[1].invalid == i + 1 && ok; + } + ok = addresses.size() == leases.size() && allocations == 2 && frees == 0 + && ok; + auto *first = leases[0].data(); + Pool::Lease moved(std::move(leases[0])); + ok = !leases[0].data() && moved.data() == first && ok; + leases[1] = std::move(moved); // Returns its previous slot exactly once. + ok = !moved.data() && leases[1].data() == first && ok; + Pool::Lease replacement; + if (pool.acquire(replacement) != cudaSuccess) + return 1; + for (auto &lease : leases) + ok = lease.data() != replacement.data() && ok; + replacement.reset(); + replacement.reset(); + leases.clear(); + + // A full release/reacquire cycle stays within the two cached pages. + leases.resize(Pool::SLOTS_PER_PAGE + 1); + addresses.clear(); + for (auto &lease : leases) { + if (pool.acquire(lease) != cudaSuccess) + return 1; + addresses.insert(lease.data()); + } + ok = addresses.size() == leases.size() && allocations == 2 && frees == 0 + && ok; + } + ok = frees == 2 && ok; + + Pool::Lease survivor; + { + Pool pool; + if (pool.acquire(survivor) != cudaSuccess) + return 1; + survivor.data()[0].value = 123.f; + } + ok = frees == 2 && survivor.data()[0].value == 123.f && ok; + survivor.reset(); + ok = frees == 3 && ok; + + { + Pool pool; + Pool::Lease warm; + if (pool.acquire(warm) != cudaSuccess) + return 1; + warm.reset(); + std::atomic concurrentOK{true}; + std::vector workers; + for (unsigned id = 0; id < 8; ++id) { + workers.emplace_back([&, id] { + for (unsigned i = 0; i < 1000; ++i) { + Pool::Lease lease; + if (pool.acquire(lease) != cudaSuccess) { + concurrentOK = false; + return; + } + const float value = float(id * 1000 + i); + lease.data()[0].value = value; + lease.data()[1].invalid = id; + std::this_thread::yield(); + if (lease.data()[0].value != value || lease.data()[1].invalid != id) + concurrentOK = false; + } + }); + } + for (auto &worker : workers) + worker.join(); + ok = concurrentOK && allocations == 4 && ok; + } + ok = allocations == frees + && attempts == allocations + (injectFailures ? 2 : 0) && ok; + std::printf("readback pool: attempts=%d allocations=%d frees=%d %s\n", + int(attempts.load()), + int(allocations.load()), + int(frees.load()), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index e16a7f3bb..49cdc2a18 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -299,23 +299,17 @@ bool finishPreparation(Geometry *g) "execution completion"); } -Preprocessing::~Preprocessing() -{ - if (m_readback) - cudaFreeHost(m_readback); -} +Preprocessing::~Preprocessing() = default; bool Preprocessing::reserveReadback(Geometry *g) { if (m_readback) return true; - Result *readback = nullptr; if (!checkPreparation(g, - cudaMallocHost( - reinterpret_cast(&readback), 2 * sizeof(Result)), + g->deviceState()->geometryReadbacks.acquire(m_readbackLease), "allocating preparation readback")) return false; - m_readback = readback; + m_readback = m_readbackLease.data(); return true; } diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 48c3e48be..673a1e704 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -31,6 +31,7 @@ #pragma once +#include "ReadbackPool.h" #include "gpu/gpu_objects.h" #include "utility/DeviceBuffer.h" @@ -56,12 +57,6 @@ struct PrimitiveInput float noiseFactor{0.f}; }; -struct PreparationResult -{ - float value; - uint32_t invalid; -}; - // Per-geometry reusable workspace. Submission retains pinned readback storage; // complete() publishes scalar results after the device's collection barrier. struct Preprocessing @@ -89,6 +84,7 @@ struct Preprocessing private: bool reserveReadback(Geometry *geometry); + GeometryReadbackPool::Lease m_readbackLease; PreparationResult *m_readback{nullptr}; float *m_scale{nullptr}; float *m_total{nullptr}; diff --git a/devices/rtx/device/geometry/ReadbackPool.h b/devices/rtx/device/geometry/ReadbackPool.h new file mode 100644 index 000000000..90f5108df --- /dev/null +++ b/devices/rtx/device/geometry/ReadbackPool.h @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace visrtx { + +struct PreparationResult +{ + float value; + uint32_t invalid; +}; + +// A device-local high-water cache of pinned pages. Each lease owns two result +// slots and retains its page independently of the pool's lifetime. Returning a +// lease is legal only after its GPU writers have completed; geometry collection +// provides that ordering. Acquisition/release may run on different host +// threads. +struct GeometryReadbackPool +{ + private: + struct Page; + + public: + static constexpr size_t SLOTS_PER_PAGE = 256; + + struct Lease + { + Lease() = default; + ~Lease(); + Lease(const Lease &) = delete; + Lease &operator=(const Lease &) = delete; + Lease(Lease &&other) noexcept; + Lease &operator=(Lease &&other) noexcept; + + PreparationResult *data() const; + void reset(); + + private: + friend struct GeometryReadbackPool; + std::shared_ptr m_page; + size_t m_index{0}; + }; + + GeometryReadbackPool() = default; + GeometryReadbackPool(const GeometryReadbackPool &) = delete; + GeometryReadbackPool &operator=(const GeometryReadbackPool &) = delete; + + cudaError_t acquire(Lease &lease); + + private: + std::mutex m_mutex; + std::vector> m_pages; +}; + +struct GeometryReadbackPool::Page +{ + Page(); + ~Page(); + bool take(size_t &index); + void release(size_t index); + + PreparationResult *memory{nullptr}; + std::mutex mutex; + std::array freeSlots; + size_t freeCount{SLOTS_PER_PAGE}; +}; + +// Inlined definitions //////////////////////////////////////////////////////// + +inline GeometryReadbackPool::Page::Page() +{ + for (size_t i = 0; i < SLOTS_PER_PAGE; ++i) + freeSlots[i] = SLOTS_PER_PAGE - i - 1; +} + +inline GeometryReadbackPool::Page::~Page() +{ + if (memory) + cudaFreeHost(memory); +} + +inline bool GeometryReadbackPool::Page::take(size_t &index) +{ + std::lock_guard lock(mutex); + if (freeCount == 0) + return false; + index = freeSlots[--freeCount]; + return true; +} + +inline void GeometryReadbackPool::Page::release(size_t index) +{ + std::lock_guard lock(mutex); + assert(index < SLOTS_PER_PAGE && freeCount < SLOTS_PER_PAGE); + freeSlots[freeCount++] = index; +} + +inline GeometryReadbackPool::Lease::~Lease() +{ + reset(); +} + +inline GeometryReadbackPool::Lease::Lease(Lease &&other) noexcept + : m_page(std::move(other.m_page)), m_index(other.m_index) +{} + +inline GeometryReadbackPool::Lease &GeometryReadbackPool::Lease::operator=( + Lease &&other) noexcept +{ + if (this != &other) { + reset(); + m_page = std::move(other.m_page); + m_index = other.m_index; + } + return *this; +} + +inline PreparationResult *GeometryReadbackPool::Lease::data() const +{ + return m_page ? m_page->memory + 2 * m_index : nullptr; +} + +inline void GeometryReadbackPool::Lease::reset() +{ + if (m_page) { + m_page->release(m_index); + m_page.reset(); + } +} + +inline cudaError_t GeometryReadbackPool::acquire(Lease &lease) +{ + if (lease.data()) + return cudaSuccess; + { + std::lock_guard lock(m_mutex); + for (auto &page : m_pages) { + if (page->take(lease.m_index)) { + lease.m_page = page; + return cudaSuccess; + } + } + } + + // CUDA allocation can wait for other work. Do not hold a pool/page mutex + // across it; simultaneous growth may allocate an extra page, but is safe. + auto page = std::make_shared(); + void *memory = nullptr; + const auto error = + cudaMallocHost(&memory, 2 * SLOTS_PER_PAGE * sizeof(PreparationResult)); + if (error != cudaSuccess) { + cudaGetLastError(); // A failed page allocation must not poison a retry. + return error; + } + page->memory = static_cast(memory); + { + std::lock_guard lock(m_mutex); + m_pages.push_back(page); + const bool acquired = page->take(lease.m_index); + assert(acquired); + (void)acquired; + lease.m_page = std::move(page); + } + return cudaSuccess; +} + +} // namespace visrtx diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index b4e54b432..7797fae48 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -31,6 +31,7 @@ #pragma once +#include "geometry/ReadbackPool.h" #include "gpu/gpu_objects.h" #include "utility/DeviceObjectArray.h" #include "utility/PreparationStream.h" @@ -177,6 +178,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUcontext cudaContext; CUstream stream; PreparationStream preparation; + GeometryReadbackPool geometryReadbacks; cudaDeviceProp deviceProps; OptixDeviceContext optixContext; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 29a26f409..1d397fc7b 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -179,9 +179,26 @@ Status callbacks cannot reenter device property queries or rendering while collection is resolving results; those calls are refused instead of publishing a partially collected scene. -Pinned readback storage is reused per geometry. Pooling these small allocations -is a future scaling improvement. Host input upload batches still complete per -geometry to preserve their source lifetime and existing legacy consumers; +Pinned readback storage is leased from the device's `GeometryReadbackPool`. +Each page holds 256 geometry leases, each containing two result slots (a 4 KiB +page with the current result layout). A geometry keeps its lease across updates; +returning it after collection makes the slot reusable without a CUDA allocation. +The pool caches pages at its high-water mark until device teardown rather than +trimming on every geometry destruction. A lease retains its page independently +of the pool's lifetime, so cleanup cannot free storage while a lease still exists. +This reduces allocation count, not necessarily requested bytes for tiny scenes: +a partially occupied page still reserves the whole page. + +Pool/page locks protect slot accounting but are never held across CUDA allocation +or free. A failed page allocation leaves existing leases intact and clears CUDA +last-error state before retry. Concurrent growth may allocate an extra page; +source/result lifetime ordering remains the collection queue's responsibility. +`TestGeometryReadbackPool` covers first-page/growth failure and retry, slot reuse, +move/reset, pool-before-lease teardown, concurrent leases, and asynchronous DMA +into separate slots on a page. + +Host input upload batches still complete per geometry to preserve their source +lifetime and existing legacy consumers; quad/curve generated-data completion, tangent generation, and field/isosurface preparation retain their current synchronous paths. This does not introduce independent scene generations or concurrent in-place replacement during tracing. From 7e8d39f3d22f21ebb8969506849a5ed44df3a3b6 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:12:28 +0000 Subject: [PATCH 10/20] perf(rtx): batch committed geometry input uploads Capture declared input arrays during commits and upload them together before geometry finalization. Deduplicate shared array versions and retain sources through checked completion. Retire obsolete snapshots before allocating multi-geometry cohorts; preserve single-geometry ordering and observer-only fallback. Cover batch failure, observer recovery, host retirement, and in-place timing. --- .../api/BenchmarkGeometryPreprocessing.cpp | 31 +- devices/rtx/apps/tests/api/CMakeLists.txt | 7 +- .../tests/api/TestCudaPreparationFailure.cpp | 29 +- .../apps/tests/api/TestGeometryInputBatch.cpp | 304 ++++++++++++++++++ .../apps/tests/api/benchmark_preprocessing.py | 6 +- devices/rtx/device/array/Array.cpp | 12 + devices/rtx/device/geometry/Cone.cpp | 14 +- devices/rtx/device/geometry/Curve.cpp | 8 +- devices/rtx/device/geometry/Cylinder.cpp | 16 +- devices/rtx/device/geometry/Geometry.cpp | 135 ++++++-- devices/rtx/device/geometry/Geometry.h | 25 +- devices/rtx/device/geometry/Quad.cpp | 15 +- devices/rtx/device/geometry/SDF.cpp | 23 +- devices/rtx/device/geometry/Sphere.cu | 8 +- devices/rtx/device/geometry/Triangle.cpp | 28 +- devices/rtx/device/optix_visrtx.cpp | 80 ++++- devices/rtx/device/optix_visrtx.h | 9 + .../rtx/docs/geometry-preparation-reuse.md | 58 ++-- .../geometry-preprocessing-performance.md | 8 +- 19 files changed, 701 insertions(+), 115 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp diff --git a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp index b148bec74..5264cd91e 100644 --- a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp +++ b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp @@ -32,6 +32,7 @@ // Manual evidence tool, deliberately not a wall-clock CTest assertion. #include #include +#include #include #include #include @@ -67,7 +68,7 @@ int main(int argc, char **argv) { if (argc < 5 || argc > 10) { fprintf(stderr, - "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged|overlap] [frames:0=bounds] [emissive:0|1]\n", + "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged|overlap|update] [frames:0=bounds] [emissive:0|1]\n", argv[0]); return 2; } @@ -83,7 +84,8 @@ int main(int argc, char **argv) if (!n || repeats < 2 || sharedSurfaces < 1 || distinctGeometries < 1 || numFrames < 0 || (mode != "recommit" && mode != "replace" && mode != "unchanged" - && mode != "overlap") + && mode != "overlap" && mode != "update") + || (mode == "update" && (device || type == "sdf")) || (mode == "overlap" && numFrames != 1) || (type != "triangle" && type != "sphere" && type != "cone" && type != "cylinder" && type != "quad" && type != "curve" @@ -92,6 +94,7 @@ int main(int argc, char **argv) auto d = makeVisRTXDevice(status); const auto setupStart = std::chrono::steady_clock::now(); std::vector geometries; + std::vector positionArrays; std::vector positions; std::vector radii; std::vector sphereIndices; @@ -135,7 +138,13 @@ int main(int argc, char **argv) auto setInputs = [&](anari::Geometry geometry) { if (type == "sdf") setTestArray(d, geometry, "primitive.sdf", sdf, device, 0); - else + else if (mode == "update") { + auto array = anari::newArray1D(d, ANARI_FLOAT32_VEC3, positions.size()); + std::copy(positions.begin(), positions.end(), anari::map(d, array)); + anari::unmap(d, array); + anari::setParameter(d, geometry, "vertex.position", array); + positionArrays.push_back(array); + } else setTestArray(d, geometry, "vertex.position", positions, device, 0); if (type == "triangle") setTestArray(d, geometry, "primitive.index", triIndices, device, 0); @@ -216,10 +225,20 @@ int main(int argc, char **argv) for (int iteration = 0; iteration < repeats; ++iteration) { const auto start = std::chrono::steady_clock::now(); if (iteration > 0) { - for (auto geometry : geometries) { + for (size_t g = 0; g < geometries.size(); ++g) { + auto geometry = geometries[g]; + if (mode == "update") { + auto *mapped = anari::map(d, positionArrays[g]); + if (!mapped) + return 1; + std::copy(positions.begin(), positions.end(), mapped); + for (size_t i = 0; i < positions.size(); ++i) + mapped[i][2] += (iteration % 2) * 0.001f; + anari::unmap(d, positionArrays[g]); + } if (mode == "replace") setInputs(geometry); // Include allocation, staging, and H2D costs. - else if (mode == "recommit") { + else if (mode == "recommit" || mode == "update") { anari::setParameter( d, geometry, "attribute0", vec4{float(iteration), 0, 0, 0}); anari::commitParameters(d, geometry); @@ -319,6 +338,8 @@ int main(int argc, char **argv) anari::release(d, world); for (auto geometry : geometries) anari::release(d, geometry); + for (auto array : positionArrays) + anari::release(d, array); anari::release(d, d); return 0; } diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 96b9005a1..5bb2cee96 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -111,6 +111,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S make_test(TestFramePublicationRecovery) target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) + make_test(TestGeometryInputBatch) + target_link_libraries(TestGeometryInputBatch PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestGeometryInputBatch PROPERTIES ENABLE_EXPORTS ON) add_executable(TestGeometryReadbackPool TestGeometryReadbackPool.cpp) target_link_libraries(TestGeometryReadbackPool PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) @@ -125,9 +128,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency sphere-undrained-completion sphere-readback-allocation sphere-batch-completion - sphere-batch-upload-completion + sphere-batch-upload-completion sphere-batch-input-completion sphere-upload-allocation sphere-upload-copy sphere-upload-completion - sphere-upload-partial) + sphere-upload-partial sphere-upload-observer) add_test(NAME TestSpherePreparationRecovery_${geometry} COMMAND TestCudaPreparationFailure ${geometry}) endforeach() diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index e9e7bbd33..c6bd83fdd 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -332,10 +332,15 @@ int main(int argc, char **argv) sphereFailure && std::strcmp(argv[1], "sphere-undrained-completion") == 0; const bool batchCompletion = sphereFailure && std::strncmp(argv[1], "sphere-batch-", 13) == 0; + const bool inputBatchCompletion = batchCompletion + && std::strcmp(argv[1], "sphere-batch-input-completion") == 0; const bool batchUploadCompletion = batchCompletion - && std::strcmp(argv[1], "sphere-batch-upload-completion") == 0; - const bool sphereUpload = - argc > 1 && std::strncmp(argv[1], "sphere-upload-", 14) == 0; + && (std::strcmp(argv[1], "sphere-batch-upload-completion") == 0 + || inputBatchCompletion); + const bool sphereUpload = inputBatchCompletion + || (argc > 1 && std::strncmp(argv[1], "sphere-upload-", 14) == 0); + const bool observerRecovery = + sphereUpload && std::strcmp(argv[1], "sphere-upload-observer") == 0; const bool partialUpload = sphereUpload && std::strcmp(argv[1], "sphere-upload-partial") == 0; const bool bvhFailure = argc > 1 @@ -399,7 +404,7 @@ int main(int argc, char **argv) anari::setParameter(d, geometry, "isovalue", 3.5f); } else { anari::setParameter(d, geometry, "vertex.position", array); - anari::setParameter(d, geometry, "radius", 0.1f); + anari::setParameter(d, geometry, "radius", observerRecovery ? 0.2f : 0.1f); } anari::commitParameters(d, geometry); auto material = anari::newObject(d, "matte"); @@ -578,7 +583,9 @@ int main(int argc, char **argv) allocationBytes = partialUpload ? vertices.size() * sizeof(float) : sizeof(vertices); failure = isosurfaceFailure ? Failure::WORK_SYNC : Failure::ALLOCATION; - if (sphereUpload && std::strcmp(argv[1], "sphere-upload-copy") == 0) + if (sphereUpload + && (std::strcmp(argv[1], "sphere-upload-copy") == 0 + || observerRecovery)) failure = Failure::UPLOAD_COPY; if (sphereUpload && std::strcmp(argv[1], "sphere-upload-completion") == 0) failure = Failure::UPLOAD_SYNC; @@ -625,9 +632,15 @@ int main(int argc, char **argv) anari::wait(d, frame); ok = completions == 0 && ok; const int beforeErrors = errors; - anari::setParameter( - d, geometry, isosurfaceFailure ? "isovalue" : "radius", 0.2f); - anari::commitParameters(d, geometry); + if (observerRecovery) { + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); // New array version, no geometry recommit. + } else { + anari::setParameter( + d, geometry, isosurfaceFailure ? "isovalue" : "radius", 0.2f); + anari::commitParameters(d, geometry); + } if (batchCompletion) { // A completion error invalidates the whole pending batch, not just its // first geometry. Repreparing only that geometry cannot publish a world. diff --git a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp new file mode 100644 index 000000000..ef12530f5 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using vec3 = std::array; +anari::Device device = nullptr; +ANARIArray retireArray = nullptr; +void *sourceA = nullptr; +void *sourceB = nullptr; +const void *trackedA = nullptr; +const void *replacementSource = nullptr; +void *deviceA = nullptr; +bool watchReplacement = false; +bool oldDeviceFreed = false; +bool allocatedBeforeRetirement = false; +cudaStream_t preparationStream = nullptr; +int copies = 0; +int firstSyncCopies = -1; +int preparationSyncs = 0; +int errors = 0; +bool wrongStream = false; +bool retireNext = false; +bool retired = false; + +template +T next(const char *name) +{ + auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!function) + std::abort(); + return function; +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} + +bool trackedSource(const void *src) +{ + return src && (src == trackedA || src == sourceB || src == replacementSource); +} + +void resetCounts() +{ + copies = 0; + firstSyncCopies = -1; + preparationSyncs = 0; + wrongStream = false; +} +} // namespace + +extern "C" cudaError_t cudaStreamCreateWithFlags( + cudaStream_t *stream, unsigned flags) +{ + const auto error = next( + "cudaStreamCreateWithFlags")(stream, flags); + if (error == cudaSuccess && (flags & cudaStreamNonBlocking)) + preparationStream = *stream; + return error; +} + +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (watchReplacement && bytes == sizeof(vec3) && !oldDeviceFreed) + allocatedBeforeRetirement = true; + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaFree(void *ptr) +{ + const auto error = next("cudaFree")(ptr); + if (error == cudaSuccess && watchReplacement && ptr == deviceA) + oldDeviceFreed = true; + return error; +} + +extern "C" cudaError_t cudaMemcpy( + void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) +{ + if (kind == cudaMemcpyHostToDevice && trackedSource(src)) { + ++copies; + wrongStream = true; + } + return next("cudaMemcpy")(dst, src, bytes, kind); +} + +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + const bool tracked = kind == cudaMemcpyHostToDevice && trackedSource(src); + if (kind == cudaMemcpyHostToDevice && src == trackedA) + deviceA = dst; + if (tracked) { + ++copies; + wrongStream |= stream != preparationStream; + } + const auto error = next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); + if (error == cudaSuccess && tracked && src == trackedA && retireNext) { + retireNext = false; + // Reenter from the host submission path, not from a CUDA host callback. + // Public release must wait before the application frees a pinned source. + const int beforeRelease = preparationSyncs; + anariRelease(device, retireArray); + if (preparationSyncs == beforeRelease) { + ++errors; + std::fprintf(stderr, "host release omitted pending upload wait\n"); + } + retireArray = nullptr; + if (cudaFreeHost(sourceA) != cudaSuccess) + ++errors; + sourceA = nullptr; + retired = true; + } + return error; +} + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + if (stream == preparationStream) + ++preparationSyncs; + if (stream == preparationStream && copies && firstSyncCopies < 0) + firstSyncCopies = copies; + return next("cudaStreamSynchronize")( + stream); +} + +int main() +{ + device = makeVisRTXDevice(status); + if (cudaMallocHost(&sourceA, sizeof(vec3)) != cudaSuccess + || cudaMallocHost(&sourceB, sizeof(vec3)) != cudaSuccess) + return 1; + trackedA = sourceA; + *static_cast(sourceA) = {0, 0, 0}; + *static_cast(sourceB) = {2, 0, 0}; + auto a = + anariNewArray1D(device, sourceA, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto b = + anariNewArray1D(device, sourceB, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto material = anari::newObject(device, "matte"); + anari::commitParameters(device, material); + std::array geometries; + std::array surfaces; + for (size_t i = 0; i < geometries.size(); ++i) { + auto g = anari::newObject(device, "sphere"); + auto array = i == 1 ? b : a; + anariSetParameter(device, g, "vertex.position", ANARI_ARRAY1D, &array); + anari::setParameter(device, g, "radius", 0.25f); + anari::commitParameters(device, g); + geometries[i] = g; + auto s = anari::newObject(device); + anari::setParameter(device, s, "geometry", g); + anari::setParameter(device, s, "material", material); + anari::commitParameters(device, s); + surfaces[i] = s; + } + anari::release(device, material); + auto world = anari::newObject(device); + anari::setParameterArray1D( + device, world, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(device, world); + for (auto surface : surfaces) + anari::release(device, surface); + auto bounds = [&](float lo, float hi) { + std::array result{}; + return anariGetProperty(device, + world, + "bounds", + ANARI_FLOAT32_BOX3, + result.data(), + sizeof(result), + ANARI_WAIT) + && std::fabs(result[0] - lo) < 1e-4f + && std::fabs(result[3] - hi) < 1e-4f; + }; + auto commitGeometryWideAttributes = [&](float value) { + for (auto geometry : geometries) { + anari::setParameter( + device, geometry, "attribute0", std::array{value, 0, 0, 1}); + anari::commitParameters(device, geometry); + } + }; + auto change = [&](ANARIArray array, float x) { + auto *mapped = static_cast(anariMapArray(device, array)); + if (!mapped) + std::abort(); + *mapped = {x, 0, 0}; + anariUnmapArray(device, array); + }; + resetCounts(); + bool ok = bounds(-0.25f, 2.25f) && copies == 2 && firstSyncCopies == 2 + && !wrongStream; + resetCounts(); + commitGeometryWideAttributes(1.f); + ok = bounds(-0.25f, 2.25f) && copies == 0 && ok; + resetCounts(); + change(a, 1.f); // Observer-only fallback still uploads once for shared input. + ok = bounds(0.75f, 2.25f) && copies == 1 && !wrongStream && ok; + resetCounts(); + change(a, -1.f); + change(b, 3.f); + commitGeometryWideAttributes(2.f); + ok = bounds(-1.25f, 3.25f) && copies == 2 && firstSyncCopies == 2 + && !wrongStream && ok; + // Replacement must retire obsolete cached copies before allocating the + // whole new cohort, rather than keeping both cohorts resident at once. + void *replacement = nullptr; + if (cudaMallocHost(&replacement, sizeof(vec3)) != cudaSuccess) + return 1; + *static_cast(replacement) = {-1, 0, 0}; + replacementSource = replacement; + auto c = anariNewArray1D( + device, replacement, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto replaceShared = [&](ANARIArray array) { + for (size_t i = 0; i < geometries.size(); ++i) { + if (i == 1) + continue; + anariSetParameter( + device, geometries[i], "vertex.position", ANARI_ARRAY1D, &array); + anari::commitParameters(device, geometries[i]); + } + }; + watchReplacement = true; + replaceShared(c); + ok = bounds(-1.25f, 3.25f) && oldDeviceFreed && !allocatedBeforeRetirement + && ok; + watchReplacement = false; + replaceShared(a); + ok = bounds(-1.25f, 3.25f) && ok; + anariRelease(device, c); + cudaFreeHost(replacement); + replacementSource = nullptr; + resetCounts(); + change(a, -2.f); + commitGeometryWideAttributes(3.f); + retireArray = a; + retireNext = true; + ok = bounds(-2.25f, 3.25f) && retired && copies == 1 && !wrongStream && ok; + anari::release(device, world); + for (auto geometry : geometries) + anari::release(device, geometry); + if (!retired) + anariRelease(device, a); + anariRelease(device, b); + if (sourceA) + cudaFreeHost(sourceA); + cudaFreeHost(sourceB); + anari::release(device, device); + ok = errors == 0 && ok; + std::printf("geometry input batches: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/benchmark_preprocessing.py b/devices/rtx/apps/tests/api/benchmark_preprocessing.py index d8d91c72a..4723648a7 100644 --- a/devices/rtx/apps/tests/api/benchmark_preprocessing.py +++ b/devices/rtx/apps/tests/api/benchmark_preprocessing.py @@ -53,13 +53,15 @@ name, count, geometries, mode, frames = spec.split(":") case = (name, int(count), int(geometries), mode, int(frames)) if (not name or case[1] < 1 or case[2] < 1 or case[4] < 0 - or mode not in {"recommit", "replace", "unchanged"} + or mode not in {"recommit", "replace", "unchanged", "update"} + or (mode == "update" and (a.device or a.geometry == "sdf")) or name in {c[0] for c in cases}): raise ValueError() cases.append(case) except ValueError: p.error(f"bad --extra-case {spec!r}; use a unique NAME, positive COUNT/GEOMETRIES, " - "recommit|replace|unchanged, and nonnegative FRAMES") + "recommit|replace|unchanged|update, and nonnegative FRAMES; " + "update requires host inputs and non-SDF geometry") records = [] diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index a571abfce..2a5057032 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -175,6 +175,18 @@ void Array::privatize() return; bool changed = false; if (m_data.shared.host.isValid() && !m_data.shared.host.isOwner()) { + // A batched H2D copy may still use the application-owned host pointer. + // Draining does not release the queue's retained array references. + if (state.collectingGeometryInputUploads()) { + const auto completion = state.finishGeometryPreparation(); + if (completion != cudaSuccess) { + state.arrayPrivatizationFailed = true; + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "array privatization failed; device disabled: %s", + cudaGetErrorString(completion)); + return; + } + } reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, "making private copy of shared host array (type '%s') | refs: (%i:%i)", anari::toString(elementType()), diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index a26d2f373..ae1ad6881 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -53,7 +53,13 @@ Cone::Cone(DeviceGlobalState *d) m_radius(this), m_vertex(this), m_vertexCaps(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.radius", + "vertex.cap", + "caps"}); +} Cone::~Cone() = default; @@ -87,11 +93,7 @@ PrimitiveInput Cone::primitiveInput() const void Cone::finalize() { - if (!beginPreparation({"primitive.index", - "vertex.position", - "vertex.radius", - "vertex.cap", - "caps"})) + if (!beginPreparation()) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index a2ff4e9a6..6972d8cbf 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -37,7 +37,10 @@ namespace visrtx { Curve::Curve(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertexPosition(this), m_vertexRadius(this) -{} +{ + declarePreparationParameters( + {"primitive.index", "vertex.position", "vertex.radius", "radius"}); +} Curve::~Curve() = default; @@ -53,8 +56,7 @@ void Curve::commitParameters() void Curve::finalize() { - if (!beginPreparation( - {"primitive.index", "vertex.position", "vertex.radius", "radius"})) + if (!beginPreparation()) return; if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index e6d84822e..d183ef07f 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -53,7 +53,14 @@ Cylinder::Cylinder(DeviceGlobalState *d) m_radius(this), m_vertex(this), m_vertexCaps(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "primitive.radius", + "vertex.cap", + "caps", + "radius"}); +} Cylinder::~Cylinder() = default; @@ -88,12 +95,7 @@ PrimitiveInput Cylinder::primitiveInput() const void Cylinder::finalize() { - if (!beginPreparation({"primitive.index", - "vertex.position", - "primitive.radius", - "vertex.cap", - "caps", - "radius"})) + if (!beginPreparation()) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 64be4b2b4..4123ffd0c 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -114,12 +114,16 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { + if (m_inputUploadsQueued) + deviceState()->collectGeometryInputUploads(); + m_inputUploadFailed = false; if (m_preparationQueued) deviceState()->collectGeometryPreparations(); // Array observers can re-finalize without a parameter commit, but parameter // replacement can release the last reference to an aliased device array. // Complete earlier consumers before subclasses replace those references. - m_inputRetirementFailed = !canRetainPreparationInputs() + const bool retain = canRetainPreparationInputs(); + m_inputRetirementFailed = !retain && !checkPreparation(this, cudaStreamSynchronize(deviceState()->stream), "retiring previous geometry inputs"); @@ -140,6 +144,8 @@ void Geometry::commitParameters() m_uniformAttributes.attribute3 = getUniformAttribute("attribute3"); m_uniformAttributes.color = getUniformAttribute("color"); m_primitiveId = getParamObject("primitive.id"); + if (!retain && !m_inputRetirementFailed) + stageInputUploads(); } void Geometry::markFinalized() @@ -225,37 +231,120 @@ void Geometry::upload() m_hasPreparedData = !preparationFailed() && isValid(); } -bool Geometry::beginPreparation(std::initializer_list parameters) +void Geometry::declarePreparationParameters( + std::initializer_list parameters) { + for (const char *name : {"primitive.attribute0", + "primitive.attribute1", + "primitive.attribute2", + "primitive.attribute3", + "primitive.color", + "primitive.id", + "vertex.attribute0", + "vertex.attribute1", + "vertex.attribute2", + "vertex.attribute3", + "vertex.color"}) + m_preparationParameterNames.emplace_back(name); + for (const char *name : parameters) + m_preparationParameterNames.emplace_back(name); +} + +void Geometry::stageInputUploads() +{ + m_inputUploads.clear(); + for (const auto &name : m_preparationParameterNames) { + const auto value = getParamDirect(name); + if (!anari::isObject(value.type())) + continue; + auto *array = dynamic_cast(value.getObject()); + if (array && array->needToUploadData() && array->dataHost()) + m_inputUploads.push_back({array, array->lastDataModified(), false}); + } + if (m_inputUploads.empty()) + return; + deviceState()->enqueueGeometryInputUploads(this); + m_inputUploadsQueued = true; +} + +void Geometry::retirePreparationSnapshot() +{ + // Only queued by a commit whose render-consumer retirement check succeeded. + // Discard obsolete references before allocating a multi-geometry cohort. + // Until beginPreparation establishes the new generation, old GPU records + // must not be usable if a host exception aborts finalization. + m_hasPreparedData = false; + m_preparationFailed = true; + m_preparedParameters.clear(); +} + +void Geometry::submitInputUploads() +{ + if (m_inputUploadFailed) + return; + auto &state = *deviceState(); + auto fail = [&](cudaError_t error, const char *operation) { + if (error == cudaSuccess) + return false; + failInputUploads(); + checkPreparation(this, error, operation); + return true; + }; + for (auto &upload : m_inputUploads) { + upload.modified = upload.array->lastDataModified(); + const auto error = + state.stageGeometryArray(upload.array.ptr, upload.modified); + upload.submitted = error == cudaSuccess; + if (fail(error, "geometry array upload")) + return; + } +} + +void Geometry::failInputUploads() +{ + m_inputUploadFailed = true; + m_preparationFailed = true; + m_hasPreparedData = false; +} + +void Geometry::completeInputUploads() +{ + m_inputUploadsQueued = false; + for (const auto &upload : m_inputUploads) + if (!upload.submitted) + failInputUploads(); + if (m_inputUploadFailed) + m_failedInputUpdate = lastUpdated(); + else { + for (const auto &upload : m_inputUploads) { + // Array finalization or a coalesced unmap may have changed the version + // since submission. Leave that array dirty for the conservative path. + if (upload.array->lastDataModified() == upload.modified) + upload.array->markDataUploaded(); + } + } + m_inputUploads.clear(); +} + +bool Geometry::beginPreparation() +{ + if (!deviceState()->collectGeometryInputUploads()) + return false; // Observer-only finalization can arrive before a prior submission is // collected. if (m_preparationQueued) deviceState()->collectGeometryPreparations(); m_preparationPreserved = false; - if (m_inputRetirementFailed) + // A later observer update is a new generation too; it may retry a failed + // input batch without requiring a parameter commit on the geometry. + if (m_inputUploadFailed && lastUpdated() > m_failedInputUpdate) + m_inputUploadFailed = false; + if (m_inputRetirementFailed || m_inputUploadFailed) return false; std::vector current; - if (parameters.size() != 0) { - // Subtype declarations are fixed. Keep the lookup names across commits - // instead of allocating/copying their strings on every finalization. - if (m_preparationParameterNames.empty()) { - for (const char *name : {"primitive.attribute0", - "primitive.attribute1", - "primitive.attribute2", - "primitive.attribute3", - "primitive.color", - "primitive.id", - "vertex.attribute0", - "vertex.attribute1", - "vertex.attribute2", - "vertex.attribute3", - "vertex.color"}) - m_preparationParameterNames.emplace_back(name); - for (const char *name : parameters) - m_preparationParameterNames.emplace_back(name); - } - current.reserve(m_preparedParameters.size()); + if (!m_preparationParameterNames.empty()) { + current.reserve(m_preparedParameters.capacity()); // Indices remain valid if current grows; its AnariAny values retain every // source array until the batch completes (including on failure). std::vector> pendingUploads; diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index 330ce43c0..2165216a9 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -79,6 +79,10 @@ struct Geometry : public RegisteredObject void upload(); void deferPreparation(); void completePreparation(); + void retirePreparationSnapshot(); + void submitInputUploads(); + void completeInputUploads(); + void failInputUploads(); virtual void populateBuildInput(OptixBuildInput &) const = 0; virtual int optixGeometryType() const = 0; @@ -94,12 +98,14 @@ struct Geometry : public RegisteredObject void setPreparationFailed(bool failed); protected: - // Opt-in preparation reuse: list every subtype parameter except the five - // geometry-wide attributes. This declaration must stay fixed for the subtype; - // lookup names are cached. The base adds primitive and vertex arrays. + // Declare once in the subtype constructor, before the first commit. List + // every consumed parameter except geometry-wide attributes; the base adds + // primitive and vertex arrays. These inputs determine preparation reuse. + void declarePreparationParameters( + std::initializer_list parameters); // Returns false after preparation reuse and registry publication, or if // preparation cannot start. - bool beginPreparation(std::initializer_list parameters = {}); + bool beginPreparation(); GeometryGPUData gpuData() const override = 0; void commitAttributes(const char *prefix, GeometryAttributes &attrs); @@ -127,7 +133,18 @@ struct Geometry : public RegisteredObject bool operator==(const PreparationParameter &other) const; }; bool canRetainPreparationInputs() const; + void stageInputUploads(); + struct InputUpload + { + helium::IntrusivePtr array; + helium::TimeStamp modified{0}; + bool submitted{false}; + }; + std::vector m_inputUploads; + bool m_inputUploadsQueued{false}; + bool m_inputUploadFailed{false}; + helium::TimeStamp m_failedInputUpdate{0}; std::vector m_preparedParameters; std::vector m_preparationParameterNames; bool m_hasPreparedData{false}; diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 1cbb4d5e2..3bc6b7d15 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -34,7 +34,14 @@ namespace visrtx { -Quad::Quad(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) {} +Quad::Quad(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.normal", + "vertex.tangent", + "cullBackfaces"}); +} Quad::~Quad() = default; @@ -51,11 +58,7 @@ void Quad::commitParameters() void Quad::finalize() { - if (!beginPreparation({"primitive.index", - "vertex.position", - "vertex.normal", - "vertex.tangent", - "cullBackfaces"})) + if (!beginPreparation()) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index 3be2b121e..dcc118100 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -42,7 +42,18 @@ static_assert(offsetof(visrtx::SDFPrimitive, neighboursIndex) == 56, namespace visrtx { -SDF::SDF(DeviceGlobalState *d) : Geometry(d), m_sdf(this), m_neighbour(this) {} +SDF::SDF(DeviceGlobalState *d) : Geometry(d), m_sdf(this), m_neighbour(this) +{ + declarePreparationParameters({"primitive.sdf", + "primitive.neighbor", + "epsilon", + "nbMarchIterations", + "blendFactor", + "blendLerpFactor", + "omega", + "distanceFromCamera", + "noiseFactor"}); +} SDF::~SDF() = default; @@ -63,15 +74,7 @@ void SDF::commitParameters() void SDF::finalize() { - if (!beginPreparation({"primitive.sdf", - "primitive.neighbor", - "epsilon", - "nbMarchIterations", - "blendFactor", - "blendLerpFactor", - "omega", - "distanceFromCamera", - "noiseFactor"})) + if (!beginPreparation()) return; if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index 8cf884685..e2a416769 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -35,7 +35,10 @@ namespace visrtx { Sphere::Sphere(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this), m_vertexRadius(this) -{} +{ + declarePreparationParameters( + {"primitive.index", "vertex.position", "vertex.radius", "radius"}); +} Sphere::~Sphere() = default; @@ -51,8 +54,7 @@ void Sphere::commitParameters() void Sphere::finalize() { - if (!beginPreparation( - {"primitive.index", "vertex.position", "vertex.radius", "radius"})) + if (!beginPreparation()) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index 5bc8c3922..a19a724ed 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -37,7 +37,20 @@ namespace visrtx { Triangle::Triangle(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.normal", + "faceVarying.normal", + "vertex.tangent", + "faceVarying.tangent", + "cullBackfaces", + "faceVarying.attribute0", + "faceVarying.attribute1", + "faceVarying.attribute2", + "faceVarying.attribute3", + "faceVarying.color"}); +} Triangle::~Triangle() = default; @@ -76,18 +89,7 @@ void Triangle::commitParameters() void Triangle::finalize() { - if (!beginPreparation({"primitive.index", - "vertex.position", - "vertex.normal", - "faceVarying.normal", - "vertex.tangent", - "faceVarying.tangent", - "cullBackfaces", - "faceVarying.attribute0", - "faceVarying.attribute1", - "faceVarying.attribute2", - "faceVarying.attribute3", - "faceVarying.color"})) + if (!beginPreparation()) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 1b477208f..290cafaf0 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -183,6 +183,77 @@ DeviceGlobalState::DeviceGlobalState(ANARIDevice d) DeviceGlobalState::~DeviceGlobalState() = default; +void DeviceGlobalState::enqueueGeometryInputUploads(Geometry *geometry) +{ + m_geometryInputUploads.emplace_back(geometry); +} + +cudaError_t DeviceGlobalState::stageGeometryArray( + Array *array, helium::TimeStamp modified) +{ + const auto found = m_geometryInputVersions.find(array); + if (found != m_geometryInputVersions.end() && found->second == modified) + return cudaSuccess; + const auto error = array->enqueueUpload(preparation.stream()); + if (error == cudaSuccess) + m_geometryInputVersions.insert_or_assign(array, modified); + return error; +} + +bool DeviceGlobalState::collectingGeometryInputUploads() const +{ + return m_collectingGeometryInputUploads; +} + +bool DeviceGlobalState::collectGeometryInputUploads() +{ + if (m_collectingGeometryInputUploads) + return false; + if (m_geometryInputUploads.empty()) + return true; + m_collectingGeometryInputUploads = true; + bool completed = false; + auto collecting = nonstd::make_scope_exit([&] { + if (!completed) { + // A host allocation or callback can unwind after copies were submitted. + // Keep sources alive and drain before permitting public release again. + for (auto &geometry : m_geometryInputUploads) + geometry->failInputUploads(); + finishGeometryPreparation(); + m_geometryInputVersions.clear(); + } + m_collectingGeometryInputUploads = false; + }); + // Commits capture sources; the first geometry finalizer submits every input + // batch before waiting. No legacy finalizer sees partially uploaded arrays. + // Retire obsolete cached copies before allocating a whole replacement cohort. + // A single geometry retains the existing allocation/retirement order. + if (m_geometryInputUploads.size() > 1) + for (auto &geometry : m_geometryInputUploads) + geometry->retirePreparationSnapshot(); + auto error = preparation.waitFor(stream); + if (error == cudaSuccess) { + for (auto &geometry : m_geometryInputUploads) + geometry->submitInputUploads(); + error = finishGeometryPreparation(); + } + if (error != cudaSuccess) { + for (auto &geometry : m_geometryInputUploads) + geometry->failInputUploads(); + checkPreparation(m_geometryInputUploads.front().ptr, + error, + "geometry input batch completion"); + } + completed = true; + m_geometryInputVersions.clear(); + auto pending = std::move(m_geometryInputUploads); + for (auto &geometry : pending) + geometry->completeInputUploads(); + pending.clear(); + m_geometryInputUploads.swap(pending); + return true; +} + void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) { m_geometryPreparations.emplace_back(geometry); @@ -190,12 +261,13 @@ void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) bool DeviceGlobalState::collectingGeometryPreparations() const { - return m_collectingGeometryPreparations; + return m_collectingGeometryPreparations || m_collectingGeometryInputUploads; } bool DeviceGlobalState::hasPendingGeometryPreparations() const { - return m_collectingGeometryPreparations || !m_geometryPreparations.empty(); + return m_collectingGeometryPreparations || !m_geometryPreparations.empty() + || m_collectingGeometryInputUploads; } cudaError_t DeviceGlobalState::finishGeometryPreparation() @@ -206,12 +278,16 @@ cudaError_t DeviceGlobalState::finishGeometryPreparation() // point. Its stream-completion error affects all already queued results. for (auto &geometry : m_geometryPreparations) geometry->setPreparationFailed(true); + for (auto &geometry : m_geometryInputUploads) + geometry->failInputUploads(); } return error; } bool DeviceGlobalState::collectGeometryPreparations() { + if (!collectGeometryInputUploads()) + return false; if (m_collectingGeometryPreparations) return false; if (m_geometryPreparations.empty()) diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 7797fae48..57c4cdcde 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -61,6 +61,7 @@ #include #include #include +#include #include #ifdef OPAQUE @@ -159,6 +160,7 @@ namespace visrtx { struct Object; struct Geometry; +struct Array; struct MDL; struct ptx_blob @@ -277,6 +279,10 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceGlobalState(ANARIDevice d); ~DeviceGlobalState() override; + void enqueueGeometryInputUploads(Geometry *geometry); + cudaError_t stageGeometryArray(Array *array, helium::TimeStamp modified); + bool collectGeometryInputUploads(); + bool collectingGeometryInputUploads() const; void enqueueGeometryPreparation(Geometry *geometry); bool collectGeometryPreparations(); cudaError_t finishGeometryPreparation(); @@ -284,6 +290,9 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState bool hasPendingGeometryPreparations() const; private: + std::vector> m_geometryInputUploads; + std::unordered_map m_geometryInputVersions; + bool m_collectingGeometryInputUploads{false}; std::vector> m_geometryPreparations; bool m_collectingGeometryPreparations{false}; }; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 1d397fc7b..2b3ade5b5 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -37,7 +37,8 @@ existing full-preparation behavior; they do not opt in. ## Reuse contract -`Geometry::beginPreparation(parameters)` is the opt-in seam. A subtype must list +`Geometry::declarePreparationParameters(parameters)` is the opt-in seam, called +once in the subtype constructor before its first commit. A subtype must list **every consumed parameter except geometry-wide attributes**, including inputs read lazily by tangent generation or `gpuData()`. These are the subtype's preparation inputs. The base adds primitive and vertex @@ -61,8 +62,12 @@ Only present parameters occupy snapshot storage. The cached `AnariAny` values retain internal references to the current input objects until replacement or geometry destruction; they do not copy authored data. This also prevents cached parameter identity from becoming a dangling object pointer. The extra reference -lifetime is intentional; old snapshot references are dropped on the next full -preparation after the retirement check. +lifetime is intentional. For a multi-geometry input batch, obsolete snapshot +references are dropped after commit-time retirement checks and parameter reads, +before replacement input uploads are allocated. This avoids retaining a whole +cohort of obsolete device copies through the replacement batch. Single-geometry +and observer-only updates retain the existing snapshot replacement order during +full preparation. Geometry-wide attribute values are excluded because they do not change geometric area or bounds. @@ -74,15 +79,15 @@ time. Material changes continue to use their existing light-set invalidation. `TestGeometryPreparationReuse` exercises seven types with host and shared-device inputs. It verifies all five geometry-wide attributes and their removal against -the initial full-preparation rendering, stable bounds, and no preparation/BVH-build diagnostic -messages. Debug rendering modulates attributes by geometric facing, so the initial +the initial full-preparation rendering, stable bounds, and no preparation/BVH-build +diagnostic messages. Debug rendering modulates attributes by geometric facing, so the initial full-preparation image is the exact per-shape reference, with a separate nonzero control. Scalar/string edits, array ranges, in-place host unmaps, and device-array privatization act as positive controls requiring preparation and BVH rebuilding. The test also stages an input removal **after** a geometry-wide attribute commit: -that uncommitted edit must not leak into the committed update. Emissive materials request area data -where supported. Existing numeric-failure tests additionally verify that a +that uncommitted edit must not leak into the committed update. Emissive materials +request area data where supported. Existing numeric-failure tests additionally verify that a geometry-wide attribute commit cannot rehabilitate a failed generation. ## Local performance checks @@ -105,12 +110,18 @@ serialized; each event wait captures the corresponding record before the event is reused. - Full preparation imports prior render work before overwriting derived buffers. -- For the seven opt-in geometry types, pending host uploads of declared arrays - are batched on the preparation stream before finalization. The committed - snapshot retains source arrays through completion. Uploaded timestamps and - device-pointer snapshots are published only after the whole batch succeeds; - partial failures remain dirty and are retried. Legacy consumers can safely - use the completed device copy afterward. +- For the seven opt-in geometry types, parameter commits capture references to + dirty declared host arrays. The first geometry finalizer submits the captured + inputs across geometries on the preparation stream and waits once before any + finalizer consumes them. Shared arrays are deduplicated by handle and data + version. Sources remain retained through completion; only successful geometry + submissions mark their still-current array versions uploaded. A failed + geometry remains unprepared even if another geometry successfully shares one + of its arrays. Legacy consumers can safely use completed copies afterward. +- Observer-only updates, or arrays modified after submission, retain the local + per-geometry upload path. A later geometry commit or observer update may retry + a failed input generation; unchanged failed inputs cannot silently become + prepared. Preparation reuse does not capture or submit an upload batch. - These checked geometry kernels no longer import the default stream: authored inputs are ready before they run. Other array consumers retain their existing upload path. @@ -197,9 +208,11 @@ source/result lifetime ordering remains the collection queue's responsibility. move/reset, pool-before-lease teardown, concurrent leases, and asynchronous DMA into separate slots on a page. -Host input upload batches still complete per geometry to preserve their source -lifetime and existing legacy consumers; -quad/curve generated-data completion, tangent generation, and field/isosurface +Committed host inputs now complete in a cross-geometry batch before finalizers +run. Observer-only input updates remain conservative. Last-public-release of +shared host arrays during an active upload joins the preparation stream before +the application may free its source memory. Quad/curve generated-data completion, +tangent generation, and field/isosurface preparation retain their current synchronous paths. This does not introduce independent scene generations or concurrent in-place replacement during tracing. @@ -208,15 +221,20 @@ captured-device inputs, last-reference queue ownership through teardown, unrelat numeric failures, and collection-time callback reentry. Injection cases also cover pinned-readback allocation failure, completion failure across multiple queued geometries, an intervening upload completion failure, and shared CUDA -array retirement while preparation remains pending. +array retirement while preparation remains pending. `TestGeometryInputBatch` +checks submission-before-wait across multiple geometries, shared-array dedup, +preparation-preserving and observer-only controls, coalesced unmaps/commits, and host-source +retirement during an active copy. Input failure cases cover batch-wide completion +failure and recovery through an array unmap without a geometry recommit. ## Remaining work Broader array/shading invalidation precision, reducing the extra CPU snapshot comparison cost, batched readback/dispatch, and fine-grained area-vs-bounds invalidation are separate improvements. Registry, bounds, and area-result -collection now span geometries. Batching the remaining host-input uploads and -legacy finalizers requires further producer migration while preserving source -lifetimes and failure propagation. This change does not repack or download +collection and committed input uploads now span geometries. Observer-only input +batching, legacy finalizers, and allocation-related synchronization require +further producer migration while preserving source lifetimes and failure +propagation. This change does not repack or download inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs are prepared on the GPU before their derived data is published. diff --git a/devices/rtx/docs/geometry-preprocessing-performance.md b/devices/rtx/docs/geometry-preprocessing-performance.md index fab99a0de..1625adcfb 100644 --- a/devices/rtx/docs/geometry-preprocessing-performance.md +++ b/devices/rtx/docs/geometry-preprocessing-performance.md @@ -59,7 +59,7 @@ The executable can also run one workload directly: ```text BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ [SHARED_SURFACES] [DISTINCT_GEOMETRIES] \ - [recommit|replace|unchanged|overlap] [FRAMES:0=bounds] [EMISSIVE:0|1] + [recommit|replace|unchanged|overlap|update] [FRAMES:0=bounds] [EMISSIVE:0|1] ``` - COUNT is primitives **per geometry**. The paired runner uses emissive geometry, @@ -68,6 +68,12 @@ BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ - `recommit` changes a geometry-wide attribute; `replace` replaces inputs, including allocation, host staging, application H2D copy and parameter installation in the measured interval; `unchanged` retains the initial inputs. +- `update` maps and changes existing host position arrays in place, unmaps them, + and commits a geometry-wide attribute on each geometry. It measures coalesced array + updates plus geometry commits without replacing the input allocations; it is + not an observer-only workload. Supported for host inputs of non-SDF types. + For example, add `--extra-case in-place-ready:32:64:update:0` and + `--extra-case in-place-frame:32:64:update:1` to the paired runner. - FRAMES=0 ends at completed bounds/BVH readiness. FRAMES>0 includes submission and completion of all frames, registry publication and tracing, then bounds. Multiple frames share one device/world; this is not a concurrency benchmark. From 234236c072b38ff6788ae3a1704ba548db6f9690 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:36:09 -0500 Subject: [PATCH 11/20] perf(rtx): batch small geometry preprocessing --- devices/rtx/apps/tests/api/CMakeLists.txt | 3 + .../tests/api/TestCudaPreparationFailure.cpp | 37 ++- .../apps/tests/api/TestSmallGeometryBatch.cpp | 212 ++++++++++++++++++ devices/rtx/device/geometry/Preprocessing.cu | 174 ++++++++++++-- devices/rtx/device/geometry/Preprocessing.h | 38 +++- devices/rtx/device/optix_visrtx.cpp | 6 +- devices/rtx/device/optix_visrtx.h | 3 +- .../rtx/docs/geometry-preparation-reuse.md | 29 ++- 8 files changed, 480 insertions(+), 22 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 5bb2cee96..10964af58 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -98,6 +98,8 @@ target_compile_definitions(TestRegistrySnapshot PRIVATE GLM_ENABLE_EXPERIMENTAL) add_test(NAME TestRegistrySnapshot COMMAND TestRegistrySnapshot) make_test(TestDeferredGeometryPreparation) target_link_libraries(TestDeferredGeometryPreparation PRIVATE CUDA::cudart) +make_test(TestSmallGeometryBatch) +target_link_libraries(TestSmallGeometryBatch PRIVATE CUDA::cudart) make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) @@ -127,6 +129,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S COMMAND TestCudaPreparationFailure isosurface) foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency sphere-undrained-completion + sphere-batch-small-copy sphere-batch-small-launch sphere-batch-small-readback sphere-readback-allocation sphere-batch-completion sphere-batch-upload-completion sphere-batch-input-completion sphere-upload-allocation sphere-upload-copy sphere-upload-completion diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index c6bd83fdd..801d82e4c 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -62,6 +62,9 @@ enum class Failure COPY_SYNC, PREPARATION_SYNC, PREPARATION_EARLY_SYNC, + SMALL_DESCRIPTOR_COPY, + SMALL_LAUNCH, + SMALL_READBACK, PREPARATION_DEPENDENCY, BVH_SYNC, BVH_COPY, @@ -70,6 +73,7 @@ enum class Failure BATCH_COPY, BATCH_SYNC }; +bool smallDescriptorSubmitted = false; bool trackBatch = false; bool batchQueued = false; int batchCopiesToSkip = 0; @@ -224,12 +228,32 @@ extern "C" cudaError_t cudaStreamWaitEvent( stream, event, flags); } +extern "C" cudaError_t cudaGetLastError() +{ + const auto error = next("cudaGetLastError")(); + // The launch-status check follows the descriptor upload. Inject a failed + // report after real dispatch so cleanup must still drain the queued kernel. + if (smallDescriptorSubmitted && inject(Failure::SMALL_LAUNCH)) { + smallDescriptorSubmitted = false; + return cudaErrorInvalidConfiguration; + } + return error; +} + extern "C" cudaError_t cudaMemcpyAsync(void *dst, const void *src, size_t bytes, cudaMemcpyKind kind, cudaStream_t stream) { + // These cases use device-backed sphere inputs. The first preparation H2D + // transfer is the descriptor batch, not an authored-array upload. + if (stream == preparationStream + && ((kind == cudaMemcpyHostToDevice + && inject(Failure::SMALL_DESCRIPTOR_COPY)) + || (kind == cudaMemcpyDeviceToHost + && inject(Failure::SMALL_READBACK)))) + return cudaErrorInvalidValue; if (uploadSource && src == uploadSource && kind == cudaMemcpyHostToDevice) { ++uploadCopies; uploadOnWrongStream |= stream != preparationStream; @@ -280,8 +304,12 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, error = cudaEventRecord(pendingCompletion.done, stream); return error; } - return next("cudaMemcpyAsync")( + const auto error = next("cudaMemcpyAsync")( dst, src, bytes, kind, stream); + if (error == cudaSuccess && failure == Failure::SMALL_LAUNCH + && kind == cudaMemcpyHostToDevice && stream == preparationStream) + smallDescriptorSubmitted = true; + return error; } extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) @@ -597,6 +625,13 @@ int main(int argc, char **argv) failure = Failure::PREPARATION_SYNC; if (sphereFailure && std::strcmp(argv[1], "sphere-dependency") == 0) failure = Failure::PREPARATION_DEPENDENCY; + if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-copy") == 0) + failure = Failure::SMALL_DESCRIPTOR_COPY; + if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-launch") == 0) + failure = Failure::SMALL_LAUNCH; + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-readback") == 0) + failure = Failure::SMALL_READBACK; std::thread watchdog; if (earlyCompletion) { if (cudaEventCreateWithFlags( diff --git a/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp new file mode 100644 index 000000000..cb9e6121f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +namespace { +using vec3 = std::array; +int errors = 0; +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} +struct Case +{ + std::string type; + size_t count; + anari::Geometry geometry; + anari::Group group; + std::array bounds; +}; + +bool run(bool device) +{ + auto d = makeVisRTXDevice(status); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + std::vector cases; + std::vector instances; + for (const char *type : {"sphere", "cylinder", "cone", "triangle"}) + for (size_t n : {1, 31, 32, 33, 255, 256, 257}) { + auto g = anari::newObject(d, type); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto group = anari::newObject(d); + anari::setParameterArray1D(d, group, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, group); + auto instance = anari::newObject(d, "transform"); + anari::setParameter(d, instance, "group", group); + anari::commitParameters(d, instance); + instances.push_back(instance); + cases.push_back({type, n, g, group, {}}); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "instance", instances.data(), instances.size()); + anari::commitParameters(d, world); + for (auto instance : instances) + anari::release(d, instance); + bool ok = true; + for (int generation = 0; generation < 3; ++generation) { + for (auto &c : cases) { + // Reuse a batch's slots across degenerate results, then swap small and + // large paths to catch stale result pointers and scratch-growth errors. + const size_t n = generation == 2 ? (c.count <= 256 ? 257 : 32) : c.count; + const float r = generation == 1 ? 0.f : 0.25f; + const float h = generation == 1 ? 0.f : 0.5f; + std::vector vertices; + std::vector radii; + for (size_t i = 0; i < n; ++i) { + const float x = 2.f * i; + if (c.type == "sphere") + vertices.push_back({x, 0, 0}); + else if (c.type == "triangle") { + vertices.push_back({x - r, -h, 0}); + vertices.push_back({x + r, -h, 0}); + vertices.push_back({x, h, 0}); + } else { + vertices.push_back({x, -h, 0}); + vertices.push_back({x, h, 0}); + radii.push_back(r * 0.5f); + radii.push_back(r); + } + } + setTestArray(d, c.geometry, "vertex.position", vertices, device, 1); + if (c.type == "cone") + setTestArray(d, c.geometry, "vertex.radius", radii, device, 1); + anari::setParameter(d, c.geometry, "radius", r); + anari::setParameter(d, c.geometry, "caps", "both"); + anari::commitParameters(d, c.geometry); + const float y = c.type == "sphere" ? r : c.type == "triangle" ? h : h + r; + const float z = c.type == "triangle" ? 0.f : r; + c.bounds = {-r, -y, -z, 2.f * (n - 1) + r, y, z}; + } + // One world query flushes all geometries together, including lazy area + // requests on the first generation and bounds+area jobs on later ones. + std::array worldBounds{}; + ok = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + worldBounds.data(), + sizeof(worldBounds), + ANARI_WAIT) + && ok; + uint32_t lights = 0; + ok = anariGetProperty(d, + world, + "numLightInstances", + ANARI_UINT32, + &lights, + sizeof(lights), + ANARI_WAIT) + && lights == (generation == 1 ? 0 : cases.size()) && ok; + for (const auto &c : cases) { + std::array actual{}; + bool valid = anariGetProperty(d, + c.group, + "bounds", + ANARI_FLOAT32_BOX3, + actual.data(), + sizeof(actual), + ANARI_WAIT); + if (generation == 1) { + // OptiX drops zero-extent primitives from its emitted BVH bounds. + for (int axis = 0; axis < 3; ++axis) + valid = actual[axis] > actual[axis + 3] && valid; + } else { + // OptiX conservatively pads bounds in proportion to coordinate scale. + const float tolerance = 1e-4f + 1e-6f * c.bounds[3]; + for (int i = 0; i < 6; ++i) + valid = std::isfinite(actual[i]) + && std::abs(actual[i] - c.bounds[i]) < tolerance && valid; + } + if (!valid) + std::fprintf(stderr, + "%s count=%zu generation=%d bounds actual=(%g,%g,%g;%g,%g,%g) expected=(%g,%g,%g;%g,%g,%g)\n", + c.type.c_str(), + c.count, + generation, + actual[0], + actual[1], + actual[2], + actual[3], + actual[4], + actual[5], + c.bounds[0], + c.bounds[1], + c.bounds[2], + c.bounds[3], + c.bounds[4], + c.bounds[5]); + ok = valid && ok; + } + ok = errors == 0 && ok; + } + anari::release(d, world); + for (const auto &c : cases) { + anari::release(d, c.group); + anari::release(d, c.geometry); + } + anari::release(d, d); + std::printf( + "small geometry batch device=%d %s\n", device, ok ? "PASS" : "FAIL"); + return ok; +} +} // namespace + +int main() +{ + bool ok = run(false); + ok = run(true) && ok; + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index 49cdc2a18..4e9d3e338 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -34,6 +34,8 @@ #include "gpu/intersectPrimitives.h" #include +#include +#include #include #include #include @@ -42,12 +44,8 @@ namespace visrtx { namespace { using Result = PreparationResult; -VISRTX_GLOBAL void primitiveAreas( - PrimitiveInput in, double *areas, Result *result) +VISRTX_DEVICE double primitiveArea(PrimitiveInput in, size_t i) { - const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= in.count) - return; double area; if (in.type == GeometryType::SPHERE) { const auto *indices = static_cast(in.indices); @@ -82,6 +80,16 @@ VISRTX_GLOBAL void primitiveAreas( * glm::length(glm::cross(in.vertices[t.y] - in.vertices[t.x], in.vertices[t.z] - in.vertices[t.x])); } + return area; +} + +VISRTX_GLOBAL void primitiveAreas( + PrimitiveInput in, double *areas, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + const double area = primitiveArea(in, i); if (!isfinite(area) || area < 0.0) atomicOr(&result->invalid, 1u); areas[i] = area; @@ -140,12 +148,9 @@ VISRTX_DEVICE box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) } } -VISRTX_GLOBAL void primitiveBounds( - PrimitiveInput in, box3 *bounds, Result *result) +VISRTX_DEVICE Result primitiveBound(PrimitiveInput in, size_t i, box3 &bound) { - const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; - if (i >= in.count) - return; + Result result{}; if (in.type == GeometryType::SDF) { const SDFPrimitive &g = in.sdf[i]; box3 b = computeSDFPrimitiveAABB(g); @@ -159,12 +164,12 @@ VISRTX_GLOBAL void primitiveBounds( } b.lower -= padding; b.upper += padding; - bounds[i] = b; + bound = b; for (int axis = 0; axis < 3; ++axis) { if (!isfinite(b.lower[axis]) || !isfinite(b.upper[axis])) - atomicOr(&result->invalid, 1u); + result.invalid = 1u; } - return; + return result; } const bool sphere = in.type == GeometryType::SPHERE; const auto *indices = static_cast(in.indices); @@ -179,17 +184,76 @@ VISRTX_GLOBAL void primitiveBounds( : glm::abs(in.radii ? in.radii[sphere ? center : i] : in.radius); const vec3 v0 = in.vertices[c.x], v1 = in.vertices[c.y]; const box3 b(glm::min(v0, v1) - r, glm::max(v0, v1) + r); - bounds[i] = b; + bound = b; const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); const float scale = glm::max(m.x, glm::max(m.y, m.z)); if (!isfinite(r) || !isfinite(v0.x) || !isfinite(v0.y) || !isfinite(v0.z) || !isfinite(v1.x) || !isfinite(v1.y) || !isfinite(v1.z) || !isfinite(scale)) + result.invalid = 1u; + else + result.value = scale; + return result; +} + +VISRTX_GLOBAL void primitiveBounds( + PrimitiveInput in, box3 *bounds, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + const auto summary = primitiveBound(in, i, bounds[i]); + if (summary.invalid) atomicOr(&result->invalid, 1u); else - atomicMax( - reinterpret_cast(&result->value), __float_as_uint(scale)); + atomicMax(reinterpret_cast(&result->value), + __float_as_uint(summary.value)); +} + +// A batch is one launch, with independent block-local reductions/scans. The +// general multi-block/CUB path remains available above MAX_PRIMITIVES. +VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) +{ + constexpr int threads = SmallGeometryBatch::MAX_PRIMITIVES; + using FloatReduce = cub::BlockReduce; + using StatusReduce = cub::BlockReduce; + using Scan = cub::BlockScan; + __shared__ typename FloatReduce::TempStorage scaleStorage; + __shared__ typename StatusReduce::TempStorage statusStorage; + __shared__ typename Scan::TempStorage scanStorage; + const auto &job = jobs[blockIdx.x]; + const unsigned i = threadIdx.x; + if (job.bounds) { + Result local{}; + if (i < job.boundsInput.count) + local = primitiveBound(job.boundsInput, i, job.bounds[i]); + const float scale = + FloatReduce(scaleStorage) + .Reduce(local.value, + [] __device__(float a, float b) { return glm::max(a, b); }); + const unsigned invalid = StatusReduce(statusStorage).Sum(local.invalid); + if (i == 0) + job.results[0] = {scale, invalid}; + __syncthreads(); // statusStorage is reused for the area validation. + } + if (job.cdf) { + const auto n = job.areaInput.count; + const double area = i < n ? primitiveArea(job.areaInput, i) : 0.0; + double prefix, total; + Scan(scanStorage).InclusiveSum(area, prefix, total); + const float value = float(total); + const unsigned localInvalid = !isfinite(area) || area < 0.0 + || !isfinite(prefix) || prefix < 0.0 || !isfinite(value) + || (total > 0.0 && value == 0.f); + if (i < n) + job.cdf[i] = + total > 0.0 ? (i + 1 == n ? 1.f : float(prefix / total)) : 0.f; + const unsigned invalid = StatusReduce(statusStorage).Sum(localInvalid); + if (i == 0) + job.results[1] = {invalid ? __int_as_float(0x7fffffff) : value, invalid}; + } } + VISRTX_GLOBAL void quadIndices(const uvec4 *indices, size_t n, uvec3 *out) { const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; @@ -299,6 +363,64 @@ bool finishPreparation(Geometry *g) "execution completion"); } +void SmallGeometryBatch::enqueue(Preprocessing *preprocessing) +{ + m_pending.push_back(preprocessing); +} + +cudaError_t SmallGeometryBatch::finish(cudaStream_t stream) +{ + cudaError_t error = cudaSuccess; + if (!m_pending.empty()) { + // No host allocations after submission: descriptors and readback sources + // remain stable even when an error requires a subsequent fallback drain. + m_jobs.clear(); + m_jobs.reserve(m_pending.size()); + for (auto *p : m_pending) + m_jobs.push_back(p->m_small); + if (m_jobs.size() > size_t(std::numeric_limits::max())) + error = cudaErrorInvalidValue; + else + error = m_descriptors.enqueueUpload(m_jobs.data(), m_jobs.size(), stream); + if (error == cudaSuccess) { + smallGeometry<<>>( + m_descriptors.ptrAs()); + error = cudaGetLastError(); + } + for (auto *p : m_pending) { + if (error == cudaSuccess && p->m_small.bounds) + error = cudaMemcpyAsync(p->m_readback, + p->m_small.results, + sizeof(Result), + cudaMemcpyDeviceToHost, + stream); + if (error == cudaSuccess && p->m_small.cdf) + error = cudaMemcpyAsync(&p->m_readback[1].value, + &p->m_small.results[1].value, + sizeof(float), + cudaMemcpyDeviceToHost, + stream); + } + } + const auto completion = cudaStreamSynchronize(stream); + for (auto *p : m_pending) { + p->m_smallQueued = false; + p->m_small = {}; + } + m_pending.clear(); + if (error != cudaSuccess || completion != cudaSuccess) + cudaGetLastError(); + return error == cudaSuccess ? completion : error; +} + +void Preprocessing::enqueueSmall(Geometry *g) +{ + if (!m_smallQueued) { + g->deviceState()->smallGeometryBatch.enqueue(this); + m_smallQueued = true; + } +} + Preprocessing::~Preprocessing() = default; bool Preprocessing::reserveReadback(Geometry *g) @@ -350,6 +472,16 @@ bool Preprocessing::bounds( g->deferPreparation(); m_scale = &scale; m_readback[0] = {}; + if (in.count > 0 && in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { + if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) + || !reservePreparation(g, m_result, 2 * sizeof(Result))) + return false; + m_small.boundsInput = in; + m_small.bounds = aabbs.ptrAs(); + m_small.results = m_result.ptrAs(); + enqueueSmall(g); + return true; + } if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) || !reservePreparation(g, m_result, sizeof(Result)) || !checkPreparation(g, @@ -390,6 +522,16 @@ bool Preprocessing::areas( m_total = &total; m_cdf = &cdf; m_readback[1] = {}; + if (in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { + if (!reservePreparation(g, cdf, in.count * sizeof(float)) + || !reservePreparation(g, m_result, 2 * sizeof(Result))) + return false; + m_small.areaInput = in; + m_small.cdf = cdf.ptrAs(); + m_small.results = m_result.ptrAs(); + enqueueSmall(g); + return true; + } const auto stream = g->deviceState()->preparation.stream(); size_t scratchBytes = 0; if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 673a1e704..0f563432f 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -31,6 +31,7 @@ #pragma once +#include #include "ReadbackPool.h" #include "gpu/gpu_objects.h" #include "utility/DeviceBuffer.h" @@ -57,6 +58,36 @@ struct PrimitiveInput float noiseFactor{0.f}; }; +// One block handles one small geometry. Bounds and area inputs are separate: +// a lazily requested sphere area distribution need not carry vertex positions. +struct SmallGeometryJob +{ + PrimitiveInput boundsInput; + PrimitiveInput areaInput; + box3 *bounds{nullptr}; + float *cdf{nullptr}; + PreparationResult *results{nullptr}; +}; + +struct Preprocessing; + +// Device-owned, single-flight batch. The geometry collection queue retains +// owners until finish() drains every queued descriptor, kernel and readback. +struct SmallGeometryBatch +{ + static constexpr size_t MAX_PRIMITIVES = 256; + SmallGeometryBatch() = default; + SmallGeometryBatch(const SmallGeometryBatch &) = delete; + SmallGeometryBatch &operator=(const SmallGeometryBatch &) = delete; + void enqueue(Preprocessing *preprocessing); + cudaError_t finish(cudaStream_t stream); + + private: + std::vector m_pending; + std::vector m_jobs; + DeviceBuffer m_descriptors; +}; + // Per-geometry reusable workspace. Submission retains pinned readback storage; // complete() publishes scalar results after the device's collection barrier. struct Preprocessing @@ -68,7 +99,8 @@ struct Preprocessing Preprocessing(Preprocessing &&) = delete; Preprocessing &operator=(Preprocessing &&) = delete; - // Success means submitted, not published. Output references must be owned + // Success means queued, not published. Small jobs defer GPU submission to + // the next preparation completion boundary. Output references must be owned // by the retained geometry and remain valid until collection completes. bool areas(Geometry *geometry, const PrimitiveInput &input, @@ -83,7 +115,11 @@ struct Preprocessing bool complete(Geometry *geometry); private: + friend struct SmallGeometryBatch; bool reserveReadback(Geometry *geometry); + void enqueueSmall(Geometry *geometry); + SmallGeometryJob m_small; + bool m_smallQueued{false}; GeometryReadbackPool::Lease m_readbackLease; PreparationResult *m_readback{nullptr}; float *m_scale{nullptr}; diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 290cafaf0..1100b699f 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -272,7 +272,9 @@ bool DeviceGlobalState::hasPendingGeometryPreparations() const cudaError_t DeviceGlobalState::finishGeometryPreparation() { - const auto error = preparation.finish(); + // Flush deferred small jobs even at intervening upload/retirement waits: + // their input pointers must be consumed before a backing allocation changes. + const auto error = smallGeometryBatch.finish(preparation.stream()); if (error != cudaSuccess) { // An intervening upload/legacy consumer may wait before the collection // point. Its stream-completion error affects all already queued results. @@ -296,7 +298,7 @@ bool DeviceGlobalState::collectGeometryPreparations() auto collecting = nonstd::make_scope_exit( [&] { m_collectingGeometryPreparations = false; }); auto pending = std::move(m_geometryPreparations); - const auto error = preparation.finish(); + const auto error = finishGeometryPreparation(); if (error != cudaSuccess) { // A stream error invalidates every generation in this batch. Mark them // before reporting, so callbacks cannot see a partially valid generation. diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 57c4cdcde..d7924afd9 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -31,7 +31,7 @@ #pragma once -#include "geometry/ReadbackPool.h" +#include "geometry/Preprocessing.h" #include "gpu/gpu_objects.h" #include "utility/DeviceObjectArray.h" #include "utility/PreparationStream.h" @@ -181,6 +181,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUstream stream; PreparationStream preparation; GeometryReadbackPool geometryReadbacks; + SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; OptixDeviceContext optixContext; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 2b3ade5b5..43b298665 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -169,7 +169,7 @@ across host-vector growth and preservation of newer dirty edits. ## Geometry submission and collection -Checked bounds and area-CDF preparation submit kernels and asynchronous readbacks +Checked bounds and area-CDF preparation queue kernels and asynchronous readbacks into geometry-owned pinned storage. A successful submission is not publication: scalar outputs, numeric validation, and geometry registry updates happen only after collection. The device queue retains each submitted geometry, and thereby @@ -190,6 +190,33 @@ Status callbacks cannot reenter device property queries or rendering while collection is resolving results; those calls are refused instead of publishing a partially collected scene. +### Small-geometry computation batches + +For 1–256 primitives, bounds and area requests are held as device-owned batches +of descriptors. One CUDA block handles each geometry in a single batch launch: +block-local reductions produce its bounds summary, and a double-precision +block scan produces its area CDF. Bounds and area requests for the same geometry +share a descriptor when both arrive before the completion boundary. Requests +above 256 primitives retain the general multi-block/CUB path. Zero-count +handling is unchanged. SDF bounds retain their zero epsilon-scale convention. + +Every `finishGeometryPreparation()` flushes these descriptors before waiting, +including intervening upload waits and shared-array privatization. This is +necessary because a queued descriptor still references its original inputs even +before GPU work has been launched. Collection retains owners through descriptor +upload, dispatch and readback completion. Descriptors remain stable through +fallback drains; dispatch or transfer failure invalidates the pending batch, +while numeric failures remain local to their geometry. The first step retains +per-geometry summary copies; batching computation does not itself consolidate +readbacks. + +`TestSmallGeometryBatch` exercises mixed sphere/cone/cylinder/triangle batches +at 1, 31, 32, 33, 255, 256 and 257 primitives with host and device-backed logical +array slices. It checks independent bounds, zero-area light removal, recovery, +and transitions between small and general paths. Failure injection covers the +descriptor upload, dispatch-status check and readback, including batch-wide +invalidation and retry. + Pinned readback storage is leased from the device's `GeometryReadbackPool`. Each page holds 256 geometry leases, each containing two result slots (a 4 KiB page with the current result layout). A geometry keeps its lease across updates; From d54a6b55e7e0fc1aa84b443b6a6e1bef826482bf Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:53:06 +0000 Subject: [PATCH 12/20] perf(rtx): consolidate small geometry summary readbacks --- devices/rtx/apps/tests/api/CMakeLists.txt | 4 + .../tests/api/TestCudaPreparationFailure.cpp | 23 +++-- .../apps/tests/api/TestSmallGeometryBatch.cpp | 45 ++++++++++ devices/rtx/device/geometry/Preprocessing.cu | 85 ++++++++++++++----- devices/rtx/device/geometry/Preprocessing.h | 5 ++ .../rtx/docs/geometry-preparation-reuse.md | 19 +++-- 6 files changed, 149 insertions(+), 32 deletions(-) diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 10964af58..02f8c7329 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -110,6 +110,9 @@ add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure # CUDA API interposition needs ELF dynamic symbols; static cudart calls cannot # be intercepted. Configure with -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared to run. if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") + target_link_libraries(TestSmallGeometryBatch PRIVATE ${CMAKE_DL_LIBS}) + target_compile_definitions(TestSmallGeometryBatch PRIVATE VISRTX_TEST_INTERPOSE_CUDA) + set_target_properties(TestSmallGeometryBatch PROPERTIES ENABLE_EXPORTS ON) make_test(TestFramePublicationRecovery) target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) @@ -130,6 +133,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency sphere-undrained-completion sphere-batch-small-copy sphere-batch-small-launch sphere-batch-small-readback + sphere-batch-small-result-allocation sphere-batch-small-pinned-allocation sphere-readback-allocation sphere-batch-completion sphere-batch-upload-completion sphere-batch-input-completion sphere-upload-allocation sphere-upload-copy sphere-upload-completion diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 801d82e4c..71c81f943 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -65,6 +65,7 @@ enum class Failure SMALL_DESCRIPTOR_COPY, SMALL_LAUNCH, SMALL_READBACK, + SMALL_PINNED_ALLOCATION, PREPARATION_DEPENDENCY, BVH_SYNC, BVH_COPY, @@ -170,7 +171,9 @@ extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) constexpr size_t readbackPageBytes = 2 * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE * sizeof(visrtx::PreparationResult); - if (bytes == readbackPageBytes && inject(Failure::READBACK_ALLOCATION)) { + if ((bytes == readbackPageBytes && inject(Failure::READBACK_ALLOCATION)) + || (bytes == 4 * sizeof(visrtx::PreparationResult) + && inject(Failure::SMALL_PINNED_ALLOCATION))) { *ptr = nullptr; return next("cudaMallocHost")(ptr, size_t(-1)); } @@ -288,11 +291,12 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, } if (failure == Failure::PREPARATION_EARLY_SYNC && stream == preparationStream && kind == cudaMemcpyDeviceToHost - && bytes == sizeof(float) + sizeof(uint32_t) + && (bytes == sizeof(visrtx::PreparationResult) + || (bytes && bytes % (2 * sizeof(visrtx::PreparationResult)) == 0)) && !pendingCompletion.queued) { - // The bounds summary is a float scale and uint32 status. Gate its pinned - // readback after kernel submission, with no subsequent allocation or - // pageable copy to supply a hidden wait. + // Gate either the general bounds summary or the consolidated small-batch + // summary after kernel submission. No subsequent allocation or pageable + // copy can supply a hidden wait. auto error = cudaLaunchHostFunc(stream, blockPreparation, nullptr); if (error != cudaSuccess) return error; @@ -632,6 +636,15 @@ int main(int argc, char **argv) if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-readback") == 0) failure = Failure::SMALL_READBACK; + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-result-allocation") == 0) { + allocationBytes = + 4 * sizeof(visrtx::PreparationResult); // Two geometries. + failure = Failure::ALLOCATION; + } + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-pinned-allocation") == 0) + failure = Failure::SMALL_PINNED_ALLOCATION; std::thread watchdog; if (earlyCompletion) { if (cudaEventCreateWithFlags( diff --git a/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp index cb9e6121f..a68be8eeb 100644 --- a/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp +++ b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp @@ -37,8 +37,15 @@ #include #include #include "DeviceTestArray.h" +#ifdef VISRTX_TEST_INTERPOSE_CUDA +#include +#endif namespace { +#ifdef VISRTX_TEST_INTERPOSE_CUDA +bool trackSummaries = false; +int summaryCopies = 0; +#endif using vec3 = std::array; int errors = 0; void status(const void *, @@ -133,6 +140,10 @@ bool run(bool device) // One world query flushes all geometries together, including lazy area // requests on the first generation and bounds+area jobs on later ones. std::array worldBounds{}; +#ifdef VISRTX_TEST_INTERPOSE_CUDA + summaryCopies = 0; + trackSummaries = true; +#endif ok = anariGetProperty(d, world, "bounds", @@ -141,6 +152,20 @@ bool run(bool device) sizeof(worldBounds), ANARI_WAIT) && ok; +#ifdef VISRTX_TEST_INTERPOSE_CUDA + trackSummaries = false; + // Initial bounds and lazy areas are separate collections. Once area data + // is wanted, finalization batches both together. Large-path scalar copies + // and OptiX's 8/24-byte readbacks are not batch summaries. + const int expectedCopies = generation == 0 ? 2 : 1; + if (summaryCopies != expectedCopies) + std::fprintf(stderr, + "generation=%d summary copies=%d expected=%d\n", + generation, + summaryCopies, + expectedCopies); + ok = summaryCopies == expectedCopies && ok; +#endif uint32_t lights = 0; ok = anariGetProperty(d, world, @@ -204,6 +229,26 @@ bool run(bool device) } } // namespace +#ifdef VISRTX_TEST_INTERPOSE_CUDA +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + constexpr size_t pairBytes = 2 * (sizeof(float) + sizeof(uint32_t)); + if (trackSummaries && kind == cudaMemcpyDeviceToHost && bytes + && bytes % pairBytes == 0) + ++summaryCopies; + using Copy = cudaError_t (*)( + void *, const void *, size_t, cudaMemcpyKind, cudaStream_t); + auto real = reinterpret_cast(dlsym(RTLD_NEXT, "cudaMemcpyAsync")); + if (!real) + std::abort(); + return real(dst, src, bytes, kind, stream); +} +#endif + int main() { bool ok = run(false); diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index 4e9d3e338..2fd5f8980 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -223,6 +223,11 @@ VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) __shared__ typename Scan::TempStorage scanStorage; const auto &job = jobs[blockIdx.x]; const unsigned i = threadIdx.x; + if (i == 0) { + // Every transferred byte is initialized, including unused result slots. + job.results[0] = {}; + job.results[1] = {}; + } if (job.bounds) { Result local{}; if (i < job.boundsInput.count) @@ -363,6 +368,38 @@ bool finishPreparation(Geometry *g) "execution completion"); } +SmallGeometryBatch::~SmallGeometryBatch() +{ + if (m_readback) + cudaFreeHost(m_readback); +} + +cudaError_t SmallGeometryBatch::reserveResults(size_t count) +{ + const size_t bytes = 2 * count * sizeof(Result); + if (!m_results) + m_results.reset(); + m_results.reserve(bytes); + auto error = cudaGetLastError(); + if (error != cudaSuccess) + return error; + if (!m_results || m_results.bytes() < bytes) + return cudaErrorMemoryAllocation; + if (count > m_readbackCapacity) { + void *memory = nullptr; + error = cudaMallocHost(&memory, bytes); + if (error != cudaSuccess) + return error; + // Previous batches were drained before reuse. Keep the old allocation on + // allocation failure; no in-flight transfer refers to it during growth. + if (m_readback) + cudaFreeHost(m_readback); + m_readback = static_cast(memory); + m_readbackCapacity = count; + } + return cudaSuccess; +} + void SmallGeometryBatch::enqueue(Preprocessing *preprocessing) { m_pending.push_back(preprocessing); @@ -378,32 +415,40 @@ cudaError_t SmallGeometryBatch::finish(cudaStream_t stream) m_jobs.reserve(m_pending.size()); for (auto *p : m_pending) m_jobs.push_back(p->m_small); - if (m_jobs.size() > size_t(std::numeric_limits::max())) + if (m_jobs.size() > size_t(std::numeric_limits::max()) + || m_jobs.size() + > std::numeric_limits::max() / (2 * sizeof(Result))) error = cudaErrorInvalidValue; else + error = reserveResults(m_jobs.size()); + if (error == cudaSuccess) { + for (size_t i = 0; i < m_jobs.size(); ++i) + m_jobs[i].results = m_results.ptrAs() + 2 * i; error = m_descriptors.enqueueUpload(m_jobs.data(), m_jobs.size(), stream); + } if (error == cudaSuccess) { smallGeometry<<>>( m_descriptors.ptrAs()); error = cudaGetLastError(); } - for (auto *p : m_pending) { - if (error == cudaSuccess && p->m_small.bounds) - error = cudaMemcpyAsync(p->m_readback, - p->m_small.results, - sizeof(Result), - cudaMemcpyDeviceToHost, - stream); - if (error == cudaSuccess && p->m_small.cdf) - error = cudaMemcpyAsync(&p->m_readback[1].value, - &p->m_small.results[1].value, - sizeof(float), - cudaMemcpyDeviceToHost, - stream); - } + if (error == cudaSuccess) + error = cudaMemcpyAsync(m_readback, + m_results.ptr(), + 2 * m_jobs.size() * sizeof(Result), + cudaMemcpyDeviceToHost, + stream); } const auto completion = cudaStreamSynchronize(stream); - for (auto *p : m_pending) { + for (size_t i = 0; i < m_pending.size(); ++i) { + auto *p = m_pending[i]; + // Scatter only completed results. An intervening wait may flush bounds + // before an area request arrives: preserve the other slot in that case. + if (error == cudaSuccess && completion == cudaSuccess) { + if (p->m_small.bounds) + p->m_readback[0] = m_readback[2 * i]; + if (p->m_small.cdf) + p->m_readback[1] = m_readback[2 * i + 1]; + } p->m_smallQueued = false; p->m_small = {}; } @@ -473,12 +518,10 @@ bool Preprocessing::bounds( m_scale = &scale; m_readback[0] = {}; if (in.count > 0 && in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { - if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) - || !reservePreparation(g, m_result, 2 * sizeof(Result))) + if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) return false; m_small.boundsInput = in; m_small.bounds = aabbs.ptrAs(); - m_small.results = m_result.ptrAs(); enqueueSmall(g); return true; } @@ -523,12 +566,10 @@ bool Preprocessing::areas( m_cdf = &cdf; m_readback[1] = {}; if (in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { - if (!reservePreparation(g, cdf, in.count * sizeof(float)) - || !reservePreparation(g, m_result, 2 * sizeof(Result))) + if (!reservePreparation(g, cdf, in.count * sizeof(float))) return false; m_small.areaInput = in; m_small.cdf = cdf.ptrAs(); - m_small.results = m_result.ptrAs(); enqueueSmall(g); return true; } diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 0f563432f..76de90266 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -77,6 +77,7 @@ struct SmallGeometryBatch { static constexpr size_t MAX_PRIMITIVES = 256; SmallGeometryBatch() = default; + ~SmallGeometryBatch(); SmallGeometryBatch(const SmallGeometryBatch &) = delete; SmallGeometryBatch &operator=(const SmallGeometryBatch &) = delete; void enqueue(Preprocessing *preprocessing); @@ -86,6 +87,10 @@ struct SmallGeometryBatch std::vector m_pending; std::vector m_jobs; DeviceBuffer m_descriptors; + DeviceBuffer m_results; + PreparationResult *m_readback{nullptr}; + size_t m_readbackCapacity{0}; + cudaError_t reserveResults(size_t count); }; // Per-geometry reusable workspace. Submission retains pinned readback storage; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 43b298665..79c64706b 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -206,16 +206,25 @@ necessary because a queued descriptor still references its original inputs even before GPU work has been launched. Collection retains owners through descriptor upload, dispatch and readback completion. Descriptors remain stable through fallback drains; dispatch or transfer failure invalidates the pending batch, -while numeric failures remain local to their geometry. The first step retains -per-geometry summary copies; batching computation does not itself consolidate -readbacks. +while numeric failures remain local to their geometry. + +Small jobs write both result slots into a contiguous device-owned result buffer. +The batch performs one asynchronous transfer into a reusable pinned host buffer, +then scatters only completed, requested slots into the geometries' summaries. +Even unused slots are initialized before transfer. A bounds-only flush followed +by a later area request preserves the earlier bounds summary. Failed transfers +or completion do not scatter partial results. Both batch buffers grow to their +high-water size and remain alive through fallback drains; the per-geometry +pinned leases and general-path readbacks retain their existing ownership. `TestSmallGeometryBatch` exercises mixed sphere/cone/cylinder/triangle batches at 1, 31, 32, 33, 255, 256 and 257 primitives with host and device-backed logical array slices. It checks independent bounds, zero-area light removal, recovery, and transitions between small and general paths. Failure injection covers the -descriptor upload, dispatch-status check and readback, including batch-wide -invalidation and retry. +descriptor upload, dispatch-status check, readback and batch device/pinned +allocation, including batch-wide invalidation and retry. With shared CUDA runtime +interposition, the mixed-size test also checks one summary copy per collection +(two initial collections for bounds and lazy areas, then one for combined jobs). Pinned readback storage is leased from the device's `GeometryReadbackPool`. Each page holds 256 geometry leases, each containing two result slots (a 4 KiB From 02fb3f2a5980659f14356e0c54d0e9bd5c7c2617 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:05:12 +0000 Subject: [PATCH 13/20] perf(rtx): reuse completed render-stream retirement waits --- devices/rtx/apps/tests/api/CMakeLists.txt | 4 + .../apps/tests/api/TestStreamRetirement.cpp | 134 ++++++++++++++++++ devices/rtx/device/VisRTXDevice.cpp | 1 + devices/rtx/device/array/Array.cpp | 2 +- devices/rtx/device/frame/Denoiser.cu | 3 + devices/rtx/device/frame/Frame.cu | 3 + devices/rtx/device/geometry/Geometry.cpp | 2 +- devices/rtx/device/geometry/Isosurface.cpp | 1 + devices/rtx/device/optix_visrtx.h | 2 + devices/rtx/device/utility/StreamRetirement.h | 86 +++++++++++ .../rtx/device/volume/TransferFunction1D.cpp | 1 + .../rtx/docs/geometry-preparation-reuse.md | 24 +++- 12 files changed, 255 insertions(+), 8 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestStreamRetirement.cpp create mode 100644 devices/rtx/device/utility/StreamRetirement.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 02f8c7329..0ca7d282a 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -110,6 +110,10 @@ add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure # CUDA API interposition needs ELF dynamic symbols; static cudart calls cannot # be intercepted. Configure with -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared to run. if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") + add_executable(TestStreamRetirement TestStreamRetirement.cpp) + target_link_libraries(TestStreamRetirement PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) + set_target_properties(TestStreamRetirement PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestStreamRetirement COMMAND TestStreamRetirement) target_link_libraries(TestSmallGeometryBatch PRIVATE ${CMAKE_DL_LIBS}) target_compile_definitions(TestSmallGeometryBatch PRIVATE VISRTX_TEST_INTERPOSE_CUDA) set_target_properties(TestSmallGeometryBatch PROPERTIES ENABLE_EXPORTS ON) diff --git a/devices/rtx/apps/tests/api/TestStreamRetirement.cpp b/devices/rtx/apps/tests/api/TestStreamRetirement.cpp new file mode 100644 index 000000000..0e30de92a --- /dev/null +++ b/devices/rtx/apps/tests/api/TestStreamRetirement.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/utility/StreamRetirement.h" + +namespace { +cudaStream_t tracked{}; +std::atomic waits{0}; +std::atomic failNext{false}; +std::atomic released{false}; +std::atomic returned{false}; +std::mutex mutex; +std::condition_variable condition; +void CUDART_CB block(void *) +{ + while (!released.load()) + std::this_thread::yield(); +} +} // namespace + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + if (stream == tracked) { + { + std::lock_guard lock(mutex); + ++waits; + } + condition.notify_all(); + } + auto real = reinterpret_cast( + dlsym(RTLD_NEXT, "cudaStreamSynchronize")); + if (!real) + std::abort(); + const auto error = real(stream); + if (stream == tracked && failNext.exchange(false)) + return cudaErrorUnknown; + return error; +} + +int main() +{ + if (cudaStreamCreateWithFlags(&tracked, cudaStreamNonBlocking) != cudaSuccess) + return 1; + visrtx::StreamRetirement retirement; + retirement.initialize(tracked); + bool ok = retirement.retire() == cudaSuccess && waits == 1; + for (int i = 0; i < 64; ++i) + ok = retirement.retire() == cudaSuccess && waits == 1 && ok; + + int *device = nullptr; + if (cudaMalloc(reinterpret_cast(&device), sizeof(int)) + != cudaSuccess) + return 1; + retirement.invalidate(); + ok = cudaLaunchHostFunc(tracked, block, nullptr) == cudaSuccess && ok; + ok = cudaMemsetAsync(device, 0x2a, sizeof(int), tracked) == cudaSuccess && ok; + int gpu = 0; + cudaGetDevice(&gpu); + cudaError_t completion = cudaErrorUnknown; + std::thread waiter([&] { + cudaSetDevice(gpu); + completion = retirement.retire(); + { + std::lock_guard lock(mutex); + returned = true; + } + condition.notify_all(); + }); + { + std::unique_lock lock(mutex); + const bool entered = condition.wait_for(lock, std::chrono::seconds(5), [] { + return waits >= 2 || returned.load(); + }); + ok = entered && waits == 2 && !returned && ok; + // A submission announced during the wait must not inherit its certificate. + retirement.invalidate(); + released = true; + } + waiter.join(); + ok = completion == cudaSuccess && ok; + int result = 0; + ok = cudaMemcpy(&result, device, sizeof(int), cudaMemcpyDeviceToHost) + == cudaSuccess + && result == 0x2a2a2a2a && ok; + ok = retirement.retire() == cudaSuccess && waits == 3 && ok; + ok = retirement.retire() == cudaSuccess && waits == 3 && ok; + + retirement.invalidate(); + failNext = true; + ok = retirement.retire() == cudaErrorUnknown && waits == 4 && ok; + ok = retirement.retire() == cudaSuccess && waits == 5 && ok; + ok = retirement.retire() == cudaSuccess && waits == 5 && ok; + cudaFree(device); + cudaStreamDestroy(tracked); + std::printf( + "stream retirement waits=%d %s\n", int(waits), ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 21d141783..70e74f7b7 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -711,6 +711,7 @@ DeviceInitStatus VisRTXDevice::initOptix() OPTIX_CHECK_RETURN_VALUE(optixInit(), DeviceInitStatus::FAILURE); setCUDADevice(); cudaStreamCreate(&state.stream); + state.renderRetirement.initialize(state.stream); cudaGetDeviceProperties(&state.deviceProps, m_gpuID); reportMessage(ANARI_SEVERITY_DEBUG, diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 2a5057032..bbdaf762c 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -203,7 +203,7 @@ void Array::privatize() this->useCount(helium::RefType::INTERNAL)); // Existing frames may still read the shared pointer. The application may // free it as soon as this last PUBLIC release returns. - auto completion = cudaStreamSynchronize(state.stream); + auto completion = state.renderRetirement.retire(); // Deferred preprocessing can still read this external allocation even // when no frame is in flight. Retain it through that stream's completion. if (completion == cudaSuccess && state.hasPendingGeometryPreparations()) diff --git a/devices/rtx/device/frame/Denoiser.cu b/devices/rtx/device/frame/Denoiser.cu index cb8a4b401..680abc4ba 100644 --- a/devices/rtx/device/frame/Denoiser.cu +++ b/devices/rtx/device/frame/Denoiser.cu @@ -92,6 +92,7 @@ void Denoiser::setup(uvec2 size, m_averageColor.reserve(3 * sizeof(float)); // Setup must be sized for the largest padded tile the tiled invoke feeds. + state.renderRetirement.invalidate(); OPTIX_CHECK(optixDenoiserSetup(m_denoiser, state.stream, m_tileW + 2 * m_overlap, @@ -143,6 +144,7 @@ void Denoiser::cleanup() void Denoiser::launch() { auto &state = *deviceState(); + state.renderRetirement.invalidate(); // Tiled invoke normalizes each tile independently unless handed whole-frame // HDR exposure values. Compute them over the full input and share them so @@ -185,6 +187,7 @@ void Denoiser::convertOutput() if (m_format == ANARI_FLOAT32_VEC4) return; auto &state = *deviceState(); + state.renderRetirement.invalidate(); instrument::rangePush("denoiser transform pixels"); auto numPixels = size_t(m_layer.output.width) * size_t(m_layer.output.height); auto begin = thrust::device_ptr((vec4 *)m_pixelBuffer->dataDevice()); diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index db794e1da..ced277b32 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -431,6 +431,7 @@ Frame::Frame(DeviceGlobalState *d) : helium::BaseFrame(d), m_denoiser(d) cudaEventCreate(&m_eventStart); cudaEventCreate(&m_eventEnd); + d->renderRetirement.invalidate(); cudaEventRecord(m_eventStart, d->stream); cudaEventRecord(m_eventEnd, d->stream); } @@ -712,6 +713,7 @@ void Frame::renderFrame() if (!m_nextFrameReset && sampleLimit > 0 && hd.fb.frameID >= sampleLimit) return; + state.renderRetirement.invalidate(); cudaEventRecord(m_eventStart, state.stream); m_renderer->populateFrameData(hd); @@ -1100,6 +1102,7 @@ void Frame::resolveVec3Buffer(const DeviceBuffer &accum, const uint32_t nPixels = uint32_t(numPixels()); const uint32_t blockSize = 256; const uint32_t gridSize = (nPixels + blockSize - 1) / blockSize; + state.renderRetirement.invalidate(); resolveVec3Channel<<>>( accum.ptrAs(), out.dataDevice(), diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 4123ffd0c..02e0c68bf 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -125,7 +125,7 @@ void Geometry::commitParameters() const bool retain = canRetainPreparationInputs(); m_inputRetirementFailed = !retain && !checkPreparation(this, - cudaStreamSynchronize(deviceState()->stream), + deviceState()->renderRetirement.retire(), "retiring previous geometry inputs"); commitAttributes("primitive.", m_primitiveAttributes); diff --git a/devices/rtx/device/geometry/Isosurface.cpp b/devices/rtx/device/geometry/Isosurface.cpp index eadf2ff3c..0509d1d73 100644 --- a/devices/rtx/device/geometry/Isosurface.cpp +++ b/devices/rtx/device/geometry/Isosurface.cpp @@ -119,6 +119,7 @@ void Isosurface::finalize() // active macrocells, so the BVH culls rays missing the surface while the // in-program DDA still does fine per-cell skipping inside each brick. auto &state = *deviceState(); + state.renderRetirement.invalidate(); m_numBricks = buildIsosurfaceBricks(state.stream, m_field->m_uniformGrid.gpuData(), m_isovaluesDev, diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index d7924afd9..7f110c065 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -35,6 +35,7 @@ #include "gpu/gpu_objects.h" #include "utility/DeviceObjectArray.h" #include "utility/PreparationStream.h" +#include "utility/StreamRetirement.h" // helium #include "helium/BaseGlobalDeviceState.h" @@ -180,6 +181,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUcontext cudaContext; CUstream stream; PreparationStream preparation; + StreamRetirement renderRetirement; GeometryReadbackPool geometryReadbacks; SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; diff --git a/devices/rtx/device/utility/StreamRetirement.h b/devices/rtx/device/utility/StreamRetirement.h new file mode 100644 index 000000000..f3e4b6dd8 --- /dev/null +++ b/devices/rtx/device/utility/StreamRetirement.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include + +namespace visrtx { + +// Scene submission is serialized. Invalidate BEFORE submitting work on the +// bound stream. A successful retirement covers only the generation captured +// before its wait, never work submitted by a callback during that wait. +// Failure cleanup must still use an unconditional drain, not this cache. +struct StreamRetirement +{ + void initialize(cudaStream_t stream); + void invalidate(); + cudaError_t retire(); + + private: + cudaStream_t m_stream{nullptr}; + std::atomic m_submitted{1}; + std::atomic m_retired{0}; +}; + +inline void StreamRetirement::initialize(cudaStream_t stream) +{ + m_stream = stream; + m_submitted = 1; + m_retired = 0; +} + +inline void StreamRetirement::invalidate() +{ + m_submitted.fetch_add(1, std::memory_order_release); +} + +inline cudaError_t StreamRetirement::retire() +{ + const auto generation = m_submitted.load(std::memory_order_acquire); + if (m_retired.load(std::memory_order_acquire) >= generation) + return cudaSuccess; + const auto error = cudaStreamSynchronize(m_stream); + if (error == cudaSuccess) { + auto retired = m_retired.load(std::memory_order_relaxed); + while (retired < generation + && !m_retired.compare_exchange_weak(retired, + generation, + std::memory_order_release, + std::memory_order_relaxed)) { + } + } + return error; +} + +} // namespace visrtx diff --git a/devices/rtx/device/volume/TransferFunction1D.cpp b/devices/rtx/device/volume/TransferFunction1D.cpp index d094b2a15..f20a26d5b 100644 --- a/devices/rtx/device/volume/TransferFunction1D.cpp +++ b/devices/rtx/device/volume/TransferFunction1D.cpp @@ -89,6 +89,7 @@ void TransferFunction1D::finalize() discritizeTFData(); createTFTexture(); + deviceState()->renderRetirement.invalidate(); m_field->m_uniformGrid.computeOpacityBounds( deviceState()->stream, m_textureObject, m_tfDim, m_valueRange); upload(); diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 79c64706b..f92d08207 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -21,9 +21,10 @@ radii, bounds, or area CDFs, and without invalidating the surface BLAS timestamp Normal object-finalization timestamps still advance, so automatic accumulation reset remains intact. Before replacing parameter references, the input-retirement check compares the declared committed preparation inputs and referenced-object -versions with the last successful preparation. Unchanged inputs skip the work- -stream wait; first preparation, changed inputs, failed preparation, and non-opt-in -types retain it. This check performs no GPU uploads. Parameter lookup names are +versions with the last successful preparation. Unchanged inputs skip retirement; +first preparation, changed inputs, failed preparation, and non-opt-in types request +retirement. A device-local completion certificate deduplicates successful waits +until another render/work-stream workload is submitted. This check performs no GPU uploads. Parameter lookup names are cached once per geometry rather than rebuilt on every finalization. Finalization still revalidates values, object versions, and backing pointers before reusing derived data: dependencies can be updated between commit and finalization, so the @@ -143,9 +144,20 @@ is reused. survives through that completion; handles/bounds are published only on success. Group/World failure state prevents failed builds from being treated as ready and permits a later retry. -- Parameter-reference replacement and last-public-release privatization retain - host waits for old render consumers. Error handling drains participating work - before storage can be retired or retried. +- Parameter-reference replacement and last-public-release privatization require + completed old render consumers. `StreamRetirement` caches a successful wait + for the generation captured before synchronization. Frame submission, + denoiser setup/launch/conversion, channel resolution, and isosurface brick + preparation invalidate that certificate before submitting work. Shared arrays + and different frames use the same device-local generation. A generation + invalidated during a wait cannot inherit that wait's certificate; errors never + certify completion. Scene submission remains serialized. Error handling uses + unconditional drains, not the cached retirement path, before storage can be + retired or retried. + +`TestStreamRetirement` checks repeated retirement requests, a gated producer, +generation changes during a wait, and failure/retry. The existing shared-array, +privatization, frame, denoiser and isosurface tests exercise the producer paths. This is not concurrent in-place scene replacement. Legacy default-stream events can include preceding work on blocking streams; tangent generation and field-grid From 865f7486690e024e9d84fa007da50c1d4d40df3b Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:14:55 +0000 Subject: [PATCH 14/20] perf(rtx): cache retired geometry input allocations --- devices/rtx/apps/tests/api/CMakeLists.txt | 5 + .../tests/api/TestDeviceAllocationCache.cpp | 326 ++++++++++++++++++ .../apps/tests/api/TestGeometryInputBatch.cpp | 46 ++- devices/rtx/device/VisRTXDevice.cpp | 3 + devices/rtx/device/array/Array.cpp | 15 +- devices/rtx/device/optix_visrtx.cpp | 5 +- devices/rtx/device/optix_visrtx.h | 3 + .../device/utility/DeviceAllocationCache.h | 236 +++++++++++++ .../rtx/device/utility/MemoryAllocation.cpp | 24 +- devices/rtx/device/utility/MemoryAllocation.h | 5 + .../rtx/docs/geometry-preparation-reuse.md | 38 +- 11 files changed, 688 insertions(+), 18 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp create mode 100644 devices/rtx/device/utility/DeviceAllocationCache.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 0ca7d282a..14f963464 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -110,6 +110,11 @@ add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure # CUDA API interposition needs ELF dynamic symbols; static cudart calls cannot # be intercepted. Configure with -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared to run. if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") + add_executable(TestDeviceAllocationCache TestDeviceAllocationCache.cpp + ../../../device/utility/MemoryAllocation.cpp) + target_link_libraries(TestDeviceAllocationCache PRIVATE CUDA::cudart anari::anari_static ${CMAKE_DL_LIBS} Threads::Threads) + set_target_properties(TestDeviceAllocationCache PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestDeviceAllocationCache COMMAND TestDeviceAllocationCache) add_executable(TestStreamRetirement TestStreamRetirement.cpp) target_link_libraries(TestStreamRetirement PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) set_target_properties(TestStreamRetirement PROPERTIES ENABLE_EXPORTS ON) diff --git a/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp new file mode 100644 index 000000000..c63179ec0 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/utility/DeviceAllocationCache.h" +#include "../../../device/utility/MemoryAllocation.h" + +namespace { +std::atomic allocations{0}, frees{0}, syncs{0}, attempts{0}; +size_t failBytes = 0; +bool failSync = false; +int capturedDeletes = 0; +std::atomic trackSync{false}, syncEntered{false}, gateReleased{false}, + cohortReturned{false}; +std::mutex gateMutex; +std::condition_variable gateCondition; +void CUDART_CB blockConsumer(void *) +{ + while (!gateReleased.load()) + std::this_thread::yield(); +} +template +T next(const char *name) +{ + auto result = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!result) + std::abort(); + return result; +} +void capturedDelete(const void *, const void *pointer) +{ + ++capturedDeletes; + cudaFree(const_cast(pointer)); +} +} // namespace + +extern "C" cudaError_t cudaMalloc(void **pointer, size_t bytes) +{ + ++attempts; + if (failBytes && bytes == failBytes) { + failBytes = 0; + return next("cudaMalloc")( + pointer, std::numeric_limits::max()); + } + const auto error = next("cudaMalloc")(pointer, bytes); + if (error == cudaSuccess && *pointer) + ++allocations; + return error; +} +extern "C" cudaError_t cudaFree(void *pointer) +{ + if (pointer) + ++frees; + return next("cudaFree")(pointer); +} +extern "C" cudaError_t cudaDeviceSynchronize() +{ + ++syncs; + if (trackSync) { + { + std::lock_guard lock(gateMutex); + syncEntered = true; + } + gateCondition.notify_all(); + } + const auto error = + next("cudaDeviceSynchronize")(); + if (failSync) { + failSync = false; + return cudaErrorUnknown; + } + return error; +} + +int main() +{ + using visrtx::DeviceAllocationCache; + auto complete = [] { return cudaSuccess; }; + bool ok = true; + { + DeviceAllocationCache cache(128, 4); + void *a = nullptr, *b = nullptr, *c = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + cache.release(a, 32); + ok = cache.allocate(32, &b) == cudaSuccess && a != b && ok; + const int beforeSyncs = syncs; + // Deferred work must be submitted before the shared completion boundary. + cudaStream_t stream{}; + ok = + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess + && ok; + ok = cache.reclaim([&] { return cudaMemsetAsync(a, 0x2a, 32, stream); }) + == cudaSuccess + && syncs == beforeSyncs + 1 && ok; + ok = cache.allocate(32, &c) == cudaSuccess && c == a && ok; + int value = 0; + ok = cudaMemcpy(&value, c, sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 0x2a2a2a2a && ok; + cudaStreamDestroy(stream); + cache.release(c, 32); + cache.release(b, 32); + const int beforeFailedFlush = syncs; + ok = cache.reclaim([] { return cudaErrorInvalidValue; }) + == cudaErrorInvalidValue + && syncs == beforeFailedFlush && ok; + failSync = true; + ok = cache.reclaim(complete) == cudaErrorUnknown && ok; + void *d = nullptr; + ok = cache.allocate(32, &d) == cudaSuccess && d != a && d != b && ok; + cache.release(d, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + cache.close(); + const int afterClose = frees; + cache.close(); + ok = frees == afterClose && ok; + } + { + // A consumer outside the preparation stream must also complete before a + // returned block can be reused. The timeout only escapes a broken wait. + DeviceAllocationCache cache; + void *p = nullptr; + ok = cache.allocate(32, &p) == cudaSuccess && ok; + cudaStream_t consumer{}; + ok = cudaStreamCreateWithFlags(&consumer, cudaStreamNonBlocking) + == cudaSuccess + && ok; + ok = cudaLaunchHostFunc(consumer, blockConsumer, nullptr) == cudaSuccess + && ok; + ok = cudaMemsetAsync(p, 0x17, 32, consumer) == cudaSuccess && ok; + cache.release(p, 32); + int gpu = 0; + cudaGetDevice(&gpu); + cudaError_t completion = cudaErrorUnknown; + trackSync = true; + std::thread collector([&] { + cudaSetDevice(gpu); + completion = cache.reclaim(complete); + { + std::lock_guard lock(gateMutex); + cohortReturned = true; + } + gateCondition.notify_all(); + }); + { + std::unique_lock lock(gateMutex); + const bool entered = gateCondition.wait_for(lock, + std::chrono::seconds(5), + [] { return syncEntered.load() || cohortReturned.load(); }); + ok = entered && syncEntered && !cohortReturned && ok; + gateReleased = true; + } + collector.join(); + trackSync = false; + ok = completion == cudaSuccess && ok; + cudaStreamSynchronize(consumer); + void *reused = nullptr; + ok = cache.allocate(32, &reused) == cudaSuccess && reused == p && ok; + int value = 0; + ok = cudaMemcpy(&value, reused, sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 0x17171717 && ok; + cache.release(reused, 32); + cudaStreamDestroy(consumer); + } + { + DeviceAllocationCache cache(64, 2); + void *p[3]{}; + for (auto &pointer : p) + ok = cache.allocate(32, &pointer) == cudaSuccess && ok; + const int beforeFree = frees; + for (auto pointer : p) + cache.release(pointer, 32); + ok = + frees == beforeFree + 1 && ok; // Bound pending as well as ready blocks. + ok = cache.reclaim(complete) == cudaSuccess && ok; + void *large = nullptr; + ok = cache.allocate(65, &large) == cudaSuccess && ok; + cache.release(large, 65); + ok = frees == beforeFree + 2 && ok; + } + { + DeviceAllocationCache cache(1024, 1); + void *a = nullptr, *b = nullptr; + ok = cache.allocate(16, &a) == cudaSuccess && ok; + ok = cache.allocate(16, &b) == cudaSuccess && ok; + const int beforeFree = frees; + cache.release(a, 16); + cache.release(b, 16); + ok = + frees == beforeFree + 1 && ok; // Entry bound independent of byte bound. + } + { + DeviceAllocationCache cache(32, 1); + void *a = nullptr, *b = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + ok = cache.allocate(32, &b) == cudaSuccess && ok; + cache.release(a, 32); + const int beforeFree = frees; + ok = cache.reclaim([&] { + cache.release(b, 32); // Frozen blocks still consume the cache budget. + return cudaSuccess; + }) == cudaSuccess + && frees == beforeFree + 1 && ok; + } + { + DeviceAllocationCache cache(1024, 64); + std::array pointers{}; + for (auto &p : pointers) + ok = cache.allocate(8, &p) == cudaSuccess && ok; + const int beforeFree = frees; + std::vector workers; + for (int worker = 0; worker < 8; ++worker) + workers.emplace_back([&, worker] { + for (int i = worker; i < 64; i += 8) + cache.release(pointers[i], 8); + }); + for (auto &worker : workers) + worker.join(); + ok = frees == beforeFree && cache.reclaim(complete) == cudaSuccess && ok; + } + { + DeviceAllocationCache cache; + void *a = nullptr, *b = nullptr, *c = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + ok = cache.allocate(32, &b) == cudaSuccess && ok; + cache.release(a, 32); + ok = cache.reclaim([&] { + cache.release(b, 32); // Later returns cannot join this frozen cohort. + return cudaSuccess; + }) == cudaSuccess + && ok; + ok = cache.allocate(32, &c) == cudaSuccess && c == a && ok; + void *d = nullptr; + ok = cache.allocate(32, &d) == cudaSuccess && d != b && ok; + cache.release(c, 32); + cache.release(d, 32); + bool threw = false; + try { + cache.reclaim([]() -> cudaError_t { throw std::runtime_error("test"); }); + } catch (const std::runtime_error &) { + threw = true; + } + ok = threw && cache.reclaim(complete) == cudaSuccess && ok; + } + { + DeviceAllocationCache cache; + void *p = nullptr; + ok = cache.allocate(32, &p) == cudaSuccess && ok; + cache.release(p, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + const int beforeAttempts = attempts, beforeFrees = frees; + failBytes = 64; + ok = cache.allocate(64, &p) == cudaSuccess && attempts == beforeAttempts + 2 + && frees == beforeFrees + 1 && ok; + cache.release(p, 64); + // With no ready blocks to trim, preserve the original allocation error. + failBytes = 128; + ok = cache.allocate(128, &p) == cudaErrorMemoryAllocation && !p && ok; + cudaGetLastError(); + } + { + auto cache = std::make_shared(); + void *p = nullptr; + ok = cache->allocate(32, &p) == cudaSuccess && ok; + auto allocation = visrtx::CudaMemoryAllocation::fromCache(p, 32, cache); + auto moved = std::move(allocation); + ok = !allocation && moved.ptr() == p && moved.isOwner() && ok; + cache->close(); + cache.reset(); // A late return must free, not resurrect a closed cache. + const int beforeFree = frees; + moved = visrtx::CudaMemoryAllocation(); + ok = frees == beforeFree + 1 && ok; + ok = cudaMalloc(&p, 32) == cudaSuccess && ok; + { + visrtx::CudaMemoryAllocation captured(p, 32, capturedDelete); + } + ok = capturedDeletes == 1 && ok; + } + ok = allocations == frees && ok; + std::printf("allocation cache allocations=%d frees=%d syncs=%d %s\n", + int(allocations), + int(frees), + int(syncs), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp index ef12530f5..9da956710 100644 --- a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp +++ b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp @@ -50,7 +50,10 @@ const void *replacementSource = nullptr; void *deviceA = nullptr; bool watchReplacement = false; bool oldDeviceFreed = false; -bool allocatedBeforeRetirement = false; +bool replacementAllocated = false; +bool cohortCompleted = false; +bool replacementReused = false; +bool failCohort = false; cudaStream_t preparationStream = nullptr; int copies = 0; int firstSyncCopies = -1; @@ -109,8 +112,8 @@ extern "C" cudaError_t cudaStreamCreateWithFlags( extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) { - if (watchReplacement && bytes == sizeof(vec3) && !oldDeviceFreed) - allocatedBeforeRetirement = true; + if (watchReplacement && bytes == sizeof(vec3)) + replacementAllocated = true; return next("cudaMalloc")(ptr, bytes); } @@ -122,6 +125,19 @@ extern "C" cudaError_t cudaFree(void *ptr) return error; } +extern "C" cudaError_t cudaDeviceSynchronize() +{ + const auto error = + next("cudaDeviceSynchronize")(); + if (failCohort) { + failCohort = false; + return cudaErrorUnknown; + } + if (watchReplacement && error == cudaSuccess) + cohortCompleted = true; + return error; +} + extern "C" cudaError_t cudaMemcpy( void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) { @@ -141,6 +157,9 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, const bool tracked = kind == cudaMemcpyHostToDevice && trackedSource(src); if (kind == cudaMemcpyHostToDevice && src == trackedA) deviceA = dst; + if (watchReplacement && src == replacementSource + && kind == cudaMemcpyHostToDevice) + replacementReused = dst == deviceA && cohortCompleted; if (tracked) { ++copies; wrongStream |= stream != preparationStream; @@ -254,8 +273,8 @@ int main() commitGeometryWideAttributes(2.f); ok = bounds(-1.25f, 3.25f) && copies == 2 && firstSyncCopies == 2 && !wrongStream && ok; - // Replacement must retire obsolete cached copies before allocating the - // whole new cohort, rather than keeping both cohorts resident at once. + // Replacement must retire the obsolete snapshot cohort, then reuse its + // certified backend storage rather than allocating a second resident cohort. void *replacement = nullptr; if (cudaMallocHost(&replacement, sizeof(vec3)) != cudaSuccess) return 1; @@ -274,11 +293,22 @@ int main() }; watchReplacement = true; replaceShared(c); - ok = bounds(-1.25f, 3.25f) && oldDeviceFreed && !allocatedBeforeRetirement - && ok; + ok = bounds(-1.25f, 3.25f) && replacementReused && !oldDeviceFreed + && !replacementAllocated && ok; watchReplacement = false; replaceShared(a); ok = bounds(-1.25f, 3.25f) && ok; + // A failed shared retirement boundary cannot publish or reuse the cohort. + // Recommit the failed inputs to retry once the completion error is gone. + const int beforeFailureCopies = copies; + failCohort = true; + replaceShared(c); + ok = !bounds(-1.25f, 3.25f) && !failCohort && errors == 1 + && copies == beforeFailureCopies && ok; + commitGeometryWideAttributes(4.f); + ok = bounds(-1.25f, 3.25f) && errors == 1 && ok; + replaceShared(a); + ok = bounds(-1.25f, 3.25f) && ok; anariRelease(device, c); cudaFreeHost(replacement); replacementSource = nullptr; @@ -298,7 +328,7 @@ int main() cudaFreeHost(sourceA); cudaFreeHost(sourceB); anari::release(device, device); - ok = errors == 0 && ok; + ok = errors == 1 && ok; std::printf("geometry input batches: %s\n", ok ? "PASS" : "FAIL"); return ok ? 0 : 1; } diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 70e74f7b7..e11207d0e 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -455,6 +455,9 @@ VisRTXDevice::~VisRTXDevice() optixModuleDestroy(state.intersectionModules.customIntersectors); + // Disable cached returns and free idle/pending blocks before destroying + // streams. Any allocation outliving the device falls back to ordinary free. + state.geometryInputAllocations->close(); state.preparation.reset(); optixDeviceContextDestroy(state.optixContext); diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index bbdaf762c..9002a3754 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -264,10 +264,17 @@ cudaError_t Array::enqueueUpload(cudaStream_t stream) const return cudaSuccess; // Application-owned device inputs are already resident. if (!device->isValid()) { - CudaMemoryAllocation allocation(host->bytes()); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - return error; + auto cache = static_cast(deviceState()) + ->geometryInputAllocations; + void *memory = nullptr; + const auto allocationError = cache->allocate(host->bytes(), &memory); + auto allocation = CudaMemoryAllocation::fromCache( + memory, host->bytes(), std::move(cache)); + const auto lastError = cudaGetLastError(); + if (allocationError != cudaSuccess) + return allocationError; + if (lastError != cudaSuccess) + return lastError; if (!allocation) return cudaErrorMemoryAllocation; *device = std::move(allocation); diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 1100b699f..53c9f6bc6 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -231,7 +231,10 @@ bool DeviceGlobalState::collectGeometryInputUploads() if (m_geometryInputUploads.size() > 1) for (auto &geometry : m_geometryInputUploads) geometry->retirePreparationSnapshot(); - auto error = preparation.waitFor(stream); + auto error = geometryInputAllocations->reclaim( + [&] { return finishGeometryPreparation(); }); + if (error == cudaSuccess) + error = preparation.waitFor(stream); if (error == cudaSuccess) { for (auto &geometry : m_geometryInputUploads) geometry->submitInputUploads(); diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 7f110c065..84b9dd643 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -33,6 +33,7 @@ #include "geometry/Preprocessing.h" #include "gpu/gpu_objects.h" +#include "utility/DeviceAllocationCache.h" #include "utility/DeviceObjectArray.h" #include "utility/PreparationStream.h" #include "utility/StreamRetirement.h" @@ -182,6 +183,8 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUstream stream; PreparationStream preparation; StreamRetirement renderRetirement; + std::shared_ptr geometryInputAllocations{ + std::make_shared()}; GeometryReadbackPool geometryReadbacks; SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; diff --git a/devices/rtx/device/utility/DeviceAllocationCache.h b/devices/rtx/device/utility/DeviceAllocationCache.h new file mode 100644 index 000000000..a15d48342 --- /dev/null +++ b/devices/rtx/device/utility/DeviceAllocationCache.h @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace visrtx { + +// Device-local cache for backend-owned authored-array uploads only. Returning +// storage NEVER makes it reusable immediately. A frozen pending cohort becomes +// reusable only after deferred CPU submissions and all GPU consumers complete. +// Call allocate/reclaim in the owning device's CUDA context; scene updates and +// reclaim calls are serialized. No mutex is held across CUDA calls or +// callbacks. +struct DeviceAllocationCache +{ + static constexpr size_t MAX_BLOCKS = 256; + static constexpr size_t MAX_BYTES = 64 * 1024 * 1024; + explicit DeviceAllocationCache( + size_t byteLimit = MAX_BYTES, size_t blockLimit = MAX_BLOCKS); + ~DeviceAllocationCache(); + DeviceAllocationCache(const DeviceAllocationCache &) = delete; + DeviceAllocationCache &operator=(const DeviceAllocationCache &) = delete; + + cudaError_t allocate(size_t bytes, void **pointer); + void release(void *pointer, size_t bytes); + template + cudaError_t reclaim(CompleteDeferred completeDeferred); + void close(); + + private: + struct Block + { + void *pointer{nullptr}; + size_t bytes{0}; + }; + bool trimReady(); + void finishCohort( + const std::array &cohort, size_t count, bool reusable); + const size_t m_byteLimit; + const size_t m_blockLimit; + std::mutex m_mutex; + bool m_enabled{true}; + // Counts include a frozen cohort while reclaim() is outside the lock. + size_t m_cachedBytes{0}; + size_t m_cachedBlocks{0}; + size_t m_pendingCount{0}; + size_t m_readyCount{0}; + std::array m_pending; + std::array m_ready; +}; + +inline DeviceAllocationCache::DeviceAllocationCache( + size_t byteLimit, size_t blockLimit) + : m_byteLimit(byteLimit), m_blockLimit(std::min(blockLimit, MAX_BLOCKS)) +{} + +inline DeviceAllocationCache::~DeviceAllocationCache() +{ + close(); +} + +inline cudaError_t DeviceAllocationCache::allocate(size_t bytes, void **pointer) +{ + *pointer = nullptr; + if (!bytes) + return cudaSuccess; + { + std::lock_guard lock(m_mutex); + for (size_t i = 0; i < m_readyCount; ++i) { + if (m_ready[i].bytes == bytes) { + *pointer = m_ready[i].pointer; + m_ready[i] = m_ready[--m_readyCount]; + m_cachedBytes -= bytes; + --m_cachedBlocks; + return cudaSuccess; + } + } + } + auto error = cudaMalloc(pointer, bytes); + if (error == cudaErrorMemoryAllocation && trimReady()) { + // Release only certified idle blocks. Pending blocks are not safe to hand + // back without a completion boundary, and are never borrowed on failure. + cudaGetLastError(); + *pointer = nullptr; + error = cudaMalloc(pointer, bytes); + } + return error; +} + +inline void DeviceAllocationCache::release(void *pointer, size_t bytes) +{ + if (!pointer) + return; + { + std::lock_guard lock(m_mutex); + if (m_enabled && m_cachedBlocks < m_blockLimit + && bytes <= m_byteLimit - m_cachedBytes) { + m_pending[m_pendingCount++] = {pointer, bytes}; + m_cachedBytes += bytes; + ++m_cachedBlocks; + return; + } + } + // Overflow and late returns preserve ordinary cudaFree retirement semantics. + cudaFree(pointer); +} + +template +inline cudaError_t DeviceAllocationCache::reclaim( + CompleteDeferred completeDeferred) +{ + std::array cohort; + size_t count = 0; + { + std::lock_guard lock(m_mutex); + count = m_pendingCount; + if (!count) + return cudaSuccess; + std::copy_n(m_pending.begin(), count, cohort.begin()); + m_pendingCount = 0; + } + bool reusable = false; + // Restores the frozen cohort to pending on host exceptions too. This guard + // borrows the cache; its deleter returns blocks rather than deleting this. + auto restore = [&](DeviceAllocationCache *) { + finishCohort(cohort, count, reusable); + }; + std::unique_ptr guard( + this, restore); + auto error = completeDeferred(); + // Legacy consumers and application-visible array pointers need the same + // conservative device-wide retirement cudaFree previously provided per block. + // One boundary covers the cohort; later returns remain pending for next time. + if (error == cudaSuccess) + error = cudaDeviceSynchronize(); + reusable = error == cudaSuccess; + return error; +} + +inline void DeviceAllocationCache::finishCohort( + const std::array &cohort, size_t count, bool reusable) +{ + bool freeCohort = false; + { + std::lock_guard lock(m_mutex); + freeCohort = !m_enabled; + for (size_t i = 0; i < count; ++i) { + const auto block = cohort[i]; + if (freeCohort) { + m_cachedBytes -= block.bytes; + --m_cachedBlocks; + } else if (reusable) + m_ready[m_readyCount++] = block; + else + m_pending[m_pendingCount++] = block; + } + } + if (freeCohort) + for (size_t i = 0; i < count; ++i) + cudaFree(cohort[i].pointer); +} + +inline bool DeviceAllocationCache::trimReady() +{ + std::array blocks; + size_t count = 0; + { + std::lock_guard lock(m_mutex); + count = m_readyCount; + std::copy_n(m_ready.begin(), count, blocks.begin()); + m_readyCount = 0; + m_cachedBlocks -= count; + for (size_t i = 0; i < count; ++i) + m_cachedBytes -= blocks[i].bytes; + } + for (size_t i = 0; i < count; ++i) + cudaFree(blocks[i].pointer); + return count != 0; +} + +inline void DeviceAllocationCache::close() +{ + std::array blocks; + size_t count = 0; + { + std::lock_guard lock(m_mutex); + m_enabled = false; + for (size_t i = 0; i < m_pendingCount; ++i) + blocks[count++] = m_pending[i]; + for (size_t i = 0; i < m_readyCount; ++i) + blocks[count++] = m_ready[i]; + m_pendingCount = m_readyCount = 0; + m_cachedBlocks -= count; + for (size_t i = 0; i < count; ++i) + m_cachedBytes -= blocks[i].bytes; + } + for (size_t i = 0; i < count; ++i) + cudaFree(blocks[i].pointer); +} + +} // namespace visrtx diff --git a/devices/rtx/device/utility/MemoryAllocation.cpp b/devices/rtx/device/utility/MemoryAllocation.cpp index eb18ca941..10474cc3d 100644 --- a/devices/rtx/device/utility/MemoryAllocation.cpp +++ b/devices/rtx/device/utility/MemoryAllocation.cpp @@ -30,6 +30,8 @@ */ #include "MemoryAllocation.h" +#include +#include "DeviceAllocationCache.h" // cuda #include // std @@ -100,7 +102,8 @@ HostMemoryAllocation &HostMemoryAllocation::operator=( return *this; } -HostMemoryAllocation::HostMemoryAllocation(const CudaMemoryAllocation &o) { +HostMemoryAllocation::HostMemoryAllocation(const CudaMemoryAllocation &o) +{ (*this) = o; } @@ -181,6 +184,15 @@ CudaMemoryAllocation::~CudaMemoryAllocation() freeMemory(); } +CudaMemoryAllocation CudaMemoryAllocation::fromCache( + void *memory, size_t bytes, std::shared_ptr cache) +{ + CudaMemoryAllocation allocation(memory, bytes); + allocation.m_owner = true; + allocation.m_cache = std::move(cache); + return allocation; +} + void *CudaMemoryAllocation::ptr() const { return m_ptr; @@ -219,7 +231,8 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=( return *this; } -CudaMemoryAllocation::CudaMemoryAllocation(const HostMemoryAllocation &o) { +CudaMemoryAllocation::CudaMemoryAllocation(const HostMemoryAllocation &o) +{ (*this) = o; } @@ -252,6 +265,7 @@ CudaMemoryAllocation::CudaMemoryAllocation(CudaMemoryAllocation &&o) m_deleter = o.m_deleter; m_deleterPtr = o.m_deleterPtr; m_owner = o.m_owner; + m_cache = std::move(o.m_cache); o.clearPointers(); } @@ -263,6 +277,7 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=(CudaMemoryAllocation &&o) m_deleter = o.m_deleter; m_deleterPtr = o.m_deleterPtr; m_owner = o.m_owner; + m_cache = std::move(o.m_cache); o.clearPointers(); return *this; } @@ -270,7 +285,9 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=(CudaMemoryAllocation &&o) void CudaMemoryAllocation::freeMemory() { if (isValid()) { - if (isOwner()) + if (isOwner() && m_cache) + m_cache->release(m_ptr, m_bytes); + else if (isOwner()) cudaFree(m_ptr); else if (m_deleter) m_deleter(m_deleterPtr, m_ptr); @@ -283,6 +300,7 @@ void CudaMemoryAllocation::clearPointers() m_ptr = nullptr; m_deleter = nullptr; m_deleterPtr = nullptr; + m_cache.reset(); } } // namespace visrtx \ No newline at end of file diff --git a/devices/rtx/device/utility/MemoryAllocation.h b/devices/rtx/device/utility/MemoryAllocation.h index 522349113..7add396c0 100644 --- a/devices/rtx/device/utility/MemoryAllocation.h +++ b/devices/rtx/device/utility/MemoryAllocation.h @@ -35,11 +35,13 @@ #include // CUDA #include +#include namespace visrtx { struct HostMemoryAllocation; struct CudaMemoryAllocation; +struct DeviceAllocationCache; struct HostMemoryAllocation { @@ -90,6 +92,8 @@ struct CudaMemoryAllocation CudaMemoryAllocation(size_t bytes); CudaMemoryAllocation() = default; ~CudaMemoryAllocation(); + static CudaMemoryAllocation fromCache( + void *memory, size_t bytes, std::shared_ptr cache); void *ptr() const; size_t bytes() const; @@ -119,6 +123,7 @@ struct CudaMemoryAllocation anari::MemoryDeleter m_deleter{nullptr}; const void *m_deleterPtr{nullptr}; bool m_owner{false}; + std::shared_ptr m_cache; }; } // namespace visrtx diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index f92d08207..31b279fa7 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -147,8 +147,9 @@ is reused. - Parameter-reference replacement and last-public-release privatization require completed old render consumers. `StreamRetirement` caches a successful wait for the generation captured before synchronization. Frame submission, - denoiser setup/launch/conversion, channel resolution, and isosurface brick - preparation invalidate that certificate before submitting work. Shared arrays + denoiser setup/launch/conversion, channel resolution, transfer-function opacity + bounds, and isosurface brick preparation invalidate that certificate before + submitting work. Shared arrays and different frames use the same device-local generation. A generation invalidated during a wait cannot inherit that wait's certificate; errors never certify completion. Scene submission remains serialized. Error handling uses @@ -202,6 +203,39 @@ Status callbacks cannot reenter device property queries or rendering while collection is resolving results; those calls are refused instead of publishing a partially collected scene. +### Backend input allocation cache + +Only backend-owned device copies created by `Array::enqueueUpload()` participate +in `DeviceAllocationCache`. Imported CUDA pointers, captured-device deleters, +privatization copies, generic device buffers and legacy uploads retain their +existing allocation behavior. Reuse is exact-size, so logical array capacity +never grows to match an oversized cached block. + +Returned blocks enter a pending cohort, not the reusable list. After retiring +obsolete snapshots, committed input collection freezes that cohort, flushes +pending geometry preparation, then performs one checked `cudaDeviceSynchronize` +before promoting the blocks. This deliberately preserves the conservative +coverage of legacy consumers that ordinary `cudaFree` provided per allocation; +it is not a claim of stream-isolated replacement. Returns during the boundary +belong to the next cohort. Failure or a host exception keeps the cohort pending, +and affected input generations cannot publish until a later successful retry. +No cache mutex is held during CUDA operations or callbacks. + +The device-local cache retains at most 64 MiB and 256 returned blocks, counting +pending, reusable and frozen cohorts together. Overflow uses ordinary freeing. +On allocation OOM, certified reusable blocks of other sizes are released and +the allocation is retried once if any were freed. Pending blocks are not reused +as an OOM shortcut. Teardown closes and drains the cache before destroying its +streams; outstanding owned allocations retain the closed cache and late returns +use ordinary freeing rather than resurrecting it. + +`TestDeviceAllocationCache` checks exact-size reuse, deferred submission, +completion failure, cohort freezing, byte/entry bounds, concurrent returns, +host exceptions, OOM trimming/retry, move ownership, captured deleters and late +returns after close. `TestGeometryInputBatch` checks actual replacement reuse +without a second allocation cohort and rejects/retries a failed shared completion +boundary. + ### Small-geometry computation batches For 1–256 primitives, bounds and area requests are held as device-owned batches From ddf212a327eab2008037996a016e54cb759bbfba Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:38:50 +0000 Subject: [PATCH 15/20] fix(rtx): retain preparation owners across collection exceptions --- devices/rtx/apps/tests/api/CMakeLists.txt | 3 + .../apps/tests/api/TestPreparationQueue.cpp | 171 ++++++++++++++++++ devices/rtx/device/geometry/Geometry.cpp | 6 +- devices/rtx/device/geometry/Geometry.h | 1 + devices/rtx/device/optix_visrtx.cpp | 41 ++--- devices/rtx/device/optix_visrtx.h | 4 +- devices/rtx/device/utility/PreparationQueue.h | 120 ++++++++++++ .../rtx/docs/geometry-preparation-reuse.md | 11 +- 8 files changed, 326 insertions(+), 31 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestPreparationQueue.cpp create mode 100644 devices/rtx/device/utility/PreparationQueue.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 14f963464..ca83950dd 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -46,6 +46,9 @@ make_test(TestQuadLightShaping) make_test(TestQuadLightFocus) make_test(TestQuadLightTexture) make_test(TestDenoiserReuse) +add_executable(TestPreparationQueue TestPreparationQueue.cpp) +target_link_libraries(TestPreparationQueue PRIVATE nonstd::scope-lite) +add_test(NAME TestPreparationQueue COMMAND TestPreparationQueue) if (WIN32) return() diff --git a/devices/rtx/apps/tests/api/TestPreparationQueue.cpp b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp new file mode 100644 index 000000000..83c53bb03 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include "../../../device/utility/PreparationQueue.h" + +namespace { +struct Item +{ + explicit Item(int &destroyed); + ~Item(); + void completePreparation(); + void markPreparationCollected() noexcept; + int &destroyed; + bool queued{true}; + bool failPublication{false}; + int publications{0}; + std::function onDestroy; +}; +Item::Item(int &counter) : destroyed(counter) {} +Item::~Item() +{ + ++destroyed; + if (onDestroy) + onDestroy(); +} +void Item::completePreparation() +{ + if (failPublication) + throw std::bad_alloc(); + ++publications; +} +void Item::markPreparationCollected() noexcept +{ + queued = false; +} +using Queue = visrtx::PreparationQueue>; + +bool finishFailure(bool retry) +{ + int destroyed = 0; + { + Queue queue; + std::vector deferred; + for (int i = 0; i < 2; ++i) { + auto item = std::make_shared(destroyed); + deferred.push_back(item.get()); + queue.enqueue( + std::move(item)); // Queue is the only owner, like an orphan geometry. + } + bool threw = false; + try { + queue.collect([&](Item *) { + // SmallGeometryBatch's descriptor reserve can throw before consuming + // the raw deferred-job list. Test the same ownership boundary directly, + // without routing a host exception through ANARI's fatal C API handler. + throw std::bad_alloc(); + }); + } catch (const std::bad_alloc &) { + threw = true; + } + if (!threw || destroyed || queue.empty() || queue.collecting()) + return false; // Never dereference the raw jobs if ownership was lost. + for (auto *item : deferred) + if (!item->queued || item->publications) + return false; + if (retry) { + bool refusedReentry = false; + if (!queue.collect([&](Item *) { + refusedReentry = !queue.collect([](Item *) {}); + for (auto *item : deferred) + if (!item->queued) + throw std::bad_alloc(); + deferred.clear(); // Deferred submission and completion succeeded. + }) + || !refusedReentry || !queue.empty() || queue.collecting() + || destroyed != 2) + return false; + } + } + return destroyed == 2; // Also covers destruction after an unretried failure. +} + +bool retirementReentry() +{ + int destroyed = 0; + Queue queue; + bool safe = false; + auto item = std::make_shared(destroyed); + item->onDestroy = [&] { + int visible = 0; + queue.forEach([&](Item *) { ++visible; }); + safe = queue.empty() && queue.collecting() && visible == 0 + && !queue.collect([](Item *) {}); + }; + queue.enqueue(std::move(item)); + return queue.collect([](Item *) {}) && safe && destroyed == 1; +} + +bool publicationFailure() +{ + int destroyed = 0; + Queue queue; + auto first = std::make_shared(destroyed); + auto second = std::make_shared(destroyed); + second->failPublication = true; + queue.enqueue(first); + queue.enqueue(second); + int drains = 0; + bool threw = false; + try { + queue.collect([&](Item *) { ++drains; }); + } catch (const std::bad_alloc &) { + threw = true; + } + bool ok = threw && drains == 1 && !queue.empty() && !queue.collecting() + && first->queued && second->queued && first->publications == 1 + && second->publications == 0; + second->failPublication = false; + ok = queue.collect([&](Item *) { ++drains; }) && ok; + ok = drains == 2 && queue.empty() && !first->queued && !second->queued + && first->publications == 2 && second->publications == 1 && ok; + ok = queue.collect([&](Item *) { ++drains; }) && drains == 2 && ok; + first.reset(); + second.reset(); + return destroyed == 2 && ok; +} +} // namespace + +int main() +{ + bool ok = finishFailure(true); + ok = finishFailure(false) && ok; + ok = publicationFailure() && ok; + ok = retirementReentry() && ok; + std::printf( + "preparation queue exception ownership: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 02e0c68bf..482051954 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -213,7 +213,6 @@ void Geometry::deferPreparation() void Geometry::completePreparation() { - m_preparationQueued = false; if (!m_preprocessing.complete(this)) { m_hasPreparedData = false; return; @@ -221,6 +220,11 @@ void Geometry::completePreparation() upload(); } +void Geometry::markPreparationCollected() noexcept +{ + m_preparationQueued = false; +} + void Geometry::upload() { if (m_preprocessing.pending()) { diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index 2165216a9..0ed40d6e9 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -79,6 +79,7 @@ struct Geometry : public RegisteredObject void upload(); void deferPreparation(); void completePreparation(); + void markPreparationCollected() noexcept; void retirePreparationSnapshot(); void submitInputUploads(); void completeInputUploads(); diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 53c9f6bc6..ff1285544 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -259,17 +259,18 @@ bool DeviceGlobalState::collectGeometryInputUploads() void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) { - m_geometryPreparations.emplace_back(geometry); + m_geometryPreparations.enqueue(helium::IntrusivePtr(geometry)); } bool DeviceGlobalState::collectingGeometryPreparations() const { - return m_collectingGeometryPreparations || m_collectingGeometryInputUploads; + return m_geometryPreparations.collecting() + || m_collectingGeometryInputUploads; } bool DeviceGlobalState::hasPendingGeometryPreparations() const { - return m_collectingGeometryPreparations || !m_geometryPreparations.empty() + return m_geometryPreparations.collecting() || !m_geometryPreparations.empty() || m_collectingGeometryInputUploads; } @@ -281,8 +282,8 @@ cudaError_t DeviceGlobalState::finishGeometryPreparation() if (error != cudaSuccess) { // An intervening upload/legacy consumer may wait before the collection // point. Its stream-completion error affects all already queued results. - for (auto &geometry : m_geometryPreparations) - geometry->setPreparationFailed(true); + m_geometryPreparations.forEach( + [](Geometry *geometry) { geometry->setPreparationFailed(true); }); for (auto &geometry : m_geometryInputUploads) geometry->failInputUploads(); } @@ -293,29 +294,15 @@ bool DeviceGlobalState::collectGeometryPreparations() { if (!collectGeometryInputUploads()) return false; - if (m_collectingGeometryPreparations) - return false; - if (m_geometryPreparations.empty()) - return true; - m_collectingGeometryPreparations = true; - auto collecting = nonstd::make_scope_exit( - [&] { m_collectingGeometryPreparations = false; }); - auto pending = std::move(m_geometryPreparations); - const auto error = finishGeometryPreparation(); - if (error != cudaSuccess) { - // A stream error invalidates every generation in this batch. Mark them + return m_geometryPreparations.collect([&](Geometry *first) { + // Owners remain in the queue if descriptor allocation or later registry + // publication throws. CUDA failure still invalidates the pending batch // before reporting, so callbacks cannot see a partially valid generation. - for (auto &geometry : pending) - geometry->setPreparationFailed(true); - checkPreparation(pending.front().ptr, error, "batch completion"); - } - for (auto &geometry : pending) - geometry->completePreparation(); - pending.clear(); - m_geometryPreparations.swap(pending); // Reuse queue capacity next batch. - // Failure is local to the affected geometries; unrelated worlds remain - // usable. - return true; + const auto error = finishGeometryPreparation(); + if (error != cudaSuccess) + checkPreparation(first, error, "batch completion"); + // Numeric failures remain local to their geometries during publication. + }); } cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index 84b9dd643..fa1618962 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -35,6 +35,7 @@ #include "gpu/gpu_objects.h" #include "utility/DeviceAllocationCache.h" #include "utility/DeviceObjectArray.h" +#include "utility/PreparationQueue.h" #include "utility/PreparationStream.h" #include "utility/StreamRetirement.h" @@ -299,8 +300,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState std::vector> m_geometryInputUploads; std::unordered_map m_geometryInputVersions; bool m_collectingGeometryInputUploads{false}; - std::vector> m_geometryPreparations; - bool m_collectingGeometryPreparations{false}; + PreparationQueue> m_geometryPreparations; }; bool buildOptixBVH(std::vector buildInput, diff --git a/devices/rtx/device/utility/PreparationQueue.h b/devices/rtx/device/utility/PreparationQueue.h new file mode 100644 index 000000000..c2dc08123 --- /dev/null +++ b/devices/rtx/device/utility/PreparationQueue.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include + +namespace visrtx { + +// Serialized preparation ownership and publication. Pointer is an owning +// pointer; its object provides completePreparation() (retryable publication) +// and noexcept markPreparationCollected(). Submission cannot append while a +// collection is running. Reentrant collection is refused. +template +struct PreparationQueue +{ + void enqueue(Pointer object); + bool empty() const; + bool collecting() const; + template + void forEach(Function function); + template + bool collect(Finish finish); + + private: + std::vector m_pending; + bool m_collecting{false}; +}; + +template +inline void PreparationQueue::enqueue(Pointer object) +{ + assert(!m_collecting); + m_pending.push_back(std::move(object)); +} + +template +inline bool PreparationQueue::empty() const +{ + return m_pending.empty(); +} + +template +inline bool PreparationQueue::collecting() const +{ + return m_collecting; +} + +template +template +inline void PreparationQueue::forEach(Function function) +{ + for (auto &object : m_pending) + function(object.operator->()); +} + +template +template +inline bool PreparationQueue::collect(Finish finish) +{ + if (m_collecting) + return false; + if (m_pending.empty()) + return true; + m_collecting = true; + auto collecting = nonstd::make_scope_exit([&] { m_collecting = false; }); + // Keep owners here through both potentially throwing stages. If descriptor + // allocation or registry publication throws, raw jobs and queued flags still + // have owners, and another collection can retry without reallocating a queue. + finish(m_pending.front().operator->()); + for (auto &object : m_pending) + object->completePreparation(); + // Only retire queue membership after every publication succeeded. Earlier + // objects must remain queued if a later object's publication throws. + for (auto &object : m_pending) { + auto *pointer = object.operator->(); + static_assert(noexcept(pointer->markPreparationCollected())); + pointer->markPreparationCollected(); + } + // Remove membership before destructors/deleters can reenter the owner. + // Unlike the old pre-finish move, this happens only after GPU completion, + // successful publication and non-throwing flag retirement. + auto retired = std::move(m_pending); + retired.clear(); + m_pending.swap(retired); // Reuse capacity without allocating on retry. + return true; +} + +} // namespace visrtx diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 31b279fa7..534ed170c 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -186,7 +186,16 @@ Checked bounds and area-CDF preparation queue kernels and asynchronous readbacks into geometry-owned pinned storage. A successful submission is not publication: scalar outputs, numeric validation, and geometry registry updates happen only after collection. The device queue retains each submitted geometry, and thereby -its arrays and derived buffers, until those operations finish. +its arrays and derived buffers, until those operations finish. Ownership stays +in the queue through descriptor allocation and registry publication; queued flags +are cleared only after every publication completes. A host exception leaves the +owners and queued flags available for retry, including already-drained results +whose publication must be retried. Collection reentry remains refused. + +`TestPreparationQueue` tests this ownership transaction directly with throwing +completion/publication callbacks, orphaned owners, retry and teardown. It does +not route exceptions through ANARI's fatal C API handler or change that public +exception policy. Group/World rebuilds collect queued finalizations before constructing BVHs. Lazy Geometry Light area requests are submitted for all candidate surfaces first, From a7f64b4e84ddffb87bf80517c7bf268026710940 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:58:25 +0000 Subject: [PATCH 16/20] test(rtx): verify weighted geometry CDFs at batch boundaries --- devices/rtx/apps/tests/api/CMakeLists.txt | 14 + .../apps/tests/api/TestGeometryAreaCDF.cpp | 345 ++++++++++++++++++ .../rtx/docs/geometry-preparation-reuse.md | 11 + 3 files changed, 370 insertions(+) create mode 100644 devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index ca83950dd..48c01bd52 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -103,6 +103,20 @@ make_test(TestDeferredGeometryPreparation) target_link_libraries(TestDeferredGeometryPreparation PRIVATE CUDA::cudart) make_test(TestSmallGeometryBatch) target_link_libraries(TestSmallGeometryBatch PRIVATE CUDA::cudart) +make_test(TestGeometryAreaCDF) +target_sources(TestGeometryAreaCDF PRIVATE ../../../device/utility/MemoryAllocation.cpp) +# Inspect published device records without adding a public debug property. +# Match private host layouts, including optional MDL fields, to the device. +target_compile_definitions(TestGeometryAreaCDF PRIVATE + $) +target_include_directories(TestGeometryAreaCDF PRIVATE + $) +target_link_libraries(TestGeometryAreaCDF PRIVATE + CUDA::cudart visrtx::glm nonstd::scope-lite) +# Private layouts also require the matching built library, not a stale install +# selected by the developer shell's LD_LIBRARY_PATH. +set_tests_properties(TestGeometryAreaCDF PROPERTIES ENVIRONMENT + "LD_LIBRARY_PATH=$:$ENV{LD_LIBRARY_PATH}") make_test(TestGeometryPreparationReuse) target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) make_test(TestSharedGeometryLifecycle) diff --git a/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp b/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp new file mode 100644 index 000000000..35ae9021f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" +#include "geometry/Geometry.h" + +namespace { +using vec3 = std::array; +using uvec2 = std::array; +using uvec3 = std::array; +int errors = 0; +std::atomic completions{0}; +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +struct Case +{ + std::string type; + size_t count; + bool indexed; + bool device; + anari::Geometry geometry; + std::vector areas; +}; + +float weight(size_t i, int generation) +{ + if (generation == 1) + return 0.f; + // Put zeros on both sides of warp and small/general boundaries, then move + // them on the recovery generation. Sharp positive weights also cross warps. + const bool zero = generation == 0 ? (i == 0 || i == 30 || i == 31 || i == 32 + || i == 254 || i == 255 || i == 256) + : (i % 13 == 0); + if (zero) + return 0.f; + const float value = float((17 * i + 3 + generation) % 23 + 1) / 8.f; + return (i == 29 || i == 33 || i == 253 || i == 255) ? 16.f * value : value; +} + +void author(anari::Device d, Case &c, int generation) +{ + std::vector vertices; + std::vector radii; + std::vector caps; + std::vector sphereIndices; + std::vector segmentIndices; + std::vector triangleIndices; + const auto n = c.count; + for (size_t i = 0; i < n; ++i) { + const float x = 100.f * i; + const float w = weight(i, generation); + const float length = float(i % 5 + 1) / 2.f; + if (c.type == "triangle") { + // Independent closed form: base 2*w, height 1, hence area w. + vertices.push_back({x, 0, 0}); + vertices.push_back({x + 2.f * w, 0, 0}); + vertices.push_back({x, 1, 0}); + } else if (c.type == "sphere") { + vertices.push_back({x, 0, 0}); + radii.push_back(w); + } else { + vertices.push_back({x, 0, 0}); + vertices.push_back({x, length, 0}); + caps.push_back(i % 3 == 0); + caps.push_back(i % 5 == 0); + if (c.type == "cone") { + radii.push_back(w / 2.f); + radii.push_back(w); + } else + radii.push_back(w); // Cylinder radius is per primitive, not per vertex. + } + const uint32_t source = uint32_t(c.indexed ? n - 1 - i : i); + sphereIndices.push_back(source); + segmentIndices.push_back({2 * source, 2 * source + 1}); + triangleIndices.push_back({3 * source, 3 * source + 1, 3 * source + 2}); + } + // Use independent analytic areas in double precision, not the production + // primitiveArea helper, scan implementation or published total as an oracle. + const double pi = std::acos(-1.0); + c.areas.clear(); + for (size_t i = 0; i < n; ++i) { + const size_t source = c.indexed ? n - 1 - i : i; + const double w = weight(source, generation); + const double length = double(source % 5 + 1) / 2.0; + double area = 0; + if (c.type == "triangle") + area = w; + else if (c.type == "sphere") + area = 4.0 * pi * w * w; + else { + const double r0 = c.type == "cone" ? w / 2.0 : weight(i, generation); + const double r1 = c.type == "cone" ? w : r0; + area = c.type == "cone" + ? pi * (r0 + r1) * std::sqrt(length * length + (r0 - r1) * (r0 - r1)) + : 2.0 * pi * r0 * length; + if (source % 3 == 0) + area += pi * r0 * r0; + if (source % 5 == 0) + area += pi * r1 * r1; + } + c.areas.push_back(area); + } + setTestArray(d, c.geometry, "vertex.position", vertices, c.device, 1); + if (c.type != "triangle") + setTestArray(d, + c.geometry, + c.type == "cylinder" ? "primitive.radius" : "vertex.radius", + radii, + c.device, + 1); + if (!caps.empty()) + setTestArray(d, c.geometry, "vertex.cap", caps, c.device, 1); + if (c.indexed) { + if (c.type == "triangle") + setTestArray( + d, c.geometry, "primitive.index", triangleIndices, c.device, 1); + else if (c.type == "sphere") + setTestArray( + d, c.geometry, "primitive.index", sphereIndices, c.device, 1); + else + setTestArray( + d, c.geometry, "primitive.index", segmentIndices, c.device, 1); + } + anari::commitParameters(d, c.geometry); +} + +bool checkPublished(const Case &c, int generation) +{ + // Native VisRTX handles are Geometry pointers. Inspect the actual published + // GPU record only after a completed frame. This internal test is compiled + // with the device's layout definitions (not a new public ANARI property). + auto *geometry = reinterpret_cast(c.geometry); + auto *state = static_cast( + geometry->helium::BaseObject::deviceState()); + const auto *registry = state->registry.geometries.devicePtr(); + visrtx::GeometryGPUData data{}; + if (!registry + || cudaMemcpy(&data, + registry + geometry->index(), + sizeof(data), + cudaMemcpyDeviceToHost) + != cudaSuccess) + return false; + const float *cdf = nullptr; + uint32_t count = 0; + float total = -1; + auto sampling = [&](const auto &record) { + cdf = record.primAreaCdf; + count = record.numPrimitives; + total = record.totalArea; + }; + if (c.type == "triangle" && data.type == visrtx::GeometryType::TRIANGLE) + sampling(data.tri); + else if (c.type == "sphere" && data.type == visrtx::GeometryType::SPHERE) + sampling(data.sphere); + else if (c.type == "cone" && data.type == visrtx::GeometryType::CONE) + sampling(data.cone); + else if (c.type == "cylinder" && data.type == visrtx::GeometryType::CYLINDER) + sampling(data.cylinder); + else + return false; + const double expectedTotal = + std::accumulate(c.areas.begin(), c.areas.end(), 0.0); + bool ok = std::isfinite(total); + if (expectedTotal == 0) + ok = total == 0.f && count == 0 && !cdf && ok; + else { + ok = cdf && count == c.count + && std::abs(double(total) - expectedTotal) <= 2e-6 * expectedTotal + && ok; + if (!cdf || count != c.count) + return false; + std::vector values(count); + if (cudaMemcpy( + values.data(), cdf, count * sizeof(float), cudaMemcpyDeviceToHost) + != cudaSuccess) + return false; + double prefix = 0; + float previous = 0; + for (size_t i = 0; i < count; ++i) { + prefix += c.areas[i]; + const double expected = prefix / expectedTotal; + const bool entryOk = std::isfinite(values[i]) && values[i] >= previous + && values[i] >= 0.f && values[i] <= 1.f + && std::abs(double(values[i]) - expected) <= 2e-6 + && (c.areas[i] != 0 || std::abs(values[i] - previous) <= 2e-6f); + if (!entryOk) { + std::fprintf(stderr, + "%s n=%zu indexed=%d device=%d gen=%d bin=%zu actual=%.9g expected=%.9g\n", + c.type.c_str(), + c.count, + c.indexed, + c.device, + generation, + i, + values[i], + expected); + ok = false; + break; + } + previous = values[i]; + } + ok = values.back() == 1.f && ok; + } + if (!ok) + std::fprintf(stderr, + "%s n=%zu indexed=%d device=%d gen=%d total=%.9g expected=%.9g\n", + c.type.c_str(), + c.count, + c.indexed, + c.device, + generation, + total, + expectedTotal); + return ok; +} +} // namespace + +int main() +{ + auto d = makeVisRTXDevice(status); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + std::vector cases; + std::vector surfaces; + constexpr size_t boundary = visrtx::SmallGeometryBatch::MAX_PRIMITIVES; + for (const char *type : {"triangle", "sphere", "cone", "cylinder"}) + for (size_t n : {size_t(31), + size_t(32), + size_t(33), + boundary - 1, + boundary, + boundary + 1}) + for (bool indexed : {false, true}) + for (bool device : {false, true}) { + auto g = anari::newObject(d, type); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + surfaces.push_back(surface); + cases.push_back({type, n, indexed, device, g, {}}); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(d, world); + for (auto surface : surfaces) + anari::release(d, surface); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -100}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{2, 2}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setAndReleaseParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + bool ok = true; + for (int generation = 0; generation < 3; ++generation) { + for (auto &c : cases) + author(d, c, generation); + anari::render(d, frame); + anari::wait(d, frame); + if (errors || completions != generation + 1) { + ok = false; + break; + } + for (const auto &c : cases) + ok = checkPublished(c, generation) && ok; + } + anari::release(d, frame); + for (const auto &c : cases) + anari::release(d, c.geometry); + anari::release(d, d); + ok = errors == 0 && ok; + std::printf("weighted geometry CDF: %zu cases x 3 generations %s\n", + cases.size(), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 534ed170c..7f4766eee 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -281,6 +281,17 @@ allocation, including batch-wide invalidation and retry. With shared CUDA runtim interposition, the mixed-size test also checks one summary copy per collection (two initial collections for bounds and lazy areas, then one for combined jobs). +`TestGeometryAreaCDF` checks the actual published GPU records after completed +frames, using the device's build definitions and matching runtime library. An +independent double-precision analytic oracle checks every prefix and total area +for triangles, spheres, cones and cylinders. Counts straddle warp boundaries +(31/32/33) and the small/general cutoff (255/256/257 at the current cutoff), with +indexed/unindexed geometry and host/device-backed logical slices. Unequal weights, +sharp weight changes, zero-area bins, varying segment caps, an all-zero generation +and restoration with new weights discriminate weighting, order, normalization +and stale sampling data rather than just bounds or light counts. No public debug +property or shared production area helper is used by the oracle. + Pinned readback storage is leased from the device's `GeometryReadbackPool`. Each page holds 256 geometry leases, each containing two result slots (a 4 KiB page with the current result layout). A geometry keeps its lease across updates; From 867e28cf89f04aa932db78eaaf13f074894ef85d Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Sat, 7 Nov 2026 00:26:50 +0000 Subject: [PATCH 17/20] perf(rtx): pool pinned BVH readbacks Avoid pageable readback staging while retaining completion waits and failure drains. Reuse completed render retirement at input-batch and BVH dependency points; retain geometry-level dependency handling. Cover pinned allocation recovery and retirement certificate validity. --- devices/rtx/apps/tests/api/CMakeLists.txt | 2 +- .../tests/api/TestCudaPreparationFailure.cpp | 11 + .../apps/tests/api/TestStreamRetirement.cpp | 16 +- devices/rtx/device/geometry/ReadbackPool.h | 164 +------------- devices/rtx/device/optix_visrtx.cpp | 22 +- devices/rtx/device/optix_visrtx.h | 7 + .../rtx/device/utility/PinnedReadbackPool.h | 212 ++++++++++++++++++ devices/rtx/device/utility/StreamRetirement.h | 7 + 8 files changed, 269 insertions(+), 172 deletions(-) create mode 100644 devices/rtx/device/utility/PinnedReadbackPool.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 48c01bd52..a7ee5d239 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -172,7 +172,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S add_test(NAME TestSceneUploadRecovery_${failure} COMMAND TestCudaPreparationFailure ${failure}) endforeach() - foreach(failure bvh-copy bvh-sync tlas-sync) + foreach(failure bvh-copy bvh-sync tlas-sync bvh-pinned-allocation) add_test(NAME TestBvhPreparationRecovery_${failure} COMMAND TestCudaPreparationFailure ${failure}) endforeach() diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 71c81f943..37e228e88 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -69,6 +69,7 @@ enum class Failure PREPARATION_DEPENDENCY, BVH_SYNC, BVH_COPY, + BVH_PINNED_ALLOCATION, UPLOAD_COPY, UPLOAD_SYNC, BATCH_COPY, @@ -168,6 +169,14 @@ void complete(const void *, ANARIDevice, ANARIFrame) extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) { + // BVH results contain six bounds floats and a 64-bit compaction size. + constexpr size_t bvhPageBytes = 2 + * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE + * (6 * sizeof(float) + sizeof(uint64_t)); + if (bytes == bvhPageBytes && inject(Failure::BVH_PINNED_ALLOCATION)) { + *ptr = nullptr; + return next("cudaMallocHost")(ptr, size_t(-1)); + } constexpr size_t readbackPageBytes = 2 * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE * sizeof(visrtx::PreparationResult); @@ -561,6 +570,8 @@ int main(int argc, char **argv) } else if (bvhFailure || instanceFailure) { auto injected = std::strcmp(argv[1], "bvh-copy") == 0 ? Failure::BVH_COPY : Failure::BVH_SYNC; + if (std::strcmp(argv[1], "bvh-pinned-allocation") == 0) + injected = Failure::BVH_PINNED_ALLOCATION; if (instanceFailure) { trackBatch = true; batchCopiesToSkip = worldRecords ? 1 : 0; diff --git a/devices/rtx/apps/tests/api/TestStreamRetirement.cpp b/devices/rtx/apps/tests/api/TestStreamRetirement.cpp index 0e30de92a..5e82613ed 100644 --- a/devices/rtx/apps/tests/api/TestStreamRetirement.cpp +++ b/devices/rtx/apps/tests/api/TestStreamRetirement.cpp @@ -79,7 +79,9 @@ int main() return 1; visrtx::StreamRetirement retirement; retirement.initialize(tracked); - bool ok = retirement.retire() == cudaSuccess && waits == 1; + bool ok = !retirement.isRetired(); + ok = retirement.retire() == cudaSuccess && waits == 1 + && retirement.isRetired() && ok; for (int i = 0; i < 64; ++i) ok = retirement.retire() == cudaSuccess && waits == 1 && ok; @@ -88,6 +90,7 @@ int main() != cudaSuccess) return 1; retirement.invalidate(); + ok = !retirement.isRetired() && ok; ok = cudaLaunchHostFunc(tracked, block, nullptr) == cudaSuccess && ok; ok = cudaMemsetAsync(device, 0x2a, sizeof(int), tracked) == cudaSuccess && ok; int gpu = 0; @@ -113,18 +116,21 @@ int main() released = true; } waiter.join(); - ok = completion == cudaSuccess && ok; + ok = completion == cudaSuccess && !retirement.isRetired() && ok; int result = 0; ok = cudaMemcpy(&result, device, sizeof(int), cudaMemcpyDeviceToHost) == cudaSuccess && result == 0x2a2a2a2a && ok; - ok = retirement.retire() == cudaSuccess && waits == 3 && ok; + ok = retirement.retire() == cudaSuccess && waits == 3 + && retirement.isRetired() && ok; ok = retirement.retire() == cudaSuccess && waits == 3 && ok; retirement.invalidate(); failNext = true; - ok = retirement.retire() == cudaErrorUnknown && waits == 4 && ok; - ok = retirement.retire() == cudaSuccess && waits == 5 && ok; + ok = retirement.retire() == cudaErrorUnknown && waits == 4 + && !retirement.isRetired() && ok; + ok = retirement.retire() == cudaSuccess && waits == 5 + && retirement.isRetired() && ok; ok = retirement.retire() == cudaSuccess && waits == 5 && ok; cudaFree(device); cudaStreamDestroy(tracked); diff --git a/devices/rtx/device/geometry/ReadbackPool.h b/devices/rtx/device/geometry/ReadbackPool.h index 90f5108df..e36083ccf 100644 --- a/devices/rtx/device/geometry/ReadbackPool.h +++ b/devices/rtx/device/geometry/ReadbackPool.h @@ -31,15 +31,7 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "../utility/PinnedReadbackPool.h" namespace visrtx { @@ -49,158 +41,6 @@ struct PreparationResult uint32_t invalid; }; -// A device-local high-water cache of pinned pages. Each lease owns two result -// slots and retains its page independently of the pool's lifetime. Returning a -// lease is legal only after its GPU writers have completed; geometry collection -// provides that ordering. Acquisition/release may run on different host -// threads. -struct GeometryReadbackPool -{ - private: - struct Page; - - public: - static constexpr size_t SLOTS_PER_PAGE = 256; - - struct Lease - { - Lease() = default; - ~Lease(); - Lease(const Lease &) = delete; - Lease &operator=(const Lease &) = delete; - Lease(Lease &&other) noexcept; - Lease &operator=(Lease &&other) noexcept; - - PreparationResult *data() const; - void reset(); - - private: - friend struct GeometryReadbackPool; - std::shared_ptr m_page; - size_t m_index{0}; - }; - - GeometryReadbackPool() = default; - GeometryReadbackPool(const GeometryReadbackPool &) = delete; - GeometryReadbackPool &operator=(const GeometryReadbackPool &) = delete; - - cudaError_t acquire(Lease &lease); - - private: - std::mutex m_mutex; - std::vector> m_pages; -}; - -struct GeometryReadbackPool::Page -{ - Page(); - ~Page(); - bool take(size_t &index); - void release(size_t index); - - PreparationResult *memory{nullptr}; - std::mutex mutex; - std::array freeSlots; - size_t freeCount{SLOTS_PER_PAGE}; -}; - -// Inlined definitions //////////////////////////////////////////////////////// - -inline GeometryReadbackPool::Page::Page() -{ - for (size_t i = 0; i < SLOTS_PER_PAGE; ++i) - freeSlots[i] = SLOTS_PER_PAGE - i - 1; -} - -inline GeometryReadbackPool::Page::~Page() -{ - if (memory) - cudaFreeHost(memory); -} - -inline bool GeometryReadbackPool::Page::take(size_t &index) -{ - std::lock_guard lock(mutex); - if (freeCount == 0) - return false; - index = freeSlots[--freeCount]; - return true; -} - -inline void GeometryReadbackPool::Page::release(size_t index) -{ - std::lock_guard lock(mutex); - assert(index < SLOTS_PER_PAGE && freeCount < SLOTS_PER_PAGE); - freeSlots[freeCount++] = index; -} - -inline GeometryReadbackPool::Lease::~Lease() -{ - reset(); -} - -inline GeometryReadbackPool::Lease::Lease(Lease &&other) noexcept - : m_page(std::move(other.m_page)), m_index(other.m_index) -{} - -inline GeometryReadbackPool::Lease &GeometryReadbackPool::Lease::operator=( - Lease &&other) noexcept -{ - if (this != &other) { - reset(); - m_page = std::move(other.m_page); - m_index = other.m_index; - } - return *this; -} - -inline PreparationResult *GeometryReadbackPool::Lease::data() const -{ - return m_page ? m_page->memory + 2 * m_index : nullptr; -} - -inline void GeometryReadbackPool::Lease::reset() -{ - if (m_page) { - m_page->release(m_index); - m_page.reset(); - } -} - -inline cudaError_t GeometryReadbackPool::acquire(Lease &lease) -{ - if (lease.data()) - return cudaSuccess; - { - std::lock_guard lock(m_mutex); - for (auto &page : m_pages) { - if (page->take(lease.m_index)) { - lease.m_page = page; - return cudaSuccess; - } - } - } - - // CUDA allocation can wait for other work. Do not hold a pool/page mutex - // across it; simultaneous growth may allocate an extra page, but is safe. - auto page = std::make_shared(); - void *memory = nullptr; - const auto error = - cudaMallocHost(&memory, 2 * SLOTS_PER_PAGE * sizeof(PreparationResult)); - if (error != cudaSuccess) { - cudaGetLastError(); // A failed page allocation must not poison a retry. - return error; - } - page->memory = static_cast(memory); - { - std::lock_guard lock(m_mutex); - m_pages.push_back(page); - const bool acquired = page->take(lease.m_index); - assert(acquired); - (void)acquired; - lease.m_page = std::move(page); - } - return cudaSuccess; -} +using GeometryReadbackPool = PinnedReadbackPool; } // namespace visrtx diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index ff1285544..3ad7ab05b 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -94,7 +94,7 @@ bool buildOptixBVH(std::vector buildInput, // Legacy producers include field/isosurface work on the render stream and // authored arrays/instance uploads on the default stream. Previous rendering // must also finish before the existing BVH storage can be reused. - if (!check(preparation.waitFor(state.stream), "previous BVH consumers") + if (!check(state.waitForRenderConsumers(), "previous BVH consumers") || !check(preparation.waitFor(nullptr), "input upload dependency")) return false; @@ -110,6 +110,12 @@ bool buildOptixBVH(std::vector buildInput, "memory requirements")) return false; + // Acquire before submitting GPU work: allocation may throw, and a lease + // must never be returned while a readback still targets it. + PinnedReadbackPool::Lease readback; + if (!check(state.bvhReadbacks.acquire(readback), "allocating BVH readback")) + return false; + DeviceBuffer compactedSizeBuffer, aabbBuffer, tempBuffer, outputBuffer; if (!reserve(compactedSizeBuffer, sizeof(uint64_t)) || !reserve(aabbBuffer, sizeof(box3)) @@ -138,8 +144,8 @@ bool buildOptixBVH(std::vector buildInput, "build")) return false; - box3 builtBounds; - uint64_t compactedSize = 0; + auto &builtBounds = readback.data()->bounds; + auto &compactedSize = readback.data()->compactedSize; if (!check(cudaMemcpyAsync(&builtBounds, aabbBuffer.ptr(), sizeof(box3), @@ -234,7 +240,7 @@ bool DeviceGlobalState::collectGeometryInputUploads() auto error = geometryInputAllocations->reclaim( [&] { return finishGeometryPreparation(); }); if (error == cudaSuccess) - error = preparation.waitFor(stream); + error = waitForRenderConsumers(); if (error == cudaSuccess) { for (auto &geometry : m_geometryInputUploads) geometry->submitInputUploads(); @@ -257,6 +263,14 @@ bool DeviceGlobalState::collectGeometryInputUploads() return true; } +cudaError_t DeviceGlobalState::waitForRenderConsumers() +{ + // Scene submission is serialized. A completed retirement already covers + // these consumers; new render-stream producers invalidate that certificate. + return renderRetirement.isRetired() ? cudaSuccess + : preparation.waitFor(stream); +} + void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) { m_geometryPreparations.enqueue(helium::IntrusivePtr(geometry)); diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index fa1618962..ccb1f1aed 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -187,6 +187,12 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState std::shared_ptr geometryInputAllocations{ std::make_shared()}; GeometryReadbackPool geometryReadbacks; + struct BvhReadback + { + box3 bounds; + uint64_t compactedSize; + }; + PinnedReadbackPool bvhReadbacks; SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; @@ -293,6 +299,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState void enqueueGeometryPreparation(Geometry *geometry); bool collectGeometryPreparations(); cudaError_t finishGeometryPreparation(); + cudaError_t waitForRenderConsumers(); bool collectingGeometryPreparations() const; bool hasPendingGeometryPreparations() const; diff --git a/devices/rtx/device/utility/PinnedReadbackPool.h b/devices/rtx/device/utility/PinnedReadbackPool.h new file mode 100644 index 000000000..97dcb95c4 --- /dev/null +++ b/devices/rtx/device/utility/PinnedReadbackPool.h @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace visrtx { + +// A device-local high-water cache of pinned pages. Each lease owns two result +// slots and retains its page independently of the pool's lifetime. Returning a +// lease is legal only after its GPU writers have completed; callers provide +// that ordering. Acquisition/release may run on different host +// threads. +template +struct PinnedReadbackPool +{ + private: + struct Page; + + public: + static constexpr size_t SLOTS_PER_PAGE = 256; + + struct Lease + { + Lease() = default; + ~Lease(); + Lease(const Lease &) = delete; + Lease &operator=(const Lease &) = delete; + Lease(Lease &&other) noexcept; + Lease &operator=(Lease &&other) noexcept; + + Result *data() const; + void reset(); + + private: + friend struct PinnedReadbackPool; + std::shared_ptr m_page; + size_t m_index{0}; + }; + + PinnedReadbackPool() = default; + PinnedReadbackPool(const PinnedReadbackPool &) = delete; + PinnedReadbackPool &operator=(const PinnedReadbackPool &) = delete; + + cudaError_t acquire(Lease &lease); + + private: + std::mutex m_mutex; + std::vector> m_pages; +}; + +template +struct PinnedReadbackPool::Page +{ + Page(); + ~Page(); + bool take(size_t &index); + void release(size_t index); + + Result *memory{nullptr}; + std::mutex mutex; + std::array freeSlots; + size_t freeCount{SLOTS_PER_PAGE}; +}; + +// Inlined definitions //////////////////////////////////////////////////////// + +template +inline PinnedReadbackPool::Page::Page() +{ + for (size_t i = 0; i < SLOTS_PER_PAGE; ++i) + freeSlots[i] = SLOTS_PER_PAGE - i - 1; +} + +template +inline PinnedReadbackPool::Page::~Page() +{ + if (memory) + cudaFreeHost(memory); +} + +template +inline bool PinnedReadbackPool::Page::take(size_t &index) +{ + std::lock_guard lock(mutex); + if (freeCount == 0) + return false; + index = freeSlots[--freeCount]; + return true; +} + +template +inline void PinnedReadbackPool::Page::release(size_t index) +{ + std::lock_guard lock(mutex); + assert(index < SLOTS_PER_PAGE && freeCount < SLOTS_PER_PAGE); + freeSlots[freeCount++] = index; +} + +template +inline PinnedReadbackPool::Lease::~Lease() +{ + reset(); +} + +template +inline PinnedReadbackPool::Lease::Lease(Lease &&other) noexcept + : m_page(std::move(other.m_page)), m_index(other.m_index) +{} + +template +inline typename PinnedReadbackPool::Lease & +PinnedReadbackPool::Lease::operator=(Lease &&other) noexcept +{ + if (this != &other) { + reset(); + m_page = std::move(other.m_page); + m_index = other.m_index; + } + return *this; +} + +template +inline Result *PinnedReadbackPool::Lease::data() const +{ + return m_page ? m_page->memory + 2 * m_index : nullptr; +} + +template +inline void PinnedReadbackPool::Lease::reset() +{ + if (m_page) { + m_page->release(m_index); + m_page.reset(); + } +} + +template +inline cudaError_t PinnedReadbackPool::acquire(Lease &lease) +{ + if (lease.data()) + return cudaSuccess; + { + std::lock_guard lock(m_mutex); + for (auto &page : m_pages) { + if (page->take(lease.m_index)) { + lease.m_page = page; + return cudaSuccess; + } + } + } + + // CUDA allocation can wait for other work. Do not hold a pool/page mutex + // across it; simultaneous growth may allocate an extra page, but is safe. + auto page = std::make_shared(); + void *memory = nullptr; + const auto error = + cudaMallocHost(&memory, 2 * SLOTS_PER_PAGE * sizeof(Result)); + if (error != cudaSuccess) { + cudaGetLastError(); // A failed page allocation must not poison a retry. + return error; + } + page->memory = static_cast(memory); + { + std::lock_guard lock(m_mutex); + m_pages.push_back(page); + const bool acquired = page->take(lease.m_index); + assert(acquired); + (void)acquired; + lease.m_page = std::move(page); + } + return cudaSuccess; +} + +} // namespace visrtx diff --git a/devices/rtx/device/utility/StreamRetirement.h b/devices/rtx/device/utility/StreamRetirement.h index f3e4b6dd8..d43009fcb 100644 --- a/devices/rtx/device/utility/StreamRetirement.h +++ b/devices/rtx/device/utility/StreamRetirement.h @@ -43,6 +43,7 @@ namespace visrtx { // Failure cleanup must still use an unconditional drain, not this cache. struct StreamRetirement { + bool isRetired() const; void initialize(cudaStream_t stream); void invalidate(); cudaError_t retire(); @@ -53,6 +54,12 @@ struct StreamRetirement std::atomic m_retired{0}; }; +inline bool StreamRetirement::isRetired() const +{ + const auto generation = m_submitted.load(std::memory_order_acquire); + return m_retired.load(std::memory_order_acquire) >= generation; +} + inline void StreamRetirement::initialize(cudaStream_t stream) { m_stream = stream; From f6201fd18b2b407bd71700421211400618e9ca8d Mon Sep 17 00:00:00 2001 From: Jefferson Amstutz Date: Wed, 25 Nov 2026 09:11:34 -0600 Subject: [PATCH 18/20] refactor(rtx): gate disabled-device API calls in one place Report refused ANARI calls on a disabled device and route the gated entry points through a single gate, separate from initDevice(). - report refused API calls and gate the disabled device apart from initDevice() - reset the refusal-report guard on scope exit - pass the gated device entry points through one gate --- .../tests/api/TestCudaPreparationFailure.cpp | 22 +++- .../api/TestDeferredGeometryPreparation.cpp | 23 +++- devices/rtx/device/VisRTXDevice.cpp | 117 +++++++++++++----- devices/rtx/device/VisRTXDevice.h | 16 +++ 4 files changed, 141 insertions(+), 37 deletions(-) diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 37e228e88..e4e72dae9 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include "../../../device/geometry/ReadbackPool.h" @@ -91,6 +92,8 @@ Failure failure = Failure::NONE; size_t allocationBytes = 0; int injections = 0; int errors = 0; +int disableReports = 0; +std::vector disabledRefusals; std::atomic completions{0}; struct PendingCompletion @@ -159,8 +162,21 @@ void status(const void *, pendingCompletion.failed && !pendingCompletion.drained; ++errors; fprintf(stderr, "%s\n", message); + if (std::strstr(message, "array privatization failed")) + ++disableReports; + else if (std::strstr(message, "device disabled")) + disabledRefusals.emplace_back(message); } } + +// The disable is reported once; each later call reports its own refusal. +bool refusedWhileDisabled(const char *call) +{ + for (const auto &message : disabledRefusals) + if (message.find(call) != std::string::npos) + return disableReports == 1; + return false; +} void complete(const void *, ANARIDevice, ANARIFrame) { ++completions; @@ -533,8 +549,9 @@ int main(int argc, char **argv) ok = injections == 1 && errors > 0 && ok; cudaFree(deviceVertices); deviceVertices = nullptr; - ok = !haveBounds() && ok; + ok = !haveBounds() && refusedWhileDisabled("anariGetProperty") && ok; anari::render(d, frame); + ok = refusedWhileDisabled("anariRenderFrame") && ok; anari::wait(d, frame); ok = completions == 0 && ok; } else if (registryFailure) { @@ -767,8 +784,9 @@ int main(int argc, char **argv) ok = injections == 1 && errors > 0 && ok; cudaFree(deviceVertices); deviceVertices = nullptr; - ok = !haveBounds() && ok; + ok = !haveBounds() && refusedWhileDisabled("anariGetProperty") && ok; anari::render(d, frame); + ok = refusedWhileDisabled("anariRenderFrame") && ok; anari::wait(d, frame); ok = completions == 1 && ok; // No retry or device re-enable after the injected CUDA error is gone. diff --git a/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp index 71264f7b3..7a1cab653 100644 --- a/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp +++ b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp @@ -36,13 +36,17 @@ #include #include #include +#include #include namespace { int freed = 0; int errors = 0; int rejectedQueries = 0; +int refusedQueryReports = 0; +int refusedRenderReports = 0; anari::World callbackWorld = nullptr; +anari::Frame callbackFrame = nullptr; void releaseDevice(const void *, const void *memory) { @@ -58,10 +62,21 @@ void status(const void *, ANARIStatusCode, const char *message) { + if (severity == ANARI_SEVERITY_WARNING + && std::strstr(message, "geometry preparations are being collected")) { + refusedQueryReports += std::strstr(message, "anariGetProperty") != nullptr; + refusedRenderReports += std::strstr(message, "anariRenderFrame") != nullptr; + // Reentering from the refusal report itself must not recurse. + if (callbackFrame) + anariRenderFrame(d, callbackFrame); + return; + } if (severity > ANARI_SEVERITY_ERROR) return; ++errors; std::fprintf(stderr, "%s\n", message); + if (callbackFrame) + anariRenderFrame(d, callbackFrame); if (callbackWorld) { std::array bounds{}; if (!anariGetProperty(d, @@ -147,9 +162,15 @@ int main() auto invalid = anari::newObject(d, "sphere"); ok = position(d, invalid, std::numeric_limits::quiet_NaN()) && ok; ok = flushGeometry(d, invalid) && ok; + // Each refused reentrant call is reported, naming the call. + auto frame = anari::newObject(d); callbackWorld = world; - ok = haveBounds() && errors == 1 && rejectedQueries == 1 && ok; + callbackFrame = frame; + ok = haveBounds() && errors == 1 && rejectedQueries == 1 + && refusedQueryReports == 1 && refusedRenderReports == 1 && ok; callbackWorld = nullptr; + callbackFrame = nullptr; + anari::release(d, frame); anari::release(d, invalid); // The pending queue owns a last-reference geometry until device teardown. diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index e11207d0e..81bea0e8a 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -117,7 +117,7 @@ const char **query_extensions(); void *VisRTXDevice::mapArray(ANARIArray a) { - if (!initDevice()) + if (!enter("anariMapArray")) return nullptr; CUDADeviceScope ds(this); return helium::BaseDevice::mapArray(a); @@ -125,7 +125,7 @@ void *VisRTXDevice::mapArray(ANARIArray a) void VisRTXDevice::unmapArray(ANARIArray a) { - if (!initDevice()) + if (!enter("anariUnmapArray")) return; CUDADeviceScope ds(this); helium::BaseDevice::unmapArray(a); @@ -139,7 +139,7 @@ ANARIArray1D VisRTXDevice::newArray1D(const void *appMemory, ANARIDataType type, uint64_t numItems) { - if (!initDevice()) + if (!enter("anariNewArray1D")) return {}; CUDADeviceScope ds(this); @@ -163,7 +163,7 @@ ANARIArray2D VisRTXDevice::newArray2D(const void *appMemory, uint64_t numItems1, uint64_t numItems2) { - if (!initDevice()) + if (!enter("anariNewArray2D")) return {}; CUDADeviceScope ds(this); @@ -186,7 +186,7 @@ ANARIArray3D VisRTXDevice::newArray3D(const void *appMemory, uint64_t numItems2, uint64_t numItems3) { - if (!initDevice()) + if (!enter("anariNewArray3D")) return {}; CUDADeviceScope ds(this); @@ -204,7 +204,7 @@ ANARIArray3D VisRTXDevice::newArray3D(const void *appMemory, ANARICamera VisRTXDevice::newCamera(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewCamera")) return {}; CUDADeviceScope ds(this); return (ANARICamera)Camera::createInstance(subtype, deviceState()); @@ -212,7 +212,7 @@ ANARICamera VisRTXDevice::newCamera(const char *subtype) ANARIFrame VisRTXDevice::newFrame() { - if (!initDevice()) + if (!enter("anariNewFrame")) return {}; CUDADeviceScope ds(this); return (ANARIFrame) new Frame(deviceState()); @@ -220,7 +220,7 @@ ANARIFrame VisRTXDevice::newFrame() ANARIGeometry VisRTXDevice::newGeometry(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewGeometry")) return {}; CUDADeviceScope ds(this); return (ANARIGeometry)Geometry::createInstance(subtype, deviceState()); @@ -228,7 +228,7 @@ ANARIGeometry VisRTXDevice::newGeometry(const char *subtype) ANARIGroup VisRTXDevice::newGroup() { - if (!initDevice()) + if (!enter("anariNewGroup")) return {}; CUDADeviceScope ds(this); return (ANARIGroup) new Group(deviceState()); @@ -236,7 +236,7 @@ ANARIGroup VisRTXDevice::newGroup() ANARIInstance VisRTXDevice::newInstance(const char *type) { - if (!initDevice()) + if (!enter("anariNewInstance")) return {}; CUDADeviceScope ds(this); return (ANARIInstance) new Instance(deviceState()); @@ -244,7 +244,7 @@ ANARIInstance VisRTXDevice::newInstance(const char *type) ANARILight VisRTXDevice::newLight(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewLight")) return {}; CUDADeviceScope ds(this); return (ANARILight)Light::createInstance(subtype, deviceState()); @@ -252,7 +252,7 @@ ANARILight VisRTXDevice::newLight(const char *subtype) ANARIMaterial VisRTXDevice::newMaterial(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewMaterial")) return {}; CUDADeviceScope ds(this); return (ANARIMaterial)Material::createInstance(subtype, deviceState()); @@ -260,7 +260,7 @@ ANARIMaterial VisRTXDevice::newMaterial(const char *subtype) ANARIRenderer VisRTXDevice::newRenderer(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewRenderer")) return {}; CUDADeviceScope ds(this); return (ANARIRenderer)Renderer::createInstance(subtype, deviceState()); @@ -268,7 +268,7 @@ ANARIRenderer VisRTXDevice::newRenderer(const char *subtype) ANARISampler VisRTXDevice::newSampler(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewSampler")) return {}; CUDADeviceScope ds(this); return (ANARISampler)Sampler::createInstance(subtype, deviceState()); @@ -276,7 +276,7 @@ ANARISampler VisRTXDevice::newSampler(const char *subtype) ANARISpatialField VisRTXDevice::newSpatialField(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewSpatialField")) return {}; CUDADeviceScope ds(this); return (ANARISpatialField)SpatialField::createInstance( @@ -285,7 +285,7 @@ ANARISpatialField VisRTXDevice::newSpatialField(const char *subtype) ANARISurface VisRTXDevice::newSurface() { - if (!initDevice()) + if (!enter("anariNewSurface")) return {}; CUDADeviceScope ds(this); return (ANARISurface) new Surface(deviceState()); @@ -293,7 +293,7 @@ ANARISurface VisRTXDevice::newSurface() ANARIVolume VisRTXDevice::newVolume(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewVolume")) return {}; CUDADeviceScope ds(this); return (ANARIVolume)Volume::createInstance(subtype, deviceState()); @@ -301,7 +301,7 @@ ANARIVolume VisRTXDevice::newVolume(const char *subtype) ANARIWorld VisRTXDevice::newWorld() { - if (!initDevice()) + if (!enter("anariNewWorld")) return {}; CUDADeviceScope ds(this); return (ANARIWorld) new World(deviceState()); @@ -346,11 +346,7 @@ int VisRTXDevice::getProperty(ANARIObject object, uint64_t size, uint32_t mask) { - // A status callback during collection must not flush/re-finalize geometry - // whose readbacks and registry publication are still being resolved. - if (deviceState()->collectingGeometryPreparations()) - return 0; - if (!initDevice()) + if (!enterOutsideCollection("anariGetProperty")) return 0; CUDADeviceScope ds(this); return helium::BaseDevice::getProperty(object, name, type, mem, size, mask); @@ -364,7 +360,7 @@ const void *VisRTXDevice::frameBufferMap(ANARIFrame f, uint32_t *height, ANARIDataType *pixelType) { - if (!initDevice()) { + if (!enter("anariMapFrame")) { *width = 0; *height = 0; *pixelType = ANARI_UNKNOWN; @@ -379,9 +375,7 @@ const void *VisRTXDevice::frameBufferMap(ANARIFrame f, void VisRTXDevice::renderFrame(ANARIFrame f) { - if (deviceState()->collectingGeometryPreparations()) - return; - if (!initDevice()) + if (!enterOutsideCollection("anariRenderFrame")) return; CUDADeviceScope ds(this); helium::BaseDevice::renderFrame(f); @@ -389,7 +383,7 @@ void VisRTXDevice::renderFrame(ANARIFrame f) int VisRTXDevice::frameReady(ANARIFrame f, ANARIWaitMask m) { - if (!initDevice()) + if (!enter("anariFrameReady")) return 1; CUDADeviceScope ds(this); return helium::BaseDevice::frameReady(f, m); @@ -397,7 +391,7 @@ int VisRTXDevice::frameReady(ANARIFrame f, ANARIWaitMask m) void VisRTXDevice::discardFrame(ANARIFrame f) { - if (!initDevice()) + if (!enter("anariDiscardFrame")) return; CUDADeviceScope ds(this); return helium::BaseDevice::discardFrame(f); @@ -464,13 +458,68 @@ VisRTXDevice::~VisRTXDevice() cudaStreamDestroy(state.stream); } -bool VisRTXDevice::initDevice() +bool VisRTXDevice::enter(const char *call) +{ + // Refuse first, initialize second: a refused call initializes nothing. + return !refuseIfDisabled(call) && initDevice(); +} + +bool VisRTXDevice::enterOutsideCollection(const char *call) { - if (deviceState()->arrayPrivatizationFailed) { - reportMessage(ANARI_SEVERITY_ERROR, - "device disabled after array privatization failure; create a new device"); + return !refuseDuringCollection(call) && enter(call); +} + +bool VisRTXDevice::refuseIfDisabled(const char *call) const +{ + // A failed last-reference array copy (Array::privatize) disables the device + // for good: cached GPU pointers may alias freed application memory. The + // failure itself is reported once there; each refused call says so here so + // a missing object or frame is never silent. + if (!deviceState()->arrayPrivatizationFailed) return false; - } + reportRefusal(ANARI_SEVERITY_ERROR, + call, + "refused: device disabled after array privatization failure; " + "create a new device"); + return true; +} + +bool VisRTXDevice::refuseDuringCollection(const char *call) const +{ + // A status callback reported while geometry preparations are collected must + // not flush or re-finalize geometry whose readbacks and registry publication + // are still being resolved, so such reentrant calls do nothing. + if (!deviceState()->collectingGeometryPreparations()) + return false; + reportRefusal(ANARI_SEVERITY_WARNING, + call, + "ignored: geometry preparations are being collected " + "(reentered from a status callback?)"); + return true; +} + +void VisRTXDevice::reportRefusal( + ANARIStatusSeverity severity, const char *call, const char *reason) const +{ + // The report runs the status callback, which may call back into a refused + // entry point. Only the outermost refusal on this thread is reported; + // refusals nested in its callback (on any device) are refused silently. + static thread_local bool reporting = false; + if (reporting) + return; + struct Reset + { + ~Reset() + { + reporting = false; // Also when the callback throws. + } + } reset; + reporting = true; + reportMessage(severity, "%s %s", call, reason); +} + +bool VisRTXDevice::initDevice() +{ if (m_initStatus == DeviceInitStatus::SUCCESS) return true; else if (m_initStatus == DeviceInitStatus::FAILURE) { diff --git a/devices/rtx/device/VisRTXDevice.h b/devices/rtx/device/VisRTXDevice.h index 8dbf6de58..778aee1f6 100644 --- a/devices/rtx/device/VisRTXDevice.h +++ b/devices/rtx/device/VisRTXDevice.h @@ -131,6 +131,22 @@ struct VisRTXDevice : public helium::BaseDevice bool initDevice(); // thread safe initialization private: + // The gate an API entry point that needs the initialized device passes + // first; call is the public ANARI function name. True when the call may + // proceed: the device is not disabled and is initialized. + // enterOutsideCollection() also refuses while geometry preparations are + // being collected. + bool enter(const char *call); + bool enterOutsideCollection(const char *call); + + // The refusals behind the gate. Each reports one message naming the + // refused call, except while another refusal is being reported on this + // thread (a status callback reentering the device must not recurse). + bool refuseIfDisabled(const char *call) const; + bool refuseDuringCollection(const char *call) const; + void reportRefusal( + ANARIStatusSeverity severity, const char *call, const char *reason) const; + struct CUDADeviceScope { CUDADeviceScope(VisRTXDevice *d); From a7a9f6d0fc7cceea0858f38aeb40ead9da908747 Mon Sep 17 00:00:00 2001 From: Jefferson Amstutz Date: Wed, 25 Nov 2026 09:11:34 -0600 Subject: [PATCH 19/20] refactor(rtx): simplify geometry preprocessing state, readbacks and kernels Replace Geometry preparation flags with explicit state, let Preprocessing own its published results through one pinned results buffer, write bounds and area kernels per geometry type, and simplify allocation-cache and failure handling. - handle device allocation failure once, in DeviceBuffer - make RegisteredObject::upload() virtual - replace Geometry preparation flags with explicit state - let Preprocessing own its published results - collapse pinned readback machinery into one results buffer - collect input uploads with the shared PreparationQueue - write the bounds and area kernels per geometry type - fail preparation directly where the failure is already known - cover the general path's preparation-results reservation failure - correct the SmallGeometryJob comment - ask CUDA whether the render stream is idle - guard the allocation cache's cohort with nonstd::scope_exit - keep the allocation cache's blocks in one partitioned array - cover a failed observer-only geometry input upload - upload observer-only geometry inputs through the input batch - drop the unread Preprocessing::Status::Failed --- devices/rtx/apps/tests/api/CMakeLists.txt | 21 +- .../tests/api/TestCudaPreparationFailure.cpp | 90 ++- .../tests/api/TestDeviceAllocationCache.cpp | 48 ++ .../apps/tests/api/TestGeometryInputBatch.cpp | 29 +- .../tests/api/TestGeometryReadbackPool.cpp | 225 -------- .../apps/tests/api/TestPreparationQueue.cpp | 138 +++-- .../apps/tests/api/TestPreparationResults.cpp | 170 ++++++ .../apps/tests/api/TestStreamRetirement.cpp | 140 ----- devices/rtx/device/CMakeLists.txt | 1 + devices/rtx/device/RegisteredObject.h | 4 +- devices/rtx/device/VisRTXDevice.cpp | 1 - devices/rtx/device/array/Array.cpp | 2 +- devices/rtx/device/frame/Denoiser.cu | 3 - devices/rtx/device/frame/Frame.cu | 3 - devices/rtx/device/geometry/Cone.cpp | 36 +- devices/rtx/device/geometry/Cone.h | 2 - devices/rtx/device/geometry/Curve.cpp | 2 +- devices/rtx/device/geometry/Cylinder.cpp | 36 +- devices/rtx/device/geometry/Cylinder.h | 2 - devices/rtx/device/geometry/Geometry.cpp | 158 ++--- devices/rtx/device/geometry/Geometry.h | 106 +++- devices/rtx/device/geometry/Isosurface.cpp | 3 +- devices/rtx/device/geometry/Neural.cpp | 2 +- .../device/geometry/PreparationResults.cpp | 142 +++++ .../rtx/device/geometry/PreparationResults.h | 101 ++++ devices/rtx/device/geometry/Preprocessing.cu | 538 ++++++++++-------- devices/rtx/device/geometry/Preprocessing.h | 188 ++++-- devices/rtx/device/geometry/Quad.cpp | 2 +- devices/rtx/device/geometry/ReadbackPool.h | 46 -- devices/rtx/device/geometry/SDF.cpp | 12 +- devices/rtx/device/geometry/Sphere.cu | 56 +- devices/rtx/device/geometry/Sphere.h | 3 +- devices/rtx/device/geometry/Triangle.cpp | 23 +- devices/rtx/device/geometry/Triangle.h | 2 - devices/rtx/device/optix_visrtx.cpp | 188 +++--- devices/rtx/device/optix_visrtx.h | 22 +- .../device/utility/DeviceAllocationCache.h | 150 +++-- devices/rtx/device/utility/DeviceBuffer.h | 34 +- .../rtx/device/utility/PinnedReadbackPool.h | 212 ------- devices/rtx/device/utility/PreparationQueue.h | 75 ++- devices/rtx/device/utility/StreamRetirement.h | 93 --- .../rtx/device/volume/TransferFunction1D.cpp | 1 - .../rtx/docs/geometry-preparation-reuse.md | 105 ++-- 43 files changed, 1632 insertions(+), 1583 deletions(-) delete mode 100644 devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp create mode 100644 devices/rtx/apps/tests/api/TestPreparationResults.cpp delete mode 100644 devices/rtx/apps/tests/api/TestStreamRetirement.cpp create mode 100644 devices/rtx/device/geometry/PreparationResults.cpp create mode 100644 devices/rtx/device/geometry/PreparationResults.h delete mode 100644 devices/rtx/device/geometry/ReadbackPool.h delete mode 100644 devices/rtx/device/utility/PinnedReadbackPool.h delete mode 100644 devices/rtx/device/utility/StreamRetirement.h diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index a7ee5d239..cccff8b56 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -96,7 +96,7 @@ add_executable(TestRegistrySnapshot TestRegistrySnapshot.cpp target_include_directories(TestRegistrySnapshot PRIVATE ../../../device ../../../external/nanovdb/include ${OptiX_ROOT_DIR}/include) target_link_libraries(TestRegistrySnapshot PRIVATE - CUDA::cudart anari::anari_static visrtx::glm) + CUDA::cudart anari::anari_static visrtx::glm nonstd::scope-lite) target_compile_definitions(TestRegistrySnapshot PRIVATE GLM_ENABLE_EXPERIMENTAL) add_test(NAME TestRegistrySnapshot COMMAND TestRegistrySnapshot) make_test(TestDeferredGeometryPreparation) @@ -129,13 +129,9 @@ add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") add_executable(TestDeviceAllocationCache TestDeviceAllocationCache.cpp ../../../device/utility/MemoryAllocation.cpp) - target_link_libraries(TestDeviceAllocationCache PRIVATE CUDA::cudart anari::anari_static ${CMAKE_DL_LIBS} Threads::Threads) + target_link_libraries(TestDeviceAllocationCache PRIVATE CUDA::cudart anari::anari_static nonstd::scope-lite ${CMAKE_DL_LIBS} Threads::Threads) set_target_properties(TestDeviceAllocationCache PROPERTIES ENABLE_EXPORTS ON) add_test(NAME TestDeviceAllocationCache COMMAND TestDeviceAllocationCache) - add_executable(TestStreamRetirement TestStreamRetirement.cpp) - target_link_libraries(TestStreamRetirement PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) - set_target_properties(TestStreamRetirement PROPERTIES ENABLE_EXPORTS ON) - add_test(NAME TestStreamRetirement COMMAND TestStreamRetirement) target_link_libraries(TestSmallGeometryBatch PRIVATE ${CMAKE_DL_LIBS}) target_compile_definitions(TestSmallGeometryBatch PRIVATE VISRTX_TEST_INTERPOSE_CUDA) set_target_properties(TestSmallGeometryBatch PROPERTIES ENABLE_EXPORTS ON) @@ -145,11 +141,11 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S make_test(TestGeometryInputBatch) target_link_libraries(TestGeometryInputBatch PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) set_target_properties(TestGeometryInputBatch PROPERTIES ENABLE_EXPORTS ON) - add_executable(TestGeometryReadbackPool TestGeometryReadbackPool.cpp) - target_link_libraries(TestGeometryReadbackPool PRIVATE - CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) - set_target_properties(TestGeometryReadbackPool PROPERTIES ENABLE_EXPORTS ON) - add_test(NAME TestGeometryReadbackPool COMMAND TestGeometryReadbackPool) + add_executable(TestPreparationResults TestPreparationResults.cpp + ../../../device/geometry/PreparationResults.cpp) + target_link_libraries(TestPreparationResults PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestPreparationResults PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestPreparationResults COMMAND TestPreparationResults) make_test(TestCudaPreparationFailure) target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) target_include_directories(TestCudaPreparationFailure PRIVATE ${OptiX_ROOT_DIR}/include) @@ -160,7 +156,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "S sphere-undrained-completion sphere-batch-small-copy sphere-batch-small-launch sphere-batch-small-readback sphere-batch-small-result-allocation sphere-batch-small-pinned-allocation - sphere-readback-allocation sphere-batch-completion + sphere-readback-allocation sphere-result-allocation + sphere-batch-completion sphere-batch-upload-completion sphere-batch-input-completion sphere-upload-allocation sphere-upload-copy sphere-upload-completion sphere-upload-partial sphere-upload-observer) diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index e4e72dae9..6926c5873 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -50,7 +50,7 @@ #include #include #include -#include "../../../device/geometry/ReadbackPool.h" +#include "../../../device/geometry/PreparationResults.h" namespace { enum class Failure @@ -183,22 +183,18 @@ void complete(const void *, ANARIDevice, ANARIFrame) } } // namespace +// Bytes of the first device or pinned allocation of geometry results. +constexpr size_t RESULTS_BYTES = + visrtx::PreparationResults::MIN_CAPACITY * sizeof(visrtx::GeometryResults); + extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) { - // BVH results contain six bounds floats and a 64-bit compaction size. - constexpr size_t bvhPageBytes = 2 - * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE - * (6 * sizeof(float) + sizeof(uint64_t)); - if (bytes == bvhPageBytes && inject(Failure::BVH_PINNED_ALLOCATION)) { - *ptr = nullptr; - return next("cudaMallocHost")(ptr, size_t(-1)); - } - constexpr size_t readbackPageBytes = 2 - * visrtx::GeometryReadbackPool::SLOTS_PER_PAGE - * sizeof(visrtx::PreparationResult); - if ((bytes == readbackPageBytes && inject(Failure::READBACK_ALLOCATION)) - || (bytes == 4 * sizeof(visrtx::PreparationResult) - && inject(Failure::SMALL_PINNED_ALLOCATION))) { + // The BVH readback holds six bounds floats and a 64-bit compaction size. + constexpr size_t BVH_BYTES = 6 * sizeof(float) + sizeof(uint64_t); + if ((bytes == BVH_BYTES && inject(Failure::BVH_PINNED_ALLOCATION)) + || (bytes == RESULTS_BYTES + && (inject(Failure::READBACK_ALLOCATION) + || inject(Failure::SMALL_PINNED_ALLOCATION)))) { *ptr = nullptr; return next("cudaMallocHost")(ptr, size_t(-1)); } @@ -315,13 +311,11 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, } } if (failure == Failure::PREPARATION_EARLY_SYNC && stream == preparationStream - && kind == cudaMemcpyDeviceToHost - && (bytes == sizeof(visrtx::PreparationResult) - || (bytes && bytes % (2 * sizeof(visrtx::PreparationResult)) == 0)) + && kind == cudaMemcpyDeviceToHost && bytes + && bytes % sizeof(visrtx::GeometryResults) == 0 && !pendingCompletion.queued) { - // Gate either the general bounds summary or the consolidated small-batch - // summary after kernel submission. No subsequent allocation or pageable - // copy can supply a hidden wait. + // Gate the consolidated results readback after kernel submission. No + // subsequent allocation or pageable copy can supply a hidden wait. auto error = cudaLaunchHostFunc(stream, blockPreparation, nullptr); if (error != cudaSuccess) return error; @@ -377,6 +371,16 @@ extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) return result; } +// Retirement synchronizes the render stream only when a query finds it busy, +// and it is idle whenever a test arms WORK_SYNC. Report it busy so the wait +// that carries the injected failure happens. +extern "C" cudaError_t cudaStreamQuery(cudaStream_t stream) +{ + if (stream && stream != preparationStream && failure == Failure::WORK_SYNC) + return cudaErrorNotReady; + return next("cudaStreamQuery")(stream); +} + int main(int argc, char **argv) { const bool pendingRetirement = @@ -389,6 +393,11 @@ int main(int argc, char **argv) sphereFailure && std::strcmp(argv[1], "sphere-undrained-completion") == 0; const bool batchCompletion = sphereFailure && std::strncmp(argv[1], "sphere-batch-", 13) == 0; + // Over SmallGeometryBatch::MAX_PRIMITIVES: results are reserved at + // submission (general path), not at small-batch launch. + const bool generalResults = sphereFailure + && (std::strcmp(argv[1], "sphere-readback-allocation") == 0 + || std::strcmp(argv[1], "sphere-result-allocation") == 0); const bool inputBatchCompletion = batchCompletion && std::strcmp(argv[1], "sphere-batch-input-completion") == 0; const bool batchUploadCompletion = batchCompletion @@ -459,6 +468,13 @@ int main(int argc, char **argv) anari::commitParameters(d, field); anari::setAndReleaseParameter(d, geometry, "field", field); anari::setParameter(d, geometry, "isovalue", 3.5f); + } else if (generalResults) { + std::vector positions(300); + for (size_t i = 0; i < positions.size(); ++i) + positions[i] = {float(i % 20) * 0.1f - 1.f, float(i / 20) * 0.1f, 0.f}; + anari::setParameterArray1D( + d, geometry, "vertex.position", positions.data(), positions.size()); + anari::setParameter(d, geometry, "radius", 0.1f); } else { anari::setParameter(d, geometry, "vertex.position", array); anari::setParameter(d, geometry, "radius", observerRecovery ? 0.2f : 0.1f); @@ -652,6 +668,11 @@ int main(int argc, char **argv) if (sphereFailure && std::strcmp(argv[1], "sphere-readback-allocation") == 0) failure = Failure::READBACK_ALLOCATION; + if (sphereFailure + && std::strcmp(argv[1], "sphere-result-allocation") == 0) { + allocationBytes = RESULTS_BYTES; // Device side of the reservation. + failure = Failure::ALLOCATION; + } if ((sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) || batchCompletion) failure = Failure::PREPARATION_SYNC; @@ -666,8 +687,7 @@ int main(int argc, char **argv) failure = Failure::SMALL_READBACK; if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-result-allocation") == 0) { - allocationBytes = - 4 * sizeof(visrtx::PreparationResult); // Two geometries. + allocationBytes = RESULTS_BYTES; // Device results of both geometries. failure = Failure::ALLOCATION; } if (sphereFailure @@ -763,6 +783,30 @@ int main(int argc, char **argv) anari::commitParameters(d, geometry); ok = haveBounds() && errors == retirementErrors && ok; } + if (observerRecovery) { + // An observer-only update: no commit captures the dirty array, so the + // geometry's own finalize uploads it. A failed copy or completion there + // fails that finalize only; the next observer update retries without a + // geometry commit. + for (const auto kind : {Failure::UPLOAD_COPY, Failure::UPLOAD_SYNC}) { + const int errorsBefore = errors; + const int copiesBefore = uploadCopies; + const int injectionsBefore = injections; + uploadQueued = false; + failure = kind; + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); + ok = !haveBounds() && injections == injectionsBefore + 1 + && errors == errorsBefore + 1 && uploadCopies == copiesBefore + 1 + && ok; + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); + ok = haveBounds() && errors == errorsBefore + 1 + && uploadCopies == copiesBefore + 2 && !uploadOnWrongStream && ok; + } + } anari::release(d, array); } else { ok = haveBounds() && ok; diff --git a/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp index c63179ec0..4a25bceaa 100644 --- a/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp +++ b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp @@ -40,8 +40,10 @@ #include #include #include +#include #include #include "../../../device/utility/DeviceAllocationCache.h" +#include "../../../device/utility/DeviceBuffer.h" #include "../../../device/utility/MemoryAllocation.h" namespace { @@ -282,6 +284,35 @@ int main() } ok = threw && cache.reclaim(complete) == cudaSuccess && ok; } + { + // Reusing a block while a cohort is frozen and a later return waits must + // leave each of the other two where it was. + DeviceAllocationCache cache; + void *ready = nullptr, *frozen = nullptr, *waiting = nullptr, *p = nullptr; + ok = cache.allocate(32, &ready) == cudaSuccess && ok; + ok = cache.allocate(48, &frozen) == cudaSuccess && ok; + ok = cache.allocate(64, &waiting) == cudaSuccess && ok; + cache.release(ready, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + cache.release(frozen, 48); + ok = cache.reclaim([&] { + cache.release(waiting, 64); + ok = cache.allocate(32, &p) == cudaSuccess && p == ready && ok; + ok = cache.allocate(48, &p) == cudaSuccess && p != frozen && ok; + cache.release(p, 48); + return cudaSuccess; + }) == cudaSuccess + && ok; + ok = cache.allocate(48, &p) == cudaSuccess && p == frozen && ok; + void *other = nullptr; + ok = cache.allocate(64, &other) == cudaSuccess && other != waiting && ok; + ok = cache.reclaim(complete) == cudaSuccess && ok; + void *q = nullptr; + ok = cache.allocate(64, &q) == cudaSuccess && q == waiting && ok; + for (auto [pointer, bytes] : + {std::pair{ready, 32}, {p, 48}, {other, 64}, {q, 64}}) + cache.release(pointer, bytes); + } { DeviceAllocationCache cache; void *p = nullptr; @@ -316,6 +347,23 @@ int main() } ok = capturedDeletes == 1 && ok; } + { + // A failed reservation leaves the buffer empty, consumes the runtime + // error, and lets the same size be retried. + visrtx::DeviceBuffer buffer; + failBytes = 96; + ok = buffer.tryReserve(96) == cudaErrorMemoryAllocation && !buffer + && buffer.bytes() == 0 && cudaGetLastError() == cudaSuccess && ok; + ok = buffer.tryReserve(96) == cudaSuccess && buffer && buffer.bytes() >= 96 + && ok; + const auto *storage = buffer.ptr(); + ok = buffer.tryReserve(48) == cudaSuccess && buffer.ptr() == storage + && buffer.tryReserve(0) == cudaSuccess && buffer.ptr() == storage && ok; + failBytes = 192; + ok = buffer.tryReserve(192) == cudaErrorMemoryAllocation && !buffer + && buffer.bytes() == 0 && cudaGetLastError() == cudaSuccess && ok; + ok = buffer.tryReserve(192) == cudaSuccess && buffer.bytes() >= 192 && ok; + } ok = allocations == frees && ok; std::printf("allocation cache allocations=%d frees=%d syncs=%d %s\n", int(allocations), diff --git a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp index 9da956710..11807ce7d 100644 --- a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp +++ b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp @@ -43,6 +43,7 @@ namespace { using vec3 = std::array; anari::Device device = nullptr; ANARIArray retireArray = nullptr; +void **retireSource = nullptr; void *sourceA = nullptr; void *sourceB = nullptr; const void *trackedA = nullptr; @@ -166,7 +167,7 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, } const auto error = next("cudaMemcpyAsync")( dst, src, bytes, kind, stream); - if (error == cudaSuccess && tracked && src == trackedA && retireNext) { + if (error == cudaSuccess && tracked && retireNext && src == *retireSource) { retireNext = false; // Reenter from the host submission path, not from a CUDA host callback. // Public release must wait before the application frees a pinned source. @@ -177,9 +178,9 @@ extern "C" cudaError_t cudaMemcpyAsync(void *dst, std::fprintf(stderr, "host release omitted pending upload wait\n"); } retireArray = nullptr; - if (cudaFreeHost(sourceA) != cudaSuccess) + if (cudaFreeHost(*retireSource) != cudaSuccess) ++errors; - sourceA = nullptr; + *retireSource = nullptr; retired = true; } return error; @@ -312,21 +313,33 @@ int main() anariRelease(device, c); cudaFreeHost(replacement); replacementSource = nullptr; + // An observer-only update has no commit to capture it: its geometry's + // finalizer uploads it. A release from inside that copy must wait too. + resetCounts(); + change(b, 4.f); + retireArray = b; + retireSource = &sourceB; + retireNext = true; + ok = bounds(-1.25f, 4.25f) && retired && copies == 1 && !wrongStream && ok; + retired = false; resetCounts(); change(a, -2.f); commitGeometryWideAttributes(3.f); retireArray = a; + retireSource = &sourceA; retireNext = true; - ok = bounds(-2.25f, 3.25f) && retired && copies == 1 && !wrongStream && ok; + ok = bounds(-2.25f, 4.25f) && retired && copies == 1 && !wrongStream && ok; anari::release(device, world); for (auto geometry : geometries) anari::release(device, geometry); - if (!retired) + if (sourceA) { anariRelease(device, a); - anariRelease(device, b); - if (sourceA) cudaFreeHost(sourceA); - cudaFreeHost(sourceB); + } + if (sourceB) { + anariRelease(device, b); + cudaFreeHost(sourceB); + } anari::release(device, device); ok = errors == 1 && ok; std::printf("geometry input batches: %s\n", ok ? "PASS" : "FAIL"); diff --git a/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp b/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp deleted file mode 100644 index 7e8f233a5..000000000 --- a/devices/rtx/apps/tests/api/TestGeometryReadbackPool.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "../../../device/geometry/ReadbackPool.h" - -namespace { -std::atomic failNext{false}; -std::atomic attempts{0}; -std::atomic allocations{0}; -std::atomic frees{0}; - -template -T next(const char *name) -{ - auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); - if (!function) - std::abort(); - return function; -} -} // namespace - -extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) -{ - ++attempts; - if (failNext.exchange(false)) { - *ptr = nullptr; - return next("cudaMallocHost")(ptr, size_t(-1)); - } - const auto error = - next("cudaMallocHost")(ptr, bytes); - if (error == cudaSuccess) - ++allocations; - return error; -} - -extern "C" cudaError_t cudaFreeHost(void *ptr) -{ - const auto error = next("cudaFreeHost")(ptr); - if (error == cudaSuccess && ptr) - ++frees; - return error; -} - -int main(int argc, char **argv) -{ - if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "--no-failure") != 0)) - return 2; - const bool injectFailures = argc == 1; - using Pool = visrtx::GeometryReadbackPool; - bool ok = true; - { - Pool pool; - Pool::Lease failed; - if (injectFailures) { - failNext = true; - ok = pool.acquire(failed) != cudaSuccess - && cudaGetLastError() == cudaSuccess && !failed.data() - && allocations == 0 && ok; - } - - std::vector leases(Pool::SLOTS_PER_PAGE + 1); - for (size_t i = 0; i < leases.size(); ++i) { - if (injectFailures && i == Pool::SLOTS_PER_PAGE) { - failNext = true; - ok = pool.acquire(leases[i]) != cudaSuccess - && cudaGetLastError() == cudaSuccess && !leases[i].data() - && allocations == 1 && ok; - } - if (pool.acquire(leases[i]) != cudaSuccess) - return 1; - leases[i].data()[0] = {float(i), uint32_t(i)}; - leases[i].data()[1] = {-float(i), uint32_t(i + 1)}; - } - // Exercise independent asynchronous DMA targets on the same pinned page, - // including writes to one slot while the CPU initializes a later slot. - std::vector source(2 * leases.size()); - for (size_t i = 0; i < leases.size(); ++i) { - source[2 * i] = leases[i].data()[0]; - source[2 * i + 1] = leases[i].data()[1]; - } - void *device = nullptr; - cudaStream_t stream = nullptr; - const size_t bytes = source.size() * sizeof(source[0]); - if (cudaMalloc(&device, bytes) != cudaSuccess - || cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) - != cudaSuccess - || cudaMemcpyAsync( - device, source.data(), bytes, cudaMemcpyHostToDevice, stream) - != cudaSuccess) - return 1; - for (size_t i = 0; i < leases.size(); ++i) { - leases[i].data()[0] = {}; - leases[i].data()[1] = {}; - if (cudaMemcpyAsync(leases[i].data(), - static_cast(device) + 2 * i, - 2 * sizeof(source[0]), - cudaMemcpyDeviceToHost, - stream) - != cudaSuccess) - return 1; - } - if (cudaStreamSynchronize(stream) != cudaSuccess) - return 1; - cudaFree(device); - cudaStreamDestroy(stream); - std::unordered_set addresses; - for (size_t i = 0; i < leases.size(); ++i) { - addresses.insert(leases[i].data()); - ok = leases[i].data()[0].value == float(i) - && leases[i].data()[1].invalid == i + 1 && ok; - } - ok = addresses.size() == leases.size() && allocations == 2 && frees == 0 - && ok; - auto *first = leases[0].data(); - Pool::Lease moved(std::move(leases[0])); - ok = !leases[0].data() && moved.data() == first && ok; - leases[1] = std::move(moved); // Returns its previous slot exactly once. - ok = !moved.data() && leases[1].data() == first && ok; - Pool::Lease replacement; - if (pool.acquire(replacement) != cudaSuccess) - return 1; - for (auto &lease : leases) - ok = lease.data() != replacement.data() && ok; - replacement.reset(); - replacement.reset(); - leases.clear(); - - // A full release/reacquire cycle stays within the two cached pages. - leases.resize(Pool::SLOTS_PER_PAGE + 1); - addresses.clear(); - for (auto &lease : leases) { - if (pool.acquire(lease) != cudaSuccess) - return 1; - addresses.insert(lease.data()); - } - ok = addresses.size() == leases.size() && allocations == 2 && frees == 0 - && ok; - } - ok = frees == 2 && ok; - - Pool::Lease survivor; - { - Pool pool; - if (pool.acquire(survivor) != cudaSuccess) - return 1; - survivor.data()[0].value = 123.f; - } - ok = frees == 2 && survivor.data()[0].value == 123.f && ok; - survivor.reset(); - ok = frees == 3 && ok; - - { - Pool pool; - Pool::Lease warm; - if (pool.acquire(warm) != cudaSuccess) - return 1; - warm.reset(); - std::atomic concurrentOK{true}; - std::vector workers; - for (unsigned id = 0; id < 8; ++id) { - workers.emplace_back([&, id] { - for (unsigned i = 0; i < 1000; ++i) { - Pool::Lease lease; - if (pool.acquire(lease) != cudaSuccess) { - concurrentOK = false; - return; - } - const float value = float(id * 1000 + i); - lease.data()[0].value = value; - lease.data()[1].invalid = id; - std::this_thread::yield(); - if (lease.data()[0].value != value || lease.data()[1].invalid != id) - concurrentOK = false; - } - }); - } - for (auto &worker : workers) - worker.join(); - ok = concurrentOK && allocations == 4 && ok; - } - ok = allocations == frees - && attempts == allocations + (injectFailures ? 2 : 0) && ok; - std::printf("readback pool: attempts=%d allocations=%d frees=%d %s\n", - int(attempts.load()), - int(allocations.load()), - int(frees.load()), - ok ? "PASS" : "FAIL"); - return ok ? 0 : 1; -} diff --git a/devices/rtx/apps/tests/api/TestPreparationQueue.cpp b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp index 83c53bb03..f4bd6bc3d 100644 --- a/devices/rtx/apps/tests/api/TestPreparationQueue.cpp +++ b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp @@ -41,8 +41,7 @@ struct Item { explicit Item(int &destroyed); ~Item(); - void completePreparation(); - void markPreparationCollected() noexcept; + void publish(); int &destroyed; bool queued{true}; bool failPublication{false}; @@ -56,19 +55,19 @@ Item::~Item() if (onDestroy) onDestroy(); } -void Item::completePreparation() +void Item::publish() { if (failPublication) throw std::bad_alloc(); ++publications; } -void Item::markPreparationCollected() noexcept -{ - queued = false; -} using Queue = visrtx::PreparationQueue>; -bool finishFailure(bool retry) +auto retire = [](Item *item) noexcept { item->queued = false; }; + +// Batch work that throws before touching any object, like a descriptor +// reserve. Owners must survive, unwind must see them all, nothing is retired. +bool runFailure(bool retry) { int destroyed = 0; { @@ -77,58 +76,46 @@ bool finishFailure(bool retry) for (int i = 0; i < 2; ++i) { auto item = std::make_shared(destroyed); deferred.push_back(item.get()); - queue.enqueue( - std::move(item)); // Queue is the only owner, like an orphan geometry. + queue.enqueue(std::move(item)); // The queue is the only owner. } bool threw = false; + int unwound = 0; try { - queue.collect([&](Item *) { - // SmallGeometryBatch's descriptor reserve can throw before consuming - // the raw deferred-job list. Test the same ownership boundary directly, - // without routing a host exception through ANARI's fatal C API handler. - throw std::bad_alloc(); - }); + queue.collect([&](Item *) { throw std::bad_alloc(); }, + retire, + [&] { + if (queue.collecting()) + queue.forEach([&](Item *) { ++unwound; }); + }); } catch (const std::bad_alloc &) { threw = true; } - if (!threw || destroyed || queue.empty() || queue.collecting()) - return false; // Never dereference the raw jobs if ownership was lost. + if (!threw || unwound != 2 || destroyed || queue.size() != 2 + || queue.collecting()) + return false; for (auto *item : deferred) if (!item->queued || item->publications) return false; if (retry) { bool refusedReentry = false; - if (!queue.collect([&](Item *) { - refusedReentry = !queue.collect([](Item *) {}); - for (auto *item : deferred) - if (!item->queued) - throw std::bad_alloc(); - deferred.clear(); // Deferred submission and completion succeeded. - }) - || !refusedReentry || !queue.empty() || queue.collecting() - || destroyed != 2) + bool unwoundAgain = false; + if (!queue.collect( + [&](Item *) { + refusedReentry = !queue.collect([](Item *) {}, retire, [] {}); + queue.forEach([](Item *item) { item->publish(); }); + }, + retire, + [&] { unwoundAgain = true; }) + || !refusedReentry || unwoundAgain || !queue.empty() + || queue.collecting() || destroyed != 2) return false; } } return destroyed == 2; // Also covers destruction after an unretried failure. } -bool retirementReentry() -{ - int destroyed = 0; - Queue queue; - bool safe = false; - auto item = std::make_shared(destroyed); - item->onDestroy = [&] { - int visible = 0; - queue.forEach([&](Item *) { ++visible; }); - safe = queue.empty() && queue.collecting() && visible == 0 - && !queue.collect([](Item *) {}); - }; - queue.enqueue(std::move(item)); - return queue.collect([](Item *) {}) && safe && destroyed == 1; -} - +// A later object's publication throws after an earlier one published. Both +// stay queued and unretired; a retry publishes both and retires both. bool publicationFailure() { int destroyed = 0; @@ -138,33 +125,80 @@ bool publicationFailure() second->failPublication = true; queue.enqueue(first); queue.enqueue(second); - int drains = 0; + auto publishAll = [&](Item *) { + queue.forEach([](Item *item) { item->publish(); }); + }; bool threw = false; try { - queue.collect([&](Item *) { ++drains; }); + queue.collect(publishAll, retire, [] {}); } catch (const std::bad_alloc &) { threw = true; } - bool ok = threw && drains == 1 && !queue.empty() && !queue.collecting() - && first->queued && second->queued && first->publications == 1 + bool ok = threw && queue.size() == 2 && !queue.collecting() && first->queued + && second->queued && first->publications == 1 && second->publications == 0; second->failPublication = false; - ok = queue.collect([&](Item *) { ++drains; }) && ok; - ok = drains == 2 && queue.empty() && !first->queued && !second->queued + ok = queue.collect(publishAll, retire, [] {}) && ok; + ok = queue.empty() && !first->queued && !second->queued && first->publications == 2 && second->publications == 1 && ok; - ok = queue.collect([&](Item *) { ++drains; }) && drains == 2 && ok; + ok = queue.collect(publishAll, retire, [] {}) && first->publications == 2 + && ok; first.reset(); second.reset(); return destroyed == 2 && ok; } + +// Retirement sees the object still queued. The last owner is released after +// membership is gone but while the queue is still collecting, so a destructor +// can neither see it nor collect again. +bool retirementReentry() +{ + int destroyed = 0; + Queue queue; + bool safe = false; + auto item = std::make_shared(destroyed); + Item *raw = item.get(); + item->onDestroy = [&] { + int visible = 0; + queue.forEach([&](Item *) { ++visible; }); + safe = queue.empty() && queue.collecting() && visible == 0 + && !queue.collect([](Item *) {}, retire, [] {}); + }; + bool retiredBeforeRelease = false; + queue.enqueue(std::move(item)); + const bool collected = queue.collect([](Item *) {}, + [&](Item *object) noexcept { + retiredBeforeRelease = object == raw && !destroyed && queue.size() == 1; + }, + [] {}); + return collected && retiredBeforeRelease && safe && destroyed == 1 + && !queue.collecting(); +} + +// Positions index the queue in enqueue order and restart after a collection; +// run() receives the oldest object. +bool positionsRestartAfterCollection() +{ + int destroyed = 0; + Queue queue; + auto oldest = std::make_shared(destroyed); + bool ok = queue.enqueue(oldest) == 0 + && queue.enqueue(std::make_shared(destroyed)) == 1; + Item *first = nullptr; + ok = queue.collect([&](Item *item) { first = item; }, retire, [] {}) && ok; + ok = first == oldest.get() && ok; + ok = queue.enqueue(std::make_shared(destroyed)) == 0 && ok; + return ok; +} } // namespace int main() { - bool ok = finishFailure(true); - ok = finishFailure(false) && ok; + bool ok = runFailure(true); + ok = runFailure(false) && ok; ok = publicationFailure() && ok; ok = retirementReentry() && ok; + ok = positionsRestartAfterCollection() && ok; std::printf( "preparation queue exception ownership: %s\n", ok ? "PASS" : "FAIL"); return ok ? 0 : 1; diff --git a/devices/rtx/apps/tests/api/TestPreparationResults.cpp b/devices/rtx/apps/tests/api/TestPreparationResults.cpp new file mode 100644 index 000000000..e7c1f6246 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationResults.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "../../../device/geometry/PreparationResults.h" + +namespace { +bool failDevice = false; +bool failHost = false; + +template +T next(const char *name) +{ + auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!function) + std::abort(); + return function; +} + +using visrtx::GeometryResults; +using visrtx::PreparationResults; + +// Writes one geometry's results as a kernel would. +bool write(PreparationResults &results, + size_t position, + float value, + cudaStream_t stream) +{ + const GeometryResults written{ + {value, uint32_t(position)}, {-value, uint32_t(position) + 1}}; + return cudaMemcpyAsync(results.device(position), + &written, + sizeof(written), + cudaMemcpyHostToDevice, + stream) + == cudaSuccess + && cudaStreamSynchronize(stream) == cudaSuccess; +} + +bool holds(const PreparationResults &results, size_t position, float value) +{ + const auto &read = results.host(position); + return read.bounds.value == value && read.bounds.invalid == uint32_t(position) + && read.area.value == -value + && read.area.invalid == uint32_t(position) + 1; +} + +// Reads back and waits, as finishGeometryPreparation() does. +bool readBackAndWait( + PreparationResults &results, size_t count, cudaStream_t stream) +{ + return results.readback(count, stream) == cudaSuccess + && cudaStreamSynchronize(stream) == cudaSuccess; +} +} // namespace + +// Real failed allocations, so CUDA last-error state is set as in production. +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (failDevice) { + failDevice = false; + *ptr = nullptr; + return next("cudaMalloc")(ptr, size_t(-1)); + } + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) +{ + if (failHost) { + failHost = false; + *ptr = nullptr; + return next("cudaMallocHost")(ptr, size_t(-1)); + } + return next("cudaMallocHost")(ptr, bytes); +} + +int main() +{ + constexpr size_t INITIAL = PreparationResults::MIN_CAPACITY; + cudaStream_t stream{}; + if (cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) != cudaSuccess) + return 1; + bool ok = true; + { + PreparationResults results; + + // Nothing reserved or written: readback transfers nothing. + ok = readBackAndWait(results, 1, stream) && ok; + + // A failed first allocation of either side is reported, leaves no stale + // error, and retries. + for (bool *fail : {&failHost, &failDevice}) { + *fail = true; + ok = results.reserve(1, stream) != cudaSuccess && ok; + ok = cudaGetLastError() == cudaSuccess && ok; + } + ok = results.reserve(1, stream) == cudaSuccess && ok; + + ok = write(results, 0, 1.f, stream) && ok; + ok = readBackAndWait(results, 1, stream) && holds(results, 0, 1.f) && ok; + + // Failed growth keeps the existing storage and its results. + ok = write(results, INITIAL - 1, 2.f, stream) && ok; + for (bool *fail : {&failHost, &failDevice}) { + *fail = true; + ok = results.reserve(INITIAL + 1, stream) != cudaSuccess && ok; + ok = cudaGetLastError() == cudaSuccess && ok; + } + ok = readBackAndWait(results, INITIAL, stream) && holds(results, 0, 1.f) + && holds(results, INITIAL - 1, 2.f) && ok; + + // Growth keeps device results written before it, including at the last + // position of the old capacity; never-written positions read back zero. + ok = write(results, 0, 3.f, stream) && ok; + ok = results.reserve(INITIAL + 1, stream) == cudaSuccess && ok; + ok = write(results, INITIAL, 4.f, stream) && ok; + ok = readBackAndWait(results, INITIAL + 1, stream) && ok; + ok = holds(results, 0, 3.f) && holds(results, INITIAL - 1, 2.f) + && holds(results, INITIAL, 4.f) && ok; + const auto &unwritten = results.host(1); + ok = unwritten.bounds.value == 0.f && unwritten.bounds.invalid == 0 + && unwritten.area.value == 0.f && unwritten.area.invalid == 0 && ok; + + // A rewrite after a readback reaches the host on the next readback, which + // also transfers the untouched positions again. + ok = write(results, 0, 5.f, stream) && ok; + ok = readBackAndWait(results, INITIAL + 1, stream) && ok; + ok = holds(results, 0, 5.f) && holds(results, INITIAL, 4.f) && ok; + + // Readback is limited to positions that have storage. + ok = write(results, 0, 6.f, stream) && ok; + ok = readBackAndWait(results, 4 * INITIAL, stream) && holds(results, 0, 6.f) + && ok; + } + cudaStreamDestroy(stream); + std::printf("preparation results %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestStreamRetirement.cpp b/devices/rtx/apps/tests/api/TestStreamRetirement.cpp deleted file mode 100644 index 5e82613ed..000000000 --- a/devices/rtx/apps/tests/api/TestStreamRetirement.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "../../../device/utility/StreamRetirement.h" - -namespace { -cudaStream_t tracked{}; -std::atomic waits{0}; -std::atomic failNext{false}; -std::atomic released{false}; -std::atomic returned{false}; -std::mutex mutex; -std::condition_variable condition; -void CUDART_CB block(void *) -{ - while (!released.load()) - std::this_thread::yield(); -} -} // namespace - -extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) -{ - if (stream == tracked) { - { - std::lock_guard lock(mutex); - ++waits; - } - condition.notify_all(); - } - auto real = reinterpret_cast( - dlsym(RTLD_NEXT, "cudaStreamSynchronize")); - if (!real) - std::abort(); - const auto error = real(stream); - if (stream == tracked && failNext.exchange(false)) - return cudaErrorUnknown; - return error; -} - -int main() -{ - if (cudaStreamCreateWithFlags(&tracked, cudaStreamNonBlocking) != cudaSuccess) - return 1; - visrtx::StreamRetirement retirement; - retirement.initialize(tracked); - bool ok = !retirement.isRetired(); - ok = retirement.retire() == cudaSuccess && waits == 1 - && retirement.isRetired() && ok; - for (int i = 0; i < 64; ++i) - ok = retirement.retire() == cudaSuccess && waits == 1 && ok; - - int *device = nullptr; - if (cudaMalloc(reinterpret_cast(&device), sizeof(int)) - != cudaSuccess) - return 1; - retirement.invalidate(); - ok = !retirement.isRetired() && ok; - ok = cudaLaunchHostFunc(tracked, block, nullptr) == cudaSuccess && ok; - ok = cudaMemsetAsync(device, 0x2a, sizeof(int), tracked) == cudaSuccess && ok; - int gpu = 0; - cudaGetDevice(&gpu); - cudaError_t completion = cudaErrorUnknown; - std::thread waiter([&] { - cudaSetDevice(gpu); - completion = retirement.retire(); - { - std::lock_guard lock(mutex); - returned = true; - } - condition.notify_all(); - }); - { - std::unique_lock lock(mutex); - const bool entered = condition.wait_for(lock, std::chrono::seconds(5), [] { - return waits >= 2 || returned.load(); - }); - ok = entered && waits == 2 && !returned && ok; - // A submission announced during the wait must not inherit its certificate. - retirement.invalidate(); - released = true; - } - waiter.join(); - ok = completion == cudaSuccess && !retirement.isRetired() && ok; - int result = 0; - ok = cudaMemcpy(&result, device, sizeof(int), cudaMemcpyDeviceToHost) - == cudaSuccess - && result == 0x2a2a2a2a && ok; - ok = retirement.retire() == cudaSuccess && waits == 3 - && retirement.isRetired() && ok; - ok = retirement.retire() == cudaSuccess && waits == 3 && ok; - - retirement.invalidate(); - failNext = true; - ok = retirement.retire() == cudaErrorUnknown && waits == 4 - && !retirement.isRetired() && ok; - ok = retirement.retire() == cudaSuccess && waits == 5 - && retirement.isRetired() && ok; - ok = retirement.retire() == cudaSuccess && waits == 5 && ok; - cudaFree(device); - cudaStreamDestroy(tracked); - std::printf( - "stream retirement waits=%d %s\n", int(waits), ok ? "PASS" : "FAIL"); - return ok ? 0 : 1; -} diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 661459180..131f5d6c7 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -137,6 +137,7 @@ set(SOURCES frame/Frame.cu geometry/ComputeTangent.cu + geometry/PreparationResults.cpp geometry/Preprocessing.cu geometry/Cone.cpp geometry/Curve.cpp diff --git a/devices/rtx/device/RegisteredObject.h b/devices/rtx/device/RegisteredObject.h index 34b106cc8..e623795a7 100644 --- a/devices/rtx/device/RegisteredObject.h +++ b/devices/rtx/device/RegisteredObject.h @@ -46,7 +46,9 @@ struct RegisteredObject : public Object virtual ~RegisteredObject(); void finalize() override; - void upload(); + // Publishes gpuData() to the registry slot. Subtypes may override to defer + // publication until their data is ready; virtual so finalize() honors that. + virtual void upload(); DeviceObjectIndex index() const; diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 81bea0e8a..b0eedcc28 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -763,7 +763,6 @@ DeviceInitStatus VisRTXDevice::initOptix() OPTIX_CHECK_RETURN_VALUE(optixInit(), DeviceInitStatus::FAILURE); setCUDADevice(); cudaStreamCreate(&state.stream); - state.renderRetirement.initialize(state.stream); cudaGetDeviceProperties(&state.deviceProps, m_gpuID); reportMessage(ANARI_SEVERITY_DEBUG, diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 9002a3754..b45fff5be 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -203,7 +203,7 @@ void Array::privatize() this->useCount(helium::RefType::INTERNAL)); // Existing frames may still read the shared pointer. The application may // free it as soon as this last PUBLIC release returns. - auto completion = state.renderRetirement.retire(); + auto completion = state.retireRenderConsumers(); // Deferred preprocessing can still read this external allocation even // when no frame is in flight. Retain it through that stream's completion. if (completion == cudaSuccess && state.hasPendingGeometryPreparations()) diff --git a/devices/rtx/device/frame/Denoiser.cu b/devices/rtx/device/frame/Denoiser.cu index 680abc4ba..cb8a4b401 100644 --- a/devices/rtx/device/frame/Denoiser.cu +++ b/devices/rtx/device/frame/Denoiser.cu @@ -92,7 +92,6 @@ void Denoiser::setup(uvec2 size, m_averageColor.reserve(3 * sizeof(float)); // Setup must be sized for the largest padded tile the tiled invoke feeds. - state.renderRetirement.invalidate(); OPTIX_CHECK(optixDenoiserSetup(m_denoiser, state.stream, m_tileW + 2 * m_overlap, @@ -144,7 +143,6 @@ void Denoiser::cleanup() void Denoiser::launch() { auto &state = *deviceState(); - state.renderRetirement.invalidate(); // Tiled invoke normalizes each tile independently unless handed whole-frame // HDR exposure values. Compute them over the full input and share them so @@ -187,7 +185,6 @@ void Denoiser::convertOutput() if (m_format == ANARI_FLOAT32_VEC4) return; auto &state = *deviceState(); - state.renderRetirement.invalidate(); instrument::rangePush("denoiser transform pixels"); auto numPixels = size_t(m_layer.output.width) * size_t(m_layer.output.height); auto begin = thrust::device_ptr((vec4 *)m_pixelBuffer->dataDevice()); diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index ced277b32..db794e1da 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -431,7 +431,6 @@ Frame::Frame(DeviceGlobalState *d) : helium::BaseFrame(d), m_denoiser(d) cudaEventCreate(&m_eventStart); cudaEventCreate(&m_eventEnd); - d->renderRetirement.invalidate(); cudaEventRecord(m_eventStart, d->stream); cudaEventRecord(m_eventEnd, d->stream); } @@ -713,7 +712,6 @@ void Frame::renderFrame() if (!m_nextFrameReset && sampleLimit > 0 && hd.fb.frameID >= sampleLimit) return; - state.renderRetirement.invalidate(); cudaEventRecord(m_eventStart, state.stream); m_renderer->populateFrameData(hd); @@ -1102,7 +1100,6 @@ void Frame::resolveVec3Buffer(const DeviceBuffer &accum, const uint32_t nPixels = uint32_t(numPixels()); const uint32_t blockSize = 256; const uint32_t gridSize = (nPixels + blockSize - 1) / blockSize; - state.renderRetirement.invalidate(); resolveVec3Channel<<>>( accum.ptrAs(), out.dataDevice(), diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index ae1ad6881..90e41e532 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -76,24 +76,17 @@ void Cone::commitParameters() PrimitiveInput Cone::primitiveInput() const { - PrimitiveInput input; - input.type = GeometryType::CONE; - input.count = m_index ? m_index->size() : m_vertex->size() / 2; - input.vertices = m_vertex->beginAs(AddressSpace::GPU); - input.indices = - m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + ConeInput input{}; + input.segments = segmentInput( + *m_vertex, m_index.get(), m_vertexCaps.get(), m_defaultCapFlags); input.radii = m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; - input.caps = m_vertexCaps ? m_vertexCaps->beginAs(AddressSpace::GPU) - : nullptr; - input.radius = 0.f; - input.capFlags = m_defaultCapFlags; - return input; + return {segmentCount(*m_vertex, m_index.get()), input}; } void Cone::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, @@ -111,7 +104,7 @@ void Cone::finalize() "finalizing %s cone geometry", m_index ? "indexed" : "soup"); - if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs, m_epsilonScale)) + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); @@ -121,10 +114,8 @@ void Cone::finalize() m_areaDataValid = false; if (m_areaDataWanted) buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.reset(); - } + else + m_preprocessing.releaseAreas(); if (!preparationFailed()) upload(); @@ -132,8 +123,7 @@ void Cone::finalize() void Cone::buildAreaData() { - m_areaDataValid = - m_preprocessing.areas(this, primitiveInput(), m_primAreaCdf, m_totalArea); + m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); } bool Cone::isAreaSamplingSupported() const @@ -153,7 +143,7 @@ void Cone::ensureAreaData() float Cone::totalArea() const { - return m_totalArea; + return m_preprocessing.totalArea(); } bool Cone::isValid() const @@ -196,9 +186,9 @@ GeometryGPUData Cone::gpuData() const populateAttributeDataSet(m_vertexAttributes, cone.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cone.primAreaCdf = m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; - cone.numPrimitives = m_totalArea > 0.f ? uint32_t(primitiveInput().count) : 0; - cone.totalArea = m_totalArea; + cone.primAreaCdf = m_preprocessing.areaCdf(); + cone.numPrimitives = cone.primAreaCdf ? uint32_t(primitiveInput().count) : 0; + cone.totalArea = m_preprocessing.totalArea(); return retval; } diff --git a/devices/rtx/device/geometry/Cone.h b/devices/rtx/device/geometry/Cone.h index 4a2b9a146..e808e5692 100644 --- a/devices/rtx/device/geometry/Cone.h +++ b/devices/rtx/device/geometry/Cone.h @@ -75,8 +75,6 @@ struct Cone : public Geometry // Geometry Light sampling data, built lazily by ensureAreaData(); see // Triangle. - DeviceBuffer m_primAreaCdf; - float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; }; diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index 6972d8cbf..12c85711d 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -56,7 +56,7 @@ void Curve::commitParameters() void Curve::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index d183ef07f..2d0b1c559 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -78,24 +78,18 @@ void Cylinder::commitParameters() PrimitiveInput Cylinder::primitiveInput() const { - PrimitiveInput input; - input.type = GeometryType::CYLINDER; - input.count = m_index ? m_index->size() : m_vertex->size() / 2; - input.vertices = m_vertex->beginAs(AddressSpace::GPU); - input.indices = - m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + CylinderInput input{}; + input.segments = segmentInput( + *m_vertex, m_index.get(), m_vertexCaps.get(), m_defaultCapFlags); input.radii = m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; - input.caps = m_vertexCaps ? m_vertexCaps->beginAs(AddressSpace::GPU) - : nullptr; input.radius = m_globalRadius; - input.capFlags = m_defaultCapFlags; - return input; + return {segmentCount(*m_vertex, m_index.get()), input}; } void Cylinder::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, @@ -107,7 +101,7 @@ void Cylinder::finalize() "finalizing %s cylinder geometry", m_index ? "indexed" : "soup"); - if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs, m_epsilonScale)) + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); @@ -117,10 +111,8 @@ void Cylinder::finalize() m_areaDataValid = false; if (m_areaDataWanted) buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.reset(); - } + else + m_preprocessing.releaseAreas(); if (!preparationFailed()) upload(); @@ -128,8 +120,7 @@ void Cylinder::finalize() void Cylinder::buildAreaData() { - m_areaDataValid = - m_preprocessing.areas(this, primitiveInput(), m_primAreaCdf, m_totalArea); + m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); } bool Cylinder::isAreaSamplingSupported() const @@ -149,7 +140,7 @@ void Cylinder::ensureAreaData() float Cylinder::totalArea() const { - return m_totalArea; + return m_preprocessing.totalArea(); } bool Cylinder::isValid() const @@ -190,11 +181,10 @@ GeometryGPUData Cylinder::gpuData() const populateAttributeDataSet(m_vertexAttributes, cylinder.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cylinder.primAreaCdf = - m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; + cylinder.primAreaCdf = m_preprocessing.areaCdf(); cylinder.numPrimitives = - m_totalArea > 0.f ? uint32_t(primitiveInput().count) : 0; - cylinder.totalArea = m_totalArea; + cylinder.primAreaCdf ? uint32_t(primitiveInput().count) : 0; + cylinder.totalArea = m_preprocessing.totalArea(); return retval; } diff --git a/devices/rtx/device/geometry/Cylinder.h b/devices/rtx/device/geometry/Cylinder.h index eb1aa190d..6ac715907 100644 --- a/devices/rtx/device/geometry/Cylinder.h +++ b/devices/rtx/device/geometry/Cylinder.h @@ -77,8 +77,6 @@ struct Cylinder : public Geometry // Geometry Light sampling data, built lazily by ensureAreaData(); see // Triangle. - DeviceBuffer m_primAreaCdf; - float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; }; diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 482051954..0805b1acf 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -114,19 +114,24 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { - if (m_inputUploadsQueued) + if (m_inputBatch != InputBatch::None) deviceState()->collectGeometryInputUploads(); - m_inputUploadFailed = false; - if (m_preparationQueued) + // A parameter commit retries every failure. + if (m_inputBatch == InputBatch::Failed) + m_inputBatch = InputBatch::Queued; + if (retryBlocked()) + m_preparationState = PreparationState::Failed; + if (m_preparationPosition) deviceState()->collectGeometryPreparations(); // Array observers can re-finalize without a parameter commit, but parameter // replacement can release the last reference to an aliased device array. // Complete earlier consumers before subclasses replace those references. const bool retain = canRetainPreparationInputs(); - m_inputRetirementFailed = !retain - && !checkPreparation(this, - deviceState()->renderRetirement.retire(), - "retiring previous geometry inputs"); + if (!retain + && !failPreparationOnError(this, + deviceState()->retireRenderConsumers(), + "retiring previous geometry inputs")) + m_preparationState = PreparationState::RetirementFailed; commitAttributes("primitive.", m_primitiveAttributes); auto getUniformAttribute = @@ -144,14 +149,14 @@ void Geometry::commitParameters() m_uniformAttributes.attribute3 = getUniformAttribute("attribute3"); m_uniformAttributes.color = getUniformAttribute("color"); m_primitiveId = getParamObject("primitive.id"); - if (!retain && !m_inputRetirementFailed) + if (!retain && m_preparationState != PreparationState::RetirementFailed) stageInputUploads(); } void Geometry::markFinalized() { Object::markFinalized(); - if (!m_preparationPreserved) + if (m_preparationState != PreparationState::Reused) deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); } @@ -170,7 +175,8 @@ bool Geometry::PreparationParameter::operator==( bool Geometry::canRetainPreparationInputs() const { - if (!m_hasPreparedData || preparationFailed() || m_inputRetirementFailed + if ((m_preparationState != PreparationState::Prepared + && m_preparationState != PreparationState::Reused) || m_preparationParameterNames.empty()) return false; @@ -203,36 +209,38 @@ bool Geometry::canRetainPreparationInputs() const return present == m_preparedParameters.size(); } -void Geometry::deferPreparation() +size_t Geometry::deferPreparation() { - if (!m_preparationQueued) { - deviceState()->enqueueGeometryPreparation(this); - m_preparationQueued = true; - } + if (!m_preparationPosition) + m_preparationPosition = deviceState()->enqueueGeometryPreparation(this); + return *m_preparationPosition; } void Geometry::completePreparation() { - if (!m_preprocessing.complete(this)) { - m_hasPreparedData = false; - return; - } - upload(); + // complete() fails the geometry whenever it returns false. + if (m_preprocessing.complete(this)) + upload(); } void Geometry::markPreparationCollected() noexcept { - m_preparationQueued = false; + m_preparationPosition.reset(); } void Geometry::upload() { - if (m_preprocessing.pending()) { + if (m_preprocessing.status() == Preprocessing::Status::Pending) { deferPreparation(); return; } RegisteredObject::upload(); - m_hasPreparedData = !preparationFailed() && isValid(); + if (preparationFailed()) + return; + if (!isValid()) + m_preparationState = PreparationState::Unprepared; + else if (m_preparationState != PreparationState::Reused) + m_preparationState = PreparationState::Prepared; } void Geometry::declarePreparationParameters( @@ -268,7 +276,7 @@ void Geometry::stageInputUploads() if (m_inputUploads.empty()) return; deviceState()->enqueueGeometryInputUploads(this); - m_inputUploadsQueued = true; + m_inputBatch = InputBatch::Queued; } void Geometry::retirePreparationSnapshot() @@ -277,21 +285,20 @@ void Geometry::retirePreparationSnapshot() // Discard obsolete references before allocating a multi-geometry cohort. // Until beginPreparation establishes the new generation, old GPU records // must not be usable if a host exception aborts finalization. - m_hasPreparedData = false; - m_preparationFailed = true; + markPreparationFailed(); m_preparedParameters.clear(); } void Geometry::submitInputUploads() { - if (m_inputUploadFailed) + if (m_inputBatch == InputBatch::Failed) return; auto &state = *deviceState(); auto fail = [&](cudaError_t error, const char *operation) { if (error == cudaSuccess) return false; failInputUploads(); - checkPreparation(this, error, operation); + failPreparation(this, error, operation); return true; }; for (auto &upload : m_inputUploads) { @@ -306,18 +313,19 @@ void Geometry::submitInputUploads() void Geometry::failInputUploads() { - m_inputUploadFailed = true; - m_preparationFailed = true; - m_hasPreparedData = false; + m_inputBatch = InputBatch::Failed; + if (m_preparationState != PreparationState::RetirementFailed) + m_preparationState = PreparationState::InputUploadFailed; } -void Geometry::completeInputUploads() +void Geometry::completeInputUploads() noexcept { - m_inputUploadsQueued = false; for (const auto &upload : m_inputUploads) if (!upload.submitted) failInputUploads(); - if (m_inputUploadFailed) + const bool failed = m_inputBatch == InputBatch::Failed; + m_inputBatch = InputBatch::None; + if (failed) m_failedInputUpdate = lastUpdated(); else { for (const auto &upload : m_inputUploads) { @@ -330,21 +338,23 @@ void Geometry::completeInputUploads() m_inputUploads.clear(); } -bool Geometry::beginPreparation() +Geometry::PreparationStart Geometry::beginPreparation() { if (!deviceState()->collectGeometryInputUploads()) - return false; + return PreparationStart::Blocked; // Observer-only finalization can arrive before a prior submission is // collected. - if (m_preparationQueued) + if (m_preparationPosition) deviceState()->collectGeometryPreparations(); - m_preparationPreserved = false; + if (m_preparationState == PreparationState::Reused) + m_preparationState = PreparationState::Prepared; // A later observer update is a new generation too; it may retry a failed // input batch without requiring a parameter commit on the geometry. - if (m_inputUploadFailed && lastUpdated() > m_failedInputUpdate) - m_inputUploadFailed = false; - if (m_inputRetirementFailed || m_inputUploadFailed) - return false; + if (m_preparationState == PreparationState::InputUploadFailed + && lastUpdated() > m_failedInputUpdate) + m_preparationState = PreparationState::Failed; + if (retryBlocked()) + return PreparationStart::Blocked; std::vector current; if (!m_preparationParameterNames.empty()) { @@ -381,58 +391,64 @@ bool Geometry::beginPreparation() append(name); if (!pendingUploads.empty()) { + // No commit captured these: an observer-only update, or an array + // modified after its batch was submitted. Upload them the same way, as + // a batch of this geometry alone. Its failure is this finalize's, so + // the next one retries. + for (const auto &[index, array] : pendingUploads) + m_inputUploads.push_back({array, array->lastDataModified(), false}); auto &state = *deviceState(); - if (!checkPreparation(this, - state.preparation.waitFor(state.stream), - "previous array consumers")) - return false; - for (const auto &[index, array] : pendingUploads) { - if (!checkPreparation(this, - array->enqueueUpload(state.preparation.stream()), - "geometry array upload")) - return false; + state.enqueueGeometryInputUploads(this); + m_inputBatch = InputBatch::Queued; + state.collectGeometryInputUploads(); + if (retryBlocked()) { + m_preparationState = PreparationState::Failed; + return PreparationStart::Blocked; } - if (!checkPreparation(this, - state.finishGeometryPreparation(), - "geometry array upload completion")) - return false; - // Never mark a partial/failed batch uploaded: a later commit must retry. - for (const auto &[index, array] : pendingUploads) { - array->markDataUploaded(); + for (const auto &[index, array] : pendingUploads) current[index].devicePointer = array->dataGPU(); - } } // Observer-only updates always take the preparation path. A geometry-wide // attribute edit coalesced with an array change cannot hide that change; // the versions/pointers above still invalidate preparation reuse. - if (m_hasPreparedData && !preparationFailed() && isValid() + if (m_preparationState == PreparationState::Prepared && isValid() && lastCommitted() > lastFinalized() && current == m_preparedParameters) { - m_preparationPreserved = true; + m_preparationState = PreparationState::Reused; upload(); - return false; + return PreparationStart::Reused; } } m_preparedParameters = std::move(current); - m_hasPreparedData = false; - m_preparationFailed = false; + m_preparationState = PreparationState::Unprepared; // Full preparation can overwrite derived buffers read by earlier frames. // Keep that dependency on the GPU; parameter-reference retirement above // still requires a host wait before releasing old application storage. - return checkPreparation(this, - deviceState()->preparation.waitFor(deviceState()->stream), - "previous geometry consumers"); + return failPreparationOnError(this, + deviceState()->preparation.waitFor(deviceState()->stream), + "previous geometry consumers") + ? PreparationStart::Prepare + : PreparationStart::Blocked; } bool Geometry::preparationFailed() const { - return m_preparationFailed; + return m_preparationState == PreparationState::Failed + || m_preparationState == PreparationState::InputUploadFailed + || m_preparationState == PreparationState::RetirementFailed; +} + +bool Geometry::retryBlocked() const +{ + return m_preparationState == PreparationState::InputUploadFailed + || m_preparationState == PreparationState::RetirementFailed; } -void Geometry::setPreparationFailed(bool failed) +void Geometry::markPreparationFailed() { - m_preparationFailed = failed; + if (!preparationFailed()) + m_preparationState = PreparationState::Failed; } void Geometry::ensureAreaData() {} @@ -460,7 +476,7 @@ GeometryGPUData Geometry::gpuData() const populateAttributeDataSet(m_primitiveAttributes, retval.attr); retval.primitiveId = (const uint32_t *)(m_primitiveId ? m_primitiveId->dataGPU() : nullptr); - retval.epsilonScale = m_epsilonScale; + retval.epsilonScale = m_preprocessing.epsilonScale(); return retval; } diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index 0ed40d6e9..fe8f64695 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -76,13 +76,15 @@ struct Geometry : public RegisteredObject void commitParameters() override; void markFinalized() override; - void upload(); - void deferPreparation(); + // Defers registry publication while preprocessing results are pending. + void upload() override; + // Queues the geometry for collection once; returns its queue position. + size_t deferPreparation(); void completePreparation(); void markPreparationCollected() noexcept; void retirePreparationSnapshot(); void submitInputUploads(); - void completeInputUploads(); + void completeInputUploads() noexcept; void failInputUploads(); virtual void populateBuildInput(OptixBuildInput &) const = 0; @@ -95,8 +97,10 @@ struct Geometry : public RegisteredObject virtual void ensureAreaData(); virtual float totalArea() const; + // True in any of the failed preparation states below. bool preparationFailed() const; - void setPreparationFailed(bool failed); + // Fails the current generation; keeps a more specific failed state. + void markPreparationFailed(); protected: // Declare once in the subtype constructor, before the first commit. List @@ -104,9 +108,15 @@ struct Geometry : public RegisteredObject // primitive and vertex arrays. These inputs determine preparation reuse. void declarePreparationParameters( std::initializer_list parameters); - // Returns false after preparation reuse and registry publication, or if - // preparation cannot start. - bool beginPreparation(); + + enum class PreparationStart + { + Prepare, // The subtype prepares and publishes the new generation. + Reused, // Inputs are unchanged; the registry is already republished. + Blocked, // Failed, an earlier failure awaits retry, or an input + // collection is in progress. The subtype returns. + }; + PreparationStart beginPreparation(); GeometryGPUData gpuData() const override = 0; void commitAttributes(const char *prefix, GeometryAttributes &attrs); @@ -116,9 +126,6 @@ struct Geometry : public RegisteredObject GeometryAttributes m_primitiveAttributes; UniformAttributes m_uniformAttributes; helium::IntrusivePtr m_primitiveId; - // Set by analytic-primitive subtypes in finalize(); see - // GeometryGPUData::epsilonScale. - float m_epsilonScale{0.f}; Preprocessing m_preprocessing; private: @@ -143,16 +150,79 @@ struct Geometry : public RegisteredObject bool submitted{false}; }; std::vector m_inputUploads; - bool m_inputUploadsQueued{false}; - bool m_inputUploadFailed{false}; - helium::TimeStamp m_failedInputUpdate{0}; std::vector m_preparedParameters; std::vector m_preparationParameterNames; - bool m_hasPreparedData{false}; - bool m_preparationPreserved{false}; - bool m_preparationFailed{false}; - bool m_inputRetirementFailed{false}; - bool m_preparationQueued{false}; + + // Preparation state of the current generation. + // + // Unprepared Nothing published for the current inputs: initial, + // preparing, or published while !isValid(). + // Prepared Published; a commit may retain its inputs. + // Reused Prepared, and the latest finalize reused it, so + // markFinalized() leaves the BLAS change stamp alone. + // Failed The next finalize retries. + // InputUploadFailed An input upload batch queued by a commit failed. A + // parameter commit, or an observer update newer than + // m_failedInputUpdate, retries. + // RetirementFailed Retiring the previous inputs failed. Only a + // parameter commit retries. + // + // Transitions. An event leaves every state it does not list unchanged. + // + // Event From To + // commitParameters() InputUploadFailed Failed + // RetirementFailed Failed + // then retiring inputs fails any RetirementFailed + // beginPreparation() Reused Prepared + // observer update newer than InputUploadFailed Failed + // m_failedInputUpdate + // inputs unchanged, isValid() Prepared Reused + // full preparation Unprepared Unprepared + // Prepared Unprepared + // Failed Unprepared + // upload(), isValid() Unprepared Prepared + // Prepared Prepared + // Reused Reused + // upload(), !isValid() any not failed Unprepared + // markPreparationFailed() (every any not failed Failed + // CUDA or numeric failure, and + // retirePreparationSnapshot()) + // failInputUploads() any but InputUploadFailed + // RetirementFailed + // beginPreparation(), the batch it InputUploadFailed Failed + // queued itself fails + // + // beginPreparation() returns Blocked in InputUploadFailed and + // RetirementFailed (retryBlocked()). RetirementFailed outranks + // InputUploadFailed: both need a commit, and the commit clears both. Whether + // the queued input batch failed is kept in m_inputBatch, so a batch that + // fails in RetirementFailed still leaves its arrays dirty. + enum class PreparationState + { + Unprepared, + Prepared, + Reused, + Failed, + InputUploadFailed, + RetirementFailed, + }; + PreparationState m_preparationState{PreparationState::Unprepared}; + // lastUpdated() when the input upload batch failed (InputUploadFailed). + helium::TimeStamp m_failedInputUpdate{0}; + + bool retryBlocked() const; + + // Queue membership, independent of the state above. + enum class InputBatch + { + None, // Not queued for input uploads. + Queued, + Failed, // Queued; the batch failed, so submit nothing and mark no array + // uploaded. A commit retries it. + }; + InputBatch m_inputBatch{InputBatch::None}; + // Position in the device's preparation queue while queued. + std::optional m_preparationPosition; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Isosurface.cpp b/devices/rtx/device/geometry/Isosurface.cpp index 0509d1d73..b8960c031 100644 --- a/devices/rtx/device/geometry/Isosurface.cpp +++ b/devices/rtx/device/geometry/Isosurface.cpp @@ -56,7 +56,7 @@ void Isosurface::commitParameters() void Isosurface::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; m_numBricks = 0; m_isovaluesDev = nullptr; @@ -119,7 +119,6 @@ void Isosurface::finalize() // active macrocells, so the BVH culls rays missing the surface while the // in-program DDA still does fine per-cell skipping inside each brick. auto &state = *deviceState(); - state.renderRetirement.invalidate(); m_numBricks = buildIsosurfaceBricks(state.stream, m_field->m_uniformGrid.gpuData(), m_isovaluesDev, diff --git a/devices/rtx/device/geometry/Neural.cpp b/devices/rtx/device/geometry/Neural.cpp index b41c01a89..62c4bf428 100644 --- a/devices/rtx/device/geometry/Neural.cpp +++ b/devices/rtx/device/geometry/Neural.cpp @@ -29,7 +29,7 @@ void Neural::commitParameters() void Neural::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; Geometry::finalize(); m_aabbs.resize(1); diff --git a/devices/rtx/device/geometry/PreparationResults.cpp b/devices/rtx/device/geometry/PreparationResults.cpp new file mode 100644 index 000000000..da76d78d2 --- /dev/null +++ b/devices/rtx/device/geometry/PreparationResults.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "PreparationResults.h" + +#include +#include +#include + +namespace visrtx { +namespace { + +// Returns 0 when `count` geometries cannot be addressed. +size_t grownCapacity(size_t current, size_t count) +{ + constexpr size_t LIMIT = + std::numeric_limits::max() / sizeof(GeometryResults); + if (count > LIMIT) + return 0; + const size_t doubled = current <= LIMIT / 2 ? 2 * current : LIMIT; + return std::max({PreparationResults::MIN_CAPACITY, doubled, count}); +} + +// Returns `error`, or the stream's completion error if `error` is success. +cudaError_t completeStream(cudaError_t error, cudaStream_t stream) +{ + const auto completion = cudaStreamSynchronize(stream); + return error == cudaSuccess ? completion : error; +} + +} // namespace + +void PinnedDeleter::operator()(void *memory) const +{ + cudaFreeHost(memory); +} + +void PreparationResults::DeviceDeleter::operator()(void *memory) const +{ + cudaFree(memory); +} + +const GeometryResults &PreparationResults::host(size_t position) const +{ + assert(position < m_capacity); + return m_host.get()[position]; +} + +cudaError_t PreparationResults::reserve(size_t count, cudaStream_t stream) +{ + if (count <= m_capacity) + return cudaSuccess; + const size_t capacity = grownCapacity(m_capacity, count); + if (capacity == 0) + return cudaErrorInvalidValue; + const size_t bytes = capacity * sizeof(GeometryResults); + void *memory = nullptr; + auto error = cudaMallocHost(&memory, bytes); + std::unique_ptr host( + static_cast(memory)); + memory = nullptr; + if (error == cudaSuccess) + error = cudaMalloc(&memory, bytes); + std::unique_ptr device( + static_cast(memory)); + // Readback transfers every position below the queue length, including ones + // no kernel has written yet: never transfer uninitialized bytes. + if (error == cudaSuccess) + error = cudaMemsetAsync(device.get(), 0, bytes, stream); + if (error == cudaSuccess && m_device) + error = cudaMemcpyAsync(device.get(), + m_device.get(), + m_capacity * sizeof(GeometryResults), + cudaMemcpyDeviceToDevice, + stream); + // Earlier kernels may still write the old device storage, and the copy + // reads it: free neither buffer before the stream completes. The first + // allocation needs no wait; later kernels on `stream` follow its memset. + // Every earlier readback completed in its own finish, and the next one + // transfers the whole queued range, so the old host storage is free to go. + if (device && (m_device || error != cudaSuccess)) + error = completeStream(error, stream); + if (error != cudaSuccess) { + cudaGetLastError(); // A failed growth must not poison a retry. + return error; + } + m_device = std::move(device); + m_host = std::move(host); + m_capacity = capacity; + return cudaSuccess; +} + +GeometryResults *PreparationResults::device(size_t position) +{ + assert(position < m_capacity); + m_unread = true; + return m_device.get() + position; +} + +cudaError_t PreparationResults::readback(size_t count, cudaStream_t stream) +{ + // Positions past the capacity were never written. + count = std::min(count, m_capacity); + if (!m_unread || count == 0) + return cudaSuccess; + m_unread = false; + return cudaMemcpyAsync(m_host.get(), + m_device.get(), + count * sizeof(GeometryResults), + cudaMemcpyDeviceToHost, + stream); +} + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/PreparationResults.h b/devices/rtx/device/geometry/PreparationResults.h new file mode 100644 index 000000000..27b5b2035 --- /dev/null +++ b/devices/rtx/device/geometry/PreparationResults.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include + +namespace visrtx { + +struct PreparationResult +{ + float value; + uint32_t invalid; +}; + +// One geometry's scalar preparation results. +struct GeometryResults +{ + PreparationResult bounds; // Epsilon scale and validity. + PreparationResult area; // Total area; NaN when invalid. +}; + +// Frees pinned host memory from cudaMallocHost(). +struct PinnedDeleter +{ + void operator()(void *memory) const; +}; + +// Scalar preparation results of the queued geometries, indexed by position in +// the device's preparation queue. Kernels write device storage; readback() +// copies the queued range to pinned host storage in one transfer. Device and +// host storage grow together to their high-water size and live until device +// teardown. +struct PreparationResults +{ + // Geometries; the first allocation holds this many. + static constexpr size_t MIN_CAPACITY = 256; + + PreparationResults() = default; + PreparationResults(const PreparationResults &) = delete; + PreparationResults &operator=(const PreparationResults &) = delete; + PreparationResults(PreparationResults &&) = delete; + PreparationResults &operator=(PreparationResults &&) = delete; + + // Valid after a completed readback() covering `position`. + const GeometryResults &host(size_t position) const; + + // Grows storage to hold `count` geometries, keeping earlier device results. + // Growth after the first allocation synchronizes `stream`, the only stream + // that writes results. Readback itself never allocates. + cudaError_t reserve(size_t count, cudaStream_t stream); + // Device results for a reserved position; marks them for the next readback. + GeometryResults *device(size_t position); + // Copies the first `count` geometries' results to the host if any were + // written since the last readback. The caller synchronizes `stream` before + // reading host() and before the next readback. + cudaError_t readback(size_t count, cudaStream_t stream); + + private: + struct DeviceDeleter + { + void operator()(void *memory) const; + }; + std::unique_ptr m_device; + std::unique_ptr m_host; + size_t m_capacity{0}; // Geometries, on both sides. + bool m_unread{false}; // Device results written since the last readback. +}; + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index 2fd5f8980..970979f30 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -33,6 +33,7 @@ #include "Preprocessing.h" #include "gpu/intersectPrimitives.h" +#include #include #include #include @@ -44,47 +45,85 @@ namespace visrtx { namespace { using Result = PreparationResult; -VISRTX_DEVICE double primitiveArea(PrimitiveInput in, size_t i) -{ - double area; - if (in.type == GeometryType::SPHERE) { - const auto *indices = static_cast(in.indices); - const uint32_t v = indices ? indices[i] : uint32_t(i); - const float r = glm::abs(in.radii ? in.radii[v] : in.radius); - area = 4.0 * double(kPi) * double(r) * double(r); - } else if (in.type == GeometryType::CONE - || in.type == GeometryType::CYLINDER) { - const auto *indices = static_cast(in.indices); - const uvec2 c = indices ? indices[i] : uvec2(2 * i, 2 * i + 1); - const bool cone = in.type == GeometryType::CONE; - const double r0 = - double(glm::abs(in.radii ? in.radii[cone ? c.x : i] : in.radius)); - const double r1 = cone ? double(glm::abs(in.radii[c.y])) : r0; - const double len = double(glm::length(in.vertices[c.y] - in.vertices[c.x])); - const bool cap0 = in.caps ? in.caps[c.x] != 0 : in.capFlags & CAP_FIRST; - const bool cap1 = in.caps ? in.caps[c.y] != 0 : in.capFlags & CAP_SECOND; - area = 0.0; - if (len > 0.0 && (cone || r0 > 0.0)) { - area = cone - ? double(kPi) * (r0 + r1) * sqrt(len * len + (r0 - r1) * (r0 - r1)) - : 2.0 * double(kPi) * r0 * len; - if (cap0) - area += double(kPi) * r0 * r0; - if (cap1) - area += double(kPi) * r1 * r1; - } - } else { - const auto *indices = static_cast(in.indices); - const uvec3 t = indices ? indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); - area = 0.5 - * glm::length(glm::cross(in.vertices[t.y] - in.vertices[t.x], - in.vertices[t.z] - in.vertices[t.x])); - } +VISRTX_DEVICE double triangleArea(const TriangleInput &in, size_t i) +{ + const uvec3 t = in.indices ? in.indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); + const vec3 a = in.vertices[t.x], b = in.vertices[t.y], c = in.vertices[t.z]; + return 0.5 * glm::length(glm::cross(b - a, c - a)); +} + +VISRTX_DEVICE double sphereArea(const SphereInput &in, size_t i) +{ + const uint32_t v = in.indices ? in.indices[i] : uint32_t(i); + const double r = glm::abs(in.radii ? in.radii[v] : in.radius); + return 4.0 * double(kPi) * r * r; +} + +VISRTX_DEVICE uvec2 segmentEndpoints(const SegmentInput &in, size_t i) +{ + return in.indices ? in.indices[i] : uvec2(2 * i, 2 * i + 1); +} + +VISRTX_DEVICE double segmentLength(const SegmentInput &in, uvec2 c) +{ + return double(glm::length(in.vertices[c.y] - in.vertices[c.x])); +} + +// Adds the disk areas of a segment's capped ends, of radii r0 and r1, to its +// side area. +VISRTX_DEVICE double addCapAreas( + double side, const SegmentInput &in, uvec2 c, double r0, double r1) +{ + const bool cap0 = in.caps ? in.caps[c.x] != 0 : in.capFlags & CAP_FIRST; + const bool cap1 = in.caps ? in.caps[c.y] != 0 : in.capFlags & CAP_SECOND; + double area = side; + if (cap0) + area += double(kPi) * r0 * r0; + if (cap1) + area += double(kPi) * r1 * r1; return area; } +VISRTX_DEVICE double coneArea(const ConeInput &in, size_t i) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const double r0 = glm::abs(in.radii[c.x]); + const double r1 = glm::abs(in.radii[c.y]); + const double len = segmentLength(in.segments, c); + if (!(len > 0.0)) + return 0.0; + const double slant = sqrt(len * len + (r0 - r1) * (r0 - r1)); + return addCapAreas(double(kPi) * (r0 + r1) * slant, in.segments, c, r0, r1); +} + +VISRTX_DEVICE double cylinderArea(const CylinderInput &in, size_t i) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const double r = glm::abs(in.radii ? in.radii[i] : in.radius); + const double len = segmentLength(in.segments, c); + if (!(len > 0.0 && r > 0.0)) + return 0.0; + return addCapAreas(2.0 * double(kPi) * r * len, in.segments, c, r, r); +} + +VISRTX_DEVICE double primitiveArea(const PrimitiveInput &in, size_t i) +{ + switch (in.type) { + case GeometryType::TRIANGLE: + return triangleArea(in.triangle, i); + case GeometryType::SPHERE: + return sphereArea(in.sphere, i); + case GeometryType::CONE: + return coneArea(in.cone, i); + case GeometryType::CYLINDER: + return cylinderArea(in.cylinder, i); + default: + return NAN; // No area sampling; fails the area validation. + } +} + VISRTX_GLOBAL void primitiveAreas( - PrimitiveInput in, double *areas, Result *result) + const PrimitiveInput in, double *areas, Result *result) { const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; if (i >= in.count) @@ -148,45 +187,37 @@ VISRTX_DEVICE box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) } } -VISRTX_DEVICE Result primitiveBound(PrimitiveInput in, size_t i, box3 &bound) +VISRTX_DEVICE Result sdfBound(const SDFInput &in, size_t i, box3 &bound) { + const SDFPrimitive &g = in.primitives[i]; + box3 b = computeSDFPrimitiveAABB(g); + float padding = in.noiseFactor * glm::max(0.f, g.r0) * 0.1f; + if (g.numNeighbours > 0) { + const float r0 = glm::max(0.f, g.r0); + const float r1 = glm::max(0.f, g.r1 >= 0.f ? g.r1 : g.r0); + padding += glm::mix(glm::min(r0, r1), glm::max(r0, r1), in.blendLerpFactor) + * in.blendFactor; + } + b.lower -= padding; + b.upper += padding; + bound = b; Result result{}; - if (in.type == GeometryType::SDF) { - const SDFPrimitive &g = in.sdf[i]; - box3 b = computeSDFPrimitiveAABB(g); - float padding = in.noiseFactor * glm::max(0.f, g.r0) * 0.1f; - if (g.numNeighbours > 0) { - const float r0 = glm::max(0.f, g.r0); - const float r1 = glm::max(0.f, g.r1 >= 0.f ? g.r1 : g.r0); - padding += - glm::mix(glm::min(r0, r1), glm::max(r0, r1), in.blendLerpFactor) - * in.blendFactor; - } - b.lower -= padding; - b.upper += padding; - bound = b; - for (int axis = 0; axis < 3; ++axis) { - if (!isfinite(b.lower[axis]) || !isfinite(b.upper[axis])) - result.invalid = 1u; - } - return result; + for (int axis = 0; axis < 3; ++axis) { + if (!isfinite(b.lower[axis]) || !isfinite(b.upper[axis])) + result.invalid = 1u; } - const bool sphere = in.type == GeometryType::SPHERE; - const auto *indices = static_cast(in.indices); - const auto *sphereIndices = static_cast(in.indices); - const size_t center = sphere ? (sphereIndices ? sphereIndices[i] : i) : 0; - const uvec2 c = sphere ? uvec2(center) - : indices ? indices[i] - : uvec2(2 * i, 2 * i + 1); - const bool cone = in.type == GeometryType::CONE; - const float r = cone - ? glm::max(glm::abs(in.radii[c.x]), glm::abs(in.radii[c.y])) - : glm::abs(in.radii ? in.radii[sphere ? center : i] : in.radius); - const vec3 v0 = in.vertices[c.x], v1 = in.vertices[c.y]; + return result; // SDF bounds carry no epsilon scale. +} + +// Bounds of the sphere of radius r swept from v0 to v1, with the largest +// coordinate magnitude as the epsilon scale. +VISRTX_DEVICE Result sweptSphereBound(vec3 v0, vec3 v1, float r, box3 &bound) +{ const box3 b(glm::min(v0, v1) - r, glm::max(v0, v1) + r); bound = b; const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); const float scale = glm::max(m.x, glm::max(m.y, m.z)); + Result result{}; if (!isfinite(r) || !isfinite(v0.x) || !isfinite(v0.y) || !isfinite(v0.z) || !isfinite(v1.x) || !isfinite(v1.y) || !isfinite(v1.z) || !isfinite(scale)) @@ -196,8 +227,49 @@ VISRTX_DEVICE Result primitiveBound(PrimitiveInput in, size_t i, box3 &bound) return result; } +VISRTX_DEVICE Result sphereBound(const SphereInput &in, size_t i, box3 &bound) +{ + const size_t v = in.indices ? in.indices[i] : i; + const float r = glm::abs(in.radii ? in.radii[v] : in.radius); + return sweptSphereBound(in.vertices[v], in.vertices[v], r, bound); +} + +VISRTX_DEVICE Result coneBound(const ConeInput &in, size_t i, box3 &bound) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const float r = glm::max(glm::abs(in.radii[c.x]), glm::abs(in.radii[c.y])); + const vec3 *v = in.segments.vertices; + return sweptSphereBound(v[c.x], v[c.y], r, bound); +} + +VISRTX_DEVICE Result cylinderBound( + const CylinderInput &in, size_t i, box3 &bound) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const float r = glm::abs(in.radii ? in.radii[i] : in.radius); + const vec3 *v = in.segments.vertices; + return sweptSphereBound(v[c.x], v[c.y], r, bound); +} + +VISRTX_DEVICE Result primitiveBound( + const PrimitiveInput &in, size_t i, box3 &bound) +{ + switch (in.type) { + case GeometryType::SPHERE: + return sphereBound(in.sphere, i, bound); + case GeometryType::CONE: + return coneBound(in.cone, i, bound); + case GeometryType::CYLINDER: + return cylinderBound(in.cylinder, i, bound); + case GeometryType::SDF: + return sdfBound(in.sdf, i, bound); + default: + return {0.f, 1u}; // No custom-primitive bounds. + } +} + VISRTX_GLOBAL void primitiveBounds( - PrimitiveInput in, box3 *bounds, Result *result) + const PrimitiveInput in, box3 *bounds, Result *result) { const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; if (i >= in.count) @@ -223,11 +295,8 @@ VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) __shared__ typename Scan::TempStorage scanStorage; const auto &job = jobs[blockIdx.x]; const unsigned i = threadIdx.x; - if (i == 0) { - // Every transferred byte is initialized, including unused result slots. - job.results[0] = {}; - job.results[1] = {}; - } + // Write only the requested results: an earlier launch in this collection + // may have written the other one. if (job.bounds) { Result local{}; if (i < job.boundsInput.count) @@ -238,7 +307,7 @@ VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) [] __device__(float a, float b) { return glm::max(a, b); }); const unsigned invalid = StatusReduce(statusStorage).Sum(local.invalid); if (i == 0) - job.results[0] = {scale, invalid}; + job.results->bounds = {scale, invalid}; __syncthreads(); // statusStorage is reused for the area validation. } if (job.cdf) { @@ -255,7 +324,8 @@ VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) total > 0.0 ? (i + 1 == n ? 1.f : float(prefix / total)) : 0.f; const unsigned invalid = StatusReduce(statusStorage).Sum(localInvalid); if (i == 0) - job.results[1] = {invalid ? __int_as_float(0x7fffffff) : value, invalid}; + job.results->area = { + invalid ? __int_as_float(0x7fffffff) : value, invalid}; } } @@ -284,6 +354,25 @@ VISRTX_GLOBAL void curveRadii(size_t n, float radius, float *out) } } // namespace +size_t segmentCount(const Array1D &vertices, const Array1D *indices) +{ + return indices ? indices->size() : vertices.size() / 2; +} + +SegmentInput segmentInput(const Array1D &vertices, + const Array1D *indices, + const Array1D *caps, + uint8_t capFlags) +{ + SegmentInput input{}; + input.vertices = vertices.beginAs(AddressSpace::GPU); + input.indices = + indices ? indices->beginAs(AddressSpace::GPU) : nullptr; + input.caps = caps ? caps->beginAs(AddressSpace::GPU) : nullptr; + input.capFlags = capFlags; + return input; +} + bool generateQuadIndices( Geometry *g, const uvec4 *indices, size_t n, DeviceBuffer &out) { @@ -307,7 +396,7 @@ bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) 256, 0, g->deviceState()->preparation.stream()>>>(n, out.ptrAs()); - return checkPreparation(g, cudaGetLastError(), "curve indices"); + return failPreparationOnError(g, cudaGetLastError(), "curve indices"); } bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) @@ -320,14 +409,12 @@ bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) 0, g->deviceState()->preparation.stream()>>>( n, radius, out.ptrAs()); - return checkPreparation(g, cudaGetLastError(), "curve radii"); + return failPreparationOnError(g, cudaGetLastError(), "curve radii"); } -bool checkPreparation(Geometry *g, cudaError_t error, const char *operation) +void failPreparation(Geometry *g, cudaError_t error, const char *operation) { - if (error == cudaSuccess) - return true; - g->setPreparationFailed(true); + g->markPreparationFailed(); // A failed dispatch/readback can follow successful queued kernels. Drain // preparation before retrying or freeing scratch. Keep the render-stream // drain on this error path too: this helper also handles input retirement @@ -338,92 +425,58 @@ bool checkPreparation(Geometry *g, cudaError_t error, const char *operation) "geometry preprocessing failed during %s: %s", operation, cudaGetErrorString(error)); +} + +bool failPreparationOnError( + Geometry *g, cudaError_t error, const char *operation) +{ + if (error == cudaSuccess) + return true; + failPreparation(g, error, operation); return false; } bool reservePreparation(Geometry *g, DeviceBuffer &buffer, size_t bytes) { - // Failed allocations can retain their requested capacity without storage. - // Clear it so a later preparation can retry the same-sized allocation. - if (!buffer) - buffer.reset(); - buffer.reserve(bytes); - // Consume the runtime error even when missing storage identifies allocation - // failure. Otherwise the next successful allocation inherits this error. - const auto error = cudaGetLastError(); - return checkPreparation(g, - error != cudaSuccess ? error - : bytes && (!buffer || buffer.bytes() < bytes) - ? cudaErrorMemoryAllocation - : cudaSuccess, - "allocating device storage"); + return failPreparationOnError( + g, buffer.tryReserve(bytes), "allocating device storage"); } bool finishPreparation(Geometry *g) { // Also establishes an explicit boundary for legacy default-stream consumers. - return checkPreparation(g, cudaGetLastError(), "launch") - && checkPreparation(g, + return failPreparationOnError(g, cudaGetLastError(), "launch") + && failPreparationOnError(g, g->deviceState()->finishGeometryPreparation(), "execution completion"); } -SmallGeometryBatch::~SmallGeometryBatch() -{ - if (m_readback) - cudaFreeHost(m_readback); -} - -cudaError_t SmallGeometryBatch::reserveResults(size_t count) -{ - const size_t bytes = 2 * count * sizeof(Result); - if (!m_results) - m_results.reset(); - m_results.reserve(bytes); - auto error = cudaGetLastError(); - if (error != cudaSuccess) - return error; - if (!m_results || m_results.bytes() < bytes) - return cudaErrorMemoryAllocation; - if (count > m_readbackCapacity) { - void *memory = nullptr; - error = cudaMallocHost(&memory, bytes); - if (error != cudaSuccess) - return error; - // Previous batches were drained before reuse. Keep the old allocation on - // allocation failure; no in-flight transfer refers to it during growth. - if (m_readback) - cudaFreeHost(m_readback); - m_readback = static_cast(memory); - m_readbackCapacity = count; - } - return cudaSuccess; -} - void SmallGeometryBatch::enqueue(Preprocessing *preprocessing) { m_pending.push_back(preprocessing); } -cudaError_t SmallGeometryBatch::finish(cudaStream_t stream) +cudaError_t SmallGeometryBatch::launch( + PreparationResults &results, cudaStream_t stream) { cudaError_t error = cudaSuccess; if (!m_pending.empty()) { - // No host allocations after submission: descriptors and readback sources - // remain stable even when an error requires a subsequent fallback drain. + size_t positions = 0; + for (auto *p : m_pending) + positions = std::max(positions, p->m_position + 1); + // No host allocations after submission: descriptors remain stable even + // when an error requires a subsequent fallback drain. m_jobs.clear(); m_jobs.reserve(m_pending.size()); - for (auto *p : m_pending) - m_jobs.push_back(p->m_small); - if (m_jobs.size() > size_t(std::numeric_limits::max()) - || m_jobs.size() - > std::numeric_limits::max() / (2 * sizeof(Result))) + if (m_pending.size() > size_t(std::numeric_limits::max())) error = cudaErrorInvalidValue; else - error = reserveResults(m_jobs.size()); + error = results.reserve(positions, stream); if (error == cudaSuccess) { - for (size_t i = 0; i < m_jobs.size(); ++i) - m_jobs[i].results = m_results.ptrAs() + 2 * i; + for (auto *p : m_pending) { + m_jobs.push_back(p->m_small); + m_jobs.back().results = results.device(p->m_position); + } error = m_descriptors.enqueueUpload(m_jobs.data(), m_jobs.size(), stream); } if (error == cudaSuccess) { @@ -431,31 +484,13 @@ cudaError_t SmallGeometryBatch::finish(cudaStream_t stream) m_descriptors.ptrAs()); error = cudaGetLastError(); } - if (error == cudaSuccess) - error = cudaMemcpyAsync(m_readback, - m_results.ptr(), - 2 * m_jobs.size() * sizeof(Result), - cudaMemcpyDeviceToHost, - stream); } - const auto completion = cudaStreamSynchronize(stream); - for (size_t i = 0; i < m_pending.size(); ++i) { - auto *p = m_pending[i]; - // Scatter only completed results. An intervening wait may flush bounds - // before an area request arrives: preserve the other slot in that case. - if (error == cudaSuccess && completion == cudaSuccess) { - if (p->m_small.bounds) - p->m_readback[0] = m_readback[2 * i]; - if (p->m_small.cdf) - p->m_readback[1] = m_readback[2 * i + 1]; - } + for (auto *p : m_pending) { p->m_smallQueued = false; p->m_small = {}; } m_pending.clear(); - if (error != cudaSuccess || completion != cudaSuccess) - cudaGetLastError(); - return error == cudaSuccess ? completion : error; + return error; } void Preprocessing::enqueueSmall(Geometry *g) @@ -468,55 +503,86 @@ void Preprocessing::enqueueSmall(Geometry *g) Preprocessing::~Preprocessing() = default; -bool Preprocessing::reserveReadback(Geometry *g) +void Preprocessing::submit(Geometry *g) { - if (m_readback) - return true; - if (!checkPreparation(g, - g->deviceState()->geometryReadbacks.acquire(m_readbackLease), - "allocating preparation readback")) - return false; - m_readback = m_readbackLease.data(); - return true; + m_position = g->deferPreparation(); + m_status = Status::Pending; +} + +GeometryResults *Preprocessing::reserveResults(Geometry *g) +{ + auto *state = g->deviceState(); + if (!failPreparationOnError(g, + state->preparationResults.reserve( + m_position + 1, state->preparation.stream()), + "allocating preparation results")) + return nullptr; + return state->preparationResults.device(m_position); +} + +Preprocessing::Status Preprocessing::status() const +{ + return m_status; } -bool Preprocessing::pending() const +float Preprocessing::epsilonScale() const { - return m_scale || m_total; + return m_epsilonScale; +} + +float Preprocessing::totalArea() const +{ + return m_totalArea; +} + +const float *Preprocessing::areaCdf() const +{ + return m_totalArea > 0.f ? m_areaCdf.ptrAs() : nullptr; +} + +void Preprocessing::releaseAreas() +{ + m_areasSubmitted = false; + m_totalArea = 0.f; + m_areaCdf.reset(); } bool Preprocessing::complete(Geometry *g) { - auto *scale = std::exchange(m_scale, nullptr); - auto *total = std::exchange(m_total, nullptr); - auto *cdf = std::exchange(m_cdf, nullptr); + const bool bounds = std::exchange(m_boundsSubmitted, false); + const bool areas = std::exchange(m_areasSubmitted, false); + m_status = Status::Ready; if (g->preparationFailed()) return false; - if (scale && m_readback[0].invalid) - return checkPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); - if (total && !std::isfinite(m_readback[1].value)) - return checkPreparation( - g, cudaErrorInvalidValue, "non-publishable primitive area"); - if (scale) - *scale = m_readback[0].value; - if (total) { - *total = m_readback[1].value; - if (*total == 0.f) - cdf->reset(); + if (!bounds && !areas) + return true; + const auto &results = g->deviceState()->preparationResults.host(m_position); + if (bounds && results.bounds.invalid) { + failPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); + return false; + } + if (areas && !std::isfinite(results.area.value)) { + failPreparation(g, cudaErrorInvalidValue, "non-publishable primitive area"); + return false; + } + if (bounds) + m_epsilonScale = m_boundsHaveEpsilonScale ? results.bounds.value : 0.f; + if (areas) { + m_totalArea = results.area.value; + if (m_totalArea == 0.f) + m_areaCdf.reset(); } return true; } bool Preprocessing::bounds( - Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs, float &scale) + Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs) { const auto stream = g->deviceState()->preparation.stream(); - scale = 0.f; - if (!reserveReadback(g)) - return false; - g->deferPreparation(); - m_scale = &scale; - m_readback[0] = {}; + m_epsilonScale = 0.f; + submit(g); + m_boundsSubmitted = true; + m_boundsHaveEpsilonScale = in.type != GeometryType::SDF; if (in.count > 0 && in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) return false; @@ -525,74 +591,64 @@ bool Preprocessing::bounds( enqueueSmall(g); return true; } - if (!reservePreparation(g, aabbs, in.count * sizeof(box3)) - || !reservePreparation(g, m_result, sizeof(Result)) - || !checkPreparation(g, - cudaMemsetAsync(m_result.ptr(), 0, sizeof(Result), stream), + if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) + return false; + auto *results = reserveResults(g); + auto *result = results ? &results->bounds : nullptr; + if (!result + || !failPreparationOnError(g, + cudaMemsetAsync(result, 0, sizeof(Result), stream), "clearing bounds status")) return false; if (in.count) primitiveBounds<<<(in.count + 255) / 256, 256, 0, stream>>>( - in, aabbs.ptrAs(), m_result.ptrAs()); - auto &host = m_readback[0]; - const bool sdf = in.type == GeometryType::SDF; - if (!checkPreparation(g, cudaGetLastError(), "bounds evaluation") - || !checkPreparation(g, - cudaMemcpyAsync(sdf ? static_cast(&host.invalid) : &host, - sdf ? static_cast(&m_result.ptrAs()->invalid) - : m_result.ptr(), - sdf ? sizeof(host.invalid) : sizeof(host), - cudaMemcpyDeviceToHost, - stream), - "bounds summary")) - return false; - return true; + in, aabbs.ptrAs(), result); + return failPreparationOnError(g, cudaGetLastError(), "bounds evaluation"); } -bool Preprocessing::areas( - Geometry *g, const PrimitiveInput &in, DeviceBuffer &cdf, float &total) +bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) { - total = 0.f; + m_totalArea = 0.f; if (in.count == 0) { - cdf.reset(); + m_areaCdf.reset(); return true; } - if (in.count > size_t(std::numeric_limits::max())) - return checkPreparation(g, cudaErrorInvalidValue, "primitive count"); - if (!reserveReadback(g)) + if (in.count > size_t(std::numeric_limits::max())) { + failPreparation(g, cudaErrorInvalidValue, "primitive count"); return false; - g->deferPreparation(); - m_total = &total; - m_cdf = &cdf; - m_readback[1] = {}; + } + submit(g); + m_areasSubmitted = true; if (in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { - if (!reservePreparation(g, cdf, in.count * sizeof(float))) + if (!reservePreparation(g, m_areaCdf, in.count * sizeof(float))) return false; m_small.areaInput = in; - m_small.cdf = cdf.ptrAs(); + m_small.cdf = m_areaCdf.ptrAs(); enqueueSmall(g); return true; } const auto stream = g->deviceState()->preparation.stream(); size_t scratchBytes = 0; if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) - || !reservePreparation(g, cdf, in.count * sizeof(float)) - || !reservePreparation(g, m_result, sizeof(Result)) - || !checkPreparation(g, - cudaMemsetAsync(m_result.ptr(), 0, sizeof(Result), stream), + || !reservePreparation(g, m_areaCdf, in.count * sizeof(float))) + return false; + auto *results = reserveResults(g); + auto *result = results ? &results->area : nullptr; + if (!result + || !failPreparationOnError(g, + cudaMemsetAsync(result, 0, sizeof(Result), stream), "clearing area status")) return false; auto *prefix = m_prefix.ptrAs(); - auto *result = m_result.ptrAs(); primitiveAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( in, prefix, result); - if (!checkPreparation(g, cudaGetLastError(), "area evaluation") - || !checkPreparation(g, + if (!failPreparationOnError(g, cudaGetLastError(), "area evaluation") + || !failPreparationOnError(g, cub::DeviceScan::InclusiveSum( nullptr, scratchBytes, prefix, prefix, int(in.count), stream), "scan workspace query") || !reservePreparation(g, m_scratch, scratchBytes) - || !checkPreparation(g, + || !failPreparationOnError(g, cub::DeviceScan::InclusiveSum(m_scratch.ptr(), scratchBytes, prefix, @@ -602,20 +658,10 @@ bool Preprocessing::areas( "area scan")) return false; normalizeAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( - prefix, in.count, cdf.ptrAs(), result); - if (!checkPreparation(g, cudaGetLastError(), "CDF normalization")) + prefix, in.count, m_areaCdf.ptrAs(), result); + if (!failPreparationOnError(g, cudaGetLastError(), "CDF normalization")) return false; publishArea<<<1, 1, 0, stream>>>(result); - auto &host = m_readback[1]; - if (!checkPreparation(g, cudaGetLastError(), "area publication") - || !checkPreparation(g, - cudaMemcpyAsync(&host.value, - &result->value, - sizeof(host.value), - cudaMemcpyDeviceToHost, - stream), - "area readback")) - return false; - return true; + return failPreparationOnError(g, cudaGetLastError(), "area publication"); } } // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 76de90266..3794290e9 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -32,71 +32,148 @@ #pragma once #include -#include "ReadbackPool.h" +#include "PreparationResults.h" #include "gpu/gpu_objects.h" #include "utility/DeviceBuffer.h" namespace visrtx { +struct Array1D; struct Geometry; -// GPU views use logical array beginnings, never application allocation bases. -// Geometry::beginPreparation() completes authored host-array uploads before -// these views are consumed; kernels need no legacy default-stream dependency. +// Per-type preprocessing inputs. GPU views use logical array beginnings, never +// application allocation bases. Geometry::beginPreparation() completes +// authored host-array uploads before these views are consumed; kernels need no +// legacy default-stream dependency. A null `indices` means unindexed input. + +struct TriangleInput +{ + const vec3 *vertices; + const uvec3 *indices; // Else consecutive vertex triples. +}; + +struct SphereInput +{ + const vec3 *vertices; + const uint32_t *indices; // Else one sphere per vertex. + const float *radii; // Per vertex; else `radius`. + float radius; +}; + +// The endpoints and caps cones and cylinders share. +struct SegmentInput +{ + const vec3 *vertices; + const uvec2 *indices; // Else consecutive vertex pairs. + const uint8_t *caps; // Per vertex; else `capFlags`. + uint8_t capFlags; +}; + +struct ConeInput +{ + SegmentInput segments; + const float *radii; // Per vertex; required. +}; + +struct CylinderInput +{ + SegmentInput segments; + const float *radii; // Per primitive; else `radius`. + float radius; +}; + +struct SDFInput +{ + const SDFPrimitive *primitives; + float blendFactor; + float blendLerpFactor; + float noiseFactor; +}; + +// One geometry's preprocessing input: its primitive count and the input of +// its type. A tagged union rather than a per-type kernel so that the small +// geometry batch can mix types in one launch. struct PrimitiveInput { GeometryType type{GeometryType::TRIANGLE}; size_t count{0}; - const vec3 *vertices{nullptr}; - const void *indices{nullptr}; - const float *radii{nullptr}; - const uint8_t *caps{nullptr}; - float radius{0.f}; - uint8_t capFlags{0}; - const SDFPrimitive *sdf{nullptr}; - float blendFactor{1.f}; - float blendLerpFactor{0.5f}; - float noiseFactor{0.f}; + union + { + TriangleInput triangle; + SphereInput sphere; + ConeInput cone; + CylinderInput cylinder; + SDFInput sdf; + }; + + PrimitiveInput() : triangle{} {} + PrimitiveInput(size_t n, const TriangleInput &in) + : type(GeometryType::TRIANGLE), count(n), triangle(in) + {} + PrimitiveInput(size_t n, const SphereInput &in) + : type(GeometryType::SPHERE), count(n), sphere(in) + {} + PrimitiveInput(size_t n, const ConeInput &in) + : type(GeometryType::CONE), count(n), cone(in) + {} + PrimitiveInput(size_t n, const CylinderInput &in) + : type(GeometryType::CYLINDER), count(n), cylinder(in) + {} + PrimitiveInput(size_t n, const SDFInput &in) + : type(GeometryType::SDF), count(n), sdf(in) + {} }; -// One block handles one small geometry. Bounds and area inputs are separate: -// a lazily requested sphere area distribution need not carry vertex positions. +// Cone and cylinder endpoints: `indices` pairs vertices, else consecutive +// vertices pair up. +size_t segmentCount(const Array1D &vertices, const Array1D *indices); +SegmentInput segmentInput(const Array1D &vertices, + const Array1D *indices, + const Array1D *caps, + uint8_t capFlags); + +// One block handles one small geometry. bounds() and areas() fill their halves +// independently; a half left at zero count is skipped. struct SmallGeometryJob { PrimitiveInput boundsInput; PrimitiveInput areaInput; box3 *bounds{nullptr}; float *cdf{nullptr}; - PreparationResult *results{nullptr}; + GeometryResults *results{nullptr}; }; struct Preprocessing; // Device-owned, single-flight batch. The geometry collection queue retains -// owners until finish() drains every queued descriptor, kernel and readback. +// owners until the stream completes every queued descriptor and kernel. struct SmallGeometryBatch { static constexpr size_t MAX_PRIMITIVES = 256; - SmallGeometryBatch() = default; - ~SmallGeometryBatch(); - SmallGeometryBatch(const SmallGeometryBatch &) = delete; - SmallGeometryBatch &operator=(const SmallGeometryBatch &) = delete; void enqueue(Preprocessing *preprocessing); - cudaError_t finish(cudaStream_t stream); + // Launches every queued job, writing each geometry's results at its queue + // position in `results`. Always empties the batch; the caller synchronizes + // `stream`. + cudaError_t launch(PreparationResults &results, cudaStream_t stream); private: std::vector m_pending; std::vector m_jobs; DeviceBuffer m_descriptors; - DeviceBuffer m_results; - PreparationResult *m_readback{nullptr}; - size_t m_readbackCapacity{0}; - cudaError_t reserveResults(size_t count); }; -// Per-geometry reusable workspace. Submission retains pinned readback storage; -// complete() publishes scalar results after the device's collection barrier. +// Per-geometry reusable workspace and the owner of its scalar results. +// Submission writes the device's PreparationResults at the geometry's queue +// position; complete() publishes the epsilon scale, total area and area CDF +// from their readback after the device's collection barrier. struct Preprocessing { + enum class Status + { + Ready, // Nothing awaits complete(): published, or its collection failed + // and what it was to publish stays zero. + Pending, // Submitted results await complete(). + }; + Preprocessing() = default; ~Preprocessing(); Preprocessing(const Preprocessing &) = delete; @@ -104,38 +181,51 @@ struct Preprocessing Preprocessing(Preprocessing &&) = delete; Preprocessing &operator=(Preprocessing &&) = delete; + Status status() const; + // Published results. The CDF is null when the total area is zero. + float epsilonScale() const; + float totalArea() const; + const float *areaCdf() const; + // Success means queued, not published. Small jobs defer GPU submission to - // the next preparation completion boundary. Output references must be owned - // by the retained geometry and remain valid until collection completes. - bool areas(Geometry *geometry, - const PrimitiveInput &input, - DeviceBuffer &cdf, - float &total); - bool bounds(Geometry *geometry, - const PrimitiveInput &input, - DeviceBuffer &aabbs, - float &scale); - - bool pending() const; + // the next preparation completion boundary. Submission zeroes the result it + // replaces until complete() publishes the new one. + bool areas(Geometry *geometry, const PrimitiveInput &input); + bool bounds( + Geometry *geometry, const PrimitiveInput &input, DeviceBuffer &aabbs); + // Drops the published area distribution and its storage, and cancels the + // publication of an area submission still awaiting complete(). + void releaseAreas(); bool complete(Geometry *geometry); private: friend struct SmallGeometryBatch; - bool reserveReadback(Geometry *geometry); void enqueueSmall(Geometry *geometry); + void submit(Geometry *geometry); + // Device results for a general-path submission; null after failing it. + GeometryResults *reserveResults(Geometry *geometry); SmallGeometryJob m_small; bool m_smallQueued{false}; - GeometryReadbackPool::Lease m_readbackLease; - PreparationResult *m_readback{nullptr}; - float *m_scale{nullptr}; - float *m_total{nullptr}; - DeviceBuffer *m_cdf{nullptr}; + // Position in the device's preparation queue, set by submit(). + size_t m_position{0}; + Status m_status{Status::Ready}; + bool m_boundsSubmitted{false}; + bool m_areasSubmitted{false}; + // SDF bounds are padded per primitive and carry no epsilon scale. + bool m_boundsHaveEpsilonScale{false}; + float m_epsilonScale{0.f}; + float m_totalArea{0.f}; + DeviceBuffer m_areaCdf; DeviceBuffer m_prefix; DeviceBuffer m_scratch; - DeviceBuffer m_result; }; -bool checkPreparation( +// Marks the geometry's preparation failed, drains the preparation and render +// streams so no queued work still targets its storage, and reports the error. +void failPreparation( + Geometry *geometry, cudaError_t error, const char *operation); +// Returns true on cudaSuccess; otherwise calls failPreparation(). +bool failPreparationOnError( Geometry *geometry, cudaError_t error, const char *operation); bool reservePreparation(Geometry *geometry, DeviceBuffer &buffer, size_t bytes); bool finishPreparation(Geometry *geometry); diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 3bc6b7d15..355294aee 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -58,7 +58,7 @@ void Quad::commitParameters() void Quad::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, diff --git a/devices/rtx/device/geometry/ReadbackPool.h b/devices/rtx/device/geometry/ReadbackPool.h deleted file mode 100644 index e36083ccf..000000000 --- a/devices/rtx/device/geometry/ReadbackPool.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#pragma once - -#include "../utility/PinnedReadbackPool.h" - -namespace visrtx { - -struct PreparationResult -{ - float value; - uint32_t invalid; -}; - -using GeometryReadbackPool = PinnedReadbackPool; - -} // namespace visrtx diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index dcc118100..50fa2f9b0 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -74,7 +74,7 @@ void SDF::commitParameters() void SDF::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, @@ -90,14 +90,11 @@ void SDF::finalize() "finalizing sdf geometry with %zu primitives", m_numPrimitives); - PrimitiveInput input; - input.type = GeometryType::SDF; - input.count = m_numPrimitives; const void *source = m_sdf->begin(AddressSpace::GPU); if (reinterpret_cast(source) % alignof(SDFPrimitive) != 0) { const size_t bytes = m_numPrimitives * sizeof(SDFPrimitive); if (!reservePreparation(this, m_alignedPrimitives, bytes) - || !checkPreparation(this, + || !failPreparationOnError(this, cudaMemcpyAsync(m_alignedPrimitives.ptr(), source, bytes, @@ -108,11 +105,12 @@ void SDF::finalize() m_primitives = m_alignedPrimitives.ptrAs(); } else m_primitives = static_cast(source); - input.sdf = m_primitives; + SDFInput input{}; + input.primitives = m_primitives; input.blendFactor = m_blendFactor; input.blendLerpFactor = m_blendLerpFactor; input.noiseFactor = m_noiseFactor; - if (!m_preprocessing.bounds(this, input, m_aabbs, m_epsilonScale)) + if (!m_preprocessing.bounds(this, {m_numPrimitives, input}, m_aabbs)) return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index e2a416769..dd52e7d6d 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -52,9 +52,24 @@ void Sphere::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } +PrimitiveInput Sphere::primitiveInput() const +{ + SphereInput input{}; + // Area sampling reads no positions and may run without them. + input.vertices = + m_vertex ? m_vertex->beginAs(AddressSpace::GPU) : nullptr; + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radii = m_vertexRadius + ? m_vertexRadius->beginAs(AddressSpace::GPU) + : nullptr; + input.radius = m_globalRadius; + return {m_numSpheres, input}; +} + void Sphere::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, @@ -69,17 +84,7 @@ void Sphere::finalize() // Calculate bounds // m_numSpheres = m_index ? m_index->size() : m_vertex->size(); - PrimitiveInput input; - input.type = GeometryType::SPHERE; - input.count = m_numSpheres; - input.vertices = m_vertex->beginAs(AddressSpace::GPU); - input.indices = - m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - input.radii = m_vertexRadius - ? m_vertexRadius->beginAs(AddressSpace::GPU) - : nullptr; - input.radius = m_globalRadius; - if (!m_preprocessing.bounds(this, input, m_aabbs, m_epsilonScale)) + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) return; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); @@ -89,10 +94,8 @@ void Sphere::finalize() m_areaDataValid = false; if (m_areaDataWanted) buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.reset(); - } + else + m_preprocessing.releaseAreas(); if (!preparationFailed()) upload(); @@ -100,17 +103,7 @@ void Sphere::finalize() void Sphere::buildAreaData() { - PrimitiveInput input; - input.type = GeometryType::SPHERE; - input.count = m_numSpheres; - input.radii = m_vertexRadius - ? m_vertexRadius->beginAs(AddressSpace::GPU) - : nullptr; - input.indices = - m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - input.radius = m_globalRadius; - m_areaDataValid = - m_preprocessing.areas(this, input, m_primAreaCdf, m_totalArea); + m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); } bool Sphere::isAreaSamplingSupported() const @@ -130,7 +123,7 @@ void Sphere::ensureAreaData() float Sphere::totalArea() const { - return m_totalArea; + return m_preprocessing.totalArea(); } bool Sphere::isValid() const @@ -168,10 +161,9 @@ GeometryGPUData Sphere::gpuData() const populateAttributeDataSet(m_vertexAttributes, sphere.vertexAttr); // Geometry Light sampling data; null/zero until ensureAreaData() runs. - sphere.primAreaCdf = - m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; - sphere.numPrimitives = m_totalArea > 0.f ? uint32_t(m_numSpheres) : 0; - sphere.totalArea = m_totalArea; + sphere.primAreaCdf = m_preprocessing.areaCdf(); + sphere.numPrimitives = sphere.primAreaCdf ? uint32_t(m_numSpheres) : 0; + sphere.totalArea = m_preprocessing.totalArea(); return retval; } diff --git a/devices/rtx/device/geometry/Sphere.h b/devices/rtx/device/geometry/Sphere.h index bcf07355f..0b9e97c6d 100644 --- a/devices/rtx/device/geometry/Sphere.h +++ b/devices/rtx/device/geometry/Sphere.h @@ -61,6 +61,7 @@ struct Sphere : public Geometry GeometryGPUData gpuData() const override; void cleanup(); void buildAreaData(); + PrimitiveInput primitiveInput() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_vertex; @@ -77,8 +78,6 @@ struct Sphere : public Geometry // the normalized cumulative object-space area over primitives. // m_areaDataWanted persists across recommits so a re-finalize rebuilds it // order-independently. - DeviceBuffer m_primAreaCdf; - float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; }; diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index a19a724ed..7b033870b 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -89,7 +89,7 @@ void Triangle::commitParameters() void Triangle::finalize() { - if (!beginPreparation()) + if (beginPreparation() != PreparationStart::Prepare) return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, @@ -159,10 +159,8 @@ void Triangle::finalize() m_areaDataValid = false; if (m_areaDataWanted) buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.reset(); - } + else + m_preprocessing.releaseAreas(); if (!preparationFailed()) upload(); @@ -170,13 +168,12 @@ void Triangle::finalize() void Triangle::buildAreaData() { - PrimitiveInput input; - input.count = m_index ? m_index->size() : m_vertex->size() / 3; + TriangleInput input{}; input.vertices = m_vertex->beginAs(AddressSpace::GPU); input.indices = m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - m_areaDataValid = - m_preprocessing.areas(this, input, m_primAreaCdf, m_totalArea); + const size_t count = m_index ? m_index->size() : m_vertex->size() / 3; + m_areaDataValid = m_preprocessing.areas(this, {count, input}); } bool Triangle::isAreaSamplingSupported() const @@ -196,7 +193,7 @@ void Triangle::ensureAreaData() float Triangle::totalArea() const { - return m_totalArea; + return m_preprocessing.totalArea(); } void Triangle::populateBuildInput(OptixBuildInput &buildInput) const @@ -260,11 +257,11 @@ GeometryGPUData Triangle::gpuData() const tri.cullBackfaces = m_cullBackfaces; // Geometry Light sampling data; null/zero until ensureAreaData() runs. - tri.primAreaCdf = m_totalArea > 0.f ? m_primAreaCdf.ptrAs() : nullptr; - tri.numPrimitives = m_totalArea > 0.f + tri.primAreaCdf = m_preprocessing.areaCdf(); + tri.numPrimitives = tri.primAreaCdf ? uint32_t(m_index ? m_index->size() : m_vertex->size() / 3) : 0; - tri.totalArea = m_totalArea; + tri.totalArea = m_preprocessing.totalArea(); return retval; } diff --git a/devices/rtx/device/geometry/Triangle.h b/devices/rtx/device/geometry/Triangle.h index ffc527d1c..daf706126 100644 --- a/devices/rtx/device/geometry/Triangle.h +++ b/devices/rtx/device/geometry/Triangle.h @@ -94,8 +94,6 @@ struct Triangle : public Geometry // the normalized cumulative object-space area over primitives. // m_areaDataWanted persists across recommits so a re-finalize rebuilds it // order-independently. - DeviceBuffer m_primAreaCdf; - float m_totalArea{0.f}; bool m_areaDataValid{false}; bool m_areaDataWanted{false}; }; diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 3ad7ab05b..4e8c09b38 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -30,7 +30,6 @@ */ #include "optix_visrtx.h" -#include #include "Object.h" #include "geometry/Geometry.h" @@ -80,15 +79,7 @@ bool buildOptixBVH(std::vector buildInput, return false; }; auto reserve = [&](DeviceBuffer &buffer, size_t bytes) { - if (!buffer) - buffer.reset(); - buffer.reserve(bytes); - const auto error = cudaGetLastError(); - return check(error != cudaSuccess ? error - : bytes && (!buffer || buffer.bytes() < bytes) - ? cudaErrorMemoryAllocation - : cudaSuccess, - "allocating device storage"); + return check(buffer.tryReserve(bytes), "allocating device storage"); }; // Legacy producers include field/isosurface work on the render stream and @@ -110,11 +101,17 @@ bool buildOptixBVH(std::vector buildInput, "memory requirements")) return false; - // Acquire before submitting GPU work: allocation may throw, and a lease - // must never be returned while a readback still targets it. - PinnedReadbackPool::Lease readback; - if (!check(state.bvhReadbacks.acquire(readback), "allocating BVH readback")) - return false; + // Allocate before submitting GPU work. Every earlier build completed, so + // no transfer still targets the readback. + if (!state.bvhReadback) { + void *memory = nullptr; + const auto error = + cudaMallocHost(&memory, sizeof(DeviceGlobalState::BvhReadback)); + if (!check(error, "allocating BVH readback")) + return false; + state.bvhReadback.reset( + static_cast(memory)); + } DeviceBuffer compactedSizeBuffer, aabbBuffer, tempBuffer, outputBuffer; if (!reserve(compactedSizeBuffer, sizeof(uint64_t)) @@ -144,8 +141,8 @@ bool buildOptixBVH(std::vector buildInput, "build")) return false; - auto &builtBounds = readback.data()->bounds; - auto &compactedSize = readback.data()->compactedSize; + auto &builtBounds = state.bvhReadback->bounds; + auto &compactedSize = state.bvhReadback->compactedSize; if (!check(cudaMemcpyAsync(&builtBounds, aabbBuffer.ptr(), sizeof(box3), @@ -191,7 +188,7 @@ DeviceGlobalState::~DeviceGlobalState() = default; void DeviceGlobalState::enqueueGeometryInputUploads(Geometry *geometry) { - m_geometryInputUploads.emplace_back(geometry); + m_geometryInputUploads.enqueue(helium::IntrusivePtr(geometry)); } cudaError_t DeviceGlobalState::stageGeometryArray( @@ -208,98 +205,107 @@ cudaError_t DeviceGlobalState::stageGeometryArray( bool DeviceGlobalState::collectingGeometryInputUploads() const { - return m_collectingGeometryInputUploads; + return m_geometryInputUploads.collecting(); } bool DeviceGlobalState::collectGeometryInputUploads() { - if (m_collectingGeometryInputUploads) - return false; - if (m_geometryInputUploads.empty()) - return true; - m_collectingGeometryInputUploads = true; - bool completed = false; - auto collecting = nonstd::make_scope_exit([&] { - if (!completed) { - // A host allocation or callback can unwind after copies were submitted. - // Keep sources alive and drain before permitting public release again. - for (auto &geometry : m_geometryInputUploads) - geometry->failInputUploads(); - finishGeometryPreparation(); - m_geometryInputVersions.clear(); - } - m_collectingGeometryInputUploads = false; - }); - // Commits capture sources; the first geometry finalizer submits every input - // batch before waiting. No legacy finalizer sees partially uploaded arrays. - // Retire obsolete cached copies before allocating a whole replacement cohort. - // A single geometry retains the existing allocation/retirement order. - if (m_geometryInputUploads.size() > 1) - for (auto &geometry : m_geometryInputUploads) - geometry->retirePreparationSnapshot(); - auto error = geometryInputAllocations->reclaim( - [&] { return finishGeometryPreparation(); }); - if (error == cudaSuccess) - error = waitForRenderConsumers(); - if (error == cudaSuccess) { - for (auto &geometry : m_geometryInputUploads) - geometry->submitInputUploads(); - error = finishGeometryPreparation(); - } - if (error != cudaSuccess) { - for (auto &geometry : m_geometryInputUploads) - geometry->failInputUploads(); - checkPreparation(m_geometryInputUploads.front().ptr, - error, - "geometry input batch completion"); - } - completed = true; - m_geometryInputVersions.clear(); - auto pending = std::move(m_geometryInputUploads); - for (auto &geometry : pending) - geometry->completeInputUploads(); - pending.clear(); - m_geometryInputUploads.swap(pending); - return true; + return m_geometryInputUploads.collect( + [&](Geometry *first) { + // The only route by which a geometry's host inputs reach the device. + // Commits capture sources; the first geometry finalizer submits every + // input batch before waiting. No legacy finalizer sees partially + // uploaded arrays. A finalizer then queues what no commit captured + // as a batch of its own. Retire obsolete cached copies before + // allocating a whole replacement cohort. A single geometry retains + // the existing allocation/retirement order. + if (m_geometryInputUploads.size() > 1) + m_geometryInputUploads.forEach([](Geometry *geometry) { + geometry->retirePreparationSnapshot(); + }); + auto error = geometryInputAllocations->reclaim( + [&] { return finishGeometryPreparation(); }); + if (error == cudaSuccess) + error = waitForRenderConsumers(); + if (error == cudaSuccess) { + m_geometryInputUploads.forEach( + [](Geometry *geometry) { geometry->submitInputUploads(); }); + error = finishGeometryPreparation(); + } + if (error != cudaSuccess) { + failGeometryInputUploads(); + failPreparation(first, error, "geometry input batch completion"); + } + m_geometryInputVersions.clear(); + }, + [](Geometry *geometry) noexcept { geometry->completeInputUploads(); }, + [&] { + // A host allocation or callback can unwind after copies were + // submitted. Keep sources alive and drain before permitting public + // release again. + failGeometryInputUploads(); + finishGeometryPreparation(); + m_geometryInputVersions.clear(); + }); +} + +void DeviceGlobalState::failGeometryInputUploads() +{ + m_geometryInputUploads.forEach( + [](Geometry *geometry) { geometry->failInputUploads(); }); } cudaError_t DeviceGlobalState::waitForRenderConsumers() { - // Scene submission is serialized. A completed retirement already covers - // these consumers; new render-stream producers invalidate that certificate. - return renderRetirement.isRetired() ? cudaSuccess - : preparation.waitFor(stream); + return cudaStreamQuery(stream) == cudaSuccess ? cudaSuccess + : preparation.waitFor(stream); +} + +cudaError_t DeviceGlobalState::retireRenderConsumers() +{ + // Anything but success, a failed query included, takes the wait: only a + // completed stream permits releasing what its work reads. + return cudaStreamQuery(stream) == cudaSuccess ? cudaSuccess + : cudaStreamSynchronize(stream); } -void DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) +size_t DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) { - m_geometryPreparations.enqueue(helium::IntrusivePtr(geometry)); + return m_geometryPreparations.enqueue( + helium::IntrusivePtr(geometry)); } bool DeviceGlobalState::collectingGeometryPreparations() const { return m_geometryPreparations.collecting() - || m_collectingGeometryInputUploads; + || m_geometryInputUploads.collecting(); } bool DeviceGlobalState::hasPendingGeometryPreparations() const { return m_geometryPreparations.collecting() || !m_geometryPreparations.empty() - || m_collectingGeometryInputUploads; + || m_geometryInputUploads.collecting(); } cudaError_t DeviceGlobalState::finishGeometryPreparation() { // Flush deferred small jobs even at intervening upload/retirement waits: // their input pointers must be consumed before a backing allocation changes. - const auto error = smallGeometryBatch.finish(preparation.stream()); + // Then read back every queued result in one transfer. + const auto stream = preparation.stream(); + auto error = smallGeometryBatch.launch(preparationResults, stream); + if (error == cudaSuccess) + error = preparationResults.readback(m_geometryPreparations.size(), stream); + const auto completion = cudaStreamSynchronize(stream); + if (error == cudaSuccess) + error = completion; if (error != cudaSuccess) { + cudaGetLastError(); // An intervening upload/legacy consumer may wait before the collection // point. Its stream-completion error affects all already queued results. m_geometryPreparations.forEach( - [](Geometry *geometry) { geometry->setPreparationFailed(true); }); - for (auto &geometry : m_geometryInputUploads) - geometry->failInputUploads(); + [](Geometry *geometry) { geometry->markPreparationFailed(); }); + failGeometryInputUploads(); } return error; } @@ -308,15 +314,21 @@ bool DeviceGlobalState::collectGeometryPreparations() { if (!collectGeometryInputUploads()) return false; - return m_geometryPreparations.collect([&](Geometry *first) { - // Owners remain in the queue if descriptor allocation or later registry - // publication throws. CUDA failure still invalidates the pending batch - // before reporting, so callbacks cannot see a partially valid generation. - const auto error = finishGeometryPreparation(); - if (error != cudaSuccess) - checkPreparation(first, error, "batch completion"); - // Numeric failures remain local to their geometries during publication. - }); + // Owners remain queued if descriptor allocation or registry publication + // throws. CUDA failure still invalidates the pending batch before reporting, + // so callbacks cannot see a partially valid generation. Numeric failures + // remain local to their geometries during publication. Every publication + // must succeed before any geometry leaves the queue. + return m_geometryPreparations.collect( + [&](Geometry *first) { + const auto error = finishGeometryPreparation(); + if (error != cudaSuccess) + failPreparation(first, error, "batch completion"); + m_geometryPreparations.forEach( + [](Geometry *geometry) { geometry->completePreparation(); }); + }, + [](Geometry *geometry) noexcept { geometry->markPreparationCollected(); }, + [] {}); } cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index ccb1f1aed..e39054b19 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -37,7 +37,6 @@ #include "utility/DeviceObjectArray.h" #include "utility/PreparationQueue.h" #include "utility/PreparationStream.h" -#include "utility/StreamRetirement.h" // helium #include "helium/BaseGlobalDeviceState.h" @@ -183,16 +182,18 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUcontext cudaContext; CUstream stream; PreparationStream preparation; - StreamRetirement renderRetirement; std::shared_ptr geometryInputAllocations{ std::make_shared()}; - GeometryReadbackPool geometryReadbacks; + // Scalar results of queued geometry preparations, by queue position. + PreparationResults preparationResults; struct BvhReadback { box3 bounds; uint64_t compactedSize; }; - PinnedReadbackPool bvhReadbacks; + // Pinned; the first BVH build allocates it. Builds are serialized and + // complete before returning, so one serves them all. + std::unique_ptr bvhReadback; SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; @@ -296,17 +297,24 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState cudaError_t stageGeometryArray(Array *array, helium::TimeStamp modified); bool collectGeometryInputUploads(); bool collectingGeometryInputUploads() const; - void enqueueGeometryPreparation(Geometry *geometry); + // Returns the geometry's position in the preparation queue. + size_t enqueueGeometryPreparation(Geometry *geometry); bool collectGeometryPreparations(); cudaError_t finishGeometryPreparation(); + // Both ask CUDA whether the render stream is idle, so no submission site + // has to announce itself. The first orders the preparation stream after + // outstanding render work without blocking the host; the second blocks the + // host, for callers about to release memory that work may still read. cudaError_t waitForRenderConsumers(); + cudaError_t retireRenderConsumers(); bool collectingGeometryPreparations() const; bool hasPendingGeometryPreparations() const; private: - std::vector> m_geometryInputUploads; + void failGeometryInputUploads(); + + PreparationQueue> m_geometryInputUploads; std::unordered_map m_geometryInputVersions; - bool m_collectingGeometryInputUploads{false}; PreparationQueue> m_geometryPreparations; }; diff --git a/devices/rtx/device/utility/DeviceAllocationCache.h b/devices/rtx/device/utility/DeviceAllocationCache.h index a15d48342..4a716d3e4 100644 --- a/devices/rtx/device/utility/DeviceAllocationCache.h +++ b/devices/rtx/device/utility/DeviceAllocationCache.h @@ -35,17 +35,17 @@ #include #include #include -#include #include +#include namespace visrtx { // Device-local cache for backend-owned authored-array uploads only. Returning -// storage NEVER makes it reusable immediately. A frozen pending cohort becomes -// reusable only after deferred CPU submissions and all GPU consumers complete. -// Call allocate/reclaim in the owning device's CUDA context; scene updates and -// reclaim calls are serialized. No mutex is held across CUDA calls or -// callbacks. +// storage NEVER makes it reusable immediately: reclaim() freezes the blocks +// returned so far, and they become reusable only after deferred CPU +// submissions and all GPU consumers complete. Call allocate/reclaim in the +// owning device's CUDA context; scene updates and reclaim calls are +// serialized. No mutex is held across CUDA calls or callbacks. struct DeviceAllocationCache { static constexpr size_t MAX_BLOCKS = 256; @@ -68,20 +68,20 @@ struct DeviceAllocationCache void *pointer{nullptr}; size_t bytes{0}; }; - bool trimReady(); - void finishCohort( - const std::array &cohort, size_t count, bool reusable); + void *remove(size_t index); + bool freeBlocks(bool readyOnly); const size_t m_byteLimit; const size_t m_blockLimit; std::mutex m_mutex; bool m_enabled{true}; - // Counts include a frozen cohort while reclaim() is outside the lock. size_t m_cachedBytes{0}; - size_t m_cachedBlocks{0}; - size_t m_pendingCount{0}; - size_t m_readyCount{0}; - std::array m_pending; - std::array m_ready; + // m_blocks holds three runs: [0, m_readyEnd) is reusable, [m_readyEnd, + // m_frozenEnd) is the cohort a reclaim() in progress froze, and + // [m_frozenEnd, m_count) was returned since and waits for the next one. + size_t m_readyEnd{0}; + size_t m_frozenEnd{0}; + size_t m_count{0}; + std::array m_blocks; }; inline DeviceAllocationCache::DeviceAllocationCache( @@ -101,18 +101,15 @@ inline cudaError_t DeviceAllocationCache::allocate(size_t bytes, void **pointer) return cudaSuccess; { std::lock_guard lock(m_mutex); - for (size_t i = 0; i < m_readyCount; ++i) { - if (m_ready[i].bytes == bytes) { - *pointer = m_ready[i].pointer; - m_ready[i] = m_ready[--m_readyCount]; - m_cachedBytes -= bytes; - --m_cachedBlocks; + for (size_t i = 0; i < m_readyEnd; ++i) { + if (m_blocks[i].bytes == bytes) { + *pointer = remove(i); return cudaSuccess; } } } auto error = cudaMalloc(pointer, bytes); - if (error == cudaErrorMemoryAllocation && trimReady()) { + if (error == cudaErrorMemoryAllocation && freeBlocks(true)) { // Release only certified idle blocks. Pending blocks are not safe to hand // back without a completion boundary, and are never borrowed on failure. cudaGetLastError(); @@ -128,11 +125,10 @@ inline void DeviceAllocationCache::release(void *pointer, size_t bytes) return; { std::lock_guard lock(m_mutex); - if (m_enabled && m_cachedBlocks < m_blockLimit + if (m_enabled && m_count < m_blockLimit && bytes <= m_byteLimit - m_cachedBytes) { - m_pending[m_pendingCount++] = {pointer, bytes}; + m_blocks[m_count++] = {pointer, bytes}; m_cachedBytes += bytes; - ++m_cachedBlocks; return; } } @@ -144,93 +140,75 @@ template inline cudaError_t DeviceAllocationCache::reclaim( CompleteDeferred completeDeferred) { - std::array cohort; - size_t count = 0; { std::lock_guard lock(m_mutex); - count = m_pendingCount; - if (!count) + if (m_frozenEnd == m_count) return cudaSuccess; - std::copy_n(m_pending.begin(), count, cohort.begin()); - m_pendingCount = 0; + m_frozenEnd = m_count; } bool reusable = false; - // Restores the frozen cohort to pending on host exceptions too. This guard - // borrows the cache; its deleter returns blocks rather than deleting this. - auto restore = [&](DeviceAllocationCache *) { - finishCohort(cohort, count, reusable); - }; - std::unique_ptr guard( - this, restore); + // Runs on host exceptions too: a cohort that was not certified idle goes + // back to waiting. + auto finish = nonstd::make_scope_exit([&] { + std::lock_guard lock(m_mutex); + if (reusable) + m_readyEnd = m_frozenEnd; + else + m_frozenEnd = m_readyEnd; + }); auto error = completeDeferred(); - // Legacy consumers and application-visible array pointers need the same - // conservative device-wide retirement cudaFree previously provided per block. - // One boundary covers the cohort; later returns remain pending for next time. + // These blocks used to be retired by cudaFree, which waits for the whole + // context. One wait of the same reach covers the cohort without a list of + // the streams that may have read it; later returns wait for the next + // reclaim(). if (error == cudaSuccess) error = cudaDeviceSynchronize(); reusable = error == cudaSuccess; return error; } -inline void DeviceAllocationCache::finishCohort( - const std::array &cohort, size_t count, bool reusable) +// Call with the mutex held. The hole is filled from the end of the block's own +// run, then from the end of each later run, so the three stay contiguous. +inline void *DeviceAllocationCache::remove(size_t index) { - bool freeCohort = false; - { - std::lock_guard lock(m_mutex); - freeCohort = !m_enabled; - for (size_t i = 0; i < count; ++i) { - const auto block = cohort[i]; - if (freeCohort) { - m_cachedBytes -= block.bytes; - --m_cachedBlocks; - } else if (reusable) - m_ready[m_readyCount++] = block; - else - m_pending[m_pendingCount++] = block; - } + const auto block = m_blocks[index]; + if (index < m_readyEnd) { + m_blocks[index] = m_blocks[--m_readyEnd]; + index = m_readyEnd; } - if (freeCohort) - for (size_t i = 0; i < count; ++i) - cudaFree(cohort[i].pointer); + if (index < m_frozenEnd) { + m_blocks[index] = m_blocks[--m_frozenEnd]; + index = m_frozenEnd; + } + m_blocks[index] = m_blocks[--m_count]; + m_cachedBytes -= block.bytes; + return block.pointer; } -inline bool DeviceAllocationCache::trimReady() +// Frees the reusable blocks, or every block. Returns whether any was freed. +inline bool DeviceAllocationCache::freeBlocks(bool readyOnly) { - std::array blocks; - size_t count = 0; - { - std::lock_guard lock(m_mutex); - count = m_readyCount; - std::copy_n(m_ready.begin(), count, blocks.begin()); - m_readyCount = 0; - m_cachedBlocks -= count; - for (size_t i = 0; i < count; ++i) - m_cachedBytes -= blocks[i].bytes; + bool freed = false; + for (;;) { + void *pointer = nullptr; + { + std::lock_guard lock(m_mutex); + if ((readyOnly ? m_readyEnd : m_count) == 0) + return freed; + pointer = remove(0); + } + cudaFree(pointer); + freed = true; } - for (size_t i = 0; i < count; ++i) - cudaFree(blocks[i].pointer); - return count != 0; } inline void DeviceAllocationCache::close() { - std::array blocks; - size_t count = 0; { std::lock_guard lock(m_mutex); m_enabled = false; - for (size_t i = 0; i < m_pendingCount; ++i) - blocks[count++] = m_pending[i]; - for (size_t i = 0; i < m_readyCount; ++i) - blocks[count++] = m_ready[i]; - m_pendingCount = m_readyCount = 0; - m_cachedBlocks -= count; - for (size_t i = 0; i < count; ++i) - m_cachedBytes -= blocks[i].bytes; } - for (size_t i = 0; i < count; ++i) - cudaFree(blocks[i].pointer); + freeBlocks(false); } } // namespace visrtx diff --git a/devices/rtx/device/utility/DeviceBuffer.h b/devices/rtx/device/utility/DeviceBuffer.h index 9fc629763..85049819b 100644 --- a/devices/rtx/device/utility/DeviceBuffer.h +++ b/devices/rtx/device/utility/DeviceBuffer.h @@ -73,6 +73,9 @@ struct DeviceBuffer void reset(); void reserve(size_t bytes); + // Grows storage to at least `bytes` and consumes the CUDA error the attempt + // leaves pending. On failure the buffer is empty, so a retry allocates. + cudaError_t tryReserve(size_t bytes); operator bool() const; @@ -128,17 +131,9 @@ inline cudaError_t DeviceBuffer::enqueueUpload(const T *src, > (std::numeric_limits::max() - byteOffsetStart) / sizeof(T)) return cudaErrorInvalidValue; const auto copyBytes = bytesof(numElements); - const auto needed = copyBytes + byteOffsetStart; - if (!ptr()) - reset(); // A failed allocation may retain capacity without storage. - if (needed > bytes()) { - alloc(needed); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - return error; - } - if (!ptr() || bytes() < needed) - return cudaErrorMemoryAllocation; + const auto error = tryReserve(copyBytes + byteOffsetStart); + if (error != cudaSuccess) + return error; return cudaMemcpyAsync(static_cast(ptr()) + byteOffsetStart, src, copyBytes, @@ -193,6 +188,23 @@ inline void DeviceBuffer::reserve(size_t numBytes) alloc(numBytes); } +inline cudaError_t DeviceBuffer::tryReserve(size_t numBytes) +{ + if (!ptr()) + reset(); // reserve()/upload() failures retain capacity without storage. + if (numBytes <= bytes()) + return cudaSuccess; + alloc(numBytes); + // Consume the runtime error even when missing storage identifies the + // failure. Otherwise the next successful CUDA call inherits it. + auto error = cudaGetLastError(); + if (error == cudaSuccess && !ptr()) + error = cudaErrorMemoryAllocation; + if (error != cudaSuccess) + reset(); + return error; +} + inline DeviceBuffer::operator bool() const { return ptr() != nullptr; diff --git a/devices/rtx/device/utility/PinnedReadbackPool.h b/devices/rtx/device/utility/PinnedReadbackPool.h deleted file mode 100644 index 97dcb95c4..000000000 --- a/devices/rtx/device/utility/PinnedReadbackPool.h +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace visrtx { - -// A device-local high-water cache of pinned pages. Each lease owns two result -// slots and retains its page independently of the pool's lifetime. Returning a -// lease is legal only after its GPU writers have completed; callers provide -// that ordering. Acquisition/release may run on different host -// threads. -template -struct PinnedReadbackPool -{ - private: - struct Page; - - public: - static constexpr size_t SLOTS_PER_PAGE = 256; - - struct Lease - { - Lease() = default; - ~Lease(); - Lease(const Lease &) = delete; - Lease &operator=(const Lease &) = delete; - Lease(Lease &&other) noexcept; - Lease &operator=(Lease &&other) noexcept; - - Result *data() const; - void reset(); - - private: - friend struct PinnedReadbackPool; - std::shared_ptr m_page; - size_t m_index{0}; - }; - - PinnedReadbackPool() = default; - PinnedReadbackPool(const PinnedReadbackPool &) = delete; - PinnedReadbackPool &operator=(const PinnedReadbackPool &) = delete; - - cudaError_t acquire(Lease &lease); - - private: - std::mutex m_mutex; - std::vector> m_pages; -}; - -template -struct PinnedReadbackPool::Page -{ - Page(); - ~Page(); - bool take(size_t &index); - void release(size_t index); - - Result *memory{nullptr}; - std::mutex mutex; - std::array freeSlots; - size_t freeCount{SLOTS_PER_PAGE}; -}; - -// Inlined definitions //////////////////////////////////////////////////////// - -template -inline PinnedReadbackPool::Page::Page() -{ - for (size_t i = 0; i < SLOTS_PER_PAGE; ++i) - freeSlots[i] = SLOTS_PER_PAGE - i - 1; -} - -template -inline PinnedReadbackPool::Page::~Page() -{ - if (memory) - cudaFreeHost(memory); -} - -template -inline bool PinnedReadbackPool::Page::take(size_t &index) -{ - std::lock_guard lock(mutex); - if (freeCount == 0) - return false; - index = freeSlots[--freeCount]; - return true; -} - -template -inline void PinnedReadbackPool::Page::release(size_t index) -{ - std::lock_guard lock(mutex); - assert(index < SLOTS_PER_PAGE && freeCount < SLOTS_PER_PAGE); - freeSlots[freeCount++] = index; -} - -template -inline PinnedReadbackPool::Lease::~Lease() -{ - reset(); -} - -template -inline PinnedReadbackPool::Lease::Lease(Lease &&other) noexcept - : m_page(std::move(other.m_page)), m_index(other.m_index) -{} - -template -inline typename PinnedReadbackPool::Lease & -PinnedReadbackPool::Lease::operator=(Lease &&other) noexcept -{ - if (this != &other) { - reset(); - m_page = std::move(other.m_page); - m_index = other.m_index; - } - return *this; -} - -template -inline Result *PinnedReadbackPool::Lease::data() const -{ - return m_page ? m_page->memory + 2 * m_index : nullptr; -} - -template -inline void PinnedReadbackPool::Lease::reset() -{ - if (m_page) { - m_page->release(m_index); - m_page.reset(); - } -} - -template -inline cudaError_t PinnedReadbackPool::acquire(Lease &lease) -{ - if (lease.data()) - return cudaSuccess; - { - std::lock_guard lock(m_mutex); - for (auto &page : m_pages) { - if (page->take(lease.m_index)) { - lease.m_page = page; - return cudaSuccess; - } - } - } - - // CUDA allocation can wait for other work. Do not hold a pool/page mutex - // across it; simultaneous growth may allocate an extra page, but is safe. - auto page = std::make_shared(); - void *memory = nullptr; - const auto error = - cudaMallocHost(&memory, 2 * SLOTS_PER_PAGE * sizeof(Result)); - if (error != cudaSuccess) { - cudaGetLastError(); // A failed page allocation must not poison a retry. - return error; - } - page->memory = static_cast(memory); - { - std::lock_guard lock(m_mutex); - m_pages.push_back(page); - const bool acquired = page->take(lease.m_index); - assert(acquired); - (void)acquired; - lease.m_page = std::move(page); - } - return cudaSuccess; -} - -} // namespace visrtx diff --git a/devices/rtx/device/utility/PreparationQueue.h b/devices/rtx/device/utility/PreparationQueue.h index c2dc08123..9b2b8746d 100644 --- a/devices/rtx/device/utility/PreparationQueue.h +++ b/devices/rtx/device/utility/PreparationQueue.h @@ -38,20 +38,34 @@ namespace visrtx { -// Serialized preparation ownership and publication. Pointer is an owning -// pointer; its object provides completePreparation() (retryable publication) -// and noexcept markPreparationCollected(). Submission cannot append while a -// collection is running. Reentrant collection is refused. +// Owners of objects waiting for one stage of batched preparation (input +// uploads, deferred preparation results). Pointer is an owning pointer. +// collect() runs the stage as one transaction: +// +// run(first) Batch-wide work, including any per-object publication. +// first is the oldest queued object. May throw. +// retire(object) Per object, after run() returned. Must be noexcept. +// unwind() Only if run() throws, while every owner is still queued. +// Runs during stack unwinding, so it must not throw. +// +// Membership is released only after every object is retired, so a throw +// leaves all owners queued for the next collection. Objects are released while +// collecting() is still true, so their destructors cannot start another +// collection. enqueue() is not allowed during a collection. template -struct PreparationQueue +class PreparationQueue { - void enqueue(Pointer object); + public: + // Returns the object's position, stable until a collection retires it. + size_t enqueue(Pointer object); bool empty() const; + size_t size() const; bool collecting() const; template void forEach(Function function); - template - bool collect(Finish finish); + // Returns false, doing nothing, if a collection is already running. + template + bool collect(Run run, Retire retire, Unwind unwind); private: std::vector m_pending; @@ -59,10 +73,11 @@ struct PreparationQueue }; template -inline void PreparationQueue::enqueue(Pointer object) +inline size_t PreparationQueue::enqueue(Pointer object) { assert(!m_collecting); m_pending.push_back(std::move(object)); + return m_pending.size() - 1; } template @@ -71,6 +86,12 @@ inline bool PreparationQueue::empty() const return m_pending.empty(); } +template +inline size_t PreparationQueue::size() const +{ + return m_pending.size(); +} + template inline bool PreparationQueue::collecting() const { @@ -86,34 +107,36 @@ inline void PreparationQueue::forEach(Function function) } template -template -inline bool PreparationQueue::collect(Finish finish) +template +inline bool PreparationQueue::collect( + Run run, Retire retire, Unwind unwind) { if (m_collecting) return false; if (m_pending.empty()) return true; m_collecting = true; - auto collecting = nonstd::make_scope_exit([&] { m_collecting = false; }); - // Keep owners here through both potentially throwing stages. If descriptor - // allocation or registry publication throws, raw jobs and queued flags still - // have owners, and another collection can retry without reallocating a queue. - finish(m_pending.front().operator->()); - for (auto &object : m_pending) - object->completePreparation(); - // Only retire queue membership after every publication succeeded. Earlier - // objects must remain queued if a later object's publication throws. + bool ran = false; + // unwind() runs from this guard during stack unwinding, so a throw from it + // terminates instead of replacing the original error. + auto collecting = nonstd::make_scope_exit([&] { + if (!ran) + unwind(); + m_collecting = false; + }); + run(m_pending.front().operator->()); + ran = true; for (auto &object : m_pending) { auto *pointer = object.operator->(); - static_assert(noexcept(pointer->markPreparationCollected())); - pointer->markPreparationCollected(); + static_assert(noexcept(retire(pointer)), + "PreparationQueue retire() must be noexcept: a throw would leave " + "some objects retired and others not"); + retire(pointer); } - // Remove membership before destructors/deleters can reenter the owner. - // Unlike the old pre-finish move, this happens only after GPU completion, - // successful publication and non-throwing flag retirement. + // Release owners only now, and keep the capacity for the next collection. auto retired = std::move(m_pending); retired.clear(); - m_pending.swap(retired); // Reuse capacity without allocating on retry. + m_pending.swap(retired); return true; } diff --git a/devices/rtx/device/utility/StreamRetirement.h b/devices/rtx/device/utility/StreamRetirement.h deleted file mode 100644 index d43009fcb..000000000 --- a/devices/rtx/device/utility/StreamRetirement.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#pragma once - -#include -#include -#include - -namespace visrtx { - -// Scene submission is serialized. Invalidate BEFORE submitting work on the -// bound stream. A successful retirement covers only the generation captured -// before its wait, never work submitted by a callback during that wait. -// Failure cleanup must still use an unconditional drain, not this cache. -struct StreamRetirement -{ - bool isRetired() const; - void initialize(cudaStream_t stream); - void invalidate(); - cudaError_t retire(); - - private: - cudaStream_t m_stream{nullptr}; - std::atomic m_submitted{1}; - std::atomic m_retired{0}; -}; - -inline bool StreamRetirement::isRetired() const -{ - const auto generation = m_submitted.load(std::memory_order_acquire); - return m_retired.load(std::memory_order_acquire) >= generation; -} - -inline void StreamRetirement::initialize(cudaStream_t stream) -{ - m_stream = stream; - m_submitted = 1; - m_retired = 0; -} - -inline void StreamRetirement::invalidate() -{ - m_submitted.fetch_add(1, std::memory_order_release); -} - -inline cudaError_t StreamRetirement::retire() -{ - const auto generation = m_submitted.load(std::memory_order_acquire); - if (m_retired.load(std::memory_order_acquire) >= generation) - return cudaSuccess; - const auto error = cudaStreamSynchronize(m_stream); - if (error == cudaSuccess) { - auto retired = m_retired.load(std::memory_order_relaxed); - while (retired < generation - && !m_retired.compare_exchange_weak(retired, - generation, - std::memory_order_release, - std::memory_order_relaxed)) { - } - } - return error; -} - -} // namespace visrtx diff --git a/devices/rtx/device/volume/TransferFunction1D.cpp b/devices/rtx/device/volume/TransferFunction1D.cpp index f20a26d5b..d094b2a15 100644 --- a/devices/rtx/device/volume/TransferFunction1D.cpp +++ b/devices/rtx/device/volume/TransferFunction1D.cpp @@ -89,7 +89,6 @@ void TransferFunction1D::finalize() discritizeTFData(); createTFTexture(); - deviceState()->renderRetirement.invalidate(); m_field->m_uniformGrid.computeOpacityBounds( deviceState()->stream, m_textureObject, m_tfDim, m_valueRange); upload(); diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 7f4766eee..9f7ec1929 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -23,8 +23,8 @@ reset remains intact. Before replacing parameter references, the input-retiremen check compares the declared committed preparation inputs and referenced-object versions with the last successful preparation. Unchanged inputs skip retirement; first preparation, changed inputs, failed preparation, and non-opt-in types request -retirement. A device-local completion certificate deduplicates successful waits -until another render/work-stream workload is submitted. This check performs no GPU uploads. Parameter lookup names are +retirement. Retirement waits only when `cudaStreamQuery` reports outstanding +render-stream work. This check performs no GPU uploads. Parameter lookup names are cached once per geometry rather than rebuilt on every finalization. Finalization still revalidates values, object versions, and backing pointers before reusing derived data: dependencies can be updated between commit and finalization, so the @@ -119,10 +119,14 @@ is reused. submissions mark their still-current array versions uploaded. A failed geometry remains unprepared even if another geometry successfully shares one of its arrays. Legacy consumers can safely use completed copies afterward. -- Observer-only updates, or arrays modified after submission, retain the local - per-geometry upload path. A later geometry commit or observer update may retry - a failed input generation; unchanged failed inputs cannot silently become - prepared. Preparation reuse does not capture or submit an upload batch. +- Observer-only updates, and arrays modified after submission, have no commit + to capture them. The geometry's finalizer captures its still-dirty declared + host arrays and collects them through the same batch, as a batch of that + geometry alone: there is one upload implementation with two triggers. A + failure there fails that finalization, so the next one retries. A later + geometry commit or observer update may retry a failed input generation; + unchanged failed inputs cannot silently become prepared. Preparation reuse + does not capture or submit an upload batch. - These checked geometry kernels no longer import the default stream: authored inputs are ready before they run. Other array consumers retain their existing upload path. @@ -145,20 +149,17 @@ is reused. published only on success. Group/World failure state prevents failed builds from being treated as ready and permits a later retry. - Parameter-reference replacement and last-public-release privatization require - completed old render consumers. `StreamRetirement` caches a successful wait - for the generation captured before synchronization. Frame submission, - denoiser setup/launch/conversion, channel resolution, transfer-function opacity - bounds, and isosurface brick preparation invalidate that certificate before - submitting work. Shared arrays - and different frames use the same device-local generation. A generation - invalidated during a wait cannot inherit that wait's certificate; errors never - certify completion. Scene submission remains serialized. Error handling uses - unconditional drains, not the cached retirement path, before storage can be - retired or retried. - -`TestStreamRetirement` checks repeated retirement requests, a gated producer, -generation changes during a wait, and failure/retry. The existing shared-array, -privatization, frame, denoiser and isosurface tests exercise the producer paths. + completed old render consumers. `DeviceGlobalState::retireRenderConsumers()` + asks `cudaStreamQuery` whether the render stream is idle and synchronizes it + only when it is not, so frame submission, denoising, channel resolution, + transfer-function opacity bounds and isosurface brick preparation need no + bookkeeping of their own. A failed query never counts as idle: it takes the + synchronize and reports that result. Scene submission remains serialized. + Error handling uses unconditional drains, not the query, before storage can + be retired or retried. + +The existing shared-array, privatization, frame, denoiser and isosurface tests +exercise the producer paths. This is not concurrent in-place scene replacement. Legacy default-stream events can include preceding work on blocking streams; tangent generation and field-grid @@ -182,8 +183,9 @@ across host-vector growth and preservation of newer dirty edits. ## Geometry submission and collection -Checked bounds and area-CDF preparation queue kernels and asynchronous readbacks -into geometry-owned pinned storage. A successful submission is not publication: +Checked bounds and area-CDF preparation queue kernels that write their scalar +results into the device's `PreparationResults`, at the geometry's position in the +preparation queue. A successful submission is not publication: scalar outputs, numeric validation, and geometry registry updates happen only after collection. The device queue retains each submitted geometry, and thereby its arrays and derived buffers, until those operations finish. Ownership stays @@ -191,6 +193,9 @@ in the queue through descriptor allocation and registry publication; queued flag are cleared only after every publication completes. A host exception leaves the owners and queued flags available for retry, including already-drained results whose publication must be retried. Collection reentry remains refused. +Committed input uploads are queued and collected by the same `PreparationQueue` +transaction; their unwind step fails and drains the batch before the owners +become collectable again. `TestPreparationQueue` tests this ownership transaction directly with throwing completion/publication callbacks, orphaned owners, retry and teardown. It does @@ -263,14 +268,10 @@ upload, dispatch and readback completion. Descriptors remain stable through fallback drains; dispatch or transfer failure invalidates the pending batch, while numeric failures remain local to their geometry. -Small jobs write both result slots into a contiguous device-owned result buffer. -The batch performs one asynchronous transfer into a reusable pinned host buffer, -then scatters only completed, requested slots into the geometries' summaries. -Even unused slots are initialized before transfer. A bounds-only flush followed -by a later area request preserves the earlier bounds summary. Failed transfers -or completion do not scatter partial results. Both batch buffers grow to their -high-water size and remain alive through fallback drains; the per-geometry -pinned leases and general-path readbacks retain their existing ownership. +Small jobs and the general path write the same results storage, so a geometry's +bounds and area results sit at its queue position whichever path produced them. +Small jobs write only the results they request: a bounds-only flush followed by a +later area request preserves the earlier bounds result. `TestSmallGeometryBatch` exercises mixed sphere/cone/cylinder/triangle batches at 1, 31, 32, 33, 255, 256 and 257 primitives with host and device-backed logical @@ -292,26 +293,32 @@ and restoration with new weights discriminate weighting, order, normalization and stale sampling data rather than just bounds or light counts. No public debug property or shared production area helper is used by the oracle. -Pinned readback storage is leased from the device's `GeometryReadbackPool`. -Each page holds 256 geometry leases, each containing two result slots (a 4 KiB -page with the current result layout). A geometry keeps its lease across updates; -returning it after collection makes the slot reusable without a CUDA allocation. -The pool caches pages at its high-water mark until device teardown rather than -trimming on every geometry destruction. A lease retains its page independently -of the pool's lifetime, so cleanup cannot free storage while a lease still exists. -This reduces allocation count, not necessarily requested bytes for tiny scenes: -a partially occupied page still reserves the whole page. - -Pool/page locks protect slot accounting but are never held across CUDA allocation -or free. A failed page allocation leaves existing leases intact and clears CUDA -last-error state before retry. Concurrent growth may allocate an extra page; -source/result lifetime ordering remains the collection queue's responsibility. -`TestGeometryReadbackPool` covers first-page/growth failure and retry, slot reuse, -move/reset, pool-before-lease teardown, concurrent leases, and asynchronous DMA -into separate slots on a page. +`PreparationResults` holds two results per queued geometry: bounds (epsilon +scale and validity) and total area. Kernels write its device storage; every +`finishGeometryPreparation()` that follows a write copies the queued range to +pinned host storage in one transfer, then synchronizes. `complete()` reads the +host copy at the geometry's queue position. There is no per-geometry pinned +storage and no host-side copy between pinned buffers. Device and pinned storage +grow together, starting at 256 geometries (4 KiB each with the current result +layout), doubling when the queue outgrows them, and staying at their high-water +size until device teardown. The general path reserves at submission, so an +allocation failure fails only the submitting geometry; the small batch reserves +when it launches, so a failure there fails the whole batch. Device growth +synchronizes the preparation stream and copies the earlier results into the new +storage; the old pinned storage holds nothing still needed, because each +readback completes in its own finish and the next one transfers the whole +queued range. A failed allocation keeps existing storage and clears CUDA +last-error state, so a retry can succeed. `TestPreparationResults` covers first +and growth allocation failure and retry on either side, preservation across +growth, rewrites between readbacks and the readback range. + +BVH builds read back their bounds and compacted size through one pinned +`BvhReadback` owned by the device state. The first build allocates it; builds are +serialized and complete before returning, so no transfer outlives a build. Committed host inputs now complete in a cross-geometry batch before finalizers -run. Observer-only input updates remain conservative. Last-public-release of +run. Observer-only input updates take the same path one geometry at a time. +Last-public-release of shared host arrays during an active upload joins the preparation stream before the application may free its source memory. Quad/curve generated-data completion, tangent generation, and field/isosurface @@ -321,7 +328,7 @@ independent scene generations or concurrent in-place replacement during tracing. `TestDeferredGeometryPreparation` covers recommitting a queued geometry, retained captured-device inputs, last-reference queue ownership through teardown, unrelated numeric failures, and collection-time callback reentry. Injection cases also -cover pinned-readback allocation failure, completion failure across multiple +cover results allocation failure, completion failure across multiple queued geometries, an intervening upload completion failure, and shared CUDA array retirement while preparation remains pending. `TestGeometryInputBatch` checks submission-before-wait across multiple geometries, shared-array dedup, From 4773aff9780d7e2605595f6025878158bb4a3d6d Mon Sep 17 00:00:00 2001 From: Jefferson Amstutz Date: Wed, 25 Nov 2026 09:11:34 -0600 Subject: [PATCH 20/20] refactor(rtx): extract GeometryPreparation and run the lifecycle once Move the preparation stream, storage, queues, render-stream waits and failure API into a private GeometryPreparation, run the preparation lifecycle once in Geometry::finalize(), and report every reason not to upload (including World and Group build failures) by return value. - add GeometryPreparation to hold the preparation stream and storage - move the render-stream waits and upload-and-wait into GeometryPreparation - move the geometry preparation queues into GeometryPreparation - give Array::privatize() two waits on GeometryPreparation - put the preparation failure API on GeometryPreparation - make the geometry preparation protocol private - describe the geometry preparation lifecycle in GeometryPreparation.h - run the preparation lifecycle once, in Geometry::finalize() - report every reason not to upload through prepare()'s result - report rejected geometry input without the CUDA failure path - reserve the bounds buffer once in Preprocessing::bounds() - report World and Group build failures by return value - keep the Geometry Light area data in the Geometry base - narrow the Geometry preparation state to three values - separate the scene-update stream from GeometryPreparation - walk the Geometry preparation parameters in one place - share the Array upload selection and privatization failure --- devices/rtx/AGENTS.md | 3 + .../tests/api/TestCudaPreparationFailure.cpp | 11 +- .../apps/tests/api/TestPreparationResults.cpp | 2 +- .../apps/tests/api/TestPreparationStream.cpp | 14 +- .../apps/tests/api/TestRegistrySnapshot.cpp | 12 +- devices/rtx/device/CMakeLists.txt | 1 + devices/rtx/device/VisRTXDevice.cpp | 13 +- devices/rtx/device/array/Array.cpp | 78 +++-- devices/rtx/device/array/Array.h | 9 + devices/rtx/device/frame/Frame.cu | 3 +- devices/rtx/device/geometry/Cone.cpp | 60 +--- devices/rtx/device/geometry/Cone.h | 18 +- devices/rtx/device/geometry/Curve.cpp | 45 +-- devices/rtx/device/geometry/Curve.h | 6 +- devices/rtx/device/geometry/Cylinder.cpp | 59 +--- devices/rtx/device/geometry/Cylinder.h | 18 +- devices/rtx/device/geometry/Geometry.cpp | 239 +++++++-------- devices/rtx/device/geometry/Geometry.h | 209 ++++++++----- .../device/geometry/GeometryPreparation.cpp | 279 ++++++++++++++++++ .../rtx/device/geometry/GeometryPreparation.h | 154 ++++++++++ .../rtx/device/geometry/Intersectors_ptx.cu | 2 +- devices/rtx/device/geometry/Isosurface.cpp | 16 +- devices/rtx/device/geometry/Isosurface.h | 2 +- devices/rtx/device/geometry/Neural.cpp | 6 +- devices/rtx/device/geometry/Neural.h | 2 +- devices/rtx/device/geometry/Preprocessing.cu | 144 +++------ devices/rtx/device/geometry/Preprocessing.h | 38 +-- devices/rtx/device/geometry/Quad.cpp | 19 +- devices/rtx/device/geometry/Quad.h | 4 +- devices/rtx/device/geometry/SDF.cpp | 16 +- devices/rtx/device/geometry/SDF.h | 2 +- devices/rtx/device/geometry/Sphere.cu | 48 +-- devices/rtx/device/geometry/Sphere.h | 19 +- devices/rtx/device/geometry/Triangle.cpp | 62 +--- devices/rtx/device/geometry/Triangle.h | 21 +- .../rtx/device/geometry/UnknownGeometry.cpp | 5 + devices/rtx/device/geometry/UnknownGeometry.h | 1 + devices/rtx/device/optix_visrtx.cpp | 197 ++----------- devices/rtx/device/optix_visrtx.h | 51 +--- .../rtx/device/utility/PreparationStream.h | 97 ++++-- devices/rtx/device/world/Group.cpp | 119 ++++---- devices/rtx/device/world/Group.h | 9 +- devices/rtx/device/world/World.cpp | 118 +++++--- devices/rtx/device/world/World.h | 20 +- .../rtx/docs/geometry-preparation-reuse.md | 40 ++- 45 files changed, 1246 insertions(+), 1045 deletions(-) create mode 100644 devices/rtx/device/geometry/GeometryPreparation.cpp create mode 100644 devices/rtx/device/geometry/GeometryPreparation.h diff --git a/devices/rtx/AGENTS.md b/devices/rtx/AGENTS.md index 1a18e3f7f..ad4d62ffd 100644 --- a/devices/rtx/AGENTS.md +++ b/devices/rtx/AGENTS.md @@ -57,6 +57,8 @@ Test sources: `apps/tests/api/` (e.g. `ctest -C Release -R TestSpheres`). Run vi - OptiX device context - All precompiled PTX modules (one per renderer type, one per material/sampler type) - `DeviceObjectArray` registries for materials, geometries, samplers, spatial fields +- `preparationStream`, the `PreparationStream` that geometry preparation, BVH builds, registry uploads and world-table uploads submit to +- `preparation`, the one `GeometryPreparation` that owns GPU geometry preparation (its queues, batch, results and input allocation cache); read `device/geometry/GeometryPreparation.h` for the lifecycle **Frame::renderFrame()** orchestrates each frame: @@ -121,6 +123,7 @@ After rebuild, `OptixTraversableHandle`s are stored in `WorldGPUData` and passed | `device/renderer/Renderer.h` | Base renderer: pipeline init, SBT construction | | `device/world/World.h/.cpp` | BVH (TLAS/BLAS) management | | `device/utility/DeviceObjectArray.h` | Thread-safe GPU slot allocator / registry | +| `device/geometry/GeometryPreparation.h` | Owner of GPU geometry preparation: one scene update as one commit/upload/submit/collect transaction | ### Renderer Types diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp index 6926c5873..278f66647 100644 --- a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -371,12 +371,15 @@ extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) return result; } -// Retirement synchronizes the render stream only when a query finds it busy, -// and it is idle whenever a test arms WORK_SYNC. Report it busy so the wait -// that carries the injected failure happens. +// Retirement synchronizes the render stream, and full preparation orders +// itself after it, only when a query finds it busy; it is idle whenever a test +// arms WORK_SYNC or PREPARATION_DEPENDENCY. Report it busy so the wait that +// carries the injected failure happens. extern "C" cudaError_t cudaStreamQuery(cudaStream_t stream) { - if (stream && stream != preparationStream && failure == Failure::WORK_SYNC) + if (stream && stream != preparationStream + && (failure == Failure::WORK_SYNC + || failure == Failure::PREPARATION_DEPENDENCY)) return cudaErrorNotReady; return next("cudaStreamQuery")(stream); } diff --git a/devices/rtx/apps/tests/api/TestPreparationResults.cpp b/devices/rtx/apps/tests/api/TestPreparationResults.cpp index e7c1f6246..fa5d8ff96 100644 --- a/devices/rtx/apps/tests/api/TestPreparationResults.cpp +++ b/devices/rtx/apps/tests/api/TestPreparationResults.cpp @@ -76,7 +76,7 @@ bool holds(const PreparationResults &results, size_t position, float value) && read.area.invalid == uint32_t(position) + 1; } -// Reads back and waits, as finishGeometryPreparation() does. +// Reads back and waits, as GeometryPreparation::flush() does. bool readBackAndWait( PreparationResults &results, size_t count, cudaStream_t stream) { diff --git a/devices/rtx/apps/tests/api/TestPreparationStream.cpp b/devices/rtx/apps/tests/api/TestPreparationStream.cpp index 45fc7c95b..fc207234f 100644 --- a/devices/rtx/apps/tests/api/TestPreparationStream.cpp +++ b/devices/rtx/apps/tests/api/TestPreparationStream.cpp @@ -69,7 +69,7 @@ int main() cudaStream_t other{}; cudaEvent_t done{}; int *device = nullptr; - if (!check(preparation.initialize()) + if (!check(preparation.initialize(nullptr)) || !check(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking)) || !check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming)) || !check( @@ -86,7 +86,7 @@ int main() const cudaStream_t producer = mode == 2 ? nullptr : other; ok = check(cudaMemsetAsync(device, 0, 2 * sizeof(int), preparation.stream())) - && check(preparation.finish()) && ok; + && check(preparation.sync()) && ok; Gate gate; // Watchdog is a deadlock escape, not a latency assertion. A stream-wide // or device-wide accidental wait must fail rather than hang the suite. @@ -103,11 +103,11 @@ int main() int result = 0; if (dependency) { ok = check(cudaMemsetAsync(device, 0x2a, sizeof(int), producer)) && ok; - ok = check(preparation.waitFor(producer)) && ok; + ok = check(preparation.orderAfter(producer)) && ok; } else { // Importing the default stream must not join an unrelated nonblocking // stream. The mode above separately tests a pending default producer. - ok = check(preparation.waitFor(nullptr)) && ok; + ok = check(preparation.orderAfter(nullptr)) && ok; ok = check( cudaMemsetAsync(device, 0x2a, sizeof(int), preparation.stream())) && ok; @@ -126,7 +126,7 @@ int main() if (dependency) ok = cudaEventQuery(done) == cudaErrorNotReady && ok; else { - ok = check(preparation.finish()) && ok; + ok = check(preparation.sync()) && ok; ok = cudaStreamQuery(other) == cudaErrorNotReady && ok; } { @@ -135,13 +135,13 @@ int main() } gate.condition.notify_one(); watchdog.join(); - ok = !gate.timedOut && check(preparation.finish()) && ok; + ok = !gate.timedOut && check(preparation.sync()) && ok; ok = check(cudaMemcpyAsync(&result, device + 1, sizeof(result), cudaMemcpyDeviceToHost, preparation.stream())) - && check(preparation.finish()) && result == 0x2a2a2a2a && ok; + && check(preparation.sync()) && result == 0x2a2a2a2a && ok; ok = check(cudaStreamSynchronize(producer)) && ok; } cudaFree(device); diff --git a/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp index 6e6eb7efd..ef9efc4e6 100644 --- a/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp +++ b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp @@ -37,13 +37,13 @@ int main() { visrtx::PreparationStream preparation; - if (preparation.initialize() != cudaSuccess) + if (preparation.initialize(nullptr) != cudaSuccess) return 1; visrtx::DeviceObjectArray registry; int token = 0; const auto first = registry.alloc(&token); registry.set(first, 11); - if (preparation.upload(nullptr, registry) != cudaSuccess) + if (preparation.upload(registry) != cudaSuccess) return 1; registry.markUploaded(); bool ok = !registry.dirty(); @@ -59,7 +59,7 @@ int main() for (int i = 0; i < 1024; ++i) last = registry.alloc(&token); registry.set(last, 44); - if (preparation.finish() != cudaSuccess) + if (preparation.sync() != cudaSuccess) return 1; registry.markUploaded(); ok = registry.dirty() && ok; @@ -69,7 +69,7 @@ int main() == cudaSuccess && value == 22 && ok; - if (preparation.upload(nullptr, registry) != cudaSuccess) + if (preparation.upload(registry) != cudaSuccess) return 1; registry.markUploaded(); ok = !registry.dirty() && ok; @@ -87,11 +87,11 @@ int main() visrtx::DeviceObjectArray uncommitted; uncommitted.alloc(&token); uncommitted.alloc(&token); - if (preparation.upload(nullptr, uncommitted) != cudaSuccess) + if (preparation.upload(uncommitted) != cudaSuccess) return 1; uncommitted.markUploaded(); uncommitted.set(0, 7); - if (preparation.upload(nullptr, uncommitted) != cudaSuccess) + if (preparation.upload(uncommitted) != cudaSuccess) return 1; uncommitted.markUploaded(); int pair[2]{}; diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 131f5d6c7..179f39289 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -137,6 +137,7 @@ set(SOURCES frame/Frame.cu geometry/ComputeTangent.cu + geometry/GeometryPreparation.cpp geometry/PreparationResults.cpp geometry/Preprocessing.cu geometry/Cone.cpp diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index b0eedcc28..b8f3148b9 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -426,7 +426,7 @@ VisRTXDevice::~VisRTXDevice() // material dying here releases its samplers into the registry, so the MDL // teardown below must come after (also what empties the registry before its // "not empty on destruction" check). - state.collectGeometryPreparations(); + state.preparation.collect(); state.commitBuffer.clear(); #ifdef USE_MDL @@ -449,10 +449,8 @@ VisRTXDevice::~VisRTXDevice() optixModuleDestroy(state.intersectionModules.customIntersectors); - // Disable cached returns and free idle/pending blocks before destroying - // streams. Any allocation outliving the device falls back to ordinary free. - state.geometryInputAllocations->close(); - state.preparation.reset(); + state.preparation.shutdown(); + state.preparationStream.reset(); optixDeviceContextDestroy(state.optixContext); cudaStreamDestroy(state.stream); @@ -489,7 +487,7 @@ bool VisRTXDevice::refuseDuringCollection(const char *call) const // A status callback reported while geometry preparations are collected must // not flush or re-finalize geometry whose readbacks and registry publication // are still being resolved, so such reentrant calls do nothing. - if (!deviceState()->collectingGeometryPreparations()) + if (!deviceState()->preparation.busy()) return false; reportRefusal(ANARI_SEVERITY_WARNING, call, @@ -910,7 +908,8 @@ DeviceInitStatus VisRTXDevice::initOptix() &builtinISOptions, &state.intersectionModules.curveIntersector)); - const auto preparationStatus = state.preparation.initialize(); + const auto preparationStatus = + state.preparationStream.initialize(state.stream); if (preparationStatus != cudaSuccess) { reportMessage(ANARI_SEVERITY_FATAL_ERROR, "could not initialize preparation stream: %s", diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index b45fff5be..e7a578d1a 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -173,20 +173,22 @@ void Array::privatize() // Do not retry copies from application memory that may already be freed. if (state.arrayPrivatizationFailed) return; + // Disables the device. Set before reporting: callbacks must not resume + // rendering or query bounds using cached aliases to the application-owned + // allocation. + auto fail = [&](cudaError_t error) { + state.arrayPrivatizationFailed = true; + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "array privatization failed; device disabled: %s", + cudaGetErrorString(error)); + }; bool changed = false; if (m_data.shared.host.isValid() && !m_data.shared.host.isOwner()) { // A batched H2D copy may still use the application-owned host pointer. // Draining does not release the queue's retained array references. - if (state.collectingGeometryInputUploads()) { - const auto completion = state.finishGeometryPreparation(); - if (completion != cudaSuccess) { - state.arrayPrivatizationFailed = true; - reportMessage(ANARI_SEVERITY_FATAL_ERROR, - "array privatization failed; device disabled: %s", - cudaGetErrorString(completion)); - return; - } - } + const auto completion = state.preparation.waitForHostReaders(); + if (completion != cudaSuccess) + return fail(completion); reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, "making private copy of shared host array (type '%s') | refs: (%i:%i)", anari::toString(elementType()), @@ -203,22 +205,13 @@ void Array::privatize() this->useCount(helium::RefType::INTERNAL)); // Existing frames may still read the shared pointer. The application may // free it as soon as this last PUBLIC release returns. - auto completion = state.retireRenderConsumers(); // Deferred preprocessing can still read this external allocation even // when no frame is in flight. Retain it through that stream's completion. - if (completion == cudaSuccess && state.hasPendingGeometryPreparations()) - completion = state.finishGeometryPreparation(); + auto completion = state.preparation.waitForDeviceReaders(); if (completion == cudaSuccess) completion = m_data.shared.device.privatize(); - if (completion != cudaSuccess) { - // Set before reporting: callbacks must not resume rendering or query - // bounds using cached aliases to the application-owned allocation. - state.arrayPrivatizationFailed = true; - reportMessage(ANARI_SEVERITY_FATAL_ERROR, - "array privatization failed; device disabled: %s", - cudaGetErrorString(completion)); - return; - } + if (completion != cudaSuccess) + return fail(completion); changed = true; } // Geometry may alias authored arrays directly: a new backing allocation is @@ -232,16 +225,23 @@ void Array::uploadArrayData() const if (!needToUploadData()) return; - if (m_data.shared.host.isValid()) - m_data.shared.device = m_data.shared.host; - else if (m_data.captured.host.isValid()) - m_data.captured.device = m_data.captured.host; - else if (m_data.managed.host.isValid()) - m_data.managed.device = m_data.managed.host; + if (const auto backing = hostBacking(); backing.host) + *backing.device = *backing.host; markDataUploaded(); } +Array::HostBacking Array::hostBacking() const +{ + if (m_data.shared.host.isValid()) + return {&m_data.shared.host, &m_data.shared.device}; + if (m_data.captured.host.isValid()) + return {&m_data.captured.host, &m_data.captured.device}; + if (m_data.managed.host.isValid()) + return {&m_data.managed.host, &m_data.managed.device}; + return {}; +} + cudaError_t Array::enqueueUpload(cudaStream_t stream) const { if (anari::isObject(elementType())) @@ -249,30 +249,22 @@ cudaError_t Array::enqueueUpload(cudaStream_t stream) const if (!needToUploadData()) return cudaSuccess; - const HostMemoryAllocation *host = nullptr; - CudaMemoryAllocation *device = nullptr; - if (m_data.shared.host.isValid()) { - host = &m_data.shared.host; - device = &m_data.shared.device; - } else if (m_data.captured.host.isValid()) { - host = &m_data.captured.host; - device = &m_data.captured.device; - } else if (m_data.managed.host.isValid()) { - host = &m_data.managed.host; - device = &m_data.managed.device; - } else + const auto [host, device] = hostBacking(); + if (!host) return cudaSuccess; // Application-owned device inputs are already resident. if (!device->isValid()) { auto cache = static_cast(deviceState()) - ->geometryInputAllocations; + ->preparation.inputAllocations(); void *memory = nullptr; const auto allocationError = cache->allocate(host->bytes(), &memory); - auto allocation = CudaMemoryAllocation::fromCache( - memory, host->bytes(), std::move(cache)); + // Read on every path: this also clears the error a failed allocation left. const auto lastError = cudaGetLastError(); if (allocationError != cudaSuccess) return allocationError; + // From here the owner returns the block to the cache on any early return. + auto allocation = CudaMemoryAllocation::fromCache( + memory, host->bytes(), std::move(cache)); if (lastError != cudaSuccess) return lastError; if (!allocation) diff --git a/devices/rtx/device/array/Array.h b/devices/rtx/device/array/Array.h index 9858c875a..61c171a65 100644 --- a/devices/rtx/device/array/Array.h +++ b/devices/rtx/device/array/Array.h @@ -127,6 +127,15 @@ struct Array : public UploadableArray // the supplied CUDA pointer. Never upload or expose an internal GPU copy. void *appFacingPtr() const; + // The active host allocation and the device copy uploads fill; both null + // when the array has no host storage (application-owned device memory). + struct HostBacking + { + const HostMemoryAllocation *host{nullptr}; + CudaMemoryAllocation *device{nullptr}; + }; + HostBacking hostBacking() const; + void on_NoInternalReferences() override; void on_NoPublicReferences() override; diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index db794e1da..499b4c31a 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -730,8 +730,7 @@ void Frame::renderFrame() hd.fb.buffers.trimTopK = nullptr; } - const auto registryUpload = - state.registry.upload(state.preparation, state.stream); + const auto registryUpload = state.registry.upload(state.preparationStream); if (registryUpload != cudaSuccess) { reportMessage(ANARI_SEVERITY_ERROR, "skipping render after registry upload failure: %s", diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index 90e41e532..f5bbee02e 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -74,6 +74,11 @@ void Cone::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } +size_t Cone::primitiveCount() const +{ + return m_index ? m_index->size() : m_vertex->size() / 2; +} + PrimitiveInput Cone::primitiveInput() const { ConeInput input{}; @@ -81,23 +86,21 @@ PrimitiveInput Cone::primitiveInput() const *m_vertex, m_index.get(), m_vertexCaps.get(), m_defaultCapFlags); input.radii = m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; - return {segmentCount(*m_vertex, m_index.get()), input}; + return {primitiveCount(), input}; } -void Cone::finalize() +bool Cone::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cone geometry"); - return; + return false; } if (!m_radius) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.radius' on cone geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -105,45 +108,14 @@ void Cone::finalize() m_index ? "indexed" : "soup"); if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) - return; + return false; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - - // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop stale data. Mirrors Triangle/Sphere. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else - m_preprocessing.releaseAreas(); - - if (!preparationFailed()) - upload(); -} - -void Cone::buildAreaData() -{ - m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); -} - -bool Cone::isAreaSamplingSupported() const -{ return true; } -void Cone::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - if (m_areaDataValid) - upload(); -} - -float Cone::totalArea() const +std::optional Cone::areaInput() const { - return m_preprocessing.totalArea(); + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Cone::isValid() const @@ -156,8 +128,7 @@ void Cone::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = - m_index ? m_index->size() : m_vertex->size() / 2; + buildInput.customPrimitiveArray.numPrimitives = primitiveCount(); static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -185,10 +156,7 @@ GeometryGPUData Cone::gpuData() const : nullptr; populateAttributeDataSet(m_vertexAttributes, cone.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cone.primAreaCdf = m_preprocessing.areaCdf(); - cone.numPrimitives = cone.primAreaCdf ? uint32_t(primitiveInput().count) : 0; - cone.totalArea = m_preprocessing.totalArea(); + populateAreaData(cone, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Cone.h b/devices/rtx/device/geometry/Cone.h index e808e5692..7f867ba4d 100644 --- a/devices/rtx/device/geometry/Cone.h +++ b/devices/rtx/device/geometry/Cone.h @@ -43,24 +43,19 @@ struct Cone : public Geometry ~Cone() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (lateral + - // enabled caps) used to sample this geometry as a Geometry Light. Lazy: only - // Emissive Surfaces call it. Mirrors Triangle/Sphere. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; - void buildAreaData(); + // Geometry Light sampling: the object-space area is lateral + enabled caps. + std::optional areaInput() const override; PrimitiveInput primitiveInput() const; + size_t primitiveCount() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -72,11 +67,6 @@ struct Cone : public Geometry CUdeviceptr m_aabbsBufferPtr{}; uint8_t m_defaultCapFlags{0}; - - // Geometry Light sampling data, built lazily by ensureAreaData(); see - // Triangle. - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index 12c85711d..8a614498a 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -54,31 +54,26 @@ void Curve::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Curve::finalize() +bool Curve::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on curve geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s curve geometry", m_index ? "indexed" : "soup"); - computeIndices(); - if (preparationFailed()) - return; - computeRadii(); - if (preparationFailed() || !finishPreparation(this)) - return; + if (!computeIndices() || !computeRadii() + || !deviceState()->preparation.finish(this)) + return false; m_vertexBufferPtr = (CUdeviceptr)m_vertexPosition->begin(AddressSpace::GPU); m_radiusBufferPtr = (CUdeviceptr)m_radii; - upload(); + return true; } void Curve::populateBuildInput(OptixBuildInput &buildInput) const @@ -114,24 +109,30 @@ bool Curve::isValid() const return m_vertexPosition; } -void Curve::computeIndices() +bool Curve::computeIndices() { m_numPrimitives = m_index ? m_index->size() : m_vertexPosition->size() / 2; - if (m_index) + if (m_index) { m_indices = m_index->beginAs(AddressSpace::GPU); - else if (generateCurveIndices(this, m_numPrimitives, m_generatedIndices)) - m_indices = m_generatedIndices.ptrAs(); + return true; + } + if (!generateCurveIndices(this, m_numPrimitives, m_generatedIndices)) + return false; + m_indices = m_generatedIndices.ptrAs(); + return true; } -void Curve::computeRadii() +bool Curve::computeRadii() { - if (m_vertexRadius) + if (m_vertexRadius) { m_radii = m_vertexRadius->beginAs(AddressSpace::GPU); - else if (generateCurveRadii(this, - m_vertexPosition->size(), - m_globalRadius, - m_generatedRadii)) - m_radii = m_generatedRadii.ptrAs(); + return true; + } + if (!generateCurveRadii( + this, m_vertexPosition->size(), m_globalRadius, m_generatedRadii)) + return false; + m_radii = m_generatedRadii.ptrAs(); + return true; } GeometryGPUData Curve::gpuData() const diff --git a/devices/rtx/device/geometry/Curve.h b/devices/rtx/device/geometry/Curve.h index 749915aba..180b5d89d 100644 --- a/devices/rtx/device/geometry/Curve.h +++ b/devices/rtx/device/geometry/Curve.h @@ -43,7 +43,6 @@ struct Curve : public Geometry ~Curve() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -51,8 +50,9 @@ struct Curve : public Geometry int optixGeometryType() const override; private: - void computeIndices(); - void computeRadii(); + bool prepare() override; + bool computeIndices(); + bool computeRadii(); GeometryGPUData gpuData() const override; helium::ChangeObserverPtr m_index; diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index 2d0b1c559..5ad18d15a 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -76,6 +76,11 @@ void Cylinder::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } +size_t Cylinder::primitiveCount() const +{ + return m_index ? m_index->size() : m_vertex->size() / 2; +} + PrimitiveInput Cylinder::primitiveInput() const { CylinderInput input{}; @@ -84,17 +89,15 @@ PrimitiveInput Cylinder::primitiveInput() const input.radii = m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; input.radius = m_globalRadius; - return {segmentCount(*m_vertex, m_index.get()), input}; + return {primitiveCount(), input}; } -void Cylinder::finalize() +bool Cylinder::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cylinders geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -102,45 +105,14 @@ void Cylinder::finalize() m_index ? "indexed" : "soup"); if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) - return; + return false; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - - // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop stale data. Mirrors Triangle/Sphere. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else - m_preprocessing.releaseAreas(); - - if (!preparationFailed()) - upload(); -} - -void Cylinder::buildAreaData() -{ - m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); -} - -bool Cylinder::isAreaSamplingSupported() const -{ return true; } -void Cylinder::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - if (m_areaDataValid) - upload(); -} - -float Cylinder::totalArea() const +std::optional Cylinder::areaInput() const { - return m_preprocessing.totalArea(); + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Cylinder::isValid() const @@ -153,8 +125,7 @@ void Cylinder::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = - m_index ? m_index->size() : m_vertex->size() / 2; + buildInput.customPrimitiveArray.numPrimitives = primitiveCount(); static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -180,11 +151,7 @@ GeometryGPUData Cylinder::gpuData() const : nullptr; populateAttributeDataSet(m_vertexAttributes, cylinder.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cylinder.primAreaCdf = m_preprocessing.areaCdf(); - cylinder.numPrimitives = - cylinder.primAreaCdf ? uint32_t(primitiveInput().count) : 0; - cylinder.totalArea = m_preprocessing.totalArea(); + populateAreaData(cylinder, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Cylinder.h b/devices/rtx/device/geometry/Cylinder.h index 6ac715907..bad035da2 100644 --- a/devices/rtx/device/geometry/Cylinder.h +++ b/devices/rtx/device/geometry/Cylinder.h @@ -43,24 +43,19 @@ struct Cylinder : public Geometry ~Cylinder() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (lateral + - // enabled caps) used to sample this geometry as a Geometry Light. Lazy: only - // Emissive Surfaces call it. Mirrors Triangle/Sphere. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; - void buildAreaData(); + // Geometry Light sampling: the object-space area is lateral + enabled caps. + std::optional areaInput() const override; PrimitiveInput primitiveInput() const; + size_t primitiveCount() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -74,11 +69,6 @@ struct Cylinder : public Geometry float m_globalRadius{1.f}; uint8_t m_defaultCapFlags{0}; - - // Geometry Light sampling data, built lazily by ensureAreaData(); see - // Triangle. - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index 0805b1acf..9717341de 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -115,23 +115,24 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { if (m_inputBatch != InputBatch::None) - deviceState()->collectGeometryInputUploads(); + deviceState()->preparation.uploadInputs(); // A parameter commit retries every failure. if (m_inputBatch == InputBatch::Failed) m_inputBatch = InputBatch::Queued; - if (retryBlocked()) - m_preparationState = PreparationState::Failed; + if (preparationFailed()) + m_retry = Retry::Finalize; if (m_preparationPosition) - deviceState()->collectGeometryPreparations(); + deviceState()->preparation.collect(); // Array observers can re-finalize without a parameter commit, but parameter // replacement can release the last reference to an aliased device array. // Complete earlier consumers before subclasses replace those references. const bool retain = canRetainPreparationInputs(); - if (!retain - && !failPreparationOnError(this, - deviceState()->retireRenderConsumers(), - "retiring previous geometry inputs")) - m_preparationState = PreparationState::RetirementFailed; + const bool retired = retain + || deviceState()->preparation.check(this, + deviceState()->preparation.retireRender(), + "retiring previous geometry inputs"); + if (!retired) + markPreparationFailed(Retry::Commit); commitAttributes("primitive.", m_primitiveAttributes); auto getUniformAttribute = @@ -149,34 +150,34 @@ void Geometry::commitParameters() m_uniformAttributes.attribute3 = getUniformAttribute("attribute3"); m_uniformAttributes.color = getUniformAttribute("color"); m_primitiveId = getParamObject("primitive.id"); - if (!retain && m_preparationState != PreparationState::RetirementFailed) + if (!retain && retired) stageInputUploads(); } void Geometry::markFinalized() { Object::markFinalized(); - if (m_preparationState != PreparationState::Reused) + if (!m_preparationReused) deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); } -bool Geometry::isAreaSamplingSupported() const +bool Geometry::PreparationParameter::sameInput( + const PreparationParameter &other) const { - return false; + return parameterIndex == other.parameterIndex && value == other.value + && updated == other.updated && finalized == other.finalized + && modified == other.modified; } bool Geometry::PreparationParameter::operator==( const PreparationParameter &other) const { - return parameterIndex == other.parameterIndex && value == other.value - && updated == other.updated && finalized == other.finalized - && modified == other.modified && devicePointer == other.devicePointer; + return sameInput(other) && devicePointer == other.devicePointer; } bool Geometry::canRetainPreparationInputs() const { - if ((m_preparationState != PreparationState::Prepared - && m_preparationState != PreparationState::Reused) + if (m_preparationState != PreparationState::Prepared || m_preparationParameterNames.empty()) return false; @@ -184,36 +185,12 @@ bool Geometry::canRetainPreparationInputs() const // Do not call dataGPU(): it can upload/replace storage. Pointer validation // remains in beginPreparation(), after references have been retained safely. size_t present = 0; - for (size_t i = 0; i < m_preparationParameterNames.size(); ++i) { - const auto value = getParamDirect(m_preparationParameterNames[i]); - if (!value.valid()) - continue; - if (present == m_preparedParameters.size()) - return false; - const auto &previous = m_preparedParameters[present++]; - if (previous.parameterIndex != i || !(previous.value == value)) - return false; - if (anari::isObject(value.type())) { - auto *object = value.getObject(); - if (object) { - if (previous.updated != object->lastUpdated() - || previous.finalized != object->lastFinalized()) - return false; - if (auto *array = dynamic_cast(object)) { - if (previous.modified != array->lastDataModified()) - return false; - } - } - } - } - return present == m_preparedParameters.size(); -} - -size_t Geometry::deferPreparation() -{ - if (!m_preparationPosition) - m_preparationPosition = deviceState()->enqueueGeometryPreparation(this); - return *m_preparationPosition; + const bool same = forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *) { + return present < m_preparedParameters.size() + && m_preparedParameters[present++].sameInput(parameter); + }); + return same && present == m_preparedParameters.size(); } void Geometry::completePreparation() @@ -230,17 +207,19 @@ void Geometry::markPreparationCollected() noexcept void Geometry::upload() { - if (m_preprocessing.status() == Preprocessing::Status::Pending) { - deferPreparation(); + if (m_preprocessing.pending()) { + deviceState()->preparation.defer(this); return; } RegisteredObject::upload(); if (preparationFailed()) return; - if (!isValid()) - m_preparationState = PreparationState::Unprepared; - else if (m_preparationState != PreparationState::Reused) + if (isValid()) m_preparationState = PreparationState::Prepared; + else { + m_preparationState = PreparationState::Unprepared; + m_preparationReused = false; + } } void Geometry::declarePreparationParameters( @@ -262,20 +241,23 @@ void Geometry::declarePreparationParameters( m_preparationParameterNames.emplace_back(name); } +static bool needsInputUpload(const Array *array) +{ + return array && array->needToUploadData() && array->dataHost(); +} + void Geometry::stageInputUploads() { m_inputUploads.clear(); - for (const auto &name : m_preparationParameterNames) { - const auto value = getParamDirect(name); - if (!anari::isObject(value.type())) - continue; - auto *array = dynamic_cast(value.getObject()); - if (array && array->needToUploadData() && array->dataHost()) - m_inputUploads.push_back({array, array->lastDataModified(), false}); - } + forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *array) { + if (needsInputUpload(array)) + m_inputUploads.push_back({array, parameter.modified, false}); + return true; + }); if (m_inputUploads.empty()) return; - deviceState()->enqueueGeometryInputUploads(this); + deviceState()->preparation.stageInputs(this); m_inputBatch = InputBatch::Queued; } @@ -298,13 +280,13 @@ void Geometry::submitInputUploads() if (error == cudaSuccess) return false; failInputUploads(); - failPreparation(this, error, operation); + state.preparation.fail(this, error, operation); return true; }; for (auto &upload : m_inputUploads) { upload.modified = upload.array->lastDataModified(); const auto error = - state.stageGeometryArray(upload.array.ptr, upload.modified); + state.preparation.stageArray(upload.array.ptr, upload.modified); upload.submitted = error == cudaSuccess; if (fail(error, "geometry array upload")) return; @@ -314,8 +296,7 @@ void Geometry::submitInputUploads() void Geometry::failInputUploads() { m_inputBatch = InputBatch::Failed; - if (m_preparationState != PreparationState::RetirementFailed) - m_preparationState = PreparationState::InputUploadFailed; + markPreparationFailed(Retry::Update); } void Geometry::completeInputUploads() noexcept @@ -338,21 +319,28 @@ void Geometry::completeInputUploads() noexcept m_inputUploads.clear(); } +void Geometry::finalize() +{ + if (beginPreparation() != PreparationStart::Prepare) + return; + if (prepare() && refreshAreaData()) + upload(); +} + Geometry::PreparationStart Geometry::beginPreparation() { - if (!deviceState()->collectGeometryInputUploads()) + if (!deviceState()->preparation.uploadInputs()) return PreparationStart::Blocked; // Observer-only finalization can arrive before a prior submission is // collected. if (m_preparationPosition) - deviceState()->collectGeometryPreparations(); - if (m_preparationState == PreparationState::Reused) - m_preparationState = PreparationState::Prepared; + deviceState()->preparation.collect(); + m_preparationReused = false; // A later observer update is a new generation too; it may retry a failed // input batch without requiring a parameter commit on the geometry. - if (m_preparationState == PreparationState::InputUploadFailed + if (preparationFailed() && m_retry == Retry::Update && lastUpdated() > m_failedInputUpdate) - m_preparationState = PreparationState::Failed; + m_retry = Retry::Finalize; if (retryBlocked()) return PreparationStart::Blocked; @@ -362,47 +350,27 @@ Geometry::PreparationStart Geometry::beginPreparation() // Indices remain valid if current grows; its AnariAny values retain every // source array until the batch completes (including on failure). std::vector> pendingUploads; - size_t parameterIndex = 0; - auto append = [&](const std::string &name) { - PreparationParameter parameter; - parameter.parameterIndex = parameterIndex++; - parameter.value = getParamDirect(name); // committed snapshot, not staging - if (!parameter.value.valid()) - return; // Keep only present values, retaining their parameter identity. - if (anari::isObject(parameter.value.type())) { - auto *object = parameter.value.getObject(); - if (object) { - parameter.updated = object->lastUpdated(); - parameter.finalized = object->lastFinalized(); - if (auto *array = dynamic_cast(object)) { - parameter.modified = array->lastDataModified(); - // Privatization can change backing pointers without changing values - // or the array timestamp. Never reuse cached aliases in that case. - if (array->needToUploadData() && array->dataHost()) - pendingUploads.emplace_back(current.size(), array); - else - parameter.devicePointer = array->dataGPU(); - } - } - } - current.push_back(std::move(parameter)); - }; - for (const auto &name : m_preparationParameterNames) - append(name); + forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *array) { + // Privatization can change backing pointers without changing values + // or the array timestamp. Never reuse cached aliases in that case. + if (needsInputUpload(array)) + pendingUploads.emplace_back(current.size(), array); + else if (array) + parameter.devicePointer = array->dataGPU(); + current.push_back(std::move(parameter)); + return true; + }); if (!pendingUploads.empty()) { // No commit captured these: an observer-only update, or an array // modified after its batch was submitted. Upload them the same way, as // a batch of this geometry alone. Its failure is this finalize's, so // the next one retries. - for (const auto &[index, array] : pendingUploads) - m_inputUploads.push_back({array, array->lastDataModified(), false}); - auto &state = *deviceState(); - state.enqueueGeometryInputUploads(this); - m_inputBatch = InputBatch::Queued; - state.collectGeometryInputUploads(); + stageInputUploads(); + deviceState()->preparation.uploadInputs(); if (retryBlocked()) { - m_preparationState = PreparationState::Failed; + m_retry = Retry::Finalize; return PreparationStart::Blocked; } for (const auto &[index, array] : pendingUploads) @@ -415,7 +383,7 @@ Geometry::PreparationStart Geometry::beginPreparation() if (m_preparationState == PreparationState::Prepared && isValid() && lastCommitted() > lastFinalized() && current == m_preparedParameters) { - m_preparationState = PreparationState::Reused; + m_preparationReused = true; upload(); return PreparationStart::Reused; } @@ -425,8 +393,8 @@ Geometry::PreparationStart Geometry::beginPreparation() // Full preparation can overwrite derived buffers read by earlier frames. // Keep that dependency on the GPU; parameter-reference retirement above // still requires a host wait before releasing old application storage. - return failPreparationOnError(this, - deviceState()->preparation.waitFor(deviceState()->stream), + return deviceState()->preparation.check(this, + deviceState()->preparationStream.orderAfterRender(), "previous geometry consumers") ? PreparationStart::Prepare : PreparationStart::Blocked; @@ -434,28 +402,61 @@ Geometry::PreparationStart Geometry::beginPreparation() bool Geometry::preparationFailed() const { - return m_preparationState == PreparationState::Failed - || m_preparationState == PreparationState::InputUploadFailed - || m_preparationState == PreparationState::RetirementFailed; + return m_preparationState == PreparationState::Failed; } bool Geometry::retryBlocked() const { - return m_preparationState == PreparationState::InputUploadFailed - || m_preparationState == PreparationState::RetirementFailed; + return preparationFailed() && m_retry != Retry::Finalize; +} + +void Geometry::markPreparationFailed(Retry retry) +{ + if (!preparationFailed() || retry > m_retry) + m_retry = retry; + m_preparationState = PreparationState::Failed; + m_preparationReused = false; +} + +std::optional Geometry::areaInput() const +{ + return {}; +} + +bool Geometry::isAreaSamplingSupported() const +{ + return areaInput().has_value(); } -void Geometry::markPreparationFailed() +void Geometry::ensureAreaData() { - if (!preparationFailed()) - m_preparationState = PreparationState::Failed; + if (m_areaDataValid) + return; + const auto input = areaInput(); + if (!input) + return; + m_areaDataWanted = true; + m_areaDataValid = m_preprocessing.areas(this, *input); + if (m_areaDataValid) + upload(); // republish only successfully prepared sampling data } -void Geometry::ensureAreaData() {} +bool Geometry::refreshAreaData() +{ + // prepare() may have changed what the CDF was computed from. + m_areaDataValid = false; + if (!m_areaDataWanted) { + m_preprocessing.releaseAreas(); + return true; + } + // Wanted implies that the subtype has an area input. + m_areaDataValid = m_preprocessing.areas(this, *areaInput()); + return m_areaDataValid; +} float Geometry::totalArea() const { - return 0.f; + return m_preprocessing.totalArea(); } GeometryGPUData Geometry::gpuData() const diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index fe8f64695..9d1e9055b 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -39,6 +39,7 @@ #include #include #include +#include #include namespace visrtx { @@ -75,32 +76,29 @@ struct Geometry : public RegisteredObject std::string_view subtype, DeviceGlobalState *d); void commitParameters() override; + // Final so that no subtype can skip the preparation protocol; subtypes + // implement prepare() instead. + void finalize() final; void markFinalized() override; // Defers registry publication while preprocessing results are pending. void upload() override; - // Queues the geometry for collection once; returns its queue position. - size_t deferPreparation(); - void completePreparation(); - void markPreparationCollected() noexcept; - void retirePreparationSnapshot(); - void submitInputUploads(); - void completeInputUploads() noexcept; - void failInputUploads(); virtual void populateBuildInput(OptixBuildInput &) const = 0; virtual int optixGeometryType() const = 0; - // Geometry Light area sampling. ensureAreaData() submits a per-primitive - // CDF if needed. Collect device geometry preparations before reading - // totalArea(), the object-space emitting area, or publishing a registry. - virtual bool isAreaSamplingSupported() const; - virtual void ensureAreaData(); - virtual float totalArea() const; + // Geometry Light area sampling, for the subtypes that implement areaInput(). + // ensureAreaData() submits the per-primitive area CDF if it is not current, + // and republishes the geometry. Lazy: only Emissive Surfaces call it, so + // ordinary geometry never pays for it. The request persists, so every later + // finalize rebuilds the CDF whatever the order of surface and geometry + // commits. Collect device geometry preparations before reading totalArea(), + // the object-space emitting area, or publishing a registry. + bool isAreaSamplingSupported() const; + void ensureAreaData(); + float totalArea() const; - // True in any of the failed preparation states below. + // True from a failure until a finalize prepares the geometry again. bool preparationFailed() const; - // Fails the current generation; keeps a more specific failed state. - void markPreparationFailed(); protected: // Declare once in the subtype constructor, before the first commit. List @@ -109,16 +107,25 @@ struct Geometry : public RegisteredObject void declarePreparationParameters( std::initializer_list parameters); - enum class PreparationStart - { - Prepare, // The subtype prepares and publishes the new generation. - Reused, // Inputs are unchanged; the registry is already republished. - Blocked, // Failed, an earlier failure awaits retry, or an input - // collection is in progress. The subtype returns. - }; - PreparationStart beginPreparation(); + // Builds the subtype's device data for a new generation; finalize() calls + // it only when one is needed, and uploads when it returns true. Return false + // for every reason not to upload: a missing required parameter, or a step + // that failed the geometry. finalize() does not ask preparationFailed() + // afterwards, so a failed step's result must not be discarded. Never call + // upload() here. + virtual bool prepare() = 0; GeometryGPUData gpuData() const override = 0; + // The input of the per-primitive area CDF, or nothing when the subtype + // cannot be sampled as a Geometry Light. Asked in any state: return an empty + // input while !isValid(). + virtual std::optional areaInput() const; + // Fills the Geometry Light fields of the subtype's GPU record: the CDF is + // null and the other two zero until ensureAreaData() ran and was collected. + // `count` is the subtype's primitive count, the length of the CDF. + template + void populateAreaData(RECORD_T &record, size_t count) const; + void commitAttributes(const char *prefix, GeometryAttributes &attrs); void populateAttributeDataSet( const GeometryAttributes &hostAttrs, AttributeDataSet &gpuAttrs) const; @@ -129,6 +136,41 @@ struct Geometry : public RegisteredObject Preprocessing m_preprocessing; private: + // The device's GeometryPreparation drives the steps below; see its header + // for the order. + friend struct GeometryPreparation; + void completePreparation(); + void markPreparationCollected() noexcept; + void retirePreparationSnapshot(); + void submitInputUploads(); + void completeInputUploads() noexcept; + void failInputUploads(); + // What retries a failed preparation, weakest first. Until it arrives, + // beginPreparation() returns Blocked for the two stronger ones. + enum class Retry + { + Finalize, // The next finalize: every CUDA or numeric failure, a retired + // snapshot, and an input batch that a finalize queued itself. + Update, // A parameter commit, or an observer update newer than + // m_failedInputUpdate: an input batch queued by a commit failed. + Commit, // Only a parameter commit: retiring the previous inputs failed. + }; + // Fails the current generation. Never weakens the retry already recorded. + void markPreparationFailed(Retry retry = Retry::Finalize); + + // After prepare(): resubmits the area CDF if a surface ever asked for it, + // else drops it. False means the geometry failed. + bool refreshAreaData(); + + enum class PreparationStart + { + Prepare, // finalize() runs prepare() and uploads the new generation. + Reused, // Inputs are unchanged; the registry is already republished. + Blocked, // Failed, an earlier failure awaits retry, or an input + // collection is in progress. Nothing is prepared or uploaded. + }; + PreparationStart beginPreparation(); + struct PreparationParameter { size_t parameterIndex{0}; @@ -138,9 +180,21 @@ struct Geometry : public RegisteredObject helium::TimeStamp modified{0}; const void *devicePointer{nullptr}; + // Equal in everything a commit can read. The device pointer is not: it is + // known only once the uploads finished. + bool sameInput(const PreparationParameter &other) const; bool operator==(const PreparationParameter &other) const; }; + // The one walk over the declared parameters. Calls fcn(PreparationParameter + // &&, Array *) for each one that is set, with the committed value, its + // versions and no device pointer; the array is null unless the value is one. + // Never calls dataGPU(), which can upload or replace storage. Stops, and + // returns false, when fcn does. + template + bool forEachPreparationParameter(FCN_T &&fcn) const; bool canRetainPreparationInputs() const; + // Queues every declared array with host data newer than its device copy as + // this geometry's input batch. void stageInputUploads(); struct InputUpload @@ -155,60 +209,33 @@ struct Geometry : public RegisteredObject // Preparation state of the current generation. // - // Unprepared Nothing published for the current inputs: initial, - // preparing, or published while !isValid(). - // Prepared Published; a commit may retain its inputs. - // Reused Prepared, and the latest finalize reused it, so - // markFinalized() leaves the BLAS change stamp alone. - // Failed The next finalize retries. - // InputUploadFailed An input upload batch queued by a commit failed. A - // parameter commit, or an observer update newer than - // m_failedInputUpdate, retries. - // RetirementFailed Retiring the previous inputs failed. Only a - // parameter commit retries. - // - // Transitions. An event leaves every state it does not list unchanged. + // Unprepared Nothing published for the current inputs: initial, + // preparing, or published while !isValid(). + // Prepared Published; a commit may retain its inputs. + // Failed Nothing is prepared or published until m_retry arrives. // - // Event From To - // commitParameters() InputUploadFailed Failed - // RetirementFailed Failed - // then retiring inputs fails any RetirementFailed - // beginPreparation() Reused Prepared - // observer update newer than InputUploadFailed Failed - // m_failedInputUpdate - // inputs unchanged, isValid() Prepared Reused - // full preparation Unprepared Unprepared - // Prepared Unprepared - // Failed Unprepared - // upload(), isValid() Unprepared Prepared - // Prepared Prepared - // Reused Reused - // upload(), !isValid() any not failed Unprepared - // markPreparationFailed() (every any not failed Failed - // CUDA or numeric failure, and - // retirePreparationSnapshot()) - // failInputUploads() any but InputUploadFailed - // RetirementFailed - // beginPreparation(), the batch it InputUploadFailed Failed - // queued itself fails + // Event To + // beginPreparation(), full preparation Unprepared + // upload(), unless Failed Prepared if isValid(), else + // Unprepared + // markPreparationFailed(retry) Failed // - // beginPreparation() returns Blocked in InputUploadFailed and - // RetirementFailed (retryBlocked()). RetirementFailed outranks - // InputUploadFailed: both need a commit, and the commit clears both. Whether - // the queued input batch failed is kept in m_inputBatch, so a batch that - // fails in RetirementFailed still leaves its arrays dirty. + // When its retry arrives a failure only drops to Retry::Finalize; the full + // preparation of that or the next finalize is what leaves Failed. enum class PreparationState { Unprepared, Prepared, - Reused, Failed, - InputUploadFailed, - RetirementFailed, }; PreparationState m_preparationState{PreparationState::Unprepared}; - // lastUpdated() when the input upload batch failed (InputUploadFailed). + // Meaningful while Failed. + Retry m_retry{Retry::Finalize}; + // lastUpdated() when the latest input upload batch failed (Retry::Update). helium::TimeStamp m_failedInputUpdate{0}; + // The latest finalize reused the preparation, so markFinalized() leaves the + // BLAS change stamp alone. Only ever set while Prepared. + bool m_preparationReused{false}; bool retryBlocked() const; @@ -218,13 +245,55 @@ struct Geometry : public RegisteredObject None, // Not queued for input uploads. Queued, Failed, // Queued; the batch failed, so submit nothing and mark no array - // uploaded. A commit retries it. + // uploaded. A commit retries it. Kept apart from Retry::Update + // because a batch can fail under Retry::Commit too. }; InputBatch m_inputBatch{InputBatch::None}; // Position in the device's preparation queue while queued. std::optional m_preparationPosition; + + // Geometry Light area data. Valid: the submitted CDF matches the current + // generation. Wanted: set by the first ensureAreaData() and kept across + // recommits. + bool m_areaDataValid{false}; + bool m_areaDataWanted{false}; }; +// Inlined definitions //////////////////////////////////////////////////////// + +template +inline bool Geometry::forEachPreparationParameter(FCN_T &&fcn) const +{ + for (size_t i = 0; i < m_preparationParameterNames.size(); ++i) { + // The committed value, not staging. + PreparationParameter parameter{ + i, getParamDirect(m_preparationParameterNames[i])}; + if (!parameter.value.valid()) + continue; // Keep only present values, retaining their parameter identity. + Array *array = nullptr; + if (anari::isObject(parameter.value.type())) { + if (auto *object = parameter.value.getObject()) { + parameter.updated = object->lastUpdated(); + parameter.finalized = object->lastFinalized(); + array = dynamic_cast(object); + if (array) + parameter.modified = array->lastDataModified(); + } + } + if (!fcn(std::move(parameter), array)) + return false; + } + return true; +} + +template +inline void Geometry::populateAreaData(RECORD_T &record, size_t count) const +{ + record.primAreaCdf = m_preprocessing.areaCdf(); + record.numPrimitives = record.primAreaCdf ? uint32_t(count) : 0; + record.totalArea = m_preprocessing.totalArea(); +} + } // namespace visrtx VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::Geometry *, ANARI_GEOMETRY); diff --git a/devices/rtx/device/geometry/GeometryPreparation.cpp b/devices/rtx/device/geometry/GeometryPreparation.cpp new file mode 100644 index 000000000..5a68959f5 --- /dev/null +++ b/devices/rtx/device/geometry/GeometryPreparation.cpp @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "GeometryPreparation.h" +#include "Geometry.h" +#include "array/Array.h" + +namespace visrtx { + +GeometryPreparation::GeometryPreparation(PreparationStream &stream) + : m_stream(stream) +{} + +GeometryPreparation::~GeometryPreparation() = default; + +void GeometryPreparation::shutdown() +{ + // Disable cached returns and free idle/pending blocks before the device + // destroys its streams. Any allocation outliving the device falls back to + // ordinary free. + m_inputAllocations->close(); +} + +bool GeometryPreparation::busy() const +{ + return m_preparations.collecting() || m_inputUploads.collecting(); +} + +bool GeometryPreparation::collect() +{ + if (!uploadInputs()) + return false; + // Owners remain queued if descriptor allocation or registry publication + // throws. CUDA failure still invalidates the pending batch before reporting, + // so callbacks cannot see a partially valid generation. Numeric failures + // remain local to their geometries during publication. Every publication + // must succeed before any geometry leaves the queue. + return m_preparations.collect( + [&](Geometry *first) { + const auto error = flush(); + if (error != cudaSuccess) + fail(first, error, "batch completion"); + m_preparations.forEach( + [](Geometry *geometry) { geometry->completePreparation(); }); + }, + [](Geometry *geometry) noexcept { geometry->markPreparationCollected(); }, + [] {}); +} + +cudaError_t GeometryPreparation::waitForHostReaders() +{ + // Only an input-upload collection has copies in flight. Draining does not + // release the queue's retained array references. + return uploadingInputs() ? flush() : cudaSuccess; +} + +cudaError_t GeometryPreparation::waitForDeviceReaders() +{ + auto completion = retireRender(); + if (completion == cudaSuccess && pending()) + completion = flush(); + return completion; +} + +std::shared_ptr GeometryPreparation::inputAllocations() + const +{ + return m_inputAllocations; +} + +void GeometryPreparation::stageInputs(Geometry *geometry) +{ + m_inputUploads.enqueue(helium::IntrusivePtr(geometry)); +} + +bool GeometryPreparation::uploadInputs() +{ + return m_inputUploads.collect( + [&](Geometry *first) { + // The only route by which a geometry's host inputs reach the device. + // Commits capture sources; the first geometry finalizer submits every + // input batch before waiting. No legacy finalizer sees partially + // uploaded arrays. A finalizer then queues what no commit captured + // as a batch of its own. Retire obsolete cached copies before + // allocating a whole replacement cohort. A single geometry retains + // the existing allocation/retirement order. + if (m_inputUploads.size() > 1) + m_inputUploads.forEach([](Geometry *geometry) { + geometry->retirePreparationSnapshot(); + }); + auto error = m_inputAllocations->reclaim([&] { return flush(); }); + if (error == cudaSuccess) + error = m_stream.orderAfterRender(); + if (error == cudaSuccess) { + m_inputUploads.forEach( + [](Geometry *geometry) { geometry->submitInputUploads(); }); + error = flush(); + } + if (error != cudaSuccess) { + failInputUploads(); + fail(first, error, "geometry input batch completion"); + } + m_inputVersions.clear(); + }, + [](Geometry *geometry) noexcept { geometry->completeInputUploads(); }, + [&] { + // A host allocation or callback can unwind after copies were + // submitted. Keep sources alive and drain before permitting public + // release again. + failInputUploads(); + flush(); + m_inputVersions.clear(); + }); +} + +cudaError_t GeometryPreparation::stageArray( + Array *array, helium::TimeStamp modified) +{ + const auto found = m_inputVersions.find(array); + if (found != m_inputVersions.end() && found->second == modified) + return cudaSuccess; + const auto error = array->enqueueUpload(m_stream.stream()); + if (error == cudaSuccess) + m_inputVersions.insert_or_assign(array, modified); + return error; +} + +void GeometryPreparation::defer(Geometry *geometry) +{ + if (!geometry->m_preparationPosition) + geometry->m_preparationPosition = + m_preparations.enqueue(helium::IntrusivePtr(geometry)); +} + +void GeometryPreparation::deferSmall(Geometry *geometry, Preprocessing *job) +{ + m_smallBatch.enqueue(job, position(geometry)); +} + +GeometryResults *GeometryPreparation::deviceResults(Geometry *geometry) +{ + const size_t at = position(geometry); + if (!check(geometry, + m_results.reserve(at + 1, m_stream.stream()), + "allocating preparation results")) + return nullptr; + return m_results.device(at); +} + +const GeometryResults &GeometryPreparation::hostResults( + const Geometry *geometry) const +{ + return m_results.host(position(geometry)); +} + +size_t GeometryPreparation::position(const Geometry *geometry) const +{ + return *geometry->m_preparationPosition; +} + +cudaError_t GeometryPreparation::flush() +{ + // Flush deferred small jobs even at intervening upload/retirement waits: + // their input pointers must be consumed before a backing allocation changes. + // Then read back every queued result in one transfer. + const auto stream = m_stream.stream(); + auto error = m_smallBatch.launch(m_results, stream); + if (error == cudaSuccess) + error = m_results.readback(m_preparations.size(), stream); + const auto completion = cudaStreamSynchronize(stream); + if (error == cudaSuccess) + error = completion; + if (error != cudaSuccess) { + cudaGetLastError(); + // An intervening upload/legacy consumer may wait before the collection + // point. Its stream-completion error affects all already queued results. + m_preparations.forEach( + [](Geometry *geometry) { geometry->markPreparationFailed(); }); + failInputUploads(); + } + return error; +} + +void GeometryPreparation::fail( + Geometry *geometry, cudaError_t error, const char *operation) +{ + geometry->markPreparationFailed(); + // A failed dispatch/readback can follow successful queued kernels. Drain + // preparation before retrying or freeing scratch. Keep the render-stream + // drain on this error path too: this also handles input retirement and + // dependency failures, which may precede a successful producer edge. + flush(); + cudaStreamSynchronize(m_stream.renderStream()); + geometry->reportMessage(ANARI_SEVERITY_ERROR, + "geometry preprocessing failed during %s: %s", + operation, + cudaGetErrorString(error)); +} + +bool GeometryPreparation::check( + Geometry *geometry, cudaError_t error, const char *operation) +{ + if (error == cudaSuccess) + return true; + fail(geometry, error, operation); + return false; +} + +void GeometryPreparation::reject(Geometry *geometry, const char *reason) +{ + geometry->markPreparationFailed(); + geometry->reportMessage(ANARI_SEVERITY_ERROR, + "geometry preprocessing rejected input: %s", + reason); +} + +bool GeometryPreparation::finish(Geometry *geometry) +{ + // Also establishes an explicit boundary for legacy default-stream consumers. + return check(geometry, cudaGetLastError(), "launch") + && check(geometry, flush(), "execution completion"); +} + +cudaError_t GeometryPreparation::retireRender() +{ + // Anything but success, a failed query included, takes the wait: only a + // completed stream permits releasing what its work reads. + const auto renderStream = m_stream.renderStream(); + return cudaStreamQuery(renderStream) == cudaSuccess + ? cudaSuccess + : cudaStreamSynchronize(renderStream); +} + +bool GeometryPreparation::uploadingInputs() const +{ + return m_inputUploads.collecting(); +} + +bool GeometryPreparation::pending() const +{ + return m_preparations.collecting() || !m_preparations.empty() + || m_inputUploads.collecting(); +} + +void GeometryPreparation::failInputUploads() +{ + m_inputUploads.forEach( + [](Geometry *geometry) { geometry->failInputUploads(); }); +} + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/GeometryPreparation.h b/devices/rtx/device/geometry/GeometryPreparation.h new file mode 100644 index 000000000..52be96d4d --- /dev/null +++ b/devices/rtx/device/geometry/GeometryPreparation.h @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "Preprocessing.h" +#include "utility/DeviceAllocationCache.h" +#include "utility/PreparationQueue.h" +#include "utility/PreparationStream.h" +// helium +#include +#include +// std +#include +#include + +namespace visrtx { + +struct Array; +struct Geometry; + +/* + * Owns everything that prepares geometry on the GPU: the two collection + * queues, the small-geometry batch, the scalar results and the input + * allocation cache. The work runs on the device's PreparationStream, which + * BVH builds and scene-table uploads use directly. + * + * One scene update is one transaction: + * + * commit Geometry::commitParameters() captures its dirty host arrays and + * queues itself (stageInputs). + * upload The first finalizer uploads every queued geometry's inputs and + * waits once (uploadInputs). A finalizer whose arrays no commit + * captured queues and uploads them the same way. + * submit Each finalizer queues bounds/area work; nothing is published + * (defer). Small geometries are held for one batched launch. + * collect collect() launches the batch, reads all results back in one + * transfer, waits once, then publishes each geometry. + * + * A CUDA failure fails every queued geometry; a numeric failure fails its own. + * Calls are serialized by the device's scene-update path; nothing here locks. + */ +struct GeometryPreparation +{ + explicit GeometryPreparation(PreparationStream &stream); + ~GeometryPreparation(); + GeometryPreparation(const GeometryPreparation &) = delete; + GeometryPreparation &operator=(const GeometryPreparation &) = delete; + + // Closes the allocation cache. Call collect() first, while objects may + // still be released, and reset the stream afterwards. + void shutdown(); + + // True while input uploads or results are being collected. Reentrant + // property queries and rendering are refused meanwhile. + bool busy() const; + + // Completes the transaction: publishes every queued geometry. Returns + // false, doing nothing, when reentered from a collection. + bool collect(); + + // For a caller about to hand memory back to the application. The first + // waits for a host-to-device input copy in flight; the second for rendering + // and queued preparation that read an application-owned device array. + cudaError_t waitForHostReaders(); + cudaError_t waitForDeviceReaders(); + + // Backs device copies of authored host arrays. + std::shared_ptr inputAllocations() const; + + // For geometry code. fail() marks the geometry failed, drains both streams + // so no queued work still targets its storage, and reports. check() returns + // true on cudaSuccess, otherwise fail()s. finish() waits for the geometry's + // submitted work, failing it on error. + void fail(Geometry *geometry, cudaError_t error, const char *operation); + bool check(Geometry *geometry, cudaError_t error, const char *operation); + bool finish(Geometry *geometry); + // For input the device cannot prepare, with no CUDA error behind it: marks + // the geometry failed and reports. Touches no stream and no other geometry. + void reject(Geometry *geometry, const char *reason); + + // For Preprocessing. Each addresses the geometry's place in the queue; the + // position and the storage it indexes stay in here. + // Queues the geometry for collect(), once. + void defer(Geometry *geometry); + // Holds a deferred geometry's small job for the one batched launch. + void deferSmall(Geometry *geometry, Preprocessing *job); + // Device results a deferred geometry's kernels write; null after failing + // the geometry when they cannot be allocated. + GeometryResults *deviceResults(Geometry *geometry); + // The same results read back; only while the geometry is being collected. + const GeometryResults &hostResults(const Geometry *geometry) const; + + private: + friend struct Geometry; + + // Geometry protocol, in transaction order. + void stageInputs(Geometry *geometry); + bool uploadInputs(); + cudaError_t stageArray(Array *array, helium::TimeStamp modified); + // Indexes m_results. Only between a geometry's defer() and its collection. + size_t position(const Geometry *geometry) const; + // Launches the small batch, reads back, waits. Fails all queued on error. + cudaError_t flush(); + // A host-blocking wait for rendering (skipped when the render stream is + // idle), for callers about to release memory that render work may still + // read. PreparationStream::orderAfterRender() is the GPU-side dependency. + cudaError_t retireRender(); + + bool uploadingInputs() const; + bool pending() const; + void failInputUploads(); + + PreparationStream &m_stream; + std::shared_ptr m_inputAllocations{ + std::make_shared()}; + // Scalar results of queued geometry preparations, by queue position. + PreparationResults m_results; + SmallGeometryBatch m_smallBatch; + std::unordered_map m_inputVersions; + // Last, so queued geometries are released before the storage above. + PreparationQueue> m_inputUploads; + PreparationQueue> m_preparations; +}; + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Intersectors_ptx.cu b/devices/rtx/device/geometry/Intersectors_ptx.cu index 3f342da19..c5caf2bf3 100644 --- a/devices/rtx/device/geometry/Intersectors_ptx.cu +++ b/devices/rtx/device/geometry/Intersectors_ptx.cu @@ -1008,7 +1008,7 @@ VISRTX_DEVICE void marchVoxelsMacrocellSkip(const IsosurfaceGeometryData &iso, // cubic (linearCrossing). The fixed-step ray march below is no longer reached // by built-in fields. This generic form is the ray-march fallback for fields // without analytic voxel boundaries (e.g. custom fields); built-in fields are -// gated to require a space-skipping grid in Isosurface::finalize. +// gated to require a space-skipping grid in Isosurface::prepare. template VISRTX_DEVICE void marchIsosurfaceVoxels(const IsosurfaceGeometryData &iso, const SpatialFieldGPUData &field, diff --git a/devices/rtx/device/geometry/Isosurface.cpp b/devices/rtx/device/geometry/Isosurface.cpp index b8960c031..ba3194b2b 100644 --- a/devices/rtx/device/geometry/Isosurface.cpp +++ b/devices/rtx/device/geometry/Isosurface.cpp @@ -54,10 +54,8 @@ void Isosurface::commitParameters() getParam("isovalue", ANARI_FLOAT32, &m_isovalueScalar); } -void Isosurface::finalize() +bool Isosurface::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; m_numBricks = 0; m_isovaluesDev = nullptr; m_numIsovalues = 0; @@ -65,7 +63,7 @@ void Isosurface::finalize() if (!m_field) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'field' on isosurface geometry"); - return; + return false; } if (m_field->m_uniformGrid.m_valueRanges == nullptr) { // The field's space-skipping grid isn't built yet; a field committed before @@ -74,25 +72,25 @@ void Isosurface::finalize() reportMessage(ANARI_SEVERITY_WARNING, "isosurface 'field' space-skipping grid not ready; nothing will render " "yet"); - return; + return false; } if (!m_isovalueArray && !m_hasScalarIsovalue) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'isovalue' on isosurface geometry"); - return; + return false; } if (m_isovalueArray && m_isovalueArray->size() == 0) { reportMessage(ANARI_SEVERITY_WARNING, "empty 'isovalue' array on isosurface geometry; one or more values are " "required, nothing will render"); - return; + return false; } if (m_isovalueArray && m_isovalueArray->elementType() != ANARI_FLOAT32) { // beginAs() only asserts the element type, so under NDEBUG a non- // FLOAT32 array would be silently reinterpreted as float garbage. Reject it. reportMessage(ANARI_SEVERITY_WARNING, "isosurface 'isovalue' array must be ANARI_FLOAT32; nothing will render"); - return; + return false; } // Resolve the device isovalue array (array form preferred). @@ -131,7 +129,7 @@ void Isosurface::finalize() m_numIsovalues, m_numBricks); - upload(); + return true; } void Isosurface::dropUndersizedPrimitiveArrays() diff --git a/devices/rtx/device/geometry/Isosurface.h b/devices/rtx/device/geometry/Isosurface.h index d12a1e742..d0f1574f0 100644 --- a/devices/rtx/device/geometry/Isosurface.h +++ b/devices/rtx/device/geometry/Isosurface.h @@ -44,13 +44,13 @@ struct Isosurface : public Geometry ~Isosurface() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; // Drops any per-primitive array shorter than m_numIsovalues (warns), so the diff --git a/devices/rtx/device/geometry/Neural.cpp b/devices/rtx/device/geometry/Neural.cpp index 62c4bf428..46c615e14 100644 --- a/devices/rtx/device/geometry/Neural.cpp +++ b/devices/rtx/device/geometry/Neural.cpp @@ -27,15 +27,13 @@ void Neural::commitParameters() } } -void Neural::finalize() +bool Neural::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; - Geometry::finalize(); m_aabbs.resize(1); m_aabbs.dataHost()[0] = m_aabb; m_aabbs.upload(); m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); + return true; } bool Neural::isValid() const diff --git a/devices/rtx/device/geometry/Neural.h b/devices/rtx/device/geometry/Neural.h index c36008475..369c0b1bc 100644 --- a/devices/rtx/device/geometry/Neural.h +++ b/devices/rtx/device/geometry/Neural.h @@ -14,7 +14,6 @@ struct Neural : public Geometry ~Neural() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -22,6 +21,7 @@ struct Neural : public Geometry int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; mutable std::vector> m_layers; diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu index 970979f30..d4689c25b 100644 --- a/devices/rtx/device/geometry/Preprocessing.cu +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -354,11 +354,6 @@ VISRTX_GLOBAL void curveRadii(size_t n, float radius, float *out) } } // namespace -size_t segmentCount(const Array1D &vertices, const Array1D *indices) -{ - return indices ? indices->size() : vertices.size() / 2; -} - SegmentInput segmentInput(const Array1D &vertices, const Array1D *indices, const Array1D *caps, @@ -382,9 +377,9 @@ bool generateQuadIndices( quadIndices<<<(n + 255) / 256, 256, 0, - g->deviceState()->preparation.stream()>>>( + g->deviceState()->preparationStream.stream()>>>( indices, n, out.ptrAs()); - return finishPreparation(g); + return g->deviceState()->preparation.finish(g); } bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) @@ -395,8 +390,10 @@ bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) curveIndices<<<(n + 255) / 256, 256, 0, - g->deviceState()->preparation.stream()>>>(n, out.ptrAs()); - return failPreparationOnError(g, cudaGetLastError(), "curve indices"); + g->deviceState()->preparationStream.stream()>>>( + n, out.ptrAs()); + return g->deviceState()->preparation.check( + g, cudaGetLastError(), "curve indices"); } bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) @@ -407,53 +404,21 @@ bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) curveRadii<<<(n + 255) / 256, 256, 0, - g->deviceState()->preparation.stream()>>>( + g->deviceState()->preparationStream.stream()>>>( n, radius, out.ptrAs()); - return failPreparationOnError(g, cudaGetLastError(), "curve radii"); -} - -void failPreparation(Geometry *g, cudaError_t error, const char *operation) -{ - g->markPreparationFailed(); - // A failed dispatch/readback can follow successful queued kernels. Drain - // preparation before retrying or freeing scratch. Keep the render-stream - // drain on this error path too: this helper also handles input retirement - // and dependency failures, which may precede a successful producer edge. - g->deviceState()->finishGeometryPreparation(); - cudaStreamSynchronize(g->deviceState()->stream); - g->reportMessage(ANARI_SEVERITY_ERROR, - "geometry preprocessing failed during %s: %s", - operation, - cudaGetErrorString(error)); -} - -bool failPreparationOnError( - Geometry *g, cudaError_t error, const char *operation) -{ - if (error == cudaSuccess) - return true; - failPreparation(g, error, operation); - return false; + return g->deviceState()->preparation.check( + g, cudaGetLastError(), "curve radii"); } bool reservePreparation(Geometry *g, DeviceBuffer &buffer, size_t bytes) { - return failPreparationOnError( + return g->deviceState()->preparation.check( g, buffer.tryReserve(bytes), "allocating device storage"); } -bool finishPreparation(Geometry *g) -{ - // Also establishes an explicit boundary for legacy default-stream consumers. - return failPreparationOnError(g, cudaGetLastError(), "launch") - && failPreparationOnError(g, - g->deviceState()->finishGeometryPreparation(), - "execution completion"); -} - -void SmallGeometryBatch::enqueue(Preprocessing *preprocessing) +void SmallGeometryBatch::enqueue(Preprocessing *preprocessing, size_t position) { - m_pending.push_back(preprocessing); + m_pending.push_back({preprocessing, position}); } cudaError_t SmallGeometryBatch::launch( @@ -462,8 +427,8 @@ cudaError_t SmallGeometryBatch::launch( cudaError_t error = cudaSuccess; if (!m_pending.empty()) { size_t positions = 0; - for (auto *p : m_pending) - positions = std::max(positions, p->m_position + 1); + for (const auto &p : m_pending) + positions = std::max(positions, p.position + 1); // No host allocations after submission: descriptors remain stable even // when an error requires a subsequent fallback drain. m_jobs.clear(); @@ -473,9 +438,9 @@ cudaError_t SmallGeometryBatch::launch( else error = results.reserve(positions, stream); if (error == cudaSuccess) { - for (auto *p : m_pending) { - m_jobs.push_back(p->m_small); - m_jobs.back().results = results.device(p->m_position); + for (const auto &p : m_pending) { + m_jobs.push_back(p.preprocessing->m_small); + m_jobs.back().results = results.device(p.position); } error = m_descriptors.enqueueUpload(m_jobs.data(), m_jobs.size(), stream); } @@ -485,9 +450,9 @@ cudaError_t SmallGeometryBatch::launch( error = cudaGetLastError(); } } - for (auto *p : m_pending) { - p->m_smallQueued = false; - p->m_small = {}; + for (const auto &p : m_pending) { + p.preprocessing->m_smallQueued = false; + p.preprocessing->m_small = {}; } m_pending.clear(); return error; @@ -496,33 +461,16 @@ cudaError_t SmallGeometryBatch::launch( void Preprocessing::enqueueSmall(Geometry *g) { if (!m_smallQueued) { - g->deviceState()->smallGeometryBatch.enqueue(this); + g->deviceState()->preparation.deferSmall(g, this); m_smallQueued = true; } } Preprocessing::~Preprocessing() = default; -void Preprocessing::submit(Geometry *g) -{ - m_position = g->deferPreparation(); - m_status = Status::Pending; -} - -GeometryResults *Preprocessing::reserveResults(Geometry *g) -{ - auto *state = g->deviceState(); - if (!failPreparationOnError(g, - state->preparationResults.reserve( - m_position + 1, state->preparation.stream()), - "allocating preparation results")) - return nullptr; - return state->preparationResults.device(m_position); -} - -Preprocessing::Status Preprocessing::status() const +bool Preprocessing::pending() const { - return m_status; + return m_boundsSubmitted || m_areasSubmitted; } float Preprocessing::epsilonScale() const @@ -551,18 +499,18 @@ bool Preprocessing::complete(Geometry *g) { const bool bounds = std::exchange(m_boundsSubmitted, false); const bool areas = std::exchange(m_areasSubmitted, false); - m_status = Status::Ready; if (g->preparationFailed()) return false; if (!bounds && !areas) return true; - const auto &results = g->deviceState()->preparationResults.host(m_position); + auto &preparation = g->deviceState()->preparation; + const auto &results = preparation.hostResults(g); if (bounds && results.bounds.invalid) { - failPreparation(g, cudaErrorInvalidValue, "non-finite bounds"); + preparation.reject(g, "non-finite bounds"); return false; } if (areas && !std::isfinite(results.area.value)) { - failPreparation(g, cudaErrorInvalidValue, "non-publishable primitive area"); + preparation.reject(g, "non-publishable primitive area"); return false; } if (bounds) @@ -578,32 +526,31 @@ bool Preprocessing::complete(Geometry *g) bool Preprocessing::bounds( Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs) { - const auto stream = g->deviceState()->preparation.stream(); + auto &preparation = g->deviceState()->preparation; + const auto stream = g->deviceState()->preparationStream.stream(); m_epsilonScale = 0.f; - submit(g); + preparation.defer(g); m_boundsSubmitted = true; m_boundsHaveEpsilonScale = in.type != GeometryType::SDF; + if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) + return false; if (in.count > 0 && in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { - if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) - return false; m_small.boundsInput = in; m_small.bounds = aabbs.ptrAs(); enqueueSmall(g); return true; } - if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) - return false; - auto *results = reserveResults(g); + auto *results = preparation.deviceResults(g); auto *result = results ? &results->bounds : nullptr; if (!result - || !failPreparationOnError(g, + || !preparation.check(g, cudaMemsetAsync(result, 0, sizeof(Result), stream), "clearing bounds status")) return false; if (in.count) primitiveBounds<<<(in.count + 255) / 256, 256, 0, stream>>>( in, aabbs.ptrAs(), result); - return failPreparationOnError(g, cudaGetLastError(), "bounds evaluation"); + return preparation.check(g, cudaGetLastError(), "bounds evaluation"); } bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) @@ -613,11 +560,12 @@ bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) m_areaCdf.reset(); return true; } + auto &preparation = g->deviceState()->preparation; if (in.count > size_t(std::numeric_limits::max())) { - failPreparation(g, cudaErrorInvalidValue, "primitive count"); + preparation.reject(g, "too many primitives for area sampling"); return false; } - submit(g); + preparation.defer(g); m_areasSubmitted = true; if (in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { if (!reservePreparation(g, m_areaCdf, in.count * sizeof(float))) @@ -627,28 +575,28 @@ bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) enqueueSmall(g); return true; } - const auto stream = g->deviceState()->preparation.stream(); + const auto stream = g->deviceState()->preparationStream.stream(); size_t scratchBytes = 0; if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) || !reservePreparation(g, m_areaCdf, in.count * sizeof(float))) return false; - auto *results = reserveResults(g); + auto *results = preparation.deviceResults(g); auto *result = results ? &results->area : nullptr; if (!result - || !failPreparationOnError(g, + || !preparation.check(g, cudaMemsetAsync(result, 0, sizeof(Result), stream), "clearing area status")) return false; auto *prefix = m_prefix.ptrAs(); primitiveAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( in, prefix, result); - if (!failPreparationOnError(g, cudaGetLastError(), "area evaluation") - || !failPreparationOnError(g, + if (!preparation.check(g, cudaGetLastError(), "area evaluation") + || !preparation.check(g, cub::DeviceScan::InclusiveSum( nullptr, scratchBytes, prefix, prefix, int(in.count), stream), "scan workspace query") || !reservePreparation(g, m_scratch, scratchBytes) - || !failPreparationOnError(g, + || !preparation.check(g, cub::DeviceScan::InclusiveSum(m_scratch.ptr(), scratchBytes, prefix, @@ -659,9 +607,9 @@ bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) return false; normalizeAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( prefix, in.count, m_areaCdf.ptrAs(), result); - if (!failPreparationOnError(g, cudaGetLastError(), "CDF normalization")) + if (!preparation.check(g, cudaGetLastError(), "CDF normalization")) return false; publishArea<<<1, 1, 0, stream>>>(result); - return failPreparationOnError(g, cudaGetLastError(), "area publication"); + return preparation.check(g, cudaGetLastError(), "area publication"); } } // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h index 3794290e9..9ea0cc40a 100644 --- a/devices/rtx/device/geometry/Preprocessing.h +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -125,7 +125,6 @@ struct PrimitiveInput // Cone and cylinder endpoints: `indices` pairs vertices, else consecutive // vertices pair up. -size_t segmentCount(const Array1D &vertices, const Array1D *indices); SegmentInput segmentInput(const Array1D &vertices, const Array1D *indices, const Array1D *caps, @@ -149,14 +148,21 @@ struct Preprocessing; struct SmallGeometryBatch { static constexpr size_t MAX_PRIMITIVES = 256; - void enqueue(Preprocessing *preprocessing); + // `position` is the owning geometry's preparation-queue position; it holds + // until the geometry is collected, which is after the launch. + void enqueue(Preprocessing *preprocessing, size_t position); // Launches every queued job, writing each geometry's results at its queue // position in `results`. Always empties the batch; the caller synchronizes // `stream`. cudaError_t launch(PreparationResults &results, cudaStream_t stream); private: - std::vector m_pending; + struct Pending + { + Preprocessing *preprocessing; + size_t position; + }; + std::vector m_pending; std::vector m_jobs; DeviceBuffer m_descriptors; }; @@ -167,13 +173,6 @@ struct SmallGeometryBatch // from their readback after the device's collection barrier. struct Preprocessing { - enum class Status - { - Ready, // Nothing awaits complete(): published, or its collection failed - // and what it was to publish stays zero. - Pending, // Submitted results await complete(). - }; - Preprocessing() = default; ~Preprocessing(); Preprocessing(const Preprocessing &) = delete; @@ -181,7 +180,8 @@ struct Preprocessing Preprocessing(Preprocessing &&) = delete; Preprocessing &operator=(Preprocessing &&) = delete; - Status status() const; + // True while a bounds or area submission awaits complete(). + bool pending() const; // Published results. The CDF is null when the total area is zero. float epsilonScale() const; float totalArea() const; @@ -201,14 +201,8 @@ struct Preprocessing private: friend struct SmallGeometryBatch; void enqueueSmall(Geometry *geometry); - void submit(Geometry *geometry); - // Device results for a general-path submission; null after failing it. - GeometryResults *reserveResults(Geometry *geometry); SmallGeometryJob m_small; bool m_smallQueued{false}; - // Position in the device's preparation queue, set by submit(). - size_t m_position{0}; - Status m_status{Status::Ready}; bool m_boundsSubmitted{false}; bool m_areasSubmitted{false}; // SDF bounds are padded per primitive and carry no epsilon scale. @@ -220,15 +214,9 @@ struct Preprocessing DeviceBuffer m_scratch; }; -// Marks the geometry's preparation failed, drains the preparation and render -// streams so no queued work still targets its storage, and reports the error. -void failPreparation( - Geometry *geometry, cudaError_t error, const char *operation); -// Returns true on cudaSuccess; otherwise calls failPreparation(). -bool failPreparationOnError( - Geometry *geometry, cudaError_t error, const char *operation); +// CUDA failures go through GeometryPreparation::fail() / check() / finish(); +// rejected input through reject(). bool reservePreparation(Geometry *geometry, DeviceBuffer &buffer, size_t bytes); -bool finishPreparation(Geometry *geometry); bool generateQuadIndices(Geometry *geometry, const uvec4 *indices, size_t count, diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 355294aee..93d950af1 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -56,30 +56,27 @@ void Quad::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Quad::finalize() +bool Quad::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on quad geometry"); - return; + return false; } if (!m_index && m_vertex->size() % 4 != 0) { reportMessage(ANARI_SEVERITY_ERROR, "'vertex.position' on quad geometry is a non-multiple of 4" " without 'primitive.index' present"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s quad geometry", m_index ? "indexed" : "soup"); - generateIndices(); - if (preparationFailed()) - return; + if (!generateIndices()) + return false; if (m_vertexTangent && m_vertex->size() != m_vertexTangent->size()) { reportMessage(ANARI_SEVERITY_WARNING, @@ -94,7 +91,7 @@ void Quad::finalize() m_vertexBufferPtr = (CUdeviceptr)m_vertex->beginAs(AddressSpace::GPU); - upload(); + return true; } bool Quad::isValid() const @@ -146,11 +143,11 @@ GeometryGPUData Quad::gpuData() const return retval; } -void Quad::generateIndices() +bool Quad::generateIndices() { const size_t n = m_index ? m_index->size() : m_vertex->size() / 4; m_numTriangles = 2 * n; - generateQuadIndices(this, + return generateQuadIndices(this, m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr, n, m_indices); diff --git a/devices/rtx/device/geometry/Quad.h b/devices/rtx/device/geometry/Quad.h index c2d09b349..17b6acb39 100644 --- a/devices/rtx/device/geometry/Quad.h +++ b/devices/rtx/device/geometry/Quad.h @@ -43,7 +43,6 @@ struct Quad : public Geometry ~Quad() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -51,8 +50,9 @@ struct Quad : public Geometry int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; - void generateIndices(); + bool generateIndices(); void generateTangents(); DeviceBuffer m_indices; diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index 50fa2f9b0..dbb2816dd 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -72,14 +72,12 @@ void SDF::commitParameters() m_noiseFactor = glm::clamp(getParam("noiseFactor", 0.f), 0.f, 1.f); } -void SDF::finalize() +bool SDF::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'primitive.sdf' on sdf geometry"); - return; + return false; } // primitive.sdf must be an ANARI_UINT8 array of N * sizeof(SDFPrimitive) @@ -94,14 +92,14 @@ void SDF::finalize() if (reinterpret_cast(source) % alignof(SDFPrimitive) != 0) { const size_t bytes = m_numPrimitives * sizeof(SDFPrimitive); if (!reservePreparation(this, m_alignedPrimitives, bytes) - || !failPreparationOnError(this, + || !deviceState()->preparation.check(this, cudaMemcpyAsync(m_alignedPrimitives.ptr(), source, bytes, cudaMemcpyDeviceToDevice, - deviceState()->preparation.stream()), + deviceState()->preparationStream.stream()), "aligning SDF input")) - return; + return false; m_primitives = m_alignedPrimitives.ptrAs(); } else m_primitives = static_cast(source); @@ -111,10 +109,10 @@ void SDF::finalize() input.blendLerpFactor = m_blendLerpFactor; input.noiseFactor = m_noiseFactor; if (!m_preprocessing.bounds(this, {m_numPrimitives, input}, m_aabbs)) - return; + return false; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - upload(); + return true; } bool SDF::isValid() const diff --git a/devices/rtx/device/geometry/SDF.h b/devices/rtx/device/geometry/SDF.h index a81286e92..5487eaebd 100644 --- a/devices/rtx/device/geometry/SDF.h +++ b/devices/rtx/device/geometry/SDF.h @@ -58,13 +58,13 @@ struct SDF : public Geometry ~SDF() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; helium::ChangeObserverPtr m_sdf; diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index dd52e7d6d..5892204e7 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -67,14 +67,12 @@ PrimitiveInput Sphere::primitiveInput() const return {m_numSpheres, input}; } -void Sphere::finalize() +bool Sphere::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on sphere geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -85,45 +83,14 @@ void Sphere::finalize() m_numSpheres = m_index ? m_index->size() : m_vertex->size(); if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) - return; + return false; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - - // Radii may have changed. Rebuild the Geometry Light CDF if a surface has - // ever requested it (order-independent of the surface commit), else drop - // stale data. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else - m_preprocessing.releaseAreas(); - - if (!preparationFailed()) - upload(); -} - -void Sphere::buildAreaData() -{ - m_areaDataValid = m_preprocessing.areas(this, primitiveInput()); -} - -bool Sphere::isAreaSamplingSupported() const -{ return true; } -void Sphere::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - if (m_areaDataValid) - upload(); -} - -float Sphere::totalArea() const +std::optional Sphere::areaInput() const { - return m_preprocessing.totalArea(); + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Sphere::isValid() const @@ -160,10 +127,7 @@ GeometryGPUData Sphere::gpuData() const sphere.radius = m_globalRadius; populateAttributeDataSet(m_vertexAttributes, sphere.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - sphere.primAreaCdf = m_preprocessing.areaCdf(); - sphere.numPrimitives = sphere.primAreaCdf ? uint32_t(m_numSpheres) : 0; - sphere.totalArea = m_preprocessing.totalArea(); + populateAreaData(sphere, m_numSpheres); return retval; } diff --git a/devices/rtx/device/geometry/Sphere.h b/devices/rtx/device/geometry/Sphere.h index 0b9e97c6d..622fad43f 100644 --- a/devices/rtx/device/geometry/Sphere.h +++ b/devices/rtx/device/geometry/Sphere.h @@ -43,24 +43,18 @@ struct Sphere : public Geometry ~Sphere() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (Σ 4πr²) used - // to sample this sphere set as a Geometry Light. Lazy: only Emissive Surfaces - // call it, so ordinary sphere sets never pay for it. Mirrors Triangle. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; void cleanup(); - void buildAreaData(); + // Geometry Light sampling: the object-space area is Σ 4πr². + std::optional areaInput() const override; PrimitiveInput primitiveInput() const; helium::ChangeObserverPtr m_index; @@ -73,13 +67,6 @@ struct Sphere : public Geometry size_t m_numSpheres{0}; float m_globalRadius{1.f}; - - // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. - // m_areaDataWanted persists across recommits so a re-finalize rebuilds it - // order-independently. - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index 7b033870b..ff887eddd 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -63,7 +63,7 @@ void Triangle::generateTangents() input.positions = m_vertex.get(); input.indices = m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - input.numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; + input.numTriangles = primitiveCount(); input.normals = m_vertexNormal.ptr; input.normalsFV = m_vertexNormalFV.ptr; input.uvs = uvs; @@ -87,21 +87,19 @@ void Triangle::commitParameters() commitAttributes("faceVarying.", m_vertexAttributesFV); } -void Triangle::finalize() +bool Triangle::prepare() { - if (beginPreparation() != PreparationStart::Prepare) - return; if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on triangle geometry"); - return; + return false; } if (!m_index && m_vertex->size() % 3 != 0) { reportMessage(ANARI_SEVERITY_ERROR, "'vertex.position' on triangle geometry is a non-multiple of 3" " without 'primitive.index' present"); - return; + return false; } if (m_vertexNormal && m_vertex->size() != m_vertexNormal->size()) { @@ -112,7 +110,7 @@ void Triangle::finalize() m_vertex->size()); } - const size_t numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; + const size_t numTriangles = primitiveCount(); if (m_vertexNormalFV && 3 * numTriangles != m_vertexNormalFV->size()) { reportMessage(ANARI_SEVERITY_WARNING, @@ -152,48 +150,23 @@ void Triangle::finalize() m_index ? "indexed" : "soup"); m_vertexBufferPtr = (CUdeviceptr)m_vertex->beginAs(AddressSpace::GPU); + return true; +} - // Vertices/indices may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop any stale data. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else - m_preprocessing.releaseAreas(); - - if (!preparationFailed()) - upload(); +size_t Triangle::primitiveCount() const +{ + return m_index ? m_index->size() : m_vertex->size() / 3; } -void Triangle::buildAreaData() +std::optional Triangle::areaInput() const { + if (!isValid()) + return PrimitiveInput{}; TriangleInput input{}; input.vertices = m_vertex->beginAs(AddressSpace::GPU); input.indices = m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - const size_t count = m_index ? m_index->size() : m_vertex->size() / 3; - m_areaDataValid = m_preprocessing.areas(this, {count, input}); -} - -bool Triangle::isAreaSamplingSupported() const -{ - return true; -} - -void Triangle::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - if (m_areaDataValid) - upload(); // republish only successfully prepared sampling data -} - -float Triangle::totalArea() const -{ - return m_preprocessing.totalArea(); + return PrimitiveInput{primitiveCount(), input}; } void Triangle::populateBuildInput(OptixBuildInput &buildInput) const @@ -256,12 +229,7 @@ GeometryGPUData Triangle::gpuData() const resolveTangentPtr(m_vertexTangentFV, m_vertexTangentFVFinalized); tri.cullBackfaces = m_cullBackfaces; - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - tri.primAreaCdf = m_preprocessing.areaCdf(); - tri.numPrimitives = tri.primAreaCdf - ? uint32_t(m_index ? m_index->size() : m_vertex->size() / 3) - : 0; - tri.totalArea = m_preprocessing.totalArea(); + populateAreaData(tri, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Triangle.h b/devices/rtx/device/geometry/Triangle.h index daf706126..9e2783b6b 100644 --- a/devices/rtx/device/geometry/Triangle.h +++ b/devices/rtx/device/geometry/Triangle.h @@ -44,24 +44,20 @@ struct Triangle : public Geometry ~Triangle() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area used to sample - // this geometry as a Geometry Light. Lazy: only Emissive Surfaces call it, so - // ordinary meshes never pay for it. Re-uploads GPU data to publish the CDF. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; void cleanup(); - void buildAreaData(); + // Geometry Light sampling: the normalized cumulative object-space area over + // triangles. + std::optional areaInput() const override; + size_t primitiveCount() const; // Generate tangents that follow attribute0 when none were authored, into // the per-vertex or per-corner finalized buffer (see ComputeTangent.h). @@ -89,13 +85,6 @@ struct Triangle : public Geometry CUdeviceptr m_vertexBufferPtr{}; bool m_cullBackfaces{false}; - - // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. - // m_areaDataWanted persists across recommits so a re-finalize rebuilds it - // order-independently. - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/UnknownGeometry.cpp b/devices/rtx/device/geometry/UnknownGeometry.cpp index 2681f353e..154f5c2a1 100644 --- a/devices/rtx/device/geometry/UnknownGeometry.cpp +++ b/devices/rtx/device/geometry/UnknownGeometry.cpp @@ -46,6 +46,11 @@ void UnknownGeometry::populateBuildInput(OptixBuildInput &) const // no-op } +bool UnknownGeometry::prepare() +{ + return true; +} + GeometryGPUData UnknownGeometry::gpuData() const { return {}; diff --git a/devices/rtx/device/geometry/UnknownGeometry.h b/devices/rtx/device/geometry/UnknownGeometry.h index af024b876..e3388998d 100644 --- a/devices/rtx/device/geometry/UnknownGeometry.h +++ b/devices/rtx/device/geometry/UnknownGeometry.h @@ -47,6 +47,7 @@ struct UnknownGeometry : public Geometry bool isValid() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; }; diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 4e8c09b38..c582f601e 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -55,12 +55,12 @@ bool buildOptixBVH(std::vector buildInput, } auto &state = *obj->deviceState(); - auto &preparation = state.preparation; - const auto stream = preparation.stream(); + auto &preparationStream = state.preparationStream; + const auto stream = preparationStream.stream(); auto check = [&](cudaError_t error, const char *operation) { if (error == cudaSuccess) return true; - preparation.finish(); // Drain queued consumers before scratch is freed. + preparationStream.sync(); // Drain queued consumers before scratch is freed. cudaGetLastError(); obj->reportMessage(ANARI_SEVERITY_ERROR, "BVH preparation failed during %s: %s", @@ -71,7 +71,7 @@ bool buildOptixBVH(std::vector buildInput, auto checkOptix = [&](OptixResult result, const char *operation) { if (result == OPTIX_SUCCESS) return true; - preparation.finish(); + preparationStream.sync(); obj->reportMessage(ANARI_SEVERITY_ERROR, "BVH preparation failed during %s: %s", operation, @@ -85,8 +85,9 @@ bool buildOptixBVH(std::vector buildInput, // Legacy producers include field/isosurface work on the render stream and // authored arrays/instance uploads on the default stream. Previous rendering // must also finish before the existing BVH storage can be reused. - if (!check(state.waitForRenderConsumers(), "previous BVH consumers") - || !check(preparation.waitFor(nullptr), "input upload dependency")) + if (!check(preparationStream.orderAfterRender(), "previous BVH consumers") + || !check( + preparationStream.orderAfter(nullptr), "input upload dependency")) return false; OptixAccelBuildOptions options{}; @@ -103,15 +104,16 @@ bool buildOptixBVH(std::vector buildInput, // Allocate before submitting GPU work. Every earlier build completed, so // no transfer still targets the readback. - if (!state.bvhReadback) { - void *memory = nullptr; - const auto error = - cudaMallocHost(&memory, sizeof(DeviceGlobalState::BvhReadback)); - if (!check(error, "allocating BVH readback")) - return false; - state.bvhReadback.reset( - static_cast(memory)); - } + struct Readback + { + box3 bounds; + uint64_t compactedSize; + }; + cudaError_t readbackError = cudaSuccess; + auto *readback = static_cast( + preparationStream.readback(sizeof(Readback), readbackError)); + if (!check(readbackError, "allocating BVH readback")) + return false; DeviceBuffer compactedSizeBuffer, aabbBuffer, tempBuffer, outputBuffer; if (!reserve(compactedSizeBuffer, sizeof(uint64_t)) @@ -141,8 +143,8 @@ bool buildOptixBVH(std::vector buildInput, "build")) return false; - auto &builtBounds = state.bvhReadback->bounds; - auto &compactedSize = state.bvhReadback->compactedSize; + auto &builtBounds = readback->bounds; + auto &compactedSize = readback->compactedSize; if (!check(cudaMemcpyAsync(&builtBounds, aabbBuffer.ptr(), sizeof(box3), @@ -155,7 +157,7 @@ bool buildOptixBVH(std::vector buildInput, cudaMemcpyDeviceToHost, stream), "compaction size readback") - || !check(preparation.finish(), "build completion")) + || !check(preparationStream.sync(), "build completion")) return false; if (!reserve(bvh, compactedSize) @@ -166,7 +168,7 @@ bool buildOptixBVH(std::vector buildInput, bvh.bytes(), &built), "compaction") - || !check(preparation.finish(), "compaction completion")) + || !check(preparationStream.sync(), "compaction completion")) return false; // Publication and scratch destruction happen only after this stream's work @@ -186,166 +188,15 @@ DeviceGlobalState::DeviceGlobalState(ANARIDevice d) DeviceGlobalState::~DeviceGlobalState() = default; -void DeviceGlobalState::enqueueGeometryInputUploads(Geometry *geometry) -{ - m_geometryInputUploads.enqueue(helium::IntrusivePtr(geometry)); -} - -cudaError_t DeviceGlobalState::stageGeometryArray( - Array *array, helium::TimeStamp modified) -{ - const auto found = m_geometryInputVersions.find(array); - if (found != m_geometryInputVersions.end() && found->second == modified) - return cudaSuccess; - const auto error = array->enqueueUpload(preparation.stream()); - if (error == cudaSuccess) - m_geometryInputVersions.insert_or_assign(array, modified); - return error; -} - -bool DeviceGlobalState::collectingGeometryInputUploads() const -{ - return m_geometryInputUploads.collecting(); -} - -bool DeviceGlobalState::collectGeometryInputUploads() -{ - return m_geometryInputUploads.collect( - [&](Geometry *first) { - // The only route by which a geometry's host inputs reach the device. - // Commits capture sources; the first geometry finalizer submits every - // input batch before waiting. No legacy finalizer sees partially - // uploaded arrays. A finalizer then queues what no commit captured - // as a batch of its own. Retire obsolete cached copies before - // allocating a whole replacement cohort. A single geometry retains - // the existing allocation/retirement order. - if (m_geometryInputUploads.size() > 1) - m_geometryInputUploads.forEach([](Geometry *geometry) { - geometry->retirePreparationSnapshot(); - }); - auto error = geometryInputAllocations->reclaim( - [&] { return finishGeometryPreparation(); }); - if (error == cudaSuccess) - error = waitForRenderConsumers(); - if (error == cudaSuccess) { - m_geometryInputUploads.forEach( - [](Geometry *geometry) { geometry->submitInputUploads(); }); - error = finishGeometryPreparation(); - } - if (error != cudaSuccess) { - failGeometryInputUploads(); - failPreparation(first, error, "geometry input batch completion"); - } - m_geometryInputVersions.clear(); - }, - [](Geometry *geometry) noexcept { geometry->completeInputUploads(); }, - [&] { - // A host allocation or callback can unwind after copies were - // submitted. Keep sources alive and drain before permitting public - // release again. - failGeometryInputUploads(); - finishGeometryPreparation(); - m_geometryInputVersions.clear(); - }); -} - -void DeviceGlobalState::failGeometryInputUploads() -{ - m_geometryInputUploads.forEach( - [](Geometry *geometry) { geometry->failInputUploads(); }); -} - -cudaError_t DeviceGlobalState::waitForRenderConsumers() -{ - return cudaStreamQuery(stream) == cudaSuccess ? cudaSuccess - : preparation.waitFor(stream); -} - -cudaError_t DeviceGlobalState::retireRenderConsumers() -{ - // Anything but success, a failed query included, takes the wait: only a - // completed stream permits releasing what its work reads. - return cudaStreamQuery(stream) == cudaSuccess ? cudaSuccess - : cudaStreamSynchronize(stream); -} - -size_t DeviceGlobalState::enqueueGeometryPreparation(Geometry *geometry) -{ - return m_geometryPreparations.enqueue( - helium::IntrusivePtr(geometry)); -} - -bool DeviceGlobalState::collectingGeometryPreparations() const -{ - return m_geometryPreparations.collecting() - || m_geometryInputUploads.collecting(); -} - -bool DeviceGlobalState::hasPendingGeometryPreparations() const -{ - return m_geometryPreparations.collecting() || !m_geometryPreparations.empty() - || m_geometryInputUploads.collecting(); -} - -cudaError_t DeviceGlobalState::finishGeometryPreparation() -{ - // Flush deferred small jobs even at intervening upload/retirement waits: - // their input pointers must be consumed before a backing allocation changes. - // Then read back every queued result in one transfer. - const auto stream = preparation.stream(); - auto error = smallGeometryBatch.launch(preparationResults, stream); - if (error == cudaSuccess) - error = preparationResults.readback(m_geometryPreparations.size(), stream); - const auto completion = cudaStreamSynchronize(stream); - if (error == cudaSuccess) - error = completion; - if (error != cudaSuccess) { - cudaGetLastError(); - // An intervening upload/legacy consumer may wait before the collection - // point. Its stream-completion error affects all already queued results. - m_geometryPreparations.forEach( - [](Geometry *geometry) { geometry->markPreparationFailed(); }); - failGeometryInputUploads(); - } - return error; -} - -bool DeviceGlobalState::collectGeometryPreparations() -{ - if (!collectGeometryInputUploads()) - return false; - // Owners remain queued if descriptor allocation or registry publication - // throws. CUDA failure still invalidates the pending batch before reporting, - // so callbacks cannot see a partially valid generation. Numeric failures - // remain local to their geometries during publication. Every publication - // must succeed before any geometry leaves the queue. - return m_geometryPreparations.collect( - [&](Geometry *first) { - const auto error = finishGeometryPreparation(); - if (error != cudaSuccess) - failPreparation(first, error, "batch completion"); - m_geometryPreparations.forEach( - [](Geometry *geometry) { geometry->completePreparation(); }); - }, - [](Geometry *geometry) noexcept { geometry->markPreparationCollected(); }, - [] {}); -} - cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( - PreparationStream &preparation, cudaStream_t renderStream) + PreparationStream &stream) { if (!(samplers.dirty() || geometries.dirty() || materials.dirty() || surfaces.dirty() || lights.dirty() || fields.dirty() || volumes.dirty())) return cudaSuccess; - const auto error = preparation.upload(renderStream, - samplers, - geometries, - materials, - surfaces, - lights, - fields, - volumes); + const auto error = stream.upload( + samplers, geometries, materials, surfaces, lights, fields, volumes); if (error != cudaSuccess) return error; samplers.markUploaded(); diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index e39054b19..9b3426131 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -31,12 +31,9 @@ #pragma once -#include "geometry/Preprocessing.h" +#include "geometry/GeometryPreparation.h" #include "gpu/gpu_objects.h" -#include "utility/DeviceAllocationCache.h" #include "utility/DeviceObjectArray.h" -#include "utility/PreparationQueue.h" -#include "utility/PreparationStream.h" // helium #include "helium/BaseGlobalDeviceState.h" @@ -181,20 +178,6 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState CUcontext cudaContext; CUstream stream; - PreparationStream preparation; - std::shared_ptr geometryInputAllocations{ - std::make_shared()}; - // Scalar results of queued geometry preparations, by queue position. - PreparationResults preparationResults; - struct BvhReadback - { - box3 bounds; - uint64_t compactedSize; - }; - // Pinned; the first BVH build allocates it. Builds are serialized and - // complete before returning, so one serves them all. - std::unique_ptr bvhReadback; - SmallGeometryBatch smallGeometryBatch; cudaDeviceProp deviceProps; OptixDeviceContext optixContext; @@ -251,8 +234,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceObjectArray fields; DeviceObjectArray volumes; - cudaError_t upload( - PreparationStream &preparation, cudaStream_t renderStream); + cudaError_t upload(PreparationStream &stream); } registry; // MDL @@ -293,29 +275,12 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceGlobalState(ANARIDevice d); ~DeviceGlobalState() override; - void enqueueGeometryInputUploads(Geometry *geometry); - cudaError_t stageGeometryArray(Array *array, helium::TimeStamp modified); - bool collectGeometryInputUploads(); - bool collectingGeometryInputUploads() const; - // Returns the geometry's position in the preparation queue. - size_t enqueueGeometryPreparation(Geometry *geometry); - bool collectGeometryPreparations(); - cudaError_t finishGeometryPreparation(); - // Both ask CUDA whether the render stream is idle, so no submission site - // has to announce itself. The first orders the preparation stream after - // outstanding render work without blocking the host; the second blocks the - // host, for callers about to release memory that work may still read. - cudaError_t waitForRenderConsumers(); - cudaError_t retireRenderConsumers(); - bool collectingGeometryPreparations() const; - bool hasPendingGeometryPreparations() const; - - private: - void failGeometryInputUploads(); - - PreparationQueue> m_geometryInputUploads; - std::unordered_map m_geometryInputVersions; - PreparationQueue> m_geometryPreparations; + // The scene-update stream: geometry preparation, BVH builds, registry and + // world-table uploads. + PreparationStream preparationStream; + // Declared last so it is destroyed first: the geometries it still holds are + // released while the registry and the stream above are alive. + GeometryPreparation preparation{preparationStream}; }; bool buildOptixBVH(std::vector buildInput, diff --git a/devices/rtx/device/utility/PreparationStream.h b/devices/rtx/device/utility/PreparationStream.h index e00722c59..4f008eaa2 100644 --- a/devices/rtx/device/utility/PreparationStream.h +++ b/devices/rtx/device/utility/PreparationStream.h @@ -32,12 +32,19 @@ #pragma once #include +// std +#include +#include namespace visrtx { -// Serialized by the device's scene-update path. GPU dependencies do not block -// the host; finish() is reserved for host readback/publication and scratch -// reuse. +/* + * The device's scene-update stream: a nonblocking CUDA stream beside the + * render stream. Geometry preparation, BVH builds and scene-table uploads + * submit to it, ordered after the work they depend on by event rather than by + * blocking the host. Calls are serialized by the device's scene-update path; + * nothing here locks. + */ struct PreparationStream { PreparationStream() = default; @@ -45,20 +52,45 @@ struct PreparationStream PreparationStream(const PreparationStream &) = delete; PreparationStream &operator=(const PreparationStream &) = delete; - cudaError_t initialize(); + // Device lifetime. `renderStream` is the stream frames render on. + cudaError_t initialize(cudaStream_t renderStream); void reset(); cudaStream_t stream() const; - cudaError_t waitFor(cudaStream_t producer); - cudaError_t finish(); - - // All sources must remain stable until this returns. Drain a partial batch - // on failure; callers acknowledge dirty state only after success. + cudaStream_t renderStream() const; + + // GPU-side ordering; neither blocks the host. The first asks CUDA whether + // the render stream is idle, so no submission site has to announce itself, + // and is skipped when it is: an event recorded on an idle stream is already + // complete and orders nothing. + cudaError_t orderAfterRender(); + cudaError_t orderAfter(cudaStream_t producer); + // Waits for this stream's submitted work. + cudaError_t sync(); + + // Orders after rendering, copies, waits. All sources must remain stable + // until this returns. A partial batch is drained on failure; callers + // acknowledge dirty state only after success. template - cudaError_t upload(cudaStream_t previousConsumers, Arrays &...arrays); + cudaError_t upload(Arrays &...arrays); + + // Pinned host memory of at least `bytes` for a readback that completes + // before its caller returns (the BVH build's), so one block serves every + // caller. Allocated by the first call. Null with `error` set on failure. + void *readback(size_t bytes, cudaError_t &error); private: cudaStream_t m_stream{nullptr}; + cudaStream_t m_renderStream{nullptr}; + struct PinnedDeleter + { + void operator()(void *memory) const + { + cudaFreeHost(memory); + } + }; cudaEvent_t m_dependency{nullptr}; + std::unique_ptr m_readback; + size_t m_readbackBytes{0}; }; // Inlined definitions //////////////////////////////////////////////////////// @@ -68,8 +100,9 @@ inline PreparationStream::~PreparationStream() reset(); } -inline cudaError_t PreparationStream::initialize() +inline cudaError_t PreparationStream::initialize(cudaStream_t renderStream) { + m_renderStream = renderStream; if (m_stream) return cudaSuccess; auto error = cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking); @@ -97,7 +130,19 @@ inline cudaStream_t PreparationStream::stream() const return m_stream; } -inline cudaError_t PreparationStream::waitFor(cudaStream_t producer) +inline cudaStream_t PreparationStream::renderStream() const +{ + return m_renderStream; +} + +inline cudaError_t PreparationStream::orderAfterRender() +{ + return cudaStreamQuery(m_renderStream) == cudaSuccess + ? cudaSuccess + : orderAfter(m_renderStream); +} + +inline cudaError_t PreparationStream::orderAfter(cudaStream_t producer) { auto error = cudaEventRecord(m_dependency, producer); if (error == cudaSuccess) @@ -105,25 +150,43 @@ inline cudaError_t PreparationStream::waitFor(cudaStream_t producer) return error; } -inline cudaError_t PreparationStream::finish() +inline cudaError_t PreparationStream::sync() { return cudaStreamSynchronize(m_stream); } template -inline cudaError_t PreparationStream::upload( - cudaStream_t previousConsumers, Arrays &...arrays) +inline cudaError_t PreparationStream::upload(Arrays &...arrays) { - auto error = waitFor(previousConsumers); + // Unlike orderAfterRender(), a registry or world-table upload records and + // waits on the event even when the render stream is idle. Kept as it was: + // dropping the wait there has not been decided. + auto error = orderAfter(m_renderStream); auto enqueue = [&](auto &array) { if (error == cudaSuccess) error = array.enqueueUpload(m_stream); }; (enqueue(arrays), ...); - const auto completion = finish(); + const auto completion = sync(); if (error != cudaSuccess || completion != cudaSuccess) cudaGetLastError(); // Keep a recoverable API error out of the next batch. return error == cudaSuccess ? completion : error; } +inline void *PreparationStream::readback(size_t bytes, cudaError_t &error) +{ + error = cudaSuccess; + if (bytes > m_readbackBytes) { + m_readback.reset(); + m_readbackBytes = 0; + void *memory = nullptr; + error = cudaMallocHost(&memory, bytes); + if (error == cudaSuccess) { + m_readback.reset(memory); + m_readbackBytes = bytes; + } + } + return m_readback.get(); +} + } // namespace visrtx diff --git a/devices/rtx/device/world/Group.cpp b/devices/rtx/device/world/Group.cpp index f4a502e72..b4fb8b817 100644 --- a/devices/rtx/device/world/Group.cpp +++ b/devices/rtx/device/world/Group.cpp @@ -71,13 +71,15 @@ bool Group::getProperty(const std::string_view &name, if (name == "bounds" && type == ANARI_FLOAT32_BOX3) { if (flags & ANARI_WAIT) { deviceState()->commitBuffer.flush(); - rebuildSurfaceBVHs(); - rebuildVolumeBVH(); - if (preparationFailed()) + // Not short-circuited: a surface failure leaves the volume BVH current. + const bool surfacesBuilt = rebuildSurfaceBVHs(); + const bool volumesBuilt = rebuildVolumeBVH(); + if (!surfacesBuilt || !volumesBuilt) return false; - } - if (preparationFailed()) + } else if (preparationFailed()) { + // No step ran to report a result, so ask. return false; + } auto bounds = m_triangleBounds; bounds.extend(m_curveBounds); bounds.extend(m_userBounds); @@ -229,16 +231,18 @@ bool Group::geometryPreparationFailed() const return false; } -void Group::rebuildSurfaceBVHs() +bool Group::rebuildSurfaceBVHs() { - if (!deviceState()->collectGeometryPreparations()) - return; + const bool collected = deviceState()->preparation.collect(); if (geometryPreparationFailed()) - return; + return false; + // Nothing to rebuild, or a refused collection (reentered from one): the + // BVHs stay as the last attempt left them. const auto &state = *deviceState(); - if (state.objectUpdates.lastSurfaceBLASChange - < m_objectUpdates.lastSurfaceBVHBuilt) - return; + if (!collected + || state.objectUpdates.lastSurfaceBLASChange + < m_objectUpdates.lastSurfaceBVHBuilt) + return !m_surfaceBuildFailed; m_surfaceBuildFailed = false; partitionValidGeometriesByType(); @@ -251,67 +255,61 @@ void Group::rebuildSurfaceBVHs() m_traversableUser = {}; // populateBuildInput can upload authored indices. The BVH builder imports - // those default-stream producers before submitting the build. - auto triangles = createOBI(m_surfacesTriangle); - auto curves = createOBI(m_surfacesCurve); - auto users = createOBI(m_surfacesUser); - - if (!m_surfacesTriangle.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building triangle BVH"); - if (!buildOptixBVH(std::move(triangles), - m_bvhTriangle, - m_traversableTriangle, - m_triangleBounds, - this)) { - m_surfaceBuildFailed = true; - return; - } - } else { - reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping triangle BVH build"); - } - - if (!m_surfacesCurve.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building curve BVH"); - if (!buildOptixBVH(std::move(curves), - m_bvhCurve, - m_traversableCurve, - m_curveBounds, - this)) { - m_surfaceBuildFailed = true; - return; + // those default-stream producers before submitting the build. Every + // partition's input is created before the first build. + struct Partition + { + const char *name; + std::vector input; + DeviceBuffer &bvh; + OptixTraversableHandle &traversable; + box3 &bounds; + }; + Partition partitions[] = { + {"triangle", + createOBI(m_surfacesTriangle), + m_bvhTriangle, + m_traversableTriangle, + m_triangleBounds}, + {"curve", + createOBI(m_surfacesCurve), + m_bvhCurve, + m_traversableCurve, + m_curveBounds}, + {"user", + createOBI(m_surfacesUser), + m_bvhUser, + m_traversableUser, + m_userBounds}, + }; + + for (auto &p : partitions) { + if (p.input.empty()) { + reportMessage( + ANARI_SEVERITY_DEBUG, "visrtx::Group skipping %s BVH build", p.name); + continue; } - } else { reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping curve BVH build"); - } - - if (!m_surfacesUser.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building user BVH"); - if (!buildOptixBVH(std::move(users), - m_bvhUser, - m_traversableUser, - m_userBounds, - this)) { + ANARI_SEVERITY_DEBUG, "visrtx::Group building %s BVH", p.name); + if (!buildOptixBVH( + std::move(p.input), p.bvh, p.traversable, p.bounds, this)) { m_surfaceBuildFailed = true; - return; + return false; } - } else { - reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping user BVH build"); } buildSurfaceGPUData(); m_objectUpdates.lastSurfaceBVHBuilt = helium::newTimeStamp(); + return true; } -void Group::rebuildVolumeBVH() +bool Group::rebuildVolumeBVH() { const auto &state = *deviceState(); if (state.objectUpdates.lastVolumeBLASChange < m_objectUpdates.lastVolumeBVHBuilt) - return; + return !m_volumeBuildFailed; m_volumeBuildFailed = false; partitionValidVolumes(); @@ -321,7 +319,7 @@ void Group::rebuildVolumeBVH() m_objectUpdates.lastVolumeBVHBuilt = helium::newTimeStamp(); reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping volume BVH build"); - return; + return true; } reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building volume BVH"); @@ -331,12 +329,13 @@ void Group::rebuildVolumeBVH() m_volumeBounds, this)) { m_volumeBuildFailed = true; - return; + return false; } buildVolumeGPUData(); m_objectUpdates.lastVolumeBVHBuilt = helium::newTimeStamp(); + return true; } void Group::rebuildLights() diff --git a/devices/rtx/device/world/Group.h b/devices/rtx/device/world/Group.h index bfcfbff1d..9d65a4b46 100644 --- a/devices/rtx/device/world/Group.h +++ b/devices/rtx/device/world/Group.h @@ -80,9 +80,14 @@ struct Group : public Object // area-samplable ones (Stage 1.5: Sphere) are also Geometry Light candidates. const std::vector &surfacesUser() const; + // For a caller with no build step's result in hand: one publishing bounds + // or a frame. It walks every surface. bool preparationFailed() const; - void rebuildSurfaceBVHs(); - void rebuildVolumeBVH(); + // Each returns false when this group's BVHs of that kind cannot be used: a + // surface's geometry failed preparation, or a build failed now or in the + // last attempt. + bool rebuildSurfaceBVHs(); + bool rebuildVolumeBVH(); void rebuildLights(); private: diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index 26db24ad5..753b7785e 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -42,6 +42,7 @@ #include "utility/AnariTypeHelpers.h" #include "world/Group.h" +#include #include #include #include @@ -264,7 +265,7 @@ bool World::preparationFailed() const void World::rebuildWorld() { - if (!deviceState()->collectGeometryPreparations()) + if (!deviceState()->preparation.collect()) return; if (m_bvhBuildFailed) m_objectUpdates.lastTLASBuild = 0; @@ -277,10 +278,14 @@ void World::rebuildWorld() || updates.lastVolumeBLASChange >= lastCheck || updates.lastLightSetChange >= lastCheck) { m_objectUpdates.lastTLASBuild = 0; // BLAS changed, so need to build TLAS - rebuildBLASs(); - } - if (preparationFailed()) + if (!rebuildBLASs()) + return; + } else if (preparationFailed()) { + // No step ran to report a result, so ask. A failure can outlast the BLAS + // check: area data collected for a Geometry Light fails its geometry after + // the check advanced, and a group shared with another owner can fail there. return; + } if (m_objectUpdates.lastTLASBuild <= state.objectUpdates.lastTLASChange) { m_surfaceBounds = box3(); @@ -293,15 +298,8 @@ void World::rebuildWorld() // populated: the proxy BLAS is instanced into that TLAS. Their Pick Power // is deliberately NOT computed here -- it is scaled by the scene radius, // which only exists once the TLAS has been built. See buildLightPickCdf(). - buildInstanceLightGPUData(); - if (preparationFailed()) - return; - buildLightProxies(); - if (preparationFailed()) - return; - - populateOptixInstances(); - if (preparationFailed()) + if (!buildInstanceLightGPUData() || !buildLightProxies() + || !populateOptixInstances()) return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building surface BVH over %zu instances", @@ -335,8 +333,7 @@ void World::rebuildWorld() // Both TLASs have reported their bounds, so the extent of the illuminated // scene can be resolved and the infinite lights weighted against it. - buildIlluminatedBounds(); - if (preparationFailed()) + if (!buildIlluminatedBounds()) return; buildLightPickCdf(); // These records are consumed only by tracing, not by the intervening BVH @@ -358,7 +355,7 @@ void World::rebuildWorld() } } -void World::populateOptixInstances() +bool World::populateOptixInstances() { m_numTriangleInstances = 0; m_numCurveInstances = 0; @@ -468,22 +465,30 @@ void World::populateOptixInstances() instID++; } - uploadArrays(m_optixSurfaceInstances, m_optixVolumeInstances); + return uploadArrays(m_optixSurfaceInstances, m_optixVolumeInstances); } -void World::rebuildBLASs() +bool World::rebuildBLASs() { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World rebuilding BLASs"); + // A failure does not stop the rest: the next attempt then finds every other + // group already built. + bool rebuilt = true; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { auto *group = inst->group(); - group->rebuildSurfaceBVHs(); - group->rebuildVolumeBVH(); + const bool surfacesBuilt = group->rebuildSurfaceBVHs(); + const bool volumesBuilt = group->rebuildVolumeBVH(); group->rebuildLights(); + if (!surfacesBuilt || !volumesBuilt) + rebuilt = false; }); - if (!preparationFailed()) + // Only a check that found nothing failed is remembered, so the next + // rebuildWorld() comes back here until every group builds. + if (rebuilt) m_objectUpdates.lastBLASCheck = helium::newTimeStamp(); + return rebuilt; } void World::buildInstanceSurfaceGPUData() @@ -626,7 +631,7 @@ size_t World::countGeometryLights(Group *group) const return n; } -void World::synthesizeGeometryLights() +bool World::synthesizeGeometryLights() { // Configure or drop each candidate surface's Geometry Light from current // material + geometry state. Runs over triangle and user (custom-primitive, @@ -635,21 +640,29 @@ void World::synthesizeGeometryLights() // transform like an authored light. The light carries the material's mean // radiance (Pick Power); the sampler evaluates the material at the sampled // point when its emission is not constant. - auto configure = [](Surface *surface) { + // + // ensureAreaData() and collect() report an area that could not be computed + // on its geometry, so that is where each candidate's result is read. + auto areaFailed = [](Surface *surface) { + return surface->isSampleableEmitter() + && surface->geometry()->preparationFailed(); + }; + auto configure = [&](Surface *surface) { + if (areaFailed(surface)) + return false; if (surface->isSampleableEmitter()) { auto *geometry = surface->geometry(); - if (geometry->preparationFailed()) - return; const float area = geometry->totalArea(); if (area > 0.0f) { surface->ensureGeometryLight()->configure(geometry->index(), surface->material()->index(), surface->material()->emissionAverage(), area); - return; + return true; } } surface->clearGeometryLight(); + return true; }; std::set visited; @@ -668,17 +681,24 @@ void World::synthesizeGeometryLights() for (auto *surface : candidates) if (surface->isSampleableEmitter()) surface->geometry()->ensureAreaData(); - if (!deviceState()->collectGeometryPreparations()) - return; - for (auto *surface : candidates) - configure(surface); + // A refused collection (reentered from one) configures nothing: the lights + // keep their previous configuration, and the build goes on unless a request + // above already failed. + if (!deviceState()->preparation.collect()) + return std::none_of(candidates.begin(), candidates.end(), areaFailed); + // A failure does not stop the rest: the other lights are still configured. + bool synthesized = true; + for (auto *surface : candidates) { + if (!configure(surface)) + synthesized = false; + } + return synthesized; } -void World::buildInstanceLightGPUData() +bool World::buildInstanceLightGPUData() { - synthesizeGeometryLights(); - if (preparationFailed()) - return; + if (!synthesizeGeometryLights()) + return false; // Calculate total lights (authored + synthesized Geometry Lights) size_t totalLights = 0; @@ -786,9 +806,10 @@ void World::buildInstanceLightGPUData() assert(surfaceInstanceCursor == m_instanceSurfaceGPUData.size()); // Keep records host-side until proxy flags and Light Pick are finalized. + return true; } -void World::buildIlluminatedBounds() +bool World::buildIlluminatedBounds() { // What a DIRECTIONAL or HDRI light shines on. Both estimate their Pick Power // as irradiance times the cross-section of the scene, so the extent they are @@ -813,7 +834,7 @@ void World::buildIlluminatedBounds() // No proxy instance: the TLAS already covers geometry only. m_illuminatedBounds = m_surfaceBounds; m_illuminatedBounds.extend(m_volumeBounds); - return; + return true; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -832,11 +853,12 @@ void World::buildIlluminatedBounds() geometryBounds, this)) { m_bvhBuildFailed = true; - return; + return false; } m_illuminatedBounds = geometryBounds; m_illuminatedBounds.extend(m_volumeBounds); + return true; } void World::buildLightPickCdf() @@ -922,7 +944,7 @@ void World::buildLightPickCdf() constexpr float LIGHT_PROXY_AABB_RELATIVE_PAD = 1.0e-4f; constexpr float LIGHT_PROXY_AABB_MINIMUM_PAD = 1.0e-6f; -void World::buildLightProxies() +bool World::buildLightProxies() { // Traceable stand-ins for the analytic AREA lights (ADR 0009), so a camera or // BSDF-continuation ray can hit them. Deliberately derived from the ALREADY @@ -1022,11 +1044,11 @@ void World::buildLightProxies() "instances) -- area lights will not be directly visible", lightInstanceCursor, m_instanceLightGPUData.size()); - return; + return true; } if (proxies.empty()) - return; + return true; // Tracing records (including hasAreaProxy) are uploaded once after the TLAS // build; only the proxy AABBs are needed by the BLAS below. @@ -1036,7 +1058,7 @@ void World::buildLightProxies() m_lightProxyAabbs.resize(aabbs.size(), false); std::copy(aabbs.begin(), aabbs.end(), m_lightProxyAabbs.dataHost()); if (!uploadArrays(m_lightProxyAabbs)) - return; + return false; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building light-proxy BLAS over %zu proxies", @@ -1052,11 +1074,15 @@ void World::buildLightProxies() buildInput.customPrimitiveArray.numSbtRecords = 1; box3 proxyBounds; - m_bvhBuildFailed = !buildOptixBVH({buildInput}, - m_bvhLightProxies, - m_traversableLightProxies, - proxyBounds, - this); + if (!buildOptixBVH({buildInput}, + m_bvhLightProxies, + m_traversableLightProxies, + proxyBounds, + this)) { + m_bvhBuildFailed = true; + return false; + } + return true; } } // namespace visrtx diff --git a/devices/rtx/device/world/World.h b/devices/rtx/device/world/World.h index 0aaa84a89..d456dde6f 100644 --- a/devices/rtx/device/world/World.h +++ b/devices/rtx/device/world/World.h @@ -57,17 +57,22 @@ struct World : public Object WorldGPUData gpuData() const; + // For a caller with no build step's result in hand: one publishing a frame + // or a property. It walks every surface of every instance. bool preparationFailed() const; void rebuildWorld(); private: + // The build steps that can fail return false when they did; rebuildWorld() + // stops at the first. A failed BVH build or upload also sets + // m_bvhBuildFailed, which is what preparationFailed() reports afterwards. template bool uploadArrays(Arrays &...arrays); - void populateOptixInstances(); - void rebuildBLASs(); + bool populateOptixInstances(); + bool rebuildBLASs(); void buildInstanceSurfaceGPUData(); void buildInstanceVolumeGPUData(); - void buildInstanceLightGPUData(); + bool buildInstanceLightGPUData(); // Power-proportional Light Pick over the light instances buildInstanceLight- // GPUData laid out. Split from it because the Pick Power of an infinite light // is scaled by the scene radius, which is an OUTPUT of the TLAS build, while @@ -77,12 +82,13 @@ struct World : public Object // World bounds of the ILLUMINATED scene: geometry and volumes, with the // light-proxy instance excluded. See the definition for why this is a second // acceleration-structure build rather than a subtraction. - void buildIlluminatedBounds(); + bool buildIlluminatedBounds(); // Builds the analytic area-light proxy records, their AABBs and their BLAS // (ADR 0009). Must run after buildInstanceLightGPUData: proxies reference // light-instance slots by index. - void buildLightProxies(); - void synthesizeGeometryLights(); + bool buildLightProxies(); + // False when a geometry whose emitting area it asked for failed. + bool synthesizeGeometryLights(); size_t countGeometryLights(Group *group) const; void cleanup(); @@ -171,7 +177,7 @@ inline bool World::uploadArrays(Arrays &...arrays) if ((arrays.empty() && ...)) return true; auto &state = *deviceState(); - const auto error = state.preparation.upload(state.stream, arrays...); + const auto error = state.preparationStream.upload(arrays...); if (error == cudaSuccess) return true; m_bvhBuildFailed = true; diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md index 9f7ec1929..ab14fb0c1 100644 --- a/devices/rtx/docs/geometry-preparation-reuse.md +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -105,10 +105,29 @@ boundaries and local result interpretation; no historical baseline is required. Checked geometry preprocessing (bounds, area CDFs, generated quad/curve indices and radii, and SDF alignment) and OptiX BVH build/compaction use one device-owned -nonblocking preparation stream. `utility/PreparationStream.h` owns its lifetime -and the event used to import producer dependencies. Scene-update submission is -serialized; each event wait captures the corresponding record before the event -is reused. +nonblocking preparation stream. `PreparationStream` +(`utility/PreparationStream.h`, the member +`DeviceGlobalState::preparationStream`) owns its lifetime, the event used to +import producer dependencies and the pinned BVH readback. BVH builds, registry +uploads and world-table uploads use it directly: `stream()`, +`orderAfterRender()`, `orderAfter()`, `sync()`, `upload()` and `readback()`. +`orderAfterRender()` is the one render-ordering call; it skips the event wait +when `cudaStreamQuery` reports the render stream idle. `upload()` orders its +copies after rendering itself and takes that wait even on an idle render +stream. Scene-update submission is serialized; each event wait captures the corresponding record before the +event is reused. + +`GeometryPreparation` (`geometry/GeometryPreparation.h`, the member +`DeviceGlobalState::preparation`) holds a reference to that stream and owns the +two collection queues, the small-geometry batch, the scalar results and the +input allocation cache. Its header describes one scene update as one +transaction (commit, upload, submit, collect) and is the place to read the +lifecycle. Other code sees a small surface: `collect()` and `busy()`; +`waitForHostReaders()` and `waitForDeviceReaders()` for array privatization; +`fail()`, `check()`, `reject()` and `finish()` for geometry code; `defer()`, +`deferSmall()`, `deviceResults()` and `hostResults()` for `Preprocessing`. The +steps that `Geometry` and the owner call on each other are private on both +sides. Nothing in it locks: calls are serialized by the scene-update path. - Full preparation imports prior render work before overwriting derived buffers. - For the seven opt-in geometry types, parameter commits capture references to @@ -149,14 +168,15 @@ is reused. published only on success. Group/World failure state prevents failed builds from being treated as ready and permits a later retry. - Parameter-reference replacement and last-public-release privatization require - completed old render consumers. `DeviceGlobalState::retireRenderConsumers()` + completed old render consumers. `GeometryPreparation::retireRender()` asks `cudaStreamQuery` whether the render stream is idle and synchronizes it only when it is not, so frame submission, denoising, channel resolution, transfer-function opacity bounds and isosurface brick preparation need no bookkeeping of their own. A failed query never counts as idle: it takes the synchronize and reports that result. Scene submission remains serialized. - Error handling uses unconditional drains, not the query, before storage can - be retired or retried. + Handling a CUDA error uses unconditional drains, not the query, before + storage can be retired or retried. Rejected input (`reject()`) is not a CUDA + error and does no stream work. The existing shared-array, privatization, frame, denoiser and isosurface tests exercise the producer paths. @@ -260,7 +280,7 @@ share a descriptor when both arrive before the completion boundary. Requests above 256 primitives retain the general multi-block/CUB path. Zero-count handling is unchanged. SDF bounds retain their zero epsilon-scale convention. -Every `finishGeometryPreparation()` flushes these descriptors before waiting, +Every `GeometryPreparation::flush()` flushes these descriptors before waiting, including intervening upload waits and shared-array privatization. This is necessary because a queued descriptor still references its original inputs even before GPU work has been launched. Collection retains owners through descriptor @@ -295,7 +315,7 @@ property or shared production area helper is used by the oracle. `PreparationResults` holds two results per queued geometry: bounds (epsilon scale and validity) and total area. Kernels write its device storage; every -`finishGeometryPreparation()` that follows a write copies the queued range to +`GeometryPreparation::flush()` that follows a write copies the queued range to pinned host storage in one transfer, then synchronizes. `complete()` reads the host copy at the geometry's queue position. There is no per-geometry pinned storage and no host-side copy between pinned buffers. Device and pinned storage @@ -313,7 +333,7 @@ and growth allocation failure and retry on either side, preservation across growth, rewrites between readbacks and the readback range. BVH builds read back their bounds and compacted size through one pinned -`BvhReadback` owned by the device state. The first build allocates it; builds are +block owned by `PreparationStream`. The first build allocates it; builds are serialized and complete before returning, so no transfer outlives a build. Committed host inputs now complete in a cross-geometry batch before finalizers