Repository navigation
feat(cuda-core): RAII CUDA graph capture and replay - #574
honeyspoon wants to merge 1 commit into
Conversation
…t promise Exploratory work on gap #31 (89 graph FFI entry points, none wrapped). Graph replay is the largest measured win in the harness — a fixed ~1 µs per launch, 0.170/0.179/0.178 ms across FP16/INT8/W8A16 — and it is currently driven by raw FFI with `assert_eq!` on every status. Wraps the minimum useful slice: `begin_capture` -> `StreamCapture` guard -> `CapturedGraph` -> `GraphExec::launch`, all RAII, all returning `DriverError`. Two obligations the types now discharge: * Capture must be terminated even on the error path. The driver documents that an invalidated capture leaves the stream unusable until `cuStreamEndCapture` runs, and that a capturing blocking stream also makes the legacy null stream unusable. The existing raw-FFI code panics via `assert_eq!` between begin and end, which skips termination. `StreamCapture` terminates in `Drop`, so unwinding cannot poison the stream. Two hardware tests cover it: the stream is idle and usable after an abandoned capture, and can be recaptured. * Concurrent replay of one exec is not permitted, so `launch` takes `&mut self`. And one it cannot, now measured rather than assumed. A `GraphExec` outliving a buffer captured into it is undiagnosed and silently plausible: launch = Ok(()) sync = Ok(()) read = Ok(()) dst = [7, 8, 9, 10] (captured source was [7, 8, 9, 10]) The replay read freed device memory that still held the old bytes, so it "worked". No error at launch, synchronize, or read-back. Stream-ordered deallocation returning pages to a pool makes that the likely presentation, not a rare one, and it is the worst failure mode available: correct in testing, corrupt later. Because of that, `instantiate` being `unsafe` is probably the honest default; the module names the hole and the three ways to close it instead of choosing one. Findings worth keeping regardless of what happens to this code: * The doc's "89 FFI entry points" reproduces exactly as `grep -c "pub fn cuGraph"`. About 10 of those are `cuGraphics*` GL interop and some are `_v2` aliases, so unique true graph-API names are 83. There is no bindgen allowlist, so all of them really are reachable. * This crate resolves module-level intra-doc links against the *crate root*, because every module carries both a `///` on its `pub mod` line and `//!` docs in the file. `[CudaEvent]` works only because `event::CudaEvent` is re-exported. A new module whose types are not re-exported gets broken links that `rustdoc -D warnings` rejects — the same class of failure as upstream NVIDIA#511. Fixed by following the convention and re-exporting. Gates on nightly-2026-04-03: fmt, clippy --all-targets -D warnings, rustdoc -D warnings, doctests clean. `graph_capture` is 4 passed / 1 ignored (the ignored one is the deliberate use-after-free probe). `cargo test -p cuda-core` has one failure, `device_copy_derive_compile_pass`, which reproduces identically on an untouched `main`.
|
All CI jobs pass on this branch. Workflows here need maintainer approval before they start, so I ran the repository's own workflow job set against this tree myself. All 16 succeed: That covers three gates my local pre-push script does not: Also re-ran my pre-push review checklist over the diff: no em-dashes, no unescaped intra-doc brackets, SPDX headers present on new files, |
|
Closing to pursue the prerequisite properly rather than landing On re-reading my own justification, I think it is wrong. I wrote that a capture-scope closure "only helps if the closure's captured set is exactly the referenced set, which the driver never reports" — but the driver does not need to report anything. What keeps a buffer alive is Rust's closure capture, and if the returned exec carries a lifetime tied to those captures, the borrow checker rejects the use-after-free at compile time. Exploring that on |
|
Superseded by #585, which takes the design this PR's own justification said was unavailable. Both alternatives I dismissed here got prototyped. The lifetime-only form does work for the hazard ( |
Graph replay is worth a fixed ~1 µs per launch, and there is no wrapper at all today, so it is driven by raw FFI with
assert_eq!on every status.The saving is near-constant while node counts differ by 70%, which identifies it as per-launch overhead rather than anything kernel-related.
API decisions, and the alternatives rejected
1.
instantiateisunsafe— the central decisionChosen:
pub unsafe fn instantiate(&self) -> Result<GraphExec, DriverError>, with the buffer-lifetime obligation documented.Alternatives, both real:
stream.capture(|cap| { ... })where the closure owns the buffers, so the exec cannot outlive them.Arcclones of every buffer touched during capture.Why neither, yet: capture records raw device addresses, not Rust borrows, so the API cannot observe which buffers were touched. (a) only helps if the closure's captured set is exactly the referenced set, which the driver never reports; (b) requires an allocation registry the crate does not have, and changes ownership semantics for every buffer used in a captured region.
Why
unsaferather than a safe signature with docs: the violation is silent. Measured on an RTX A2000 (tests/graph_capture.rs, the#[ignore]d probe), replaying a graph whose captured buffer had been dropped gave:The replay read freed memory that still held the old bytes, so it "worked". Stream-ordered deallocation returning pages to a pool makes that the likely presentation, so the failure mode is "passes in testing, corrupts once pages are reused". A safe signature would promise a check neither the driver nor the type system performs.
This is the decision I most want overruled if you have a preference — (a) is nicer if you are willing to accept "buffers must be owned by the closure" as a documented convention rather than a proof.
2.
launch(&mut self)rather than&selfChosen:
&mut self.Alternative:
&self, letting one exec be launched from several places.Concurrent replay of a single
CUgraphExecis not permitted.&mutmakes that a compile error instead of a documented rule. The cost is that an exec cannot be shared behind anArcwithout a lock — which is the correct constraint, just occasionally inconvenient.3.
StreamCaptureguard that terminates inDropChosen: RAII guard;
end()consumes it,Dropterminates and discards.Alternative:
begin_capture/end_captureas free calls on the stream.Not a style preference. The driver documents that after an error the stream sits in
CU_STREAM_CAPTURE_STATUS_INVALIDATEDandand separately that a capturing blocking stream makes the legacy null stream unusable too. So an early
?or a panic between begin and end leaves the stream permanently broken — and the existing raw-FFI code, whichassert_eq!s in that window, has exactly that bug. Two hardware tests cover the remedy: after an abandoned capture the stream isCaptureStatus::Noneand still usable, and it can be recaptured.4.
CaptureModeenum, defaulting toGlobalChosen: three-variant enum,
#[default] Global.Alternative: take the raw
CUstreamCaptureMode.Globalis the conservative mode (prohibits unsafe driver actions in any thread). Defaulting to it means the easy call is the safe one;Relaxedhas to be asked for by name.5. Node mutation deliberately not wrapped
cuGraphExecKernelNodeSetParamsand friends are omitted, and not merely for scope.requireslaunch contracts run on the host at launch, so replay never executes them. That is sound only while replay reuses the arguments recorded at capture — each configuration gets its own capture and therefore its own validation — which is precisely what mutation would break. Wrapping it needs that interaction resolved first, so it belongs in its own PR with that argument made explicitly.Also omitted: graphs containing memory-allocation nodes (the driver permits at most one live exec per graph then) and device-side launch.
6. Scope: capture only, no graph construction
Chosen: stream capture as the only way to build a graph.
Alternative: also wrap
cuGraphCreate+cuGraphAddKernelNodefor explicit construction.Capture is the path that carries the measured win and the one every existing user is on. Explicit construction needs typed node handles and a dependency-edge API — a much larger surface, and easier to design once capture's lifetime story is settled.
For context: CCCL does not wrap graphs either — no graph type under
cuda/, and cudax is not in thecuda_ccclpackage — so there is no upstream design to copy here.Gates
fmt, clippy
--workspace --all-targets -D warnings, rustdoc-D warningsand doctests clean onnightly-2026-04-03.graph_capture: 4 passed / 1 ignored on an RTX A2000.cargo test -p cuda-corehas one failure,device_copy_derive_compile_pass, which reproduces identically on an untouchedmain.