Skip to content

Decision: allow one unsafe opt-in in solidcraft-gpu for hardware ray tracing (wgpu ExperimentalFeatures) #3236

Open

Description

@bluecmd

Decision needed

May solidcraft-gpu contain one unsafe expression, so that the GPU path tracer can use hardware ray tracing? The expression is unsafe { wgpu::ExperimentalFeatures::enabled() }, the token wgpu 30 requires before a device can request Features::EXPERIMENTAL_RAY_QUERY.

Today the workspace has unsafe_code = "forbid". AGENTS.md lists three exceptions, all in the app crate, each because no safe API exists. This would be a fourth exception of the same kind: no safe API exists for this either.

Why it matters

The path tracer (#2067, #2191) traces rays through a software BVH in a WGSL compute shader. Ray traversal dominates render time: on an NVIDIA GB10, the 1080p coffee-machine scene with glass takes about 50 s at 256 spp. Every NVIDIA RTX, AMD RDNA2+ and recent Intel Arc GPU has dedicated ray tracing hardware that we leave idle.

Hardware ray queries are item 5 of the 1.0 must-haves in the roadmap (#3151). They are also the foundation of its 2.0 real-time ray-traced viewport (item 22). We expect a large speed-up, but we'll measure it in the prototype rather than promise it here.

What exactly needs unsafe (wgpu 30.0.1)

  • wgpu::ExperimentalFeatures::enabled() is a const unsafe fn. It returns the token passed in DeviceDescriptor::experimental_features, and every feature named EXPERIMENTAL_* is refused without it.
  • Its documented safety contract is: "You acknowledge that there may be UB-containing bugs in these APIs and those may be hit by calling otherwise safe code. You agree to report any such bugs to us."
  • Everything else is safe Rust: Device::create_blas, Device::create_tlas, CommandEncoder::build_acceleration_structures, and ray_query in WGSL.
  • The real risk isn't our unsafe line. It's that wgpu marks the feature experimental, so wgpu or driver bugs on this path could cause undefined behaviour or a GPU fault instead of an error.

Proposal

  1. Isolate it. One module, e.g. crates/gpu/src/path/hardware.rs, with #![allow(unsafe_code)] and a module comment explaining the contract, as in apps/solidcraft/src/native_crash.rs.
    • solidcraft-gpu changes from forbid to deny, as the app crate did.
    • Nothing else in the crate may use unsafe.
  2. Off by default, opt-in at runtime. Hardware ray tracing is used only when:
    • the adapter reports EXPERIMENTAL_RAY_QUERY;
    • the backend is one wgpu supports for it (wgpu 30 documents ray queries for Vulkan);
    • a setting or environment variable enables it.
      Otherwise, and on any device or pipeline error, the existing software BVH path runs, unchanged. A bad driver costs speed, never a render.
  3. Same results.
    • The hardware path must pass the existing oracle tests: glass, MIS, shadows and denoiser.
    • Closed-glass robustness depends on our exact-arithmetic hit ordering. So for transmissive bodies the hardware traversal may only return candidate hits, and the existing precise tie-breaking decides between them. A failing glass test blocks shipping.
  4. CI. Tests run where the hardware exists, on the GB10 and RTX 4090 self-hosted runners. Lavapipe keeps testing the software path. Whether lavapipe's own ray-query support is good enough to test against is checked during the prototype.
  5. Revisit the opt-in when wgpu drops the EXPERIMENTAL_ prefix and the token. At that point the unsafe goes away.

Related decision (optional, same reasoning)

Device::create_pipeline_cache is also unsafe in wgpu 30. A persistent pipeline cache would avoid recompiling the path shader at every launch, which would help both #3217 (about 2 h FXC compiles on DX12) and CI. If the maintainers accept item 1 for ray queries, they could allow pipeline caching in the same isolated module.

Asks for the maintainers

  • Accept or reject the exception in solidcraft-gpu for ExperimentalFeatures::enabled().
  • Optional: also accept create_pipeline_cache.
  • Agree that it ships off by default, behind an opt-in.

If it's accepted, the next step is a prototype PR stacked on #2191: hardware traversal for opaque geometry first, benchmarked on the GB10 and RTX 4090, interleaved against the software path.

🤖 Generated with Claude Code

https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS

Activity

  1. bluecmd commented on Oct 19, 2026

    @bluecmd
    ContributorAuthor

    Measured: hardware ray queries vs the software BVH (NVIDIA GB10)

    Summary: with the one unsafe opt-in, the opaque coffee-machine render at 1080p and 64 spp drops from 8.80 s to 2.18 s, 4.0× faster overall. That's 6.5× per sample (122 ms → 18.8 ms), with images matching the software render to 85.6 dB PSNR.

    Setup

    • Hardware: NVIDIA GB10 (DGX Spark), Vulkan, driver 595.91.07, wgpu 30.0.1, render-studio b209c11b.
    • Scene: examples/studio/coffee-exploded-sweep.json: 58,362 triangles, 1920×1080, three area lights, maximum depth 12.
    • Reproducible: the code is on the fork branch bluecmd/solidcraft@hwrt-prototype. It's evidence only and not for merging: it allows unsafe. See tools/hwrt-bench/README.md.

    1. Full renders through the production job path

    The prototype (SC_HWRT=1) replaces only trace_ordered_within, the f32 BVH traversal used for opaque launches and shadows, with a wgpu ray query on one BLAS/TLAS. Shading, sampling, light selection and tone mapping are unchanged. Runs were interleaved, three repeats each, after one warm-up per mode.

    render_and_encode_seconds Software BVH Hardware ray query
    1 spp 1.078 / 1.075 / 1.125 0.980 / 1.006 / 1.005
    64 spp 8.796 / 8.787 / 8.827 2.211 / 2.169 / 2.169
    Per sample, (64 − 1 spp) / 63 122 ms 18.8 ms
    • The 1-spp time is mostly fixed cost: the BVH, readback and PNG encode. The hardware path also replaces the 230 ms CPU BVH build with a BLAS build of a few milliseconds on the GPU. The prototype still builds the software BVH as well, so the 1-spp numbers don't show that saving.

    • Images: software vs hardware at 64 spp, same seeds:

      • maximum difference 7/255;
      • 0.0004% of pixels (about 8) differ by more than 2/255;
      • PSNR 85.6 dB.

      Two software runs are bit-identical. The few differing pixels come from hits that differ at f32 precision.

    2. Traversal only: the renderer's rays without shading

    tools/hwrt-bench loads the buffers a real job uploads (SC_DUMP). It traces each pixel's path with the renderer's own WGSL traversal over its own BVH, and again with hardware ray queries. Each path is a camera ray, then per surface vertex one shadow ray per area light and a cosine bounce, launched exactly as sample_path launches opaque rays.

    Both tracers produce the same 3,659,154 surface vertices and the same 1,346,263 occluded shadow rays for 15.66 M rays. The table shows the median of 3 runs × 20 dispatches, timed with GPU timestamps:

    Path length Software Hardware Speed-up
    5 vertices (15.0 M rays) 32.45 ms (463 Mrays/s) 1.88 ms (8.0 Grays/s) 17.3×
    12 vertices (15.7 M rays) 43.86 ms (357 Mrays/s) 2.43 ms (6.4 Grays/s) 18.1×

    3. Single ray sets (2,073,600 rays each, read from and written to buffers)

    Ray set Software, fast f32 (opaque launches) Software, precise (glass continuations) Hardware
    Camera 1.83 ms 1.78 ms 0.65 ms
    Diffuse bounce 5.74 ms 11.70 ms 0.66 ms
    Shadow 1.93 ms 6.34 ms 0.65 ms
    • These isolated sets understate the gain. The hardware time equals a kernel that only reads each ray and writes a result (0.66 ms), so here hardware traversal hides entirely behind memory traffic.
    • Agreement with the software hits:
      • camera rays 100%;
      • bounce rays: 99.98% agree on hit or miss, and 99.96% hit the same triangle;
      • shadow rays: 99.99% agree on occlusion.

    What this does not cover yet

    • Glass: closed-glass continuations need the exact ordering and tie-breaking that trace_precise_within provides. The prototype leaves those on the software path, so the physical-glass scenes weren't measured. That's the design point raised in the proposal above.
    • Other hardware: an RTX 4090 run (Vulkan) of the same branch is in progress, and I'll add it here. AMD and Apple remain untested; wgpu 30 documents ray queries for Vulkan only.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS

  2. added
    area:render
    needs-triage
    on Oct 19, 2026
  3. bluecmd commented on Oct 19, 2026

    @bluecmd
    ContributorAuthor

    RTX 4090 (Vulkan) results: same branch, scene and parameters

    Setup: NVIDIA GeForce RTX 4090, Windows 11, driver 616.56, Vulkan. The code is hwrt-prototype @ a3ffd067, with the GB10 render parameters verbatim (SHA-256 matches). The GPU was otherwise idle.

    Full renders, interleaved, three repeats after one warm-up per mode (render_and_encode_seconds):

    Software BVH Hardware ray query
    1 spp 0.557 / 0.581 / 0.560 0.535 / 0.536 / 0.517
    64 spp 3.755 / 3.762 / 3.770 1.227 / 1.237 / 1.235
    Per sample 50.7 ms 11.2 ms (4.5×)
    • At 64 spp that's 3.05× overall; the GB10 gave 4.0×.

    • The software path is already about 2.4× faster on the 4090 than on the GB10. With hardware traversal, the remaining 1.23 s is mostly shading, accumulation, readback and encoding.

    • Images: software vs hardware at 64 spp, in each of the three pairs:

      • maximum difference 18/255;
      • 0.0005% of pixels (about 10) differ by more than 2/255;
      • PSNR 82.4 dB.

      Repeats within each mode are bit-identical.

    Traversal-only paths:

    Path length Software Hardware Speed-up
    5 vertices 14.3 ms 0.66 ms 21.6×
    12 vertices 21.4 ms 0.87 ms 24.6×

    On the GB10 this was 17–18×.

    Single ray sets (2.07 M rays):

    Ray set Software, fast Software, precise Hardware
    Camera 0.69 ms 0.72 ms 0.18 ms
    Bounce 2.13 ms 10.3–10.5 ms 0.184 ms
    Shadow 0.75 ms 7.0 ms 0.179 ms
    • The hardware times sit at the floor of a kernel that only reads each ray and writes a result (0.175 ms).
    • Hit agreement matches the GB10 run: 100% for camera rays, 99.98% for bounce rays and 99.99% for shadow rays.

    Cold start: the first hardware pipeline compile on this driver took 364 s, against 0.06 s for the already-cached software pipeline. After that, setup took 0.06–0.08 s in both modes. A shipping implementation would need to account for this, as #3217 does for DX12: keep the software path available while the hardware pipeline compiles, or compile it in the background.

    Overall, on both GPUs:

    • Hardware traversal is 18–25× faster on the renderer's own rays.
    • Opaque production renders are 3–4× faster (4.5–6.5× per sample), with images matching to over 82 dB PSNR.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS

  4. wdunn001 commented on Oct 20, 2026

    @wdunn001
    Contributor

    Yes to hardware ray queries. The measurements above justify the work on their own. The proposal as written puts the capability in the wrong crate. I want the decision recorded with constraints about where it lives.

    The exception is wider than one expression

    unsafe_code = "forbid" is set twice for this crate: once in the workspace lints and again at the crate root in crates/gpu/src/lib.rs. A forbid cannot be lifted by an #[allow]. Accepting the proposal as written means demoting both to deny. Our existing exceptions are all platform FFI boundaries with no safe API: the 3Dconnexion dlopen, the Objective-C document hooks, the Windows crash filter, and the Windows window procedure. ExperimentalFeatures::enabled() is a different kind of thing. It is an acknowledgement token for an experimental API surface. solidcraft-gpu should keep forbid.

    WebGPU is a shipping target

    solidcraft-gpu is in the cargo xtask wasm crate set. The browser build is WebGPU-first (apps/solidcraft-web/src/main.rs), with WebGL2 as the fallback. WebGPU has no ray query API. The software WGSL traversal therefore stays the baseline that every target runs. Hardware traversal has to be a swappable implementation behind that baseline, selected per adapter at runtime.

    Proposal: the same seam we use everywhere else

    Make ray traversal a backend behind an interface. The repo already works this way elsewhere:

    • crates/engine/src/capture.rs holds an installed renderer trait object. Every Picture names the backend that drew it.
    • crates/gpu/src/select.rs is a pure Policy/Tier/Landing ladder driven by SOLIDCRAFT_GPU, unit tested without a GPU.
    • tessellation() in crates/gpu/src/view.rs is a capability probe returning Option<TessGpu>, with a driver denylist and an env kill switch, where None means the CPU path runs.
    • crates/mcp/src/backend.rs is one trait with remote and headless implementations.

    Concretely:

    1. Introduce a TraceBackend seam with the existing software BVH traversal as the default implementation. Selection goes through a policy in the shape of select.rs, for example SOLIDCRAFT_TRACE=auto|rayquery|bvh.
    2. The unsafe token lives in a new leaf crate, for example solidcraft-gpu-rayquery, with unsafe_code = "deny" and one #![allow(unsafe_code)] module carrying the contract comment, exactly as native_crash.rs does. The leaf crate is native-only and stays out of the xtask wasm crate set.
    3. Availability is reported through the metadata built for this purpose: the descriptors in crates/render/src/backend.rs, answering Availability::Unavailable { reason } on adapters without EXPERIMENTAL_RAY_QUERY. docs/render-backends.md already names acceleration structures as a host admission concern.
    4. The parity gate is a differential test in the shape of indexed_raycast_answers_as_the_scan_does in crates/geom/src/bvh_tests.rs: the hardware query and the software BVH must return the same nearest hit across the oracle scenes. Transmissive bodies keep the exact-arithmetic ordering on the software path, as proposed.

    Where this is heading

    docs/web-runtime.md already commits us to the craft-gpu provider model: GpuProvider and ProviderRegistry contracts, with craft-gpu-wgpu supplying WebGPU on wasm32 and Vulkan, DX12, or Metal on desktop. storytold/craft-libs#160 lands those crates with zero unsafe. Its error boundary lets no wgpu types cross. A traversal backend shaped as above can later become a provider there without redesign.

    Answers to the asks

    • The exception is accepted, scoped to a new leaf crate as in item 2 above. solidcraft-gpu keeps forbid.
    • create_pipeline_cache gets the same answer: same leaf crate, same module. The 364 s cold compile measured on the 4090 makes it worth doing together.
    • Off by default behind the opt-in is agreed. A bad driver may only ever cost speed.

    The next step stands as proposed: a prototype PR stacked on #2191, opaque geometry first, with the backend seam in place from the first commit.

  5. bluecmd commented on Oct 20, 2026

    @bluecmd
    ContributorAuthor

    Thanks, I agree with this shape and will build it that way. solidcraft-gpu keeps forbid(unsafe_code), and the software BVH stays the baseline on every target. Here is the plan, with two corrections from measurements made since.

    Correction 1: pipeline caches only help Vulkan. In wgpu 30, create_pipeline_cache is implemented for Vulkan only; D3D12 and Metal ignore it. A cache in the leaf crate will remove the ~364–375 s cold Vulkan compile on the 4090 (the driver's own cache already makes repeat runs ~2 s). It does nothing for D3D12. #3306 handles D3D12 separately: x64 builds link DXC, which takes the compile from ~2 h with FXC to ~82 s, paid once per process. The cache module still goes in the leaf crate as you say. It just won't change the D3D12 numbers.

    Correction 2: the parity gate compares nearest hits with a tolerance. Hardware traversal runs in f32 with the driver's own watertightness rules. It can choose the other triangle across a shared edge, or move t by a few ulps. So the differential test, in the shape of indexed_raycast_answers_as_the_scan_does, asserts per ray:

    • the same hit/miss;
    • t within a relative ε;
    • the same primitive, except on rays whose software hit lies within ε of a triangle edge, where either neighbour counts.

    The test reports the mismatch fraction and fails above zero outside those edge cases.

    Plan

    1. TraceBackend seam in solidcraft-gpu, from the first commit. A backend supplies the WGSL nearest-hit/any-hit functions the integrator calls (today's trace_ordered_within and the shadow query), its extra bind group layout, and the per-scene build, with an upload and BLAS/TLAS for ray queries. The software BVH is the default backend and keeps the exact-ordered precise path for glass, which always stays software. No wgpu types cross the seam's public surface, so it can later become a craft-gpu provider.
    2. Selection through a pure policy in the shape of select.rs: SOLIDCRAFT_TRACE=auto|rayquery|bvh, unit-tested without a GPU. auto stays bvh until the parity gate and driver coverage justify changing the default. A bad driver only ever costs speed.
    3. crates/gpu-rayquery (solidcraft-gpu-rayquery): a native-only leaf with unsafe_code = "deny" and one #![allow(unsafe_code)] module with the contract comment. It exposes two safe functions: open a device with EXPERIMENTAL_RAY_QUERY and the minimum acceleration-structure limits, and create the Vulkan pipeline cache. solidcraft-gpu depends on it only under cfg(not(target_arch = "wasm32")). It stays out of the xtask wasm set and gets a layers entry ordered before gpu.
    4. Availability through the descriptors in crates/render/src/backend.rs. With SOLIDCRAFT_TRACE=rayquery on an adapter without ray queries, gpu-path reports Availability::Unavailable { reason }. Under auto it falls back to bvh and logs that it did.
    5. Evidence: the tools/hwrt-bench numbers (Decision: allow one unsafe opt-in in solidcraft-gpu for hardware ray tracing (wgpu ExperimentalFeatures) #3236 comments: GB10 6.5×, 4090 4.5× per sample) rerun through the seam, plus the parity test on GB10 and the 4090.

    Order: #2191, #2780 and #3306 land first. They fix today's launch stalls: the synchronous setup and the FXC compile. Then a prototype PR stacked on #2191 with opaque geometry only. The hwrt-prototype branch stays evidence only and won't be merged.

    I'll keep this issue open until the prototype PR links back to it.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS

  6. ablasik commented on Oct 27, 2026

    @ablasik
    Contributor

    A data point for the "we'll measure it in the prototype" part, from Metal rather than Vulkan.

    I built a local prototype on top of #7185 (path tracer on Metal), using EXPERIMENTAL_RAY_QUERY behind the ExperimentalFeatures token as proposed here. On an Apple M3 Max, wgpu 30 exposes ray queries on Metal as well, so item 2's "Vulkan only" can probably include Metal.

    Scene: an e-bike battery design, 32 bodies, 57,786 triangles, no glass, 1080p. Render time in seconds, 3 runs each, median shown:

    spp software BVH hardware ray query speed-up
    8 2.50 2.18 1.15×
    64 18.07 15.18 1.19×

    The images match the software path within 6/255 per channel.

    So on Apple silicon the gain is modest, about 15–20%, not the large step one would expect on RTX hardware. Shading and sampling still dominate here once traversal gets cheaper. The GB10 and RTX numbers will decide whether it pays off. I can push the prototype branch if that helps with the RTX measurement.

  7. bluecmd commented on Oct 27, 2026

    @bluecmd
    ContributorAuthor

    Thanks @ablasik. That's a useful data point, and the first one from Metal.

    We already have GB10 and RTX 4090 numbers from the Vulkan prototype, posted above (GB10, RTX 4090): the coffee machine, 58,362 triangles, 1080p, no glass, close to your scene's size:

    Software BVH, per sample Hardware ray query, per sample 64 spp overall
    GB10 (Vulkan) 122 ms 18.8 ms (6.5×) 4.0×
    RTX 4090 (Vulkan) 50.7 ms 11.2 ms (4.5×) 3.05×
    M3 Max (Metal, from your table: (64 − 8 spp) ÷ 56) ≈ 278 ms ≈ 232 ms (≈1.2×) 1.19×

    Traversal alone was 17–25× faster on the two NVIDIA GPUs, so most of the remaining time there is shading, accumulation and readback. Your 1.2× on Apple silicon fits your reading: once traversal is cheap, shading dominates. It could also be that Metal's ray query path is less mature. A traversal-only measurement would separate the two; tools/hwrt-bench on the hwrt-prototype branch has one.

    Yes, please push the prototype branch. Running your branch on the 4090 with your battery scene would give a direct Metal-vs-Vulkan comparison of the same code. I can't give a date: our GB10 machines are unavailable for now, and the 4090 runs when we have capacity.

    On scope: the path tracer is currently Vulkan-only, with Metal listed as "later" in #3151. Whether #7183 brings Metal in is for the maintainers to decide there; this thread only records the measurements.

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:renderneeds-triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions