Skip to main content

singe_cuda/graph/
mod.rs

1//! CUDA graph construction, instantiation, update, and execution.
2
3pub mod contextual;
4mod host_data;
5pub mod memory;
6pub mod owned;
7pub mod raw;
8
9mod retained_resource;
10
11mod buffer;
12mod definition;
13mod executable;
14mod node;
15
16use std::{
17    any::Any,
18    cell::Cell,
19    collections::HashMap,
20    fmt::{self, Display, Formatter},
21    hash::{Hash, Hasher},
22    marker::PhantomData,
23    mem::MaybeUninit,
24    ops::Deref,
25    ptr,
26    result::Result as StdResult,
27    sync::{
28        Arc, Mutex,
29        atomic::{AtomicU64, Ordering},
30    },
31};
32
33use bitflags::parser;
34use num_enum::{IntoPrimitive, TryFromPrimitive};
35use singe_core::{impl_enum_display, report_cleanup_failure};
36use singe_cuda_sys::{driver, runtime};
37
38pub use self::{
39    host_data::GraphHostBuffer,
40    retained_resource::{
41        GraphRetainedResource, collect_graph_resources, has_deferred_graph_resources,
42    },
43};
44use crate::{
45    context::Context,
46    dim::Dim3,
47    error::{Error, Result},
48    event::Event,
49    memory::{DeviceMemory, MemoryAccessDescriptor, MemoryPoolProps},
50    module::{CodeOwnerId, Module},
51    try_ffi,
52    types::DevicePtr,
53    view::{
54        DeviceOutput, DeviceRange, DeviceRegion, DeviceRegionProvider, DeviceRepr, DeviceSlice,
55        DeviceSliceMut,
56    },
57};
58
59singe_core::native_enum! {
60    /// Identifiers for [`GraphKernelNodeAttribute`] values used by CUDA graph kernel nodes.
61    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
62    #[repr(u32)]
63    #[non_exhaustive]
64    pub enum GraphKernelNodeAttributeId: runtime::cudaLaunchAttributeID {
65        /// Identifies [`GraphKernelNodeAttribute::Cooperative`].
66        Cooperative = cudaLaunchAttributeCooperative,
67        /// Identifies [`GraphKernelNodeAttribute::ClusterDimension`].
68        ClusterDimension = cudaLaunchAttributeClusterDimension,
69        /// Identifies [`GraphKernelNodeAttribute::Priority`].
70        Priority = cudaLaunchAttributePriority,
71        /// Identifies [`GraphKernelNodeAttribute::PreferredSharedMemoryCarveout`].
72        /// The value is a percentage in the range `0..=100` describing the preferred shared-memory carveout for the launch.
73        /// This is a hint, and the driver may choose a different configuration if required.
74        PreferredSharedMemoryCarveout = cudaLaunchAttributePreferredSharedMemoryCarveout,
75    }
76}
77
78/// Typed launch attributes stored on a CUDA graph kernel node.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80#[non_exhaustive]
81pub enum GraphKernelNodeAttribute {
82    /// Enables or disables a cooperative kernel launch.
83    Cooperative(
84        /// Whether the kernel uses cooperative launch semantics.
85        bool,
86    ),
87    /// Sets the thread-block cluster dimensions.
88    ClusterDimension(
89        /// Cluster dimensions in thread blocks.
90        Dim3,
91    ),
92    /// Sets the scheduling priority hint for this kernel node.
93    Priority(
94        /// Requested node priority.
95        i32,
96    ),
97    /// Sets the preferred percentage of shared memory in the shared-memory/L1 partition.
98    PreferredSharedMemoryCarveout(
99        /// Preferred shared-memory percentage.
100        u32,
101    ),
102}
103
104/// Address and size returned for a graph memory-allocation node.
105///
106/// The metadata may retain the graph and its context.
107/// Access to the allocation must follow the ordering of its allocation and free nodes.
108#[derive(Debug, Clone)]
109pub struct MemoryAllocationNodeInfo {
110    ptr: DevicePtr,
111    /// Allocation size in bytes.
112    pub byte_size: usize,
113    graph_id: Option<GraphId>,
114    _graph: Option<Arc<GraphInner>>,
115    context: Option<Arc<Context>>,
116}
117
118bitflags::bitflags! {
119    /// Flags for instantiating a graph
120    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121    pub struct GraphInstantiateFlags: u64 {
122        /// Automatically free memory allocated in a graph before relaunching.
123        const AUTO_FREE_ON_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH.0 as u64;
124        /// Automatically upload the graph after instantiation.
125        ///
126        /// Only supported when instantiating with parameters, which name the stream the upload uses.
127        const UPLOAD = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD.0 as u64;
128        /// Instantiate the graph to be launchable from the device.
129        ///
130        /// This flag can only be used on platforms which support unified addressing.
131        /// This flag cannot be used in conjunction with `CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH`.
132        const DEVICE_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH.0 as u64;
133        /// Run the graph using the per-node priority attributes rather than the priority of the stream it is launched into.
134        const USE_NODE_PRIORITY = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY.0 as u64;
135    }
136}
137
138impl Display for GraphInstantiateFlags {
139    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
140        parser::to_writer(self, f)
141    }
142}
143
144bitflags::bitflags! {
145    /// Options that select what [`Graph::write_dot`] includes in its DOT output.
146    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147    pub struct GraphDebugDotFlags: u32 {
148        /// Output all debug data as if every debug flag is enabled.
149        const VERBOSE = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE.0;
150        /// Use CUDA Runtime structures for output.
151        const RUNTIME_TYPES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES.0;
152        /// Adds CUDA_KERNEL_NODE_PARAMS values to output.
153        const KERNEL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS.0;
154        /// Adds CUDA_MEMCPY3D values to output.
155        const MEMCPY_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS.0;
156        /// Adds CUDA_MEMSET_NODE_PARAMS values to output.
157        const MEMSET_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS.0;
158        /// Adds CUDA_HOST_NODE_PARAMS values to output.
159        const HOST_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS.0;
160        /// Adds CUevent handle from record and wait nodes to output.
161        const EVENT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EVENT_NODE_PARAMS.0;
162        /// Adds CUDA_EXT_SEM_SIGNAL_NODE_PARAMS values to output.
163        const EXTERNAL_SEMAPHORE_SIGNAL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_SIGNAL_NODE_PARAMS.0;
164        /// Adds CUDA_EXT_SEM_WAIT_NODE_PARAMS values to output.
165        const EXTERNAL_SEMAPHORE_WAIT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_WAIT_NODE_PARAMS.0;
166        /// Adds CUkernelNodeAttrValue values to output.
167        const KERNEL_NODE_ATTRIBUTES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES.0;
168        /// Adds node handles and every kernel function handle to output.
169        const HANDLES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES.0;
170        /// Adds memory alloc node parameters to output.
171        const MEMORY_ALLOC_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS.0;
172        /// Adds memory free node parameters to output.
173        const MEMORY_FREE_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS.0;
174        /// Adds batch mem op node parameters to output.
175        const BATCH_MEM_OP_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_BATCH_MEM_OP_NODE_PARAMS.0;
176        /// Adds edge numbering information.
177        const EXTRA_TOPOLOGY_INFO = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXTRA_TOPO_INFO.0;
178        /// Adds conditional node parameters to output.
179        const CONDITIONAL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_CONDITIONAL_NODE_PARAMS.0;
180    }
181}
182
183impl Display for GraphDebugDotFlags {
184    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
185        parser::to_writer(self, f)
186    }
187}
188
189/// Graph node types
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
191#[repr(u32)]
192#[non_exhaustive]
193pub enum GraphNodeType {
194    /// GPU kernel node.
195    Kernel = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_KERNEL.0,
196    /// Memcpy node.
197    Memcpy = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMCPY.0,
198    /// Memset node.
199    Memset = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMSET.0,
200    /// Host (executable) node.
201    Host = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_HOST.0,
202    /// Node which executes an embedded graph.
203    Graph = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_GRAPH.0,
204    /// Empty (no-op) node.
205    Empty = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EMPTY.0,
206    /// External event wait node.
207    WaitEvent = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_WAIT_EVENT.0,
208    /// External event record node.
209    EventRecord = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EVENT_RECORD.0,
210    /// External semaphore signal node.
211    ExternalSemaphoresSignal = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL.0,
212    /// External semaphore wait node.
213    ExternalSemaphoresWait = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT.0,
214    /// Memory Allocation Node.
215    MemoryAlloc = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_ALLOC.0,
216    /// Memory Free Node.
217    MemoryFree = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_FREE.0,
218    /// Batch memory-operation node; see [`Stream::memory_operations`](crate::stream::Stream::memory_operations) for what these nodes can do.
219    BatchMemOp = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_BATCH_MEM_OP.0,
220    /// Conditional Node.
221    Conditional = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_CONDITIONAL.0,
222}
223
224impl TryFrom<runtime::cudaGraphNodeType> for GraphNodeType {
225    type Error = Error;
226
227    fn try_from(value: runtime::cudaGraphNodeType) -> Result<Self> {
228        Self::try_from(value.0)
229            .map_err(|_| singe_core::UnknownEnumValue::new("GraphNodeType", value.0).into())
230    }
231}
232
233impl From<GraphNodeType> for runtime::cudaGraphNodeType {
234    fn from(value: GraphNodeType) -> Self {
235        match value {
236            GraphNodeType::Kernel => Self::CU_GRAPH_NODE_TYPE_KERNEL,
237            GraphNodeType::Memcpy => Self::CU_GRAPH_NODE_TYPE_MEMCPY,
238            GraphNodeType::Memset => Self::CU_GRAPH_NODE_TYPE_MEMSET,
239            GraphNodeType::Host => Self::CU_GRAPH_NODE_TYPE_HOST,
240            GraphNodeType::Graph => Self::CU_GRAPH_NODE_TYPE_GRAPH,
241            GraphNodeType::Empty => Self::CU_GRAPH_NODE_TYPE_EMPTY,
242            GraphNodeType::WaitEvent => Self::CU_GRAPH_NODE_TYPE_WAIT_EVENT,
243            GraphNodeType::EventRecord => Self::CU_GRAPH_NODE_TYPE_EVENT_RECORD,
244            GraphNodeType::ExternalSemaphoresSignal => Self::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL,
245            GraphNodeType::ExternalSemaphoresWait => Self::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT,
246            GraphNodeType::MemoryAlloc => Self::CU_GRAPH_NODE_TYPE_MEM_ALLOC,
247            GraphNodeType::MemoryFree => Self::CU_GRAPH_NODE_TYPE_MEM_FREE,
248            GraphNodeType::BatchMemOp => Self::CU_GRAPH_NODE_TYPE_BATCH_MEM_OP,
249            GraphNodeType::Conditional => Self::CU_GRAPH_NODE_TYPE_CONDITIONAL,
250        }
251    }
252}
253
254singe_core::native_enum! {
255    /// Dependency types applied to CUDA graph edges.
256    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
257    #[repr(u8)]
258    #[non_exhaustive]
259    pub enum GraphDependencyType: driver::CUgraphDependencyType {
260        /// This is an ordinary dependency.
261        Default = CU_GRAPH_DEPENDENCY_TYPE_DEFAULT,
262        /// This dependency type allows the downstream kernel to synchronize on the upstream grid from device code.
263        ///
264        /// It may only be used between kernel nodes, with the programmatic or launch-order outgoing port.
265        Programmatic = CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC,
266    }
267}
268
269impl_enum_display!(GraphNodeType, {
270    Self::Kernel => "cudaGraphNodeTypeKernel",
271    Self::Memcpy => "cudaGraphNodeTypeMemcpy",
272    Self::Memset => "cudaGraphNodeTypeMemset",
273    Self::Host => "cudaGraphNodeTypeHost",
274    Self::Graph => "cudaGraphNodeTypeGraph",
275    Self::Empty => "cudaGraphNodeTypeEmpty",
276    Self::WaitEvent => "cudaGraphNodeTypeWaitEvent",
277    Self::EventRecord => "cudaGraphNodeTypeEventRecord",
278    Self::ExternalSemaphoresSignal => "cudaGraphNodeTypeExternalSemaphoresSignal",
279    Self::ExternalSemaphoresWait => "cudaGraphNodeTypeExternalSemaphoresWait",
280    Self::MemoryAlloc => "cudaGraphNodeTypeMemAlloc",
281    Self::MemoryFree => "cudaGraphNodeTypeMemFree",
282    Self::BatchMemOp => "cudaGraphNodeTypeBatchMemOp",
283    Self::Conditional => "cudaGraphNodeTypeConditional",
284});
285
286singe_core::native_enum! {
287    /// CUDA Graph Update error types
288    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
289    #[repr(u32)]
290    #[non_exhaustive]
291    pub enum GraphExecUpdateResult: driver::CUgraphExecUpdateResult {
292        /// The update succeeded.
293        Success = CU_GRAPH_EXEC_UPDATE_SUCCESS,
294        /// The update failed for an unexpected reason which is described in the return value of the function.
295        Error = CU_GRAPH_EXEC_UPDATE_ERROR,
296        /// The update failed because the topology changed.
297        ErrorTopologyChanged = CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED,
298        /// The update failed because a node type changed.
299        ErrorNodeTypeChanged = CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED,
300        /// The update failed because the function of a kernel node changed (CUDA driver &lt; 11.2).
301        ErrorFunctionChanged = CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED,
302        /// The update failed because the parameters changed in a way that is not supported.
303        ErrorParametersChanged = CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED,
304        /// The update failed because something about the node is not supported.
305        ErrorNotSupported = CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED,
306        /// The update failed because the function of a kernel node changed in an unsupported way.
307        ErrorUnsupportedFunctionChange = CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE,
308        /// The update failed because the node attributes changed in a way that is not supported.
309        ErrorAttributesChanged = CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED,
310    }
311}
312
313impl_enum_display!(GraphExecUpdateResult, {
314    Self::Success => "CU_GRAPH_EXEC_UPDATE_SUCCESS",
315    Self::Error => "CU_GRAPH_EXEC_UPDATE_ERROR",
316    Self::ErrorTopologyChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED",
317    Self::ErrorNodeTypeChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED",
318    Self::ErrorFunctionChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED",
319    Self::ErrorParametersChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED",
320    Self::ErrorNotSupported => "CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED",
321    Self::ErrorUnsupportedFunctionChange => "CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE",
322    Self::ErrorAttributesChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED",
323});
324
325/// Identifies a node of a CUDA graph.
326///
327/// Nodes returned by a [`Graph`] keep their source graph alive and carry its identity, so graph methods can reject nodes from another graph.
328/// Queries and changes of a node go through its [`Graph`].
329#[derive(Debug, Clone)]
330pub struct GraphNode {
331    handle: runtime::cudaGraphNode_t,
332    graph_id: Option<GraphId>,
333    graph: Option<Arc<GraphInner>>,
334    context: Option<Arc<Context>>,
335}
336
337impl PartialEq for GraphNode {
338    fn eq(&self, other: &Self) -> bool {
339        self.handle == other.handle && self.graph_id == other.graph_id
340    }
341}
342
343impl Eq for GraphNode {}
344
345impl Hash for GraphNode {
346    fn hash<H: Hasher>(&self, state: &mut H) {
347        self.handle.hash(state);
348        self.graph_id.hash(state);
349    }
350}
351
352/// Ports and dependency semantics attached to a directed CUDA graph edge.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354pub struct GraphEdgeAttributes {
355    /// Output port of the source node.
356    pub from_port: u8,
357    /// Input port of the destination node.
358    pub to_port: u8,
359    /// Dependency semantics associated with the edge.
360    pub dependency_type: GraphDependencyType,
361}
362
363/// Adjacent graph node and the attributes of its connecting edge.
364#[derive(Debug, Clone, PartialEq, Eq, Hash)]
365pub struct GraphDependency {
366    /// Node connected by this dependency.
367    pub node: GraphNode,
368    /// Port and dependency attributes of the connecting edge.
369    pub data: GraphEdgeAttributes,
370}
371
372/// Directed edge between graph nodes, including its dependency attributes.
373#[derive(Debug, Clone, PartialEq, Eq, Hash)]
374pub struct GraphEdge {
375    /// Source node of the directed dependency.
376    pub from: GraphNode,
377    /// Destination node that depends on the source.
378    pub to: GraphNode,
379    /// Port and dependency attributes of the edge.
380    pub data: GraphEdgeAttributes,
381}
382
383/// Snapshot of graph node and edge counts, grouped by node kind.
384#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
385pub struct GraphTopologySummary {
386    /// Total number of nodes.
387    pub nodes: usize,
388    /// Number of nodes with no incoming dependencies.
389    pub root_nodes: usize,
390    /// Total number of directed dependency edges.
391    pub edges: usize,
392    /// Number of kernel nodes.
393    pub kernel_nodes: usize,
394    /// Number of memory-copy nodes.
395    pub memcpy_nodes: usize,
396    /// Number of memory-fill nodes.
397    pub memset_nodes: usize,
398    /// Number of host callback nodes.
399    pub host_nodes: usize,
400    /// Number of child-graph nodes.
401    pub child_graph_nodes: usize,
402    /// Number of empty dependency nodes.
403    pub empty_nodes: usize,
404    /// Number of event-wait nodes.
405    pub wait_event_nodes: usize,
406    /// Number of event-record nodes.
407    pub event_record_nodes: usize,
408    /// Number of external-semaphore signal nodes.
409    pub external_semaphores_signal_nodes: usize,
410    /// Number of external-semaphore wait nodes.
411    pub external_semaphores_wait_nodes: usize,
412    /// Number of memory-allocation nodes.
413    pub memory_alloc_nodes: usize,
414    /// Number of memory-free nodes.
415    pub memory_free_nodes: usize,
416    /// Number of batched memory-operation nodes.
417    pub batch_mem_op_nodes: usize,
418    /// Number of conditional nodes.
419    pub conditional_nodes: usize,
420}
421
422/// Three-dimensional origin passed to CUDA memory operations.
423///
424/// For copies, x is measured in bytes for linear memory and elements for arrays; y and z select rows and slices.
425#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
426pub struct Position {
427    /// X coordinate in bytes for linear memory or elements for arrays.
428    pub x: usize,
429    /// Row index.
430    pub y: usize,
431    /// Slice index.
432    pub z: usize,
433}
434
435/// Three-dimensional size passed to CUDA memory operations.
436///
437/// Width is measured in bytes for linear memory and elements for arrays; height and depth count rows and slices.
438#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
439pub struct Extent {
440    /// Width in bytes for linear memory or elements for arrays.
441    pub width: usize,
442    /// Number of rows.
443    pub height: usize,
444    /// Number of slices.
445    pub depth: usize,
446}
447
448/// Pool, access permissions, and byte count for a graph allocation node.
449#[derive(Debug, Clone)]
450pub struct MemoryAllocationNodeParams<'a> {
451    /// Properties of the pool backing the graph allocation.
452    pub pool_props: MemoryPoolProps,
453    /// Locations and permissions that may access the allocation.
454    pub access_descs: &'a [MemoryAccessDescriptor],
455    /// Number of bytes allocated when the node executes.
456    pub byte_size: usize,
457}
458
459impl Default for GraphEdgeAttributes {
460    fn default() -> Self {
461        Self {
462            from_port: 0,
463            to_port: 0,
464            dependency_type: GraphDependencyType::Default,
465        }
466    }
467}
468
469impl From<runtime::cudaGraphEdgeData> for GraphEdgeAttributes {
470    fn from(value: runtime::cudaGraphEdgeData) -> Self {
471        Self {
472            from_port: value.from_port,
473            to_port: value.to_port,
474            dependency_type: GraphDependencyType::try_from(value.type_)
475                .unwrap_or(GraphDependencyType::Default),
476        }
477    }
478}
479
480impl From<GraphEdgeAttributes> for runtime::cudaGraphEdgeData {
481    fn from(value: GraphEdgeAttributes) -> Self {
482        Self {
483            from_port: value.from_port,
484            to_port: value.to_port,
485            type_: value.dependency_type.into(),
486            reserved: [0; 5],
487        }
488    }
489}
490
491impl From<Position> for runtime::cudaPos {
492    fn from(value: Position) -> Self {
493        Self {
494            x: value.x as _,
495            y: value.y as _,
496            z: value.z as _,
497        }
498    }
499}
500
501impl From<Extent> for runtime::cudaExtent {
502    fn from(value: Extent) -> Self {
503        Self {
504            width: value.width as _,
505            height: value.height as _,
506            depth: value.depth as _,
507        }
508    }
509}
510
511impl MemoryAllocationNodeInfo {
512    /// Returns the address reserved for the graph allocation node.
513    #[must_use]
514    pub const fn ptr(&self) -> DevicePtr {
515        self.ptr
516    }
517
518    /// Returns the retained context, if the allocation metadata includes one.
519    #[must_use]
520    pub fn context(&self) -> Option<&Arc<Context>> {
521        self.context.as_ref()
522    }
523
524    fn from_raw_in_graph(
525        ptr: DevicePtr,
526        byte_size: usize,
527        graph_id: GraphId,
528        graph: Arc<GraphInner>,
529        context: Option<Arc<Context>>,
530    ) -> Self {
531        Self::from_raw(ptr, byte_size, Some(graph_id), Some(graph), context)
532    }
533
534    fn from_raw(
535        ptr: DevicePtr,
536        byte_size: usize,
537        graph_id: Option<GraphId>,
538        graph: Option<Arc<GraphInner>>,
539        context: Option<Arc<Context>>,
540    ) -> Self {
541        Self {
542            ptr,
543            byte_size,
544            graph_id,
545            _graph: graph,
546            context,
547        }
548    }
549}
550
551impl PartialEq for MemoryAllocationNodeInfo {
552    fn eq(&self, other: &Self) -> bool {
553        self.ptr == other.ptr
554            && self.byte_size == other.byte_size
555            && self.graph_id == other.graph_id
556    }
557}
558
559impl Eq for MemoryAllocationNodeInfo {}
560
561impl Hash for MemoryAllocationNodeInfo {
562    fn hash<H: Hasher>(&self, state: &mut H) {
563        self.ptr.hash(state);
564        self.byte_size.hash(state);
565        self.graph_id.hash(state);
566    }
567}
568
569impl GraphTopologySummary {
570    fn record_node_type(&mut self, node_type: GraphNodeType) {
571        match node_type {
572            GraphNodeType::Kernel => self.kernel_nodes += 1,
573            GraphNodeType::Memcpy => self.memcpy_nodes += 1,
574            GraphNodeType::Memset => self.memset_nodes += 1,
575            GraphNodeType::Host => self.host_nodes += 1,
576            GraphNodeType::Graph => self.child_graph_nodes += 1,
577            GraphNodeType::Empty => self.empty_nodes += 1,
578            GraphNodeType::WaitEvent => self.wait_event_nodes += 1,
579            GraphNodeType::EventRecord => self.event_record_nodes += 1,
580            GraphNodeType::ExternalSemaphoresSignal => {
581                self.external_semaphores_signal_nodes += 1;
582            }
583            GraphNodeType::ExternalSemaphoresWait => {
584                self.external_semaphores_wait_nodes += 1;
585            }
586            GraphNodeType::MemoryAlloc => self.memory_alloc_nodes += 1,
587            GraphNodeType::MemoryFree => self.memory_free_nodes += 1,
588            GraphNodeType::BatchMemOp => self.batch_mem_op_nodes += 1,
589            GraphNodeType::Conditional => self.conditional_nodes += 1,
590        }
591    }
592}
593
594/// A graph definition with exclusive host access to native graph operations.
595///
596/// Move it between threads or share it through external synchronization.
597/// Native graph objects cannot be queried or modified concurrently.
598#[derive(Debug)]
599pub struct Graph {
600    inner: Arc<GraphInner>,
601    id: GraphId,
602    context: Arc<Context>,
603    _not_sync: PhantomData<Cell<()>>,
604}
605
606/// Process-local identity used to associate nodes with their source graph.
607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
608pub struct GraphId(u64);
609
610/// Owns a CUDA graph handle that is not bound to a Singe context.
611///
612/// The caller must establish the CUDA context required for raw native operations.
613#[derive(Debug)]
614pub struct UnboundGraph {
615    inner: Arc<GraphInner>,
616}
617
618/// Raw ownership of a graph, its context, and every graph-retained resource.
619///
620/// Keep this value alive until the native handle is destroyed, or re-adopt it with [`Graph::from_raw`].
621/// Bind its context before native use and complete graph work before releasing these owners.
622#[derive(Debug)]
623pub struct RawGraph {
624    /// Native graph handle.
625    pub handle: runtime::cudaGraph_t,
626    /// Context the graph belongs to.
627    pub context: Arc<Context>,
628    /// Allocations, modules, and events the graph's nodes depend on.
629    pub retained: RetainedResources,
630    /// Identity that the graph's nodes record.
631    pub id: GraphId,
632}
633
634/// Raw ownership of an executable graph, its context, source graph, and resource dependencies.
635///
636/// Keep this value alive until native destruction, or re-adopt it with [`ExecutableGraph::from_raw`].
637/// Bind its context before native use and complete all launches before releasing these owners.
638#[derive(Debug)]
639pub struct RawExecutableGraph {
640    /// Native executable graph handle.
641    pub handle: runtime::cudaGraphExec_t,
642    /// Context the executable graph belongs to.
643    pub context: Arc<Context>,
644    /// Allocations, modules, and events the executable graph's nodes depend on.
645    pub retained: RetainedResources,
646    /// Graph the executable was instantiated from, if it retains one.
647    pub source_graph: Option<UnboundGraph>,
648    /// Identity of the source graph, which node updates check.
649    pub source_graph_id: Option<GraphId>,
650}
651
652// SAFETY: the graph handle is a plain value whose every native use is `unsafe` and binds `context`, and the retained owners are `Send` (`Arc<dyn Any + Send + Sync>` and modules).
653unsafe impl Send for RawGraph {}
654
655// SAFETY: a shared `RawGraph` only exposes the handle value and `Sync` owners; it makes no native call, so concurrent use is the caller's documented obligation.
656unsafe impl Sync for RawGraph {}
657
658// SAFETY: the executable handle is a plain value whose every native use is `unsafe` and binds `context`, and the retained owners and source graph are `Send`.
659unsafe impl Send for RawExecutableGraph {}
660
661// SAFETY: a shared `RawExecutableGraph` only exposes the handle value and `Sync` owners; it makes no native call, so concurrent launches are the caller's obligation.
662unsafe impl Sync for RawExecutableGraph {}
663
664#[derive(Debug)]
665pub(crate) struct GraphInner {
666    handle: runtime::cudaGraph_t,
667    owns_handle: bool,
668    context: Option<Arc<Context>>,
669    retained: Mutex<RetainedResources>,
670    parent: Option<Arc<Self>>,
671}
672
673// SAFETY: CUDA graph handles may be destroyed from any host thread once the owning context is bound, which `Drop` does first.
674unsafe impl Send for GraphInner {}
675
676// SAFETY: through `&GraphInner` only the handle value and the `Mutex`-guarded retained set are reachable; native graph calls go through `Graph`, which is `!Sync` and takes `&mut self` to mutate.
677unsafe impl Sync for GraphInner {}
678
679#[derive(Clone)]
680pub(crate) struct RetainedAllocation(Arc<dyn Any + Send + Sync>);
681
682impl fmt::Debug for RetainedAllocation {
683    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
684        f.debug_struct("RetainedAllocation")
685            .field("strong_count", &Arc::strong_count(&self.0))
686            .finish()
687    }
688}
689
690/// Owners that a graph retains for its nodes: device allocations, modules, and events.
691///
692/// Keep it alive until every graph and executable graph whose nodes refer to these owners is destroyed.
693#[derive(Debug, Clone, Default)]
694pub struct RetainedResources {
695    allocations: HashMap<usize, RetainedAllocation>,
696    modules: HashMap<CodeOwnerId, Module>,
697    events: HashMap<usize, Arc<Event>>,
698}
699
700impl RetainedResources {
701    fn retain_event(&mut self, event: &Arc<Event>) {
702        self.events
703            .entry(Arc::as_ptr(event).addr())
704            .or_insert_with(|| Arc::clone(event));
705    }
706
707    fn retain_allocation(&mut self, allocation: RetainedAllocation) {
708        let identity = Arc::as_ptr(&allocation.0).cast::<()>().addr();
709        self.allocations.entry(identity).or_insert(allocation);
710    }
711
712    fn retain_module(&mut self, module: &Module) {
713        self.modules
714            .entry(module.code_owner_id())
715            .or_insert_with(|| module.clone());
716    }
717
718    fn extend(&mut self, other: Self) {
719        self.allocations.extend(other.allocations);
720        self.modules.extend(other.modules);
721        self.events.extend(other.events);
722    }
723}
724
725/// Borrowed graph view tied to the graph whose child graph node embeds it.
726///
727/// Dropping the view does not destroy the borrowed native graph.
728#[derive(Debug)]
729pub struct BorrowedGraph<'graph> {
730    graph: Graph,
731    _graph: PhantomData<&'graph Graph>,
732}
733
734/// Device memory whose allocation is retained by CUDA graph objects.
735///
736/// `GraphBuffer` values are created through [`Graph::create_buffer_uninit`], [`Graph::zeroed_buffer`], or [`Graph::buffer_from_slice`].
737/// Graph and executable-graph APIs that accept `GraphBuffer` retain the underlying allocation so graph replay cannot outlive the device pointers baked into CUDA graph nodes.
738/// Each resource snapshot retains a given allocation owner once, including after graph updates and child-graph merges.
739#[derive(Debug)]
740pub struct GraphBuffer<T: DeviceRepr> {
741    memory: DeviceMemory<T>,
742}
743
744// SAFETY: this typed handle preserves the shared allocation's identity, bounds, and actual context.
745unsafe impl<T: DeviceRepr> DeviceRegionProvider for GraphBuffer<T> {
746    fn region(&self) -> DeviceRegion<'_> {
747        self.memory.region()
748    }
749}
750
751// SAFETY: the pointer and length come from the owned `DeviceMemory<T>`, which `region` also describes.
752unsafe impl<T: DeviceRepr> DeviceRange<T> for GraphBuffer<T> {
753    fn as_device_ptr(&self) -> *const T {
754        self.memory.as_ptr()
755    }
756
757    fn len(&self) -> usize {
758        self.memory.len()
759    }
760}
761
762// SAFETY: a `GraphBuffer<T>` is built zeroed, copied from host values, or by `assume_init`, whose caller guarantees initialization, so its values are initialized for the borrow.
763unsafe impl<T: DeviceRepr> DeviceSlice<T> for GraphBuffer<T> {}
764
765// SAFETY: `&mut GraphBuffer<T>` is the only path to mutable access of the owned allocation.
766unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for GraphBuffer<T> {}
767
768// SAFETY: the mutable pointer covers the same `len()` elements of the owned allocation, and `&mut self` makes the access exclusive.
769unsafe impl<T: DeviceRepr> DeviceOutput<T> for GraphBuffer<T> {
770    fn as_mut_ptr(&mut self) -> *mut T {
771        self.memory.as_mut_ptr()
772    }
773}
774
775// SAFETY: the length is the owned allocation's element count, and `MaybeUninit<T>` has the layout of `T`, so the range describes the same bytes as `region`.
776unsafe impl<T: DeviceRepr> DeviceRange<T> for GraphBuffer<MaybeUninit<T>> {
777    fn len(&self) -> usize {
778        self.memory.len()
779    }
780}
781
782// SAFETY: the cast pointer addresses the same owned elements with `T`'s layout, and `&mut self` makes the access exclusive.
783unsafe impl<T: DeviceRepr> DeviceOutput<T> for GraphBuffer<MaybeUninit<T>> {
784    fn as_mut_ptr(&mut self) -> *mut T {
785        self.memory.as_mut_ptr().cast()
786    }
787}
788
789impl UnboundGraph {
790    /// Wraps an existing CUDA graph handle and takes ownership of it.
791    ///
792    /// # Safety
793    ///
794    /// `handle` must be a valid CUDA graph handle.
795    /// Ownership of `handle` is transferred to the returned [`UnboundGraph`], and the handle must not be destroyed elsewhere after calling this function.
796    ///
797    /// # Errors
798    ///
799    /// Returns an error if the native handle is null.
800    pub unsafe fn from_raw(handle: runtime::cudaGraph_t) -> Result<Self> {
801        if handle.is_null() {
802            return Err(Error::NullHandle);
803        }
804
805        Ok(Self {
806            inner: Arc::new(GraphInner {
807                handle,
808                owns_handle: true,
809                context: None,
810                retained: Mutex::new(RetainedResources::default()),
811                parent: None,
812            }),
813        })
814    }
815
816    /// Creates an empty graph without a Singe context association.
817    ///
818    /// Prefer [`Context::create_graph`] for ordinary Singe code.
819    /// Unbound graphs do not model context association, so the caller must keep CUDA context, node, executable update, upload, and launch relationships coherent.
820    ///
821    /// # Safety
822    ///
823    /// The returned graph has no modeled CUDA context association.
824    /// The caller must ensure every node, kernel, memory operand, child graph, executable update, upload, and launch is used with the correct CUDA context.
825    ///
826    /// # Errors
827    ///
828    /// Propagates CUDA graph creation errors and rejects a null returned graph handle.
829    pub unsafe fn create() -> Result<Self> {
830        let mut handle = ptr::null_mut();
831        // SAFETY: `handle` is a local that `cudaGraphCreate` writes through an exclusive pointer.
832        unsafe {
833            try_ffi!(runtime::cudaGraphCreate(&raw mut handle, 0))?;
834        }
835        // SAFETY: CUDA just created `handle`, nothing else owns it, and `from_raw` rejects null.
836        unsafe { Self::from_raw(handle) }
837    }
838
839    /// Returns the owned native graph handle without transferring ownership.
840    #[must_use]
841    pub fn as_raw(&self) -> runtime::cudaGraph_t {
842        self.inner.handle
843    }
844
845    /// Consumes the graph and returns its native handle without destroying it.
846    ///
847    /// The caller becomes responsible for eventually destroying the returned handle with CUDA.
848    ///
849    /// # Errors
850    ///
851    /// Returns the unchanged graph if a node or another owner still retains its native graph storage.
852    pub fn into_raw(self) -> StdResult<runtime::cudaGraph_t, Self> {
853        match Arc::try_unwrap(self.inner) {
854            Ok(mut inner) => {
855                inner.owns_handle = false;
856                Ok(inner.handle)
857            }
858            Err(inner) => Err(Self { inner }),
859        }
860    }
861}
862
863static NEXT_GRAPH_ID: AtomicU64 = AtomicU64::new(1);
864
865impl GraphId {
866    /// Generates an identity for a graph in this process.
867    pub fn generate() -> Self {
868        Self(NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed))
869    }
870
871    /// Returns the integer representation of this graph identity.
872    #[must_use]
873    pub fn as_u64(self) -> u64 {
874        self.0
875    }
876}
877
878impl Display for GraphId {
879    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
880        self.0.fmt(f)
881    }
882}
883
884impl Drop for GraphInner {
885    fn drop(&mut self) {
886        if !self.owns_handle {
887            return;
888        }
889
890        if let Some(context) = &self.context
891            && let Err(error) = context.bind()
892        {
893            report_cleanup_failure("bind the cuda context to destroy", "cuda graph", &error);
894            return;
895        }
896        // SAFETY: `owns_handle` says this value owns the live graph, every node and executable holding it has dropped its `Arc`, and its context is bound above.
897        unsafe {
898            if let Err(error) = try_ffi!(runtime::cudaGraphDestroy(self.handle)) {
899                report_cleanup_failure("destroy", "cuda graph", &error);
900            }
901        }
902    }
903}
904
905impl BorrowedGraph<'_> {
906    /// Wraps an existing CUDA graph handle of `context` without taking ownership.
907    ///
908    /// # Safety
909    ///
910    /// `handle` must be a valid CUDA graph handle of `context` for the returned lifetime.
911    /// The returned graph view will not destroy `handle` when dropped.
912    ///
913    /// # Errors
914    ///
915    /// Returns an error if the native handle is null.
916    pub unsafe fn from_raw(handle: runtime::cudaGraph_t, context: Arc<Context>) -> Result<Self> {
917        if handle.is_null() {
918            return Err(Error::NullHandle);
919        }
920
921        Ok(Self {
922            // SAFETY: the caller guarantees `handle` is a live graph of `context` for the view's lifetime, which is what the borrowed constructor requires.
923            graph: unsafe { Graph::from_raw_borrowed_in_context(handle, context) },
924            _graph: PhantomData,
925        })
926    }
927
928    /// Borrows the graph API while preserving this view’s native lifetime.
929    #[must_use]
930    pub const fn as_graph(&self) -> &Graph {
931        &self.graph
932    }
933
934    /// Returns the borrowed native graph handle without transferring ownership.
935    #[must_use]
936    pub fn as_raw(&self) -> runtime::cudaGraph_t {
937        self.graph.as_raw()
938    }
939}
940
941impl Deref for BorrowedGraph<'_> {
942    type Target = Graph;
943
944    fn deref(&self) -> &Self::Target {
945        self.as_graph()
946    }
947}
948
949/// Owns an instantiated CUDA graph and retains its execution resources.
950///
951/// When available, source graph identity and context metadata allow node updates and launches to validate their inputs.
952#[derive(Debug)]
953pub struct ExecutableGraph {
954    handle: runtime::cudaGraphExec_t,
955    context: Arc<Context>,
956    source_graph_id: Option<GraphId>,
957    source_graph: Option<Arc<GraphInner>>,
958    retained: RetainedResources,
959}
960
961/// Owns a native executable-graph handle that is not bound to a Singe context or retained resources.
962#[derive(Debug)]
963pub struct UnboundExecutableGraph {
964    handle: runtime::cudaGraphExec_t,
965}
966
967impl Drop for UnboundExecutableGraph {
968    fn drop(&mut self) {
969        // SAFETY: this value owns the live executable handle, and its constructor's caller keeps the right context current for native use.
970        unsafe {
971            if let Err(error) = try_ffi!(runtime::cudaGraphExecDestroy(self.handle)) {
972                report_cleanup_failure("destroy", "cuda executable graph", &error);
973            }
974        }
975    }
976}
977
978// SAFETY: an executable graph may be launched and destroyed from any host thread once its context is bound, which every method and `Drop` do; it is not `Sync`, so native calls on one executable never run concurrently.
979unsafe impl Send for ExecutableGraph {}
980
981impl Drop for ExecutableGraph {
982    fn drop(&mut self) {
983        if let Err(error) = self.bind_context() {
984            report_cleanup_failure(
985                "bind the cuda context to destroy",
986                "cuda executable graph",
987                &error,
988            );
989            return;
990        }
991        // SAFETY: this value owns the live executable handle, its context is bound above, and the retained resources drop only after destruction.
992        unsafe {
993            if let Err(error) = try_ffi!(runtime::cudaGraphExecDestroy(self.handle)) {
994                report_cleanup_failure("destroy", "cuda executable graph", &error);
995            }
996        }
997    }
998}
999
1000/// Failure of [`ExecutableGraph::update`].
1001#[derive(Debug, thiserror::Error)]
1002#[non_exhaustive]
1003pub enum GraphUpdateError {
1004    /// CUDA did not perform the update because it violates the constraints of executable graph updates.
1005    #[error("cuda rejected the executable graph update ({result})")]
1006    Rejected {
1007        /// CUDA's classification of the failure.
1008        result: GraphExecUpdateResult,
1009        /// Node of the source graph that caused the failure, when CUDA reports one.
1010        error_node: Option<GraphNode>,
1011        /// Source node of the edge that caused the failure, when CUDA reports one.
1012        error_from_node: Option<GraphNode>,
1013    },
1014    /// A context mismatch or another CUDA failure.
1015    #[error(transparent)]
1016    Cuda(#[from] Error),
1017}
1018
1019/// Raw destination, geometry, and fill value for a graph memset node.
1020///
1021/// These parameters do not retain the destination allocation.
1022/// Its owner must outlive every graph replay that uses the stored address.
1023#[derive(Debug, Clone, Copy)]
1024pub struct MemorySetNodeParams {
1025    dst: DevicePtr,
1026    pitch: usize,
1027    value: u32,
1028    element_size: u32,
1029    width: usize,
1030    height: usize,
1031}
1032
1033impl MemorySetNodeParams {
1034    /// Creates raw memset node parameters.
1035    ///
1036    /// # Safety
1037    ///
1038    /// `dst` must be valid for writes of `element_size * width` bytes when the graph executes.
1039    /// If `height` or `pitch` are changed after construction, the caller must account for those values as required by CUDA.
1040    #[must_use]
1041    pub const unsafe fn new(dst: DevicePtr, element_size: u32, width: usize) -> Self {
1042        Self {
1043            dst,
1044            pitch: 0,
1045            value: 0,
1046            element_size,
1047            width,
1048            height: 1,
1049        }
1050    }
1051
1052    /// Sets the row stride in bytes without validating the destination range.
1053    #[must_use]
1054    pub const fn with_pitch(mut self, pitch: usize) -> Self {
1055        self.pitch = pitch;
1056        self
1057    }
1058
1059    /// Sets the fill value; CUDA uses the low bytes selected by the element size.
1060    #[must_use]
1061    pub const fn with_value(mut self, value: u32) -> Self {
1062        self.value = value;
1063        self
1064    }
1065
1066    /// Sets the number of rows without validating the destination range.
1067    #[must_use]
1068    pub const fn with_height(mut self, height: usize) -> Self {
1069        self.height = height;
1070        self
1071    }
1072
1073    /// Returns the raw destination address.
1074    #[must_use]
1075    pub const fn dst(self) -> DevicePtr {
1076        self.dst
1077    }
1078
1079    /// Returns the row stride in bytes.
1080    #[must_use]
1081    pub const fn pitch(self) -> usize {
1082        self.pitch
1083    }
1084
1085    /// Returns the fill value before truncation to the element size.
1086    #[must_use]
1087    pub const fn value(self) -> u32 {
1088        self.value
1089    }
1090
1091    /// Returns the fill element size in bytes.
1092    #[must_use]
1093    pub const fn element_size(self) -> u32 {
1094        self.element_size
1095    }
1096
1097    /// Returns the number of fill elements per row.
1098    #[must_use]
1099    pub const fn width(self) -> usize {
1100        self.width
1101    }
1102
1103    /// Returns the number of rows.
1104    #[must_use]
1105    pub const fn height(self) -> usize {
1106        self.height
1107    }
1108}
1109
1110impl From<&MemorySetNodeParams> for driver::CUDA_MEMSET_NODE_PARAMS {
1111    fn from(value: &MemorySetNodeParams) -> Self {
1112        Self {
1113            dst: value.dst().addr() as _,
1114            pitch: value.pitch() as _,
1115            value: value.value(),
1116            elementSize: value.element_size(),
1117            width: value.width() as _,
1118            height: value.height() as _,
1119        }
1120    }
1121}
1122
1123impl_enum_display!(GraphKernelNodeAttributeId, {
1124    GraphKernelNodeAttributeId::Cooperative => "cudaLaunchAttributeCooperative",
1125    GraphKernelNodeAttributeId::ClusterDimension => "cudaLaunchAttributeClusterDimension",
1126    GraphKernelNodeAttributeId::Priority => "cudaLaunchAttributePriority",
1127    GraphKernelNodeAttributeId::PreferredSharedMemoryCarveout => "cudaLaunchAttributePreferredSharedMemoryCarveout",
1128});
1129
1130impl_enum_display!(GraphDependencyType, {
1131    GraphDependencyType::Default => "CU_GRAPH_DEPENDENCY_TYPE_DEFAULT",
1132    GraphDependencyType::Programmatic => "CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC",
1133});