Repository navigation
feat(cuda-core): safe CUDA graph capture and replay - #585
Closed
honeyspoon wants to merge 1 commit into
Closed
honeyspoon wants to merge 1 commit into
honeyspoon wants to merge 1 commit into
Conversation
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.
Collaborator
|
A note: since PRs have been submitted for cuda-graphs in the past. I'm closing this for direction, not quality
|
Open
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replaces #574, which I closed. That PR shipped
unsafe instantiatewith the buffer-lifetime obligation documented; this one makes the obligation unrepresentable and exposes nounsafeat 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.Public surface:
capture_owning,OwnedGraphExec(launch/state/state_mut/into_state/node_count),CaptureMode,CaptureStatus,capture_status. Nothing else, and nounsafe.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:But it holds a shared borrow of every captured buffer, so writing new input between replays — the thing graph replay exists for — is:
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 gaveThe 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_mutgives 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 removesunsafe instantiatefrom the API surface entirely.Consequence worth flagging:
node_countmoved onto the exec and is recorded at capture time, because theCUgraphis 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_INVALIDATEDandand separately that a capturing blocking stream makes the legacy null stream unusable too. So a
recordclosure returningErrwould otherwise strand the stream permanently — which is a bug the existing raw-FFI code has, since itassert_eq!s inside that window. Two tests probe the remedy through the public API.4.
launch(&mut self)Concurrent replay of one
CUgraphExecis not permitted, so&mutmakes it a compile error rather than a documented rule. Cost: an exec cannot be shared behind anArcwithout a lock, which is the correct constraint.5. Capture only — no explicit graph construction
cuGraphCreate+cuGraphAddKernelNodewould 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
cuGraphExecKernelNodeSetParamsinteracts with launch contracts:requiresclauses 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 thecuda_ccclpackage — so there is no upstream design to copy here.What remains on the caller
launchenqueues; 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:
dststill zero after capture)node_count == 1recordleaves the streamCaptureStatus::Noneand usableNote 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 onnightly-2026-04-03.cargo test -p cuda-corehas one failure,device_copy_derive_compile_pass, which reproduces identically on an untouchedmain.