1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
use cratewith_default_device_policy;
use crateDeviceFuture;
use crate;
use crateDeviceError;
use ;
use IntoFuture;
use MaybeUninit;
use Arc;
const CU_STREAM_CAPTURE_MODE_RELAXED: CUstreamCaptureMode = 2;
/// A captured and instantiated CUDA graph, ready for replay.
///
/// Created via [`CudaGraph::capture`], which runs a [`DeviceOp`] once on a
/// capture stream, recording all GPU work into a graph. The graph can then
/// be replayed any number of times via [`launch`](CudaGraph::launch).
///
/// All device pointers used by the operation are baked into the graph at capture
/// time. To vary inputs between replays, pre-allocate an input buffer, pass it
/// into the operation, and memcpy new data into that buffer before each launch.
///
/// # Examples
///
/// ```rust,ignore
/// use cuda_async::prelude::*;
///
/// // Build a lazy operation (no GPU work yet).
/// let forward_op = build_forward_pass(&model, &bufs);
///
/// // Capture: records the op's GPU work into a graph. Nothing has run yet.
/// let mut graph = CudaGraph::capture(stream.clone(), forward_op)?;
/// let bufs = graph.take_output().unwrap();
///
/// // Replay loop.
/// for _ in 0..n_tokens {
/// // Optionally: copy new input into a pre-allocated buffer here.
/// graph.launch().sync_on(&stream)?;
/// }
/// ```
/// Owns an instantiated CUDA graph: the `CUgraph` it was instantiated from
/// and the `CUgraphExec` that replays it.
///
/// Shared (via `Arc`) between the [`CudaGraph`] and every [`GraphLaunch`] it
/// hands out, so a launch can never replay an exec that has already been
/// destroyed: the handles live until the last owner — graph or pending
/// launch — is dropped. `GraphLaunch` used to copy the raw `CUgraphExec`, so
/// `let l = graph.launch(); drop(graph); l.sync()` launched a destroyed exec.
// SAFETY: both fields are opaque driver handles that the CUDA driver
// synchronizes internally; `cuGraphLaunch` may be issued from any thread. The
// only mutation is the destroy in `Drop`, which runs exactly once, after the
// last `Arc` owner is gone.
unsafe
unsafe
/// Runs `record` with `stream` in (relaxed) capture mode and turns the
/// recorded work into an instantiated, uploaded graph.
///
/// `cuStreamEndCapture` runs on every path — success, a `record` error, and
/// (before the panic resumes) a panic inside `record` — so a failure can
/// never leave the stream stuck in capture mode, and a graph handle produced
/// on a failing path is destroyed rather than leaked.
///
/// The caller must hold the execution lock: recording executes a `DeviceOp`.
/// A [`DeviceOp`] that replays a captured CUDA graph.
///
/// Created by [`CudaGraph::launch`]. The graph executes on whichever stream
/// the op is scheduled on (via `.sync_on(&stream)`, `.sync()`, or `.await`).
/// Holds a shared reference to the instantiated graph, so it may outlive the
/// [`CudaGraph`] that created it.
/// A scope for recording GPU operations into a CUDA graph.
///
/// Created by [`CudaGraph::scope`]. Each call to [`record`](Scope::record)
/// records a [`GraphNode`] as a graph node. The op is consumed immediately,
/// releasing any borrows it holds. This means a buffer written by one
/// kernel can be read by the next — `record` releases the `&mut` borrow,
/// allowing a subsequent `record` to take `&` on the same buffer.
///
/// ```rust,ignore
/// let graph = CudaGraph::scope(&stream, |s| {
/// s.record(rms_norm((&mut bufs.norm).partition([1, d]), &input, &w))?;
/// // bufs.norm borrow released — can now read it:
/// s.record(matvec((&mut bufs.q).partition([bn]), &bufs.norm, &wq))?;
/// Ok(())
/// })?;
///
/// graph.launch().sync_on(&stream)?;
/// ```
///
/// # Safety proof: why `record` is safe
///
/// A CUDA data race occurs when two accesses to the same device memory
/// are unordered and at least one is a write. This is UB per both CUDA
/// and Rust.
///
/// `record` is safe because of two complementary mechanisms:
///
/// ## Capture mode prevents concurrent GPU execution
///
/// The scope's stream is in **capture mode** during the closure (via
/// `cuStreamBeginCapture`). In capture mode:
///
/// 1. **No GPU work executes.** `record` records operations as graph
/// nodes — kernels are not launched, memcpys are not issued. There
/// is no in-flight GPU work that could race with anything.
///
/// 2. **Same-stream ordering is preserved.** All `record` calls go to
/// the same capture stream. When the graph is later launched via
/// [`CudaGraph::launch`], the nodes execute in recorded order on a
/// single stream. Sequential same-stream execution is ordered — no
/// data races.
///
/// 3. **Other executions inside the closure are rejected.** The scope
/// holds the thread-local execution lock for the duration of the
/// closure, so `op.sync_on(&other_stream)`, `op.sync()`, and
/// `op.sync_on(&capture_stream)` all return the non-reentrant
/// `DeviceError` before reaching the driver. Nothing executes eagerly
/// alongside the recording. (Independently, CUDA itself rejects
/// synchronizing or querying a capturing stream with
/// `CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED`.) The one way around the
/// lock is a [`then_unchecked`](DeviceOp::then_unchecked) chain recorded
/// via `record`, whose closure may execute eagerly — that is exactly the
/// caller's `unsafe` assertion.
///
/// 4. **Borrow checker enforces `&mut` exclusivity.** `record` consumes
/// the op, releasing `&mut`. The next `record` can then borrow the
/// same buffer as `&` for reading.
///
/// ## `GraphNode` prevents allocation during capture
///
/// `record` accepts [`GraphNode`] (not [`DeviceOp`]). `GraphNode` is only
/// implemented by operations that do not allocate or free device memory
/// (kernel launches, `memcpy`, `value`). This prevents:
///
/// - **Address instability:** `cuMemAllocAsync` during capture allocates
/// memory, but on replay the allocation node may return a different
/// address. Subsequent nodes bake in the capture-time pointer — UB.
///
/// - **Uninitialized reads:** An allocation during capture gives the user
/// a tensor handle. The initialization (e.g., memset from `zeros`) was
/// recorded, not executed. Passing the tensor to `sync_on(&other_stream)`
/// reads uninitialized memory.
///
/// - **Invalid frees:** If a tensor allocated inside the scope is dropped,
/// `cuMemFreeAsync` is recorded. On replay, it frees the capture-time
/// address, which may no longer be valid.
///
/// Since no tensors can be allocated inside the scope, all buffers are
/// pre-allocated and passed in via borrows. No tensor created inside
/// the scope means no tensor dropped inside the scope.
///
/// # What happens if you call other operations inside the closure
///
/// While `s.record(op)` is the intended API, other operations inside
/// the closure have well-defined behavior:
///
/// | Operation | What happens |
/// |---|---|
/// | `op.sync_on(&capture_stream)` | Non-reentrant execution-lock error; nothing executes |
/// | `op.sync_on(&other_stream)` | Non-reentrant execution-lock error; nothing executes |
/// | `op.sync()` / `op.await` | Non-reentrant execution-lock error; nothing executes |
///
/// These are all defined behavior but serve no purpose inside a graph
/// capture scope — use `s.record(op)` instead.
///
/// # Thread safety
///
/// `Scope` is `!Send` — it cannot escape to another thread.
/// A graph-backed inference module.
///
/// Implementations own a [`CudaGraph`] captured at construction time.
/// Each call to [`forward`](Module::forward) updates the input buffer and
/// replays the graph, returning the result synchronously.
///
/// # Construction
///
/// Graph capture is model-specific and happens in the implementation's
/// constructor — not in the trait. A typical pattern:
///
/// ```rust,ignore
/// use cuda_async::prelude::*;
///
/// struct MyModel {
/// graph: CudaGraph<Arc<Tensor<f32>>>,
/// h_input: Tensor<f32>,
/// output: Arc<Tensor<f32>>,
/// }
///
/// impl MyModel {
/// fn new(stream: Arc<Stream>) -> Result<Self, DeviceError> {
/// let h_input = api::zeros(&[d]).sync_on(&stream)?;
/// let forward_op = build_forward(h_input.clone().into());
/// let mut graph = forward_op.graph_on(stream)?;
/// let output = graph.take_output().unwrap();
/// Ok(Self { graph, h_input, output })
/// }
/// }
///
/// impl Module for MyModel {
/// type Input = Arc<Tensor<f32>>;
/// type Output = Arc<Tensor<f32>>;
///
/// fn forward(&mut self, input: Self::Input)
/// -> Result<Self::Output, DeviceError>
/// {
/// self.graph.update(
/// api::memcpy(&mut self.h_input, &input)
/// )?;
/// self.graph.launch().sync_on(self.graph.stream())?;
/// Ok(self.output.clone())
/// }
/// }
/// ```
///
/// # Future extensions
///
/// This trait covers the forward pass. Planned companion traits:
/// - `Backward` — gradient computation for autodiff
/// - `Parameterized` — access to learnable parameters for optimizers