Skip to content

feat(cuda-core): RAII CUDA graph capture and replay - #574

Closed
honeyspoon wants to merge 1 commit into
NVIDIA:mainfrom
honeyspoon:up2/graph-capture
Closed

honeyspoon wants to merge 1 commit into
NVIDIA:mainfrom
honeyspoon:up2/graph-capture

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

path    direct P50   graph P50   saved    nodes   µs/node
FP16    3.867 ms     3.697 ms    0.170    173     0.98
INT8    4.670 ms     4.491 ms    0.179    222     0.81
W8A16   9.180 ms     9.002 ms    0.178    293     0.61

The saving is near-constant while node counts differ by 70%, which identifies it as per-launch overhead rather than anything kernel-related.

let capture = stream.begin_capture(CaptureMode::Global)?;   // RAII guard
enqueue_work(&stream)?;                                      // recorded, not run
let graph = capture.end()?;                                  // CapturedGraph
let mut exec = unsafe { graph.instantiate() }?;               // GraphExec
exec.launch(&stream)?;

API decisions, and the alternatives rejected

1. instantiate is unsafe — the central decision

Chosen: pub unsafe fn instantiate(&self) -> Result<GraphExec, DriverError>, with the buffer-lifetime obligation documented.

Alternatives, both real:

  • (a) capture-scope closure — stream.capture(|cap| { ... }) where the closure owns the buffers, so the exec cannot outlive them.
  • (b) graph holds Arc clones 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 unsafe rather 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:

launch = Ok(())   sync = Ok(())   read = Ok(())
dst    = [7, 8, 9, 10]   (captured source was [7, 8, 9, 10])
diagnosed = false

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 &self

Chosen: &mut self.

Alternative: &self, letting one exec be launched from several places.

Concurrent replay of a single CUgraphExec is not permitted. &mut makes that a compile error instead of a documented rule. The cost is that an exec cannot be shared behind an Arc without a lock — which is the correct constraint, just occasionally inconvenient.

3. StreamCapture guard that terminates in Drop

Chosen: RAII guard; end() consumes it, Drop terminates and discards.

Alternative: begin_capture / end_capture as free calls on the stream.

Not a style preference. The driver documents that after an error the stream sits in CU_STREAM_CAPTURE_STATUS_INVALIDATED and

The capture sequence must be terminated with cuStreamEndCapture on the stream where it was initiated in order to continue using hStream.

and 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, which assert_eq!s in that window, has exactly that bug. Two hardware tests cover the remedy: after an abandoned capture the stream is CaptureStatus::None and still usable, and it can be recaptured.

4. CaptureMode enum, defaulting to Global

Chosen: three-variant enum, #[default] Global.

Alternative: take the raw CUstreamCaptureMode.

Global is the conservative mode (prohibits unsafe driver actions in any thread). Defaulting to it means the easy call is the safe one; Relaxed has to be asked for by name.

5. Node mutation deliberately not wrapped

cuGraphExecKernelNodeSetParams and friends are omitted, and not merely for scope. requires launch 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 + cuGraphAddKernelNode for 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 the cuda_cccl package — so there is no upstream design to copy here.

Gates

fmt, clippy --workspace --all-targets -D warnings, rustdoc -D warnings and doctests clean on nightly-2026-04-03. graph_capture: 4 passed / 1 ignored on an RTX A2000. cargo test -p cuda-core has one failure, device_copy_derive_compile_pass, which reproduces identically on an untouched main.

…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`.
@honeyspoon

honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor Author

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:

fmt                                       clippy
fork-guard                                generated intrinsics are current and ABI-compatible
cargo test -p cuda-device                 cargo test -p dialect-nvvm
cargo test -p mir-importer                cargo test -p mir-lower
cargo test -p dialect-mir                 cargo test -p llvm-export
cargo test -p mir-transforms              cargo test -p nvvm-transforms
cargo test -p cuda-intrinsics             cargo test -p cuda-intrinsics-gen
cargo test -p oxide-artifacts             cargo test -p reserved-oxide-symbols

That covers three gates my local pre-push script does not: fmt across the rustc-codegen-cuda workspace and every example crate, clippy on those too, and generated intrinsics are current and ABI-compatible.

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, cargo fmt --check clean in both workspaces.

@honeyspoon

Copy link
Copy Markdown
Contributor Author

Closing to pursue the prerequisite properly rather than landing unsafe instantiate with a documented obligation.

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 gen/graph-scope. Will reopen with whichever design survives.

@honeyspoon

Copy link
Copy Markdown
Contributor Author

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 (E0597, zero runtime cost) but holds a shared borrow of the captured buffers, so writing new input between replays is E0502 — sound and unusable. Ownership resolves both, and drops unsafe from the public surface entirely.

@nihalpasham nihalpasham mentioned this pull request Sep 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant