Skip to main content

singe_cuda/graph/
definition.rs

1use std::{
2    ffi::CString,
3    marker::PhantomData,
4    mem::{MaybeUninit, take},
5    ptr,
6    result::Result as StdResult,
7    sync::{Arc, Mutex, MutexGuard, PoisonError},
8};
9
10use singe_core::report_cleanup_failure;
11use singe_cuda_sys::{driver, runtime};
12
13use crate::{
14    context::Context,
15    error::{Error, Result},
16    event::Event,
17    graph::{
18        ExecutableGraph, Graph, GraphBuffer, GraphDebugDotFlags, GraphEdge, GraphEdgeAttributes,
19        GraphId, GraphInner, GraphInstantiateFlags, GraphNode, GraphTopologySummary,
20        MemoryAllocationNodeInfo, MemoryAllocationNodeParams, MemorySetNodeParams, RawGraph,
21        RetainedResources,
22        raw::{
23            HostNodeParams, MemoryCopy1DNodeParams, MemoryCopy3DNodeParams,
24            MemoryCopyFromSymbolNodeParams, MemoryCopyToSymbolNodeParams,
25        },
26    },
27    memory::{DeviceMemory, MemoryCopyKind},
28    module::{KernelLaunchArgs, LaunchConfig, Module},
29    try_ffi,
30    types::{DeviceFunction, DevicePtr},
31    utility::to_usize,
32    view::{DeviceOutput, DeviceRepr, DeviceSlice, DeviceSliceMut, ZeroableDeviceRepr},
33};
34
35impl Graph {
36    pub(crate) fn bind_context(&self) -> Result<()> {
37        self.context.bind()
38    }
39
40    // The caller transfers ownership of a live graph handle of `context`.
41    pub(crate) unsafe fn from_raw_in_context(
42        handle: runtime::cudaGraph_t,
43        context: Arc<Context>,
44    ) -> Result<Self> {
45        if handle.is_null() {
46            return Err(Error::NullHandle);
47        }
48
49        Ok(Self {
50            inner: Arc::new(GraphInner {
51                handle,
52                owns_handle: true,
53                context: Some(Arc::clone(&context)),
54                retained: Mutex::new(RetainedResources::default()),
55                parent: None,
56            }),
57            id: GraphId::generate(),
58            context,
59            _not_sync: PhantomData,
60        })
61    }
62
63    pub(crate) unsafe fn from_raw_borrowed_in_context(
64        handle: runtime::cudaGraph_t,
65        context: Arc<Context>,
66    ) -> Self {
67        Self {
68            inner: Arc::new(GraphInner {
69                handle,
70                owns_handle: false,
71                context: Some(Arc::clone(&context)),
72                retained: Mutex::new(RetainedResources::default()),
73                parent: None,
74            }),
75            id: GraphId::generate(),
76            context,
77            _not_sync: PhantomData,
78        }
79    }
80
81    pub(crate) fn create_in_context(context: Arc<Context>) -> Result<Self> {
82        context.bind()?;
83        let mut handle = ptr::null_mut();
84        // SAFETY: `handle` is a local that `cudaGraphCreate` writes through an exclusive pointer, and `context` is bound above.
85        unsafe {
86            try_ffi!(runtime::cudaGraphCreate(&raw mut handle, 0))?;
87        }
88        Ok(Self {
89            inner: Arc::new(GraphInner {
90                handle,
91                owns_handle: true,
92                context: Some(Arc::clone(&context)),
93                retained: Mutex::new(RetainedResources::default()),
94                parent: None,
95            }),
96            id: GraphId::generate(),
97            context,
98            _not_sync: PhantomData,
99        })
100    }
101
102    pub(crate) fn retained_resources(&self) -> Result<RetainedResources> {
103        Ok(self.retained_lock()?.clone())
104    }
105
106    pub(crate) fn retained_lock(&self) -> Result<MutexGuard<'_, RetainedResources>> {
107        self.inner
108            .retained
109            .lock()
110            .map_err(|_| Error::lock_poisoned("graph resources"))
111    }
112
113    pub(crate) fn retain_module(&self, module: &Module) -> Result<()> {
114        self.retained_lock()?.retain_module(module);
115        Ok(())
116    }
117
118    fn retain_buffer<T>(&self, buffer: &GraphBuffer<T>) -> Result<()>
119    where
120        T: DeviceRepr,
121    {
122        self.retained_lock()?.retain_allocation(buffer.retained());
123        Ok(())
124    }
125
126    fn check_buffer_context<T>(&self, buffer: &GraphBuffer<T>) -> Result<()>
127    where
128        T: DeviceRepr,
129    {
130        if &self.context != buffer.context() {
131            return Err(Error::MemoryContextMismatch);
132        }
133        Ok(())
134    }
135
136    fn check_buffer_contexts<T, D>(&self, dst: &GraphBuffer<D>, src: &GraphBuffer<T>) -> Result<()>
137    where
138        T: DeviceRepr,
139        D: DeviceRepr,
140    {
141        self.check_buffer_context(dst)?;
142        self.check_buffer_context(src)?;
143        Ok(())
144    }
145
146    /// Allocates graph-retained device memory.
147    ///
148    /// The returned buffer can be used with graph-buffer node APIs.
149    /// Any graph or executable graph that records the buffer retains the underlying device allocation for replay.
150    ///
151    /// # Errors
152    ///
153    /// Returns an error if CUDA cannot allocate device memory, the requested byte count overflows, or CUDA reports runtime initialization diagnostics.
154    pub fn create_buffer_uninit<T>(&mut self, length: usize) -> Result<GraphBuffer<MaybeUninit<T>>>
155    where
156        T: DeviceRepr,
157    {
158        self.bind_context()?;
159        let context = &self.context;
160        let buffer = GraphBuffer::from_memory(DeviceMemory::<T>::create_uninit(context, length)?);
161        self.retain_buffer(&buffer)?;
162        Ok(buffer)
163    }
164
165    /// Allocates graph-retained device memory initialized to zero bytes.
166    ///
167    /// # Errors
168    ///
169    /// Returns an error if CUDA cannot allocate or initialize device memory, the requested byte count overflows, or CUDA reports runtime initialization diagnostics.
170    pub fn zeroed_buffer<T>(&mut self, length: usize) -> Result<GraphBuffer<T>>
171    where
172        T: ZeroableDeviceRepr,
173    {
174        self.bind_context()?;
175        let context = &self.context;
176        let buffer = GraphBuffer::from_memory(DeviceMemory::zeroed(context, length)?);
177        self.retain_buffer(&buffer)?;
178        Ok(buffer)
179    }
180
181    /// Allocates graph-retained device memory initialized from a host slice.
182    ///
183    /// # Errors
184    ///
185    /// Returns an error if CUDA cannot allocate or copy device memory, the requested byte count overflows, or CUDA reports runtime initialization diagnostics.
186    pub fn buffer_from_slice<T>(&mut self, values: &[T]) -> Result<GraphBuffer<T>>
187    where
188        T: DeviceRepr,
189    {
190        self.bind_context()?;
191        let context = &self.context;
192        let buffer = GraphBuffer::from_memory(DeviceMemory::from_slice(context, values)?);
193        self.retain_buffer(&buffer)?;
194        Ok(buffer)
195    }
196
197    /// Instantiates graph as an executable graph.
198    /// The graph is validated for any structural constraints or intra-node constraints which were not previously validated.
199    /// If instantiation is successful, returns an instantiated executable graph.
200    ///
201    /// `flags` controls the behavior of instantiation and subsequent graph launches.
202    /// Valid flags are:
203    ///
204    /// * [`GraphInstantiateFlags::AUTO_FREE_ON_LAUNCH`], which configures a graph containing memory allocation nodes to automatically free any unfreed memory allocations before the graph is relaunched.
205    ///
206    /// * [`GraphInstantiateFlags::DEVICE_LAUNCH`], which configures the graph for launch from the device.
207    ///   If this flag is passed, the executable graph handle returned can be used to launch the graph from both the host and device.
208    ///   This flag can only be used on platforms which support unified addressing.
209    ///   This flag cannot be used in conjunction with [`GraphInstantiateFlags::AUTO_FREE_ON_LAUNCH`].
210    ///
211    /// * [`GraphInstantiateFlags::USE_NODE_PRIORITY`], which causes the graph to use the priorities from the per-node attributes rather than the priority of the launch stream during execution.
212    ///   Priorities are only available on kernel nodes and are copied from stream priority during stream capture.
213    ///
214    /// If the graph contains any allocation or free nodes, there can be at most one executable graph in existence for that graph at a time.
215    /// An attempt to instantiate a second executable graph before dropping the first results in an error.
216    /// The same also applies if the graph contains any device-updatable kernel nodes.
217    ///
218    /// If the graph contains kernels which call device-side [`ExecutableGraph::launch_async`] from multiple devices, this results in an error.
219    ///
220    /// Graphs instantiated for launch on the device have additional restrictions which do not apply to host graphs:
221    ///
222    /// * The graph's nodes must reside on a single device.
223    /// * The graph can only contain kernel nodes, memcpy nodes, memset nodes, and child graph nodes.
224    /// * The graph cannot be empty and must contain at least one kernel, memcpy, or memset node.
225    ///   Operation-specific restrictions are outlined below.
226    /// * Kernel nodes:
227    ///   + Use of CUDA Dynamic Parallelism is not permitted.
228    ///   + Cooperative launches are permitted as long as MPS is not in use.
229    /// * Memcpy nodes:
230    ///   + Only copies involving device memory and/or pinned device-mapped host memory are permitted.
231    ///   + Copies involving CUDA arrays are not permitted.
232    ///   + Both operands must be accessible from the current device, and the current device must match the device of other nodes in the graph.
233    ///
234    /// Graph objects are not threadsafe.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if the context cannot be bound or CUDA rejects instantiation, including for invalid graph structure, unsupported node parameters or flags, or native restrictions on simultaneous executable instances.
239    /// CUDA may also report errors from previous asynchronous launches or runtime initialization diagnostics.
240    pub fn instantiate(&self, flags: GraphInstantiateFlags) -> Result<ExecutableGraph> {
241        self.bind_context()?;
242        let mut handle = ptr::null_mut();
243        // SAFETY: `self.inner` owns the live graph, `Graph` is not `Sync` so no other thread uses it, `handle` is a local output, and the context is bound above.
244        unsafe {
245            try_ffi!(runtime::cudaGraphInstantiateWithFlags(
246                &raw mut handle,
247                self.as_raw(),
248                flags.bits(),
249            ))?;
250        }
251        // SAFETY: CUDA instantiated this executable from the retained graph, and nothing else owns it.
252        unsafe {
253            ExecutableGraph::from_raw_with_graph(
254                handle,
255                Arc::clone(&self.context),
256                Some(self.id),
257                Some(Arc::clone(&self.inner)),
258                self.retained_resources()?,
259            )
260        }
261    }
262
263    /// Creates a copy of `original_graph`.
264    /// All parameters are copied into the cloned graph.
265    /// The original graph may be modified after this call without affecting the clone.
266    ///
267    /// Child graph nodes in the original graph are recursively copied into the clone.
268    ///
269    /// Cloning is not supported for graphs that contain memory allocation nodes, memory free nodes, or conditional nodes.
270    ///
271    /// Graph objects are not threadsafe.
272    ///
273    /// # Errors
274    ///
275    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
276    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
277    pub fn try_clone(&self) -> Result<Self> {
278        self.bind_context()?;
279        let mut handle = ptr::null_mut();
280        // SAFETY: `self.inner` owns the live graph, `handle` is a local output, and the context is bound above.
281        unsafe {
282            try_ffi!(runtime::cudaGraphClone(&raw mut handle, self.as_raw()))?;
283        }
284        Ok(Self {
285            inner: Arc::new(GraphInner {
286                handle,
287                owns_handle: true,
288                context: Some(Arc::clone(&self.context)),
289                retained: Mutex::new(self.retained_resources()?),
290                parent: None,
291            }),
292            id: GraphId::generate(),
293            context: Arc::clone(&self.context),
294            _not_sync: PhantomData,
295        })
296    }
297
298    pub(crate) fn node_from_raw(&self, handle: runtime::cudaGraphNode_t) -> GraphNode {
299        GraphNode::from_raw_in_graph(
300            handle,
301            self.id,
302            Arc::clone(&self.inner),
303            Some(Arc::clone(&self.context)),
304        )
305    }
306
307    pub(crate) fn check_node(&self, node: &GraphNode) -> Result<()> {
308        self.bind_context()?;
309        if !matches!(node.graph_id, Some(id) if id == self.id) {
310            return Err(Error::GraphNodeMismatch);
311        }
312        Ok(())
313    }
314
315    pub(crate) fn check_nodes(&self, nodes: &[GraphNode]) -> Result<()> {
316        self.bind_context()?;
317        for node in nodes {
318            if !matches!(node.graph_id, Some(id) if id == self.id) {
319                return Err(Error::GraphNodeMismatch);
320            }
321        }
322        Ok(())
323    }
324
325    fn check_child_graph_context(&self, child_graph: &Self) -> Result<()> {
326        if self.context.as_ref() != child_graph.context.as_ref() {
327            return Err(Error::context_mismatch("child graph"));
328        }
329        Ok(())
330    }
331
332    fn check_event_record_context(&self, event: &Event) -> Result<()> {
333        if &self.context != event.context() {
334            return Err(Error::context_mismatch("event"));
335        }
336        Ok(())
337    }
338
339    /// Adds a default dependency from `from` to `to`.
340    ///
341    /// # Errors
342    ///
343    /// Returns an error if any node belongs to another graph or context binding fails.
344    /// Also propagates CUDA dependency-update errors.
345    pub fn add_dependency(&mut self, from: GraphNode, to: GraphNode) -> Result<()> {
346        self.add_dependencies(&[from], &[to])
347    }
348
349    /// Adds default dependencies between corresponding entries in `from` and `to`.
350    ///
351    /// # Errors
352    ///
353    /// Returns an error if any node belongs to another graph or context binding fails.
354    /// Also propagates CUDA dependency-update errors.
355    /// Source and destination slices must have equal lengths.
356    pub fn add_dependencies(&mut self, from: &[GraphNode], to: &[GraphNode]) -> Result<()> {
357        self.add_dependency_edges(from, to, &[])
358    }
359
360    // Empty `edge_data` uses default attributes for every edge; empty `from` and `to` leave the graph unchanged.
361    fn add_dependency_edges(
362        &mut self,
363        from: &[GraphNode],
364        to: &[GraphNode],
365        edge_data: &[GraphEdgeAttributes],
366    ) -> Result<()> {
367        if from.len() != to.len() {
368            return Err(Error::GraphDependencyMismatch);
369        }
370
371        if !edge_data.is_empty() && edge_data.len() != from.len() {
372            return Err(Error::GraphDependencyMismatch);
373        }
374
375        if from.is_empty() {
376            return Ok(());
377        }
378
379        self.check_nodes(from)?;
380        self.check_nodes(to)?;
381
382        let from_raw: Vec<_> = from.iter().map(GraphNode::as_raw).collect();
383        let to_raw: Vec<_> = to.iter().map(GraphNode::as_raw).collect();
384        let edge_data_raw: Vec<_> = edge_data.iter().copied().map(Into::into).collect();
385        // SAFETY: the nodes were checked to belong to this exclusively borrowed graph, and the `from`, `to`, and edge arrays are locals of equal, validated length that outlive the call.
386        unsafe {
387            try_ffi!(runtime::cudaGraphAddDependencies(
388                self.as_raw(),
389                from_raw.as_ptr(),
390                to_raw.as_ptr(),
391                if edge_data_raw.is_empty() {
392                    ptr::null()
393                } else {
394                    edge_data_raw.as_ptr()
395                },
396                from_raw.len() as _,
397            ))?;
398        }
399        Ok(())
400    }
401
402    /// Removes the default dependency from `from` to `to`.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error if any node belongs to another graph or context binding fails.
407    /// Also propagates CUDA dependency-update errors.
408    pub fn remove_dependency(&mut self, from: GraphNode, to: GraphNode) -> Result<()> {
409        self.remove_dependencies(&[from], &[to])
410    }
411
412    /// Removes default dependencies between corresponding entries in `from` and `to`.
413    ///
414    /// # Errors
415    ///
416    /// Returns an error if any node belongs to another graph or context binding fails.
417    /// Also propagates CUDA dependency-update errors.
418    /// Source and destination slices must have equal lengths.
419    pub fn remove_dependencies(&mut self, from: &[GraphNode], to: &[GraphNode]) -> Result<()> {
420        self.remove_dependency_edges(from, to, &[])
421    }
422
423    // Empty `edge_data` matches default attributes for every edge; empty `from` and `to` leave the graph unchanged.
424    fn remove_dependency_edges(
425        &mut self,
426        from: &[GraphNode],
427        to: &[GraphNode],
428        edge_data: &[GraphEdgeAttributes],
429    ) -> Result<()> {
430        if from.len() != to.len() {
431            return Err(Error::GraphDependencyMismatch);
432        }
433
434        if !edge_data.is_empty() && edge_data.len() != from.len() {
435            return Err(Error::GraphDependencyMismatch);
436        }
437
438        if from.is_empty() {
439            return Ok(());
440        }
441
442        self.check_nodes(from)?;
443        self.check_nodes(to)?;
444
445        let from_raw: Vec<_> = from.iter().map(GraphNode::as_raw).collect();
446        let to_raw: Vec<_> = to.iter().map(GraphNode::as_raw).collect();
447        let edge_data_raw: Vec<_> = edge_data.iter().copied().map(Into::into).collect();
448        // SAFETY: the nodes were checked to belong to this exclusively borrowed graph, and the `from`, `to`, and edge arrays are locals of equal, validated length that outlive the call.
449        unsafe {
450            try_ffi!(runtime::cudaGraphRemoveDependencies(
451                self.as_raw(),
452                from_raw.as_ptr(),
453                to_raw.as_ptr(),
454                if edge_data_raw.is_empty() {
455                    ptr::null()
456                } else {
457                    edge_data_raw.as_ptr()
458                },
459                from_raw.len() as _,
460            ))?;
461        }
462        Ok(())
463    }
464
465    /// Adds directed edges with explicit port and dependency attributes.
466    ///
467    /// # Errors
468    ///
469    /// Returns an error if any node belongs to another graph or context binding fails.
470    /// Also propagates CUDA dependency-update errors.
471    pub fn add_edges(&mut self, edges: &[GraphEdge]) -> Result<()> {
472        if edges.is_empty() {
473            return Ok(());
474        }
475
476        let from: Vec<_> = edges.iter().map(|edge| edge.from.clone()).collect();
477        let to: Vec<_> = edges.iter().map(|edge| edge.to.clone()).collect();
478        let data: Vec<_> = edges.iter().map(|edge| edge.data).collect();
479        self.add_dependency_edges(&from, &to, &data)
480    }
481
482    /// Removes directed edges matching the supplied nodes and attributes.
483    ///
484    /// # Errors
485    ///
486    /// Returns an error if any node belongs to another graph or context binding fails.
487    /// Also propagates CUDA dependency-update errors.
488    pub fn remove_edges(&mut self, edges: &[GraphEdge]) -> Result<()> {
489        if edges.is_empty() {
490            return Ok(());
491        }
492
493        let from: Vec<_> = edges.iter().map(|edge| edge.from.clone()).collect();
494        let to: Vec<_> = edges.iter().map(|edge| edge.to.clone()).collect();
495        let data: Vec<_> = edges.iter().map(|edge| edge.data).collect();
496        self.remove_dependency_edges(&from, &to, &data)
497    }
498
499    /// Creates a node that performs no operation and adds it to the graph with the given dependencies.
500    /// The dependency list may be empty, in which case the node is placed at the graph root.
501    /// It may not contain duplicate entries.
502    ///
503    /// An empty node performs no operation during execution, but can be used for transitive ordering.
504    /// For example, a phased execution graph with 2 groups of n nodes with a barrier between them can be represented using an empty node and 2\*n dependency edges, rather than no empty node and n^2 dependency edges.
505    ///
506    /// Graph objects are not threadsafe.
507    ///
508    /// # Errors
509    ///
510    /// Returns an error if CUDA rejects the graph operation or reports runtime initialization diagnostics.
511    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
512    pub fn add_empty_node(&mut self, dependencies: &[GraphNode]) -> Result<GraphNode> {
513        self.check_nodes(dependencies)?;
514        let mut handle = ptr::null_mut();
515        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
516        // SAFETY: the graph and dependency handles are live, and the dependency array length matches.
517        unsafe {
518            try_ffi!(runtime::cudaGraphAddEmptyNode(
519                &raw mut handle,
520                self.as_raw(),
521                dependencies_raw.as_ptr(),
522                dependencies_raw.len() as _,
523            ))?;
524            Ok(self.node_from_raw(handle))
525        }
526    }
527
528    /// Creates an event record node and adds it to the graph with the given dependencies and event.
529    /// The dependency list may be empty, in which case the node is placed at the graph root.
530    /// It may not contain duplicate entries.
531    ///
532    /// Each graph launch records `event` to capture execution of the node's dependencies.
533    /// The graph and executables instantiated from it retain `event`.
534    ///
535    /// These nodes may not be used in loops or conditionals.
536    ///
537    /// Graph objects are not threadsafe.
538    ///
539    /// # Errors
540    ///
541    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
542    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
543    pub fn add_event_record_node(
544        &mut self,
545        dependencies: &[GraphNode],
546        event: &Arc<Event>,
547    ) -> Result<GraphNode> {
548        self.check_nodes(dependencies)?;
549        self.check_event_record_context(event)?;
550        // Retain first, so a node CUDA created never references an unretained event.
551        self.retained_lock()?.retain_event(event);
552        let mut handle = ptr::null_mut();
553        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
554        // SAFETY: the graph and dependency handles are live, and the dependency array length matches.
555        unsafe {
556            try_ffi!(runtime::cudaGraphAddEventRecordNode(
557                &raw mut handle,
558                self.as_raw(),
559                dependencies_raw.as_ptr(),
560                dependencies_raw.len() as _,
561                event.as_raw(),
562            ))?;
563            Ok(self.node_from_raw(handle))
564        }
565    }
566
567    /// Creates an event wait node and adds it to the graph with the given dependencies and event.
568    /// The dependency list may be empty, in which case the node is placed at the graph root.
569    /// It may not contain duplicate entries.
570    ///
571    /// The graph node waits for all work captured in `event`.
572    /// See [`Event::record`] for what an event captures.
573    /// Synchronization is performed efficiently on the device when applicable.
574    /// `event` may come from a different context or device than the launch stream.
575    /// The graph and executables instantiated from it retain `event`.
576    ///
577    /// These nodes may not be used in loops or conditionals.
578    ///
579    /// Graph objects are not threadsafe.
580    ///
581    /// # Errors
582    ///
583    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
584    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
585    pub fn add_event_wait_node(
586        &mut self,
587        dependencies: &[GraphNode],
588        event: &Arc<Event>,
589    ) -> Result<GraphNode> {
590        self.check_nodes(dependencies)?;
591        // Retain first, so a node CUDA created never references an unretained event.
592        self.retained_lock()?.retain_event(event);
593        let mut handle = ptr::null_mut();
594        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
595        // SAFETY: the graph and dependency handles are live, and the dependency array length matches.
596        unsafe {
597            try_ffi!(runtime::cudaGraphAddEventWaitNode(
598                &raw mut handle,
599                self.as_raw(),
600                dependencies_raw.as_ptr(),
601                dependencies_raw.len() as _,
602                event.as_raw(),
603            ))?;
604            Ok(self.node_from_raw(handle))
605        }
606    }
607
608    /// Creates a CPU execution node and adds it to the graph with the given dependencies and host-node parameters.
609    /// The dependency list may be empty, in which case the node is placed at the graph root.
610    /// It may not contain duplicate entries.
611    ///
612    /// When the graph is launched, the node invokes the specified CPU function.
613    /// Host nodes are not supported under MPS with pre-Volta GPUs.
614    ///
615    /// Graph objects are not threadsafe.
616    ///
617    /// # Safety
618    ///
619    /// CUDA stores the raw callback function and user-data pointer in the graph node for later replay.
620    /// The caller must ensure `params` remains valid according to [`HostNodeParams::new`] for every graph instantiation and launch that can execute this node.
621    ///
622    /// # Errors
623    ///
624    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
625    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
626    pub unsafe fn add_host_node(
627        &mut self,
628        dependencies: &[GraphNode],
629        params: &HostNodeParams,
630    ) -> Result<GraphNode> {
631        self.check_nodes(dependencies)?;
632        let mut handle = ptr::null_mut();
633        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
634        let params = params.into();
635        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the callback and user data valid for every launch.
636        unsafe {
637            try_ffi!(runtime::cudaGraphAddHostNode(
638                &raw mut handle,
639                self.as_raw(),
640                dependencies_raw.as_ptr(),
641                dependencies_raw.len() as _,
642                &raw const params,
643            ))?;
644            Ok(self.node_from_raw(handle))
645        }
646    }
647
648    /// Creates a kernel execution node and adds it to the graph with the given dependencies, launch configuration, and kernel parameters.
649    /// The dependency list may be empty, in which case the node is placed at the graph root.
650    /// It may not contain duplicate entries.
651    ///
652    /// When the graph is launched, the node invokes the kernel on the grid and blocks specified by [`LaunchConfig`].
653    /// [`LaunchConfig::shared_memory_bytes`](crate::module::LaunchConfig::shared_memory_bytes) sets the amount of dynamic shared memory available to each thread block.
654    /// Kernel parameters are passed with [`KernelParameters`](crate::module::KernelParameters) or tuples of shared or mutable references.
655    ///
656    /// Kernels launched using graphs must not use texture and surface references.
657    /// Reading or writing through any texture or surface reference is undefined behavior.
658    /// This restriction does not apply to texture and surface objects.
659    ///
660    /// A runtime kernel handle passed as a raw function must come from the same CUDA Runtime instance.
661    /// Passing a symbol that belongs to a different runtime instance results in undefined behavior.
662    ///
663    /// Graph objects are not threadsafe.
664    ///
665    /// # Safety
666    ///
667    /// Arguments must match `function`'s ABI and satisfy its value and access requirements.
668    /// The function must belong to the node's execution context.
669    /// Keep its code owner alive until every queued graph execution completes.
670    /// CUDA copies the kernel argument values during this call and stores those copied values in the graph node for later replay.
671    /// If an argument value is itself a pointer, only the pointer address is copied.
672    /// The caller must ensure every copied pointer value remains valid for every graph instantiation, update, and launch that can execute this node.
673    /// Mutable pointer arguments must also remain exclusive for the work ordered by those launches.
674    ///
675    /// # Errors
676    ///
677    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
678    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
679    pub unsafe fn add_kernel_node<'a, P>(
680        &mut self,
681        dependencies: &[GraphNode],
682        function: DeviceFunction,
683        config: &LaunchConfig,
684        params: P,
685    ) -> Result<GraphNode>
686    where
687        P: KernelLaunchArgs<'a>,
688    {
689        self.check_nodes(dependencies)?;
690        let mut handle = ptr::null_mut();
691        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
692        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; CUDA copies `arguments` during the call, and the caller guarantees they match `function` and point to storage valid for every launch.
693        params.with_encoded_arguments(|mut arguments| unsafe {
694            let params = runtime::cudaKernelNodeParams {
695                func: function.as_raw().cast(),
696                gridDim: config.grid_dim().into(),
697                blockDim: config.block_dim().into(),
698                sharedMemBytes: config.shared_memory_bytes_u32(),
699                kernelParams: arguments.as_mut_ptr().cast(),
700                extra: ptr::null_mut(),
701            };
702            try_ffi!(runtime::cudaGraphAddKernelNode(
703                &raw mut handle,
704                self.as_raw(),
705                dependencies_raw.as_ptr(),
706                dependencies_raw.len() as _,
707                &raw const params,
708            ))?;
709            let node = self.node_from_raw(handle);
710            for attribute in config.attributes() {
711                if let Err(error) = self.set_launch_attribute(&node, *attribute) {
712                    if let Err(destroy_error) = try_ffi!(driver::cuGraphDestroyNode(handle)) {
713                        report_cleanup_failure("destroy", "cuda graph node", &destroy_error);
714                    }
715
716                    return Err(error);
717                }
718            }
719            Ok(node)
720        })
721    }
722
723    /// Creates a new 1D memcpy node and adds it to the graph with the given dependencies.
724    /// The dependency list may be empty, in which case the node is placed at the root of the graph, and it may not contain duplicate entries.
725    ///
726    /// When the graph is launched, the node copies `count` bytes from `src` to `dst`.
727    /// The transfer direction is described by [`MemoryCopyKind`].
728    /// [`MemoryCopyKind::Default`] is recommended when unified virtual addressing is available, in which case the transfer direction is inferred from the pointer values.
729    /// Launching a memcpy node with `dst` and `src` pointers that do not match the direction of the copy results in undefined behavior.
730    ///
731    /// Memcpy nodes have additional restrictions for managed memory if any device in the system does not support concurrent managed access.
732    ///
733    /// Graph objects are not threadsafe.
734    ///
735    /// # Safety
736    ///
737    /// CUDA stores the raw source and destination addresses in the graph node for later replay.
738    /// The caller must ensure `params` remains valid according to [`MemoryCopy1DNodeParams::new`] for every graph instantiation and launch that can execute this node.
739    ///
740    /// # Errors
741    ///
742    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
743    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
744    pub unsafe fn add_memory_copy_node_1d(
745        &mut self,
746        dependencies: &[GraphNode],
747        params: &MemoryCopy1DNodeParams,
748    ) -> Result<GraphNode> {
749        self.check_nodes(dependencies)?;
750        let mut handle = ptr::null_mut();
751        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
752        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the copy's addresses valid for every launch.
753        unsafe {
754            try_ffi!(runtime::cudaGraphAddMemcpyNode1D(
755                &raw mut handle,
756                self.as_raw(),
757                dependencies_raw.as_ptr(),
758                dependencies_raw.len() as _,
759                params.dst().cast(),
760                params.src().cast(),
761                params.count() as _,
762                params.kind().into(),
763            ))?;
764            Ok(self.node_from_raw(handle))
765        }
766    }
767
768    /// Creates a device-to-device memcpy node between byte slices.
769    ///
770    /// The node copies `src.len()` bytes.
771    /// `dst` must have at least that many bytes.
772    ///
773    /// # Safety
774    ///
775    /// CUDA stores the raw source and destination addresses in the graph node for later replay.
776    /// The caller must ensure `dst` and `src` remain valid for every graph instantiation and launch that can execute this node.
777    /// `dst` must not be accessed through another mutable path while graph launches using this node can write it.
778    ///
779    /// # Errors
780    ///
781    /// Returns an error if `dst` is smaller than `src`, if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
782    pub unsafe fn add_memory_copy_node_1d_device_to_device<D, S>(
783        &mut self,
784        dependencies: &[GraphNode],
785        dst: &mut D,
786        src: &S,
787    ) -> Result<GraphNode>
788    where
789        D: DeviceSliceMut<u8> + ?Sized,
790        S: DeviceSlice<u8> + ?Sized,
791    {
792        let count = src.len();
793        if dst.len() < count {
794            return Err(Error::buffer_too_small("destination", count, dst.len()));
795        }
796
797        // SAFETY: `dst` holds at least `count` bytes (checked above) and `src` exactly `count`; the caller keeps both valid for every launch.
798        let params = unsafe {
799            MemoryCopy1DNodeParams::new(
800                dst.as_mut_ptr().cast(),
801                src.as_device_ptr().cast(),
802                count,
803                MemoryCopyKind::DeviceToDevice,
804            )
805        };
806        // SAFETY: the caller keeps `dst` and `src`, the addresses in `params`, valid and exclusive for every launch.
807        unsafe { self.add_memory_copy_node_1d(dependencies, &params) }
808    }
809
810    /// Creates a device-to-device memcpy node between graph-retained buffers.
811    ///
812    /// The node copies `src.byte_len()` bytes.
813    /// `dst` must have at least that many bytes.
814    /// The graph retains both allocations so the baked CUDA graph pointers remain live for future instantiation and replay.
815    ///
816    /// # Safety
817    ///
818    /// Keep source elements valid for every launch, and order their producers before replay.
819    /// Keep destination accesses exclusive through completion, including failed submissions.
820    /// Allocation retention preserves addresses; initialization and access ordering remain caller obligations.
821    ///
822    /// # Errors
823    ///
824    /// Returns an error if `dst` is smaller than `src`, if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
825    pub unsafe fn add_buffer_memory_copy_node_1d_device_to_device<T, D>(
826        &mut self,
827        dependencies: &[GraphNode],
828        dst: &mut GraphBuffer<D>,
829        src: &GraphBuffer<T>,
830    ) -> Result<GraphNode>
831    where
832        T: DeviceRepr,
833        D: DeviceRepr,
834        GraphBuffer<D>: DeviceOutput<T>,
835    {
836        self.check_buffer_contexts(dst, src)?;
837        let count = src.byte_len();
838        if dst.byte_len() < count {
839            return Err(Error::buffer_too_small(
840                "destination",
841                count,
842                dst.byte_len(),
843            ));
844        }
845
846        // SAFETY: `dst` holds at least `count` bytes (checked above) and `src` exactly `count`, and both allocations are retained by this graph below.
847        let params = unsafe {
848            MemoryCopy1DNodeParams::new(
849                dst.as_mut_ptr().cast(),
850                src.as_ptr().cast(),
851                count,
852                MemoryCopyKind::DeviceToDevice,
853            )
854        };
855        // SAFETY: the graph retains both allocations below, so the addresses stay valid; the caller orders producers and keeps destination access exclusive.
856        let node = unsafe { self.add_memory_copy_node_1d(dependencies, &params)? };
857        self.retain_buffer(dst)?;
858        self.retain_buffer(src)?;
859        Ok(node)
860    }
861
862    /// Creates a memcpy node and adds it to the graph with the given dependencies.
863    /// The dependency list may be empty, in which case the node is placed at the graph root.
864    /// It may not contain duplicate entries.
865    ///
866    /// When the graph is launched, the node performs the memcpy described by `params`.
867    /// [`MemoryCopy3DNodeParams`] describes the copy and its restrictions.
868    ///
869    /// Memcpy nodes have additional restrictions for managed memory if any device in the system does not support concurrent managed access.
870    ///
871    /// Graph objects are not threadsafe.
872    ///
873    /// # Safety
874    ///
875    /// CUDA stores the raw source and destination addresses in the graph node for later replay.
876    /// The caller must ensure `params` remains valid according to [`MemoryCopy3DNodeParams`] for every graph instantiation and launch that can execute this node.
877    ///
878    /// # Errors
879    ///
880    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
881    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
882    pub unsafe fn add_memory_copy_node(
883        &mut self,
884        dependencies: &[GraphNode],
885        params: &MemoryCopy3DNodeParams,
886    ) -> Result<GraphNode> {
887        self.check_nodes(dependencies)?;
888        let mut handle = ptr::null_mut();
889        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
890        let params = params.into();
891        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the 3D copy's addresses valid for every launch.
892        unsafe {
893            try_ffi!(runtime::cudaGraphAddMemcpyNode(
894                &raw mut handle,
895                self.as_raw(),
896                dependencies_raw.as_ptr(),
897                dependencies_raw.len() as _,
898                &raw const params,
899            ))?;
900            Ok(self.node_from_raw(handle))
901        }
902    }
903
904    /// Adds a node that copies host or device memory into a module symbol, as described by `params`.
905    ///
906    /// # Safety
907    ///
908    /// CUDA stores the raw symbol and source pointer in the graph node for later replay.
909    /// The caller must ensure `params` remains valid according to [`MemoryCopyToSymbolNodeParams::new`] for every graph instantiation and launch that can execute this node.
910    ///
911    /// # Errors
912    ///
913    /// Returns an error if a dependency belongs to another graph, context binding fails, or CUDA rejects the symbol, pointers, copy range, or node dependencies.
914    pub unsafe fn add_memory_copy_node_to_symbol(
915        &mut self,
916        dependencies: &[GraphNode],
917        params: &MemoryCopyToSymbolNodeParams,
918    ) -> Result<GraphNode> {
919        self.check_nodes(dependencies)?;
920        let mut handle = ptr::null_mut();
921        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
922        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the symbol and source pointer valid for every launch.
923        unsafe {
924            try_ffi!(runtime::cudaGraphAddMemcpyNodeToSymbol(
925                &raw mut handle,
926                self.as_raw(),
927                dependencies_raw.as_ptr(),
928                dependencies_raw.len() as _,
929                params.symbol().cast(),
930                params.src().cast(),
931                params.count() as _,
932                params.offset() as _,
933                params.kind().into(),
934            ))?;
935            Ok(self.node_from_raw(handle))
936        }
937    }
938
939    /// Adds a node that copies a module symbol into host or device memory, as described by `params`.
940    ///
941    /// # Safety
942    ///
943    /// CUDA stores the raw destination and symbol pointer in the graph node for later replay.
944    /// The caller must ensure `params` remains valid according to [`MemoryCopyFromSymbolNodeParams::new`] for every graph instantiation and launch that can execute this node.
945    ///
946    /// # Errors
947    ///
948    /// Returns an error if a dependency belongs to another graph, context binding fails, or CUDA rejects the symbol, pointers, copy range, or node dependencies.
949    pub unsafe fn add_memory_copy_node_from_symbol(
950        &mut self,
951        dependencies: &[GraphNode],
952        params: &MemoryCopyFromSymbolNodeParams,
953    ) -> Result<GraphNode> {
954        self.check_nodes(dependencies)?;
955        let mut handle = ptr::null_mut();
956        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
957        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the symbol and destination pointer valid for every launch.
958        unsafe {
959            try_ffi!(runtime::cudaGraphAddMemcpyNodeFromSymbol(
960                &raw mut handle,
961                self.as_raw(),
962                dependencies_raw.as_ptr(),
963                dependencies_raw.len() as _,
964                params.dst().cast(),
965                params.symbol().cast(),
966                params.count() as _,
967                params.offset() as _,
968                params.kind().into(),
969            ))?;
970            Ok(self.node_from_raw(handle))
971        }
972    }
973
974    /// Creates a new memset node and adds it to the graph with the given dependencies.
975    /// The dependency list may be empty, in which case the node is placed at the root of the graph, and it may not contain duplicate entries.
976    ///
977    /// The element size must be 1, 2, or 4 bytes.
978    /// When the graph is launched, the node performs the memset described by `params`.
979    ///
980    /// Graph objects are not threadsafe.
981    ///
982    /// # Safety
983    ///
984    /// CUDA stores the destination address in the graph node for later replay.
985    /// The caller must ensure `params` remains valid according to [`MemorySetNodeParams::new`] for every graph instantiation and launch that can execute this node.
986    ///
987    /// # Errors
988    ///
989    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
990    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
991    pub unsafe fn add_memory_set_node(
992        &mut self,
993        dependencies: &[GraphNode],
994        params: &MemorySetNodeParams,
995    ) -> Result<GraphNode> {
996        self.check_nodes(dependencies)?;
997        let mut handle = ptr::null_mut();
998        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
999        let params = params.into();
1000        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller keeps the destination valid for every launch.
1001        unsafe {
1002            try_ffi!(runtime::cudaGraphAddMemsetNode(
1003                &raw mut handle,
1004                self.as_raw(),
1005                dependencies_raw.as_ptr(),
1006                dependencies_raw.len() as _,
1007                &raw const params,
1008            ))?;
1009            Ok(self.node_from_raw(handle))
1010        }
1011    }
1012
1013    /// Creates a new node which executes an embedded graph, and adds it to the graph with the given dependencies.
1014    /// The dependency list may be empty, in which case the node is placed at the root of the graph, and it may not contain duplicate entries.
1015    ///
1016    /// If `child_graph` contains allocation nodes, free nodes, or conditional nodes, this call returns an error.
1017    ///
1018    /// The node executes an embedded child graph.
1019    /// The child graph is cloned in this call.
1020    ///
1021    /// Graph objects are not threadsafe.
1022    ///
1023    /// # Errors
1024    ///
1025    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
1026    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
1027    pub fn add_child_graph_node(
1028        &mut self,
1029        dependencies: &[GraphNode],
1030        child_graph: &Self,
1031    ) -> Result<GraphNode> {
1032        self.check_nodes(dependencies)?;
1033        self.check_child_graph_context(child_graph)?;
1034        let mut handle = ptr::null_mut();
1035        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
1036        // SAFETY: the graph and dependency handles are live, and the dependency array length matches.
1037        unsafe {
1038            try_ffi!(runtime::cudaGraphAddChildGraphNode(
1039                &raw mut handle,
1040                self.as_raw(),
1041                dependencies_raw.as_ptr(),
1042                dependencies_raw.len() as _,
1043                child_graph.as_raw(),
1044            ))?;
1045            self.retained_lock()?
1046                .extend(child_graph.retained_resources()?);
1047            Ok(self.node_from_raw(handle))
1048        }
1049    }
1050
1051    /// Creates a new memory free node for a graph allocation and adds it to the graph.
1052    /// The dependency list may be empty, in which case the node is placed at the root of the graph, and it may not contain duplicate entries.
1053    ///
1054    /// [`Graph::add_memory_free_node`] returns [`crate::error::Status::InvalidValue`] if the caller attempts to free:
1055    ///
1056    /// * an allocation twice in the same graph.
1057    /// * an address that was not returned by an allocation node.
1058    /// * an invalid address.
1059    ///
1060    /// The following restrictions apply to graphs which contain allocation and/or memory free nodes:
1061    ///
1062    /// * Nodes and edges of the graph cannot be deleted.
1063    /// * The graph can only be used in a child node if the ownership is moved to the parent.
1064    /// * Only one instantiation of the graph may exist at any point in time.
1065    /// * The graph cannot be cloned.
1066    ///
1067    /// Graph objects are not threadsafe.
1068    ///
1069    /// # Errors
1070    ///
1071    /// Returns [`Error::GraphNodeMismatch`] if `allocation` did not come from this graph.
1072    /// Returns an error if CUDA rejects the graph operation or if a previous asynchronous launch reported an error.
1073    pub fn add_memory_free_node(
1074        &mut self,
1075        dependencies: &[GraphNode],
1076        allocation: &MemoryAllocationNodeInfo,
1077    ) -> Result<GraphNode> {
1078        if allocation.graph_id != Some(self.id) {
1079            return Err(Error::GraphNodeMismatch);
1080        }
1081        // SAFETY: the graph id check above proves `allocation` came from an allocation node of this graph, and CUDA rejects a second free of it in the same graph.
1082        unsafe { self.add_memory_free_node_raw(dependencies, allocation.ptr) }
1083    }
1084
1085    /// Creates a new memory free node from a raw device address.
1086    ///
1087    /// # Safety
1088    ///
1089    /// CUDA stores the raw address in the graph.
1090    /// The caller must ensure `ptr` is a graph allocation that may be freed by this graph, is ordered after the allocation node, and is not freed more than once or by another graph in a way that violates CUDA graph allocation ownership rules.
1091    ///
1092    /// # Errors
1093    ///
1094    /// Returns an error if a dependency belongs to another graph, context binding fails, or CUDA rejects the free node or its allocation pointer.
1095    pub unsafe fn add_memory_free_node_raw(
1096        &mut self,
1097        dependencies: &[GraphNode],
1098        ptr: DevicePtr,
1099    ) -> Result<GraphNode> {
1100        self.check_nodes(dependencies)?;
1101        let mut handle = ptr::null_mut();
1102        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
1103        // SAFETY: `handle` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, and the dependency array is passed with its length; the caller guarantees `ptr` is this graph's allocation, ordered after its allocation node and freed once.
1104        unsafe {
1105            try_ffi!(runtime::cudaGraphAddMemFreeNode(
1106                &raw mut handle,
1107                self.as_raw(),
1108                dependencies_raw.as_ptr(),
1109                dependencies_raw.len() as _,
1110                ptr.as_ptr().cast(),
1111            ))?;
1112            Ok(self.node_from_raw(handle))
1113        }
1114    }
1115
1116    /// Creates a new allocation node and adds it to the graph with the given dependencies and allocation parameters.
1117    /// The dependency list may be empty, in which case the node is placed at the root of the graph, and it may not contain duplicate entries.
1118    ///
1119    /// When [`Graph::add_memory_allocation_node`] creates an allocation node, it returns the allocation metadata in [`MemoryAllocationNodeInfo`].
1120    /// The allocation's address remains fixed across instantiations and launches.
1121    ///
1122    /// If the allocation is freed in the same graph, by creating a free node using [`Graph::add_memory_free_node`], the allocation can be accessed by nodes ordered after the allocation node but before the free node.
1123    /// These allocations cannot be freed outside the owning graph, and they can only be freed once in the owning graph.
1124    ///
1125    /// If the allocation is not freed in the same graph, then it can be accessed not only by nodes in the graph which are ordered after the allocation node, but also by stream operations ordered after the graph's execution but before the allocation is freed.
1126    ///
1127    /// Allocations which are not freed in the same graph can be freed by:
1128    ///
1129    /// * passing the allocation to [`DeviceMemory::free_async`](crate::memory::DeviceMemory::free_async) or [`DeviceMemory::free`](crate::memory::DeviceMemory::free);
1130    /// * launching a graph with a free node for that allocation; or
1131    /// * specifying [`GraphInstantiateFlags::AUTO_FREE_ON_LAUNCH`] during instantiation, which makes each launch behave as though it called [`DeviceMemory::free_async`](crate::memory::DeviceMemory::free_async) for every unfreed allocation.
1132    ///
1133    /// It is not possible to free an allocation in both the owning graph and another graph.
1134    /// If the allocation is freed in the same graph, a free node cannot be added to another graph.
1135    /// If the allocation is freed in another graph, a free node can no longer be added to the owning graph.
1136    ///
1137    /// The following restrictions apply to graphs which contain allocation and/or memory free nodes:
1138    ///
1139    /// * Nodes and edges of the graph cannot be deleted.
1140    /// * The graph can only be used in a child node if the ownership is moved to the parent.
1141    /// * Only one instantiation of the graph may exist at any point in time.
1142    /// * The graph cannot be cloned.
1143    ///
1144    /// Graph objects are not threadsafe.
1145    ///
1146    /// # Errors
1147    ///
1148    /// Returns an error if CUDA rejects the graph operation or if a previous asynchronous launch reported an error.
1149    pub fn add_memory_allocation_node(
1150        &mut self,
1151        dependencies: &[GraphNode],
1152        params: &MemoryAllocationNodeParams<'_>,
1153    ) -> Result<(GraphNode, MemoryAllocationNodeInfo)> {
1154        self.check_nodes(dependencies)?;
1155        let mut handle = ptr::null_mut();
1156        let dependencies_raw: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
1157        let access_descs: Vec<_> = params
1158            .access_descs
1159            .iter()
1160            .copied()
1161            .map(Into::into)
1162            .collect();
1163        let mut params_raw = runtime::cudaMemAllocNodeParams {
1164            poolProps: params.pool_props.into(),
1165            accessDescs: access_descs.as_ptr(),
1166            accessDescCount: access_descs.len() as _,
1167            bytesize: params.byte_size as _,
1168            dptr: 0,
1169        };
1170        // SAFETY: the graph and dependency handles are live, and the dependency array length matches.
1171        unsafe {
1172            try_ffi!(runtime::cudaGraphAddMemAllocNode(
1173                &raw mut handle,
1174                self.as_raw(),
1175                dependencies_raw.as_ptr(),
1176                dependencies_raw.len() as _,
1177                &raw mut params_raw,
1178            ))?;
1179            if params_raw.dptr == 0 {
1180                return Err(Error::NullHandle);
1181            }
1182
1183            let node = self.node_from_raw(handle);
1184            let allocation = MemoryAllocationNodeInfo::from_raw_in_graph(
1185                DevicePtr::new(ptr::without_provenance_mut(to_usize(
1186                    params_raw.dptr,
1187                    "memory allocation address",
1188                )?)),
1189                params.byte_size,
1190                self.id,
1191                Arc::clone(&self.inner),
1192                Some(Arc::clone(&self.context)),
1193            );
1194            Ok((node, allocation))
1195        }
1196    }
1197
1198    /// Returns this graph's nodes.
1199    ///
1200    /// Graph objects are not threadsafe.
1201    ///
1202    /// # Errors
1203    ///
1204    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
1205    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
1206    pub fn nodes(&self) -> Result<Vec<GraphNode>> {
1207        // SAFETY: `cudaGraphGetNodes` first reports the count, then fills arrays sized to it.
1208        unsafe {
1209            let mut count = 0;
1210            try_ffi!(runtime::cudaGraphGetNodes(
1211                self.as_raw(),
1212                ptr::null_mut(),
1213                &raw mut count,
1214            ))?;
1215
1216            if count == 0 {
1217                return Ok(Vec::new());
1218            }
1219
1220            let mut handles = Vec::with_capacity(to_usize(count, "graph node count")?);
1221            try_ffi!(runtime::cudaGraphGetNodes(
1222                self.as_raw(),
1223                handles.as_mut_ptr(),
1224                &raw mut count,
1225            ))?;
1226            handles.set_len(to_usize(count, "graph node count")?);
1227
1228            Ok(handles
1229                .into_iter()
1230                .map(|handle| self.node_from_raw(handle))
1231                .collect())
1232        }
1233    }
1234
1235    /// Returns this graph's root nodes.
1236    ///
1237    /// Graph objects are not threadsafe.
1238    ///
1239    /// # Errors
1240    ///
1241    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
1242    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
1243    pub fn root_nodes(&self) -> Result<Vec<GraphNode>> {
1244        // SAFETY: `cudaGraphGetRootNodes` first reports the count, then fills arrays sized to it.
1245        unsafe {
1246            let mut count = 0;
1247            try_ffi!(runtime::cudaGraphGetRootNodes(
1248                self.as_raw(),
1249                ptr::null_mut(),
1250                &raw mut count,
1251            ))?;
1252
1253            if count == 0 {
1254                return Ok(Vec::new());
1255            }
1256
1257            let mut handles = Vec::with_capacity(to_usize(count, "graph node count")?);
1258            try_ffi!(runtime::cudaGraphGetRootNodes(
1259                self.as_raw(),
1260                handles.as_mut_ptr(),
1261                &raw mut count,
1262            ))?;
1263            handles.set_len(to_usize(count, "graph node count")?);
1264
1265            Ok(handles
1266                .into_iter()
1267                .map(|handle| self.node_from_raw(handle))
1268                .collect())
1269        }
1270    }
1271
1272    /// Returns this graph's dependency edges.
1273    ///
1274    /// Graph objects are not threadsafe.
1275    ///
1276    /// # Errors
1277    ///
1278    /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
1279    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
1280    pub fn edges(&self) -> Result<Vec<GraphEdge>> {
1281        // SAFETY: `cudaGraphGetEdges` first reports the count, then fills arrays sized to it.
1282        unsafe {
1283            let mut count = 0;
1284            try_ffi!(runtime::cudaGraphGetEdges(
1285                self.as_raw(),
1286                ptr::null_mut(),
1287                ptr::null_mut(),
1288                ptr::null_mut(),
1289                &raw mut count,
1290            ))?;
1291
1292            if count == 0 {
1293                return Ok(Vec::new());
1294            }
1295
1296            let len = to_usize(count, "graph node count")?;
1297            let mut from = Vec::with_capacity(len);
1298            let mut to = Vec::with_capacity(len);
1299            let mut edge_data = Vec::with_capacity(len);
1300            try_ffi!(runtime::cudaGraphGetEdges(
1301                self.as_raw(),
1302                from.as_mut_ptr(),
1303                to.as_mut_ptr(),
1304                edge_data.as_mut_ptr(),
1305                &raw mut count,
1306            ))?;
1307            let len = to_usize(count, "graph node count")?;
1308            from.set_len(len);
1309            to.set_len(len);
1310            edge_data.set_len(len);
1311
1312            Ok(from
1313                .into_iter()
1314                .zip(to)
1315                .zip(edge_data)
1316                .map(|((from, to), data)| GraphEdge {
1317                    from: self.node_from_raw(from),
1318                    to: self.node_from_raw(to),
1319                    data: data.into(),
1320                })
1321                .collect())
1322        }
1323    }
1324
1325    /// Returns a compact summary of this graph's native CUDA topology.
1326    ///
1327    /// The summary is computed from CUDA graph introspection APIs and counts node kinds, root nodes, and dependency edges in this graph.
1328    /// Child graph nodes are counted as child nodes here; callers that need recursive details can query the child graph returned by [`Graph::child_graph`].
1329    ///
1330    /// Graph objects are not threadsafe.
1331    ///
1332    /// # Errors
1333    ///
1334    /// Returns an error if CUDA rejects a topology query, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
1335    pub fn topology_summary(&self) -> Result<GraphTopologySummary> {
1336        let nodes = self.nodes()?;
1337        let mut summary = GraphTopologySummary {
1338            nodes: nodes.len(),
1339            root_nodes: self.root_nodes()?.len(),
1340            edges: self.edges()?.len(),
1341            ..GraphTopologySummary::default()
1342        };
1343        for node in nodes {
1344            summary.record_node_type(self.node_type(&node)?);
1345        }
1346        Ok(summary)
1347    }
1348
1349    /// Writes a DOT-formatted description of the graph to `path`.
1350    /// By default this includes the graph topology, node types, node ID, kernel names, and memcpy direction.
1351    /// `flags` can request more detailed information about each node type, such as parameter values, kernel attributes, node handles, and function handles.
1352    ///
1353    /// # Errors
1354    ///
1355    /// Returns an error if `path` contains an interior NUL byte or if CUDA Runtime cannot write the DOT file.
1356    pub fn write_dot(&self, path: &str, flags: GraphDebugDotFlags) -> Result<()> {
1357        let path = CString::new(path)?;
1358        // SAFETY: `self.inner` owns the live graph, and `path` is a NUL-terminated local that outlives the call.
1359        unsafe {
1360            try_ffi!(runtime::cudaGraphDebugDotPrint(
1361                self.as_raw(),
1362                path.as_ptr(),
1363                flags.bits(),
1364            ))?;
1365        }
1366        Ok(())
1367    }
1368
1369    /// Returns the native graph handle without transferring ownership.
1370    #[must_use]
1371    pub fn as_raw(&self) -> runtime::cudaGraph_t {
1372        self.inner.handle
1373    }
1374
1375    /// Returns the context this graph belongs to.
1376    #[must_use]
1377    pub fn context(&self) -> &Arc<Context> {
1378        &self.context
1379    }
1380
1381    /// Transfers the native graph, context, and retained resources without destruction.
1382    ///
1383    /// Returns the unchanged graph if a node or executable still shares its native owner.
1384    /// Keep the returned parts alive through completed native work and handle destruction, or re-adopt them.
1385    ///
1386    /// # Errors
1387    ///
1388    /// Returns the original graph if a node, executable, child view, or another owner still retains its native graph storage.
1389    pub fn into_raw(self) -> StdResult<RawGraph, Self> {
1390        let Self {
1391            inner,
1392            id,
1393            context,
1394            _not_sync: _,
1395        } = self;
1396        match Arc::try_unwrap(inner) {
1397            Ok(mut inner) => {
1398                inner.owns_handle = false;
1399                Ok(RawGraph {
1400                    handle: inner.handle,
1401                    context,
1402                    // The caller takes over keeping these alive through native work, whatever a panic left here.
1403                    retained: take(
1404                        inner
1405                            .retained
1406                            .get_mut()
1407                            .unwrap_or_else(PoisonError::into_inner),
1408                    ),
1409                    id,
1410                })
1411            }
1412            Err(inner) => Err(Self {
1413                inner,
1414                id,
1415                context,
1416                _not_sync: PhantomData,
1417            }),
1418        }
1419    }
1420
1421    /// Adopts a native graph together with its original context and resource owners.
1422    ///
1423    /// # Safety
1424    ///
1425    /// The native handle must still be live and unchanged, with no other destroying owner or unretained dependencies.
1426    ///
1427    /// # Errors
1428    ///
1429    /// Returns an error if the native handle is null.
1430    pub unsafe fn from_raw(raw: RawGraph) -> Result<Self> {
1431        if raw.handle.is_null() {
1432            return Err(Error::NullHandle);
1433        }
1434        Ok(Self {
1435            inner: Arc::new(GraphInner {
1436                handle: raw.handle,
1437                owns_handle: true,
1438                context: Some(Arc::clone(&raw.context)),
1439                retained: Mutex::new(raw.retained),
1440                parent: None,
1441            }),
1442            id: raw.id,
1443            context: raw.context,
1444            _not_sync: PhantomData,
1445        })
1446    }
1447}