Skip to content

feat(cuda-core): safe CUDA graph capture and replay - #585

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

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

Conversation

@honeyspoon

Copy link
Copy Markdown
Contributor

Replaces #574, which I closed. That PR shipped unsafe instantiate with the buffer-lifetime obligation documented; this one makes the obligation unrepresentable and exposes no unsafe at all.

Graph replay is worth a fixed ~1 µs per launch — measured on the harness that motivated this, 0.170 / 0.179 / 0.178 ms across FP16 / INT8 / W8A16, near-constant while node counts differ by 70%, which is what identifies it as per-launch overhead. There is no wrapper today, so it runs through raw FFI with assert_eq! on every status.

let mut exec = stream.capture_owning(CaptureMode::Global, bufs, |b| {
    b.dst.copy_from_device_async(&b.src, &stream)
})?;

for input in batches {
    exec.state_mut().src.copy_from_host(&stream, input)?;
    exec.launch(&stream)?;
    stream.synchronize()?;
}
let bufs = exec.into_state();

Public surface: capture_owning, OwnedGraphExec (launch / state / state_mut / into_state / node_count), CaptureMode, CaptureStatus, capture_status. Nothing else, and no unsafe.


API decisions, and the alternatives rejected

1. The exec owns the captured state — this is the whole design

Chosen: capture_owning(mode, state, |&mut state| ...) -> OwnedGraphExec<S>.

Alternatives, both prototyped rather than argued about:

(a) Lifetime-only. An exec carrying PhantomData<&'captures ()> derived from the closure. This works for the hazard — zero runtime cost, no ownership change, and the use-after-free becomes:

error[E0597]: `src` does not live long enough

But it holds a shared borrow of every captured buffer, so writing new input between replays — the thing graph replay exists for — is:

error[E0502]: cannot borrow `src` as mutable because it is also borrowed as immutable

Sound, zero-cost, and unusable. I only found that by building it.

(b) unsafe instantiate + documented obligation (what #574 did). Usable and unsound, and unsound in the worst way: the violation is silent. Measured on an RTX A2000, replaying a graph whose captured buffer had been freed gave

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. 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" rather than a fault.

Owning resolves both. Capture records raw device addresses, not Rust borrows, so the driver can never report which allocations a graph references — but it does not need to, because nothing outside the exec can name the buffers. The hazard is unrepresentable rather than rejected, and state_mut gives the write-then-replay loop back.

Cost, stated plainly: the caller must group the buffers into one value and hand ownership over. That is a real ergonomic imposition, and the reason I would still take it is that the alternative is a silent-corruption footgun.

2. One public type, not five

The prototype exposed StreamCapture, CapturedGraph, GraphExec, a borrow-based exec and an owning one. That is five vocabularies for one concept, which is the mistake #583 documents. All the intermediates are now private, which also removes unsafe instantiate from the API surface entirely.

Consequence worth flagging: node_count moved onto the exec and is recorded at capture time, because the CUgraph is released once the executable graph exists.

3. Internal RAII guard, kept private

Not a style choice. 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 a record closure returning Err would otherwise strand the stream permanently — which is a bug the existing raw-FFI code has, since it assert_eq!s inside that window. Two tests probe the remedy through the public API.

4. launch(&mut self)

Concurrent replay of one CUgraphExec is not permitted, so &mut makes it a compile error rather than a documented rule. Cost: an exec cannot be shared behind an Arc without a lock, which is the correct constraint.

5. Capture only — no explicit graph construction

cuGraphCreate + cuGraphAddKernelNode would need typed node handles and a dependency-edge API. Capture is the path that carries the measured win and the one existing users are on; explicit construction is easier to design once the lifetime story is settled.

6. Node mutation deliberately absent

cuGraphExecKernelNodeSetParams interacts with launch contracts: requires clauses run on the host at launch, so replay never executes them. That is sound only while replay reuses the arguments recorded at capture — precisely what mutation would break. It needs that resolved first, in its own PR.

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.

What remains on the caller

launch enqueues; it does not wait. A write issued after it returns is only safe if ordered behind the replay, which holds when both go on the same stream — DeviceBuffer's copy helpers are all stream-ordered, so the natural usage is correct. Writing from a different stream, or from the host without synchronising, races the in-flight graph. I do not see a way to encode that in types, since the API cannot observe which stream a future write will use.

Tests

Six, all on the public API only, on an RTX A2000:

  • capture → replay a device copy, and that capture records rather than executes (dst still zero after capture)
  • node_count == 1
  • write-then-replay across three iterations, each observing the input written before it
  • a failing record leaves the stream CaptureStatus::None and usable
  • a stream can be recaptured after a failed capture
  • an idle stream reports no capture

Note what is absent: there is no test for replaying a graph whose captured buffer was freed. That program cannot be written through this API.

Gates

fmt, clippy --workspace --all-targets -D warnings, rustdoc -D warnings, doctests clean on nightly-2026-04-03. cargo test -p cuda-core has one failure, device_copy_derive_compile_pass, which reproduces identically on an untouched main.

Graph replay is worth a fixed ~1 us per launch and there is no wrapper today, so
it is driven by raw FFI with `assert_eq!` on every status.

The public surface is deliberately one constructor and one type:

    let mut exec = stream.capture_owning(CaptureMode::Global, bufs, |b| {
        b.dst.copy_from_device_async(&b.src, &stream)
    })?;
    exec.state_mut().src.copy_from_host(&stream, input)?;
    exec.launch(&stream)?;

No `unsafe` anywhere in it. The capture guard, `CapturedGraph` and the raw
`instantiate` are private implementation detail.

Ownership is what makes it safe. Capture records raw device *addresses*, not Rust
borrows, so the driver can never report which allocations a graph references.
Moving the state into the exec sidesteps that: nothing outside can name the
buffers, so the use-after-free is unrepresentable rather than rejected. That
matters because the violation is silent -- measured on an RTX A2000, replaying a
graph whose captured buffer had been freed returned `Ok(())` from launch,
synchronize and read-back, with the expected data.

A borrow-based alternative was prototyped first and rejected on evidence: a
`PhantomData<&'captures ()>` exec does turn the use-after-free into `E0597` at
zero runtime cost, but it holds a shared borrow of every captured buffer, so
writing new input between replays is `E0502`. Sound and unusable for the thing
graphs are for.

Six hardware tests on the public API only, including that a failing `record`
closure leaves the stream usable -- the driver requires even an invalidated
capture be terminated before the stream works again, and a capturing blocking
stream also makes the legacy null stream unusable.

The residual obligation is documented, not claimed away: `launch` enqueues, so a
write issued afterwards is only ordered behind the replay if both are on the same
stream.
@nihalpasham nihalpasham added enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) labels Jul 30, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

A note: since PRs have been submitted for cuda-graphs in the past.

I'm closing this for direction, not quality

  • same reasoning as feat: fp and cuda-graph support #346: we're moving cuda-oxide's host-side crates (cuda-bindings/cuda-core/cuda-async) onto the crates.io-published crates cutile-rs uses, so a Graph API added to cuda-core today lands on a foundation we're about to swap out.
  • This design belongs upstream in those crates, where the current graph surface is the raw begin/end_capture + CUgraph FFI your PR body describes.
  • CUDA Graph API #107 tracks how that unfolds.

@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

enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants