Skip to main content

singe_cuda/graph/
node.rs

1use std::{ffi::c_void, ptr, sync::Arc};
2
3use singe_cuda_sys::{driver, runtime};
4
5use crate::{
6    context::Context,
7    dim::Dim3,
8    error::{Error, Result},
9    graph::{
10        BorrowedGraph, Graph, GraphDependency, GraphId, GraphInner, GraphKernelNodeAttribute,
11        GraphKernelNodeAttributeId, GraphNode, GraphNodeType, MemoryAllocationNodeInfo,
12        MemorySetNodeParams, raw::MemoryCopy1DNodeParams,
13    },
14    module::LaunchAttribute,
15    try_ffi,
16    types::{ClusterSchedulingPolicy, DevicePtr, SharedMemoryMode},
17    utility::to_usize,
18};
19
20// Every query and change of a node goes through its `Graph`, which is not `Sync`, so native graph access follows Rust's borrow of the graph.
21// A `GraphNode` only identifies a node and keeps its graph alive so that its handle stays valid.
22impl GraphNode {
23    /// Wraps an existing CUDA graph node handle.
24    ///
25    /// The returned node has no [`Graph`] identity, so graph, executable-graph, and stream-capture methods reject it with `Error::GraphNodeMismatch`.
26    ///
27    /// # Safety
28    ///
29    /// `handle` must be a valid CUDA graph node handle.
30    /// The caller must ensure the node remains valid for every operation using the returned token and that it belongs to the graph or executable graph passed to those operations.
31    pub const unsafe fn from_raw(handle: runtime::cudaGraphNode_t) -> Self {
32        Self {
33            handle,
34            graph_id: None,
35            graph: None,
36            context: None,
37        }
38    }
39
40    pub(crate) fn from_raw_in_graph(
41        handle: runtime::cudaGraphNode_t,
42        graph_id: GraphId,
43        graph: Arc<GraphInner>,
44        context: Option<Arc<Context>>,
45    ) -> Self {
46        Self {
47            handle,
48            graph_id: Some(graph_id),
49            graph: Some(graph),
50            context,
51        }
52    }
53
54    /// Returns the native node handle without transferring graph ownership.
55    #[must_use]
56    pub const fn as_raw(&self) -> runtime::cudaGraphNode_t {
57        self.handle
58    }
59
60    pub(crate) fn graph_raw(&self) -> Option<runtime::cudaGraph_t> {
61        self.graph.as_ref().map(|graph| graph.handle)
62    }
63
64    /// Returns the retained context, if this node has context metadata.
65    #[must_use]
66    pub fn context(&self) -> Option<&Arc<Context>> {
67        self.context.as_ref()
68    }
69}
70
71impl Graph {
72    /// Returns the type of `node`.
73    ///
74    /// # Errors
75    ///
76    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph, and `Error::UnknownEnumValue` if CUDA reports a node type this crate does not know.
77    /// Also returns an error if CUDA cannot query the node type or a previous asynchronous launch reported an error.
78    pub fn node_type(&self, node: &GraphNode) -> Result<GraphNodeType> {
79        self.check_node(node)?;
80        let mut kind = runtime::cudaGraphNodeType::CU_GRAPH_NODE_TYPE_KERNEL;
81        // SAFETY: `node` belongs to this live graph, and `kind` is a valid output location.
82        unsafe {
83            try_ffi!(runtime::cudaGraphNodeGetType(node.as_raw(), &raw mut kind))?;
84        }
85        GraphNodeType::try_from(kind)
86    }
87
88    /// Returns the dependencies of `node`.
89    ///
90    /// # Errors
91    ///
92    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
93    /// Also returns an error if CUDA cannot query the dependencies or a previous asynchronous launch reports an error.
94    pub fn node_dependencies(&self, node: &GraphNode) -> Result<Vec<GraphDependency>> {
95        self.check_node(node)?;
96        // SAFETY: `node` belongs to this live graph, and the native call first reports the count, then fills arrays sized to it.
97        unsafe {
98            let mut count = 0;
99            try_ffi!(runtime::cudaGraphNodeGetDependencies(
100                node.as_raw(),
101                ptr::null_mut(),
102                ptr::null_mut(),
103                &raw mut count,
104            ))?;
105
106            if count == 0 {
107                return Ok(Vec::new());
108            }
109
110            let mut handles = Vec::with_capacity(to_usize(count, "graph node count")?);
111            let mut edge_data = Vec::with_capacity(to_usize(count, "graph node count")?);
112            try_ffi!(runtime::cudaGraphNodeGetDependencies(
113                node.as_raw(),
114                handles.as_mut_ptr(),
115                edge_data.as_mut_ptr(),
116                &raw mut count,
117            ))?;
118            handles.set_len(to_usize(count, "graph node count")?);
119            edge_data.set_len(to_usize(count, "graph node count")?);
120
121            Ok(handles
122                .into_iter()
123                .zip(edge_data)
124                .map(|(handle, data)| GraphDependency {
125                    node: self.node_from_raw(handle),
126                    data: data.into(),
127                })
128                .collect())
129        }
130    }
131
132    /// Returns the nodes that depend on `node`.
133    ///
134    /// # Errors
135    ///
136    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
137    /// Also returns an error if CUDA cannot query the dependent nodes or a previous asynchronous launch reports an error.
138    pub fn node_dependents(&self, node: &GraphNode) -> Result<Vec<GraphDependency>> {
139        self.check_node(node)?;
140        // SAFETY: `node` belongs to this live graph, and the native call first reports the count, then fills arrays sized to it.
141        unsafe {
142            let mut count = 0;
143            try_ffi!(runtime::cudaGraphNodeGetDependentNodes(
144                node.as_raw(),
145                ptr::null_mut(),
146                ptr::null_mut(),
147                &raw mut count,
148            ))?;
149
150            if count == 0 {
151                return Ok(Vec::new());
152            }
153
154            let mut handles = Vec::with_capacity(to_usize(count, "graph node count")?);
155            let mut edge_data = Vec::with_capacity(to_usize(count, "graph node count")?);
156            try_ffi!(runtime::cudaGraphNodeGetDependentNodes(
157                node.as_raw(),
158                handles.as_mut_ptr(),
159                edge_data.as_mut_ptr(),
160                &raw mut count,
161            ))?;
162            handles.set_len(to_usize(count, "graph node count")?);
163            edge_data.set_len(to_usize(count, "graph node count")?);
164
165            Ok(handles
166                .into_iter()
167                .zip(edge_data)
168                .map(|(handle, data)| GraphDependency {
169                    node: self.node_from_raw(handle),
170                    data: data.into(),
171                })
172                .collect())
173        }
174    }
175
176    /// Borrows the graph embedded in the child graph node `node` without cloning it.
177    ///
178    /// The returned [`BorrowedGraph`] borrows this graph, so this graph cannot change while it lives, and it does not destroy the embedded graph when dropped.
179    /// Allocation and free nodes cannot be added to the returned graph.
180    ///
181    /// # Errors
182    ///
183    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
184    /// Also returns an error if `node` is not a child graph node, CUDA cannot query the child graph, CUDA returns a null graph handle, or a previous asynchronous launch reports an error.
185    ///
186    /// # Panics
187    ///
188    /// Panics if the newly constructed borrowed graph unexpectedly has multiple owners.
189    pub fn child_graph(&self, node: &GraphNode) -> Result<BorrowedGraph<'_>> {
190        self.check_node(node)?;
191        let mut graph = ptr::null_mut();
192        // SAFETY: `node` belongs to this live graph, and `graph` is a valid output location.
193        unsafe {
194            try_ffi!(runtime::cudaGraphChildGraphNodeGetGraph(
195                node.as_raw(),
196                &raw mut graph,
197            ))?;
198        }
199
200        if graph.is_null() {
201            return Err(Error::NullHandle);
202        }
203
204        // SAFETY: CUDA returned this graph, owned by a node of this graph in this graph's context, and the view borrows this graph.
205        let mut borrowed = unsafe { BorrowedGraph::from_raw(graph, Arc::clone(&self.context)) }?;
206        let inner =
207            Arc::get_mut(&mut borrowed.graph.inner).expect("new borrowed graph has one owner");
208        inner.parent = Some(Arc::clone(&self.inner));
209        *inner
210            .retained
211            .get_mut()
212            .map_err(|_| Error::lock_poisoned("graph resources"))? = self.retained_resources()?;
213        Ok(borrowed)
214    }
215
216    /// Returns the address and size of the memory allocation node `node`.
217    ///
218    /// # Errors
219    ///
220    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
221    /// Also returns an error if `node` is not a memory allocation node, CUDA cannot query the parameters, or a previous asynchronous launch reports an error.
222    pub fn memory_allocation_node_info(
223        &self,
224        node: &GraphNode,
225    ) -> Result<MemoryAllocationNodeInfo> {
226        self.check_node(node)?;
227        let mut params = runtime::cudaMemAllocNodeParams::default();
228        // SAFETY: `node` belongs to this live graph, and `params` is a valid output location.
229        unsafe {
230            try_ffi!(runtime::cudaGraphMemAllocNodeGetParams(
231                node.as_raw(),
232                &raw mut params,
233            ))?;
234        }
235        Ok(MemoryAllocationNodeInfo::from_raw_in_graph(
236            // SAFETY: the address is the graph allocation CUDA reported and is only stored; dereferencing it requires further unsafe code.
237            unsafe {
238                DevicePtr::new(ptr::without_provenance_mut(to_usize(
239                    params.dptr,
240                    "memory allocation address",
241                )?))
242            },
243            to_usize(params.bytesize, "memory allocation byte count")?,
244            self.id,
245            Arc::clone(&self.inner),
246            Some(Arc::clone(&self.context)),
247        ))
248    }
249
250    /// Returns the address that the memory free node `node` frees.
251    ///
252    /// # Safety
253    ///
254    /// The returned pointer must not be used after the graph frees it.
255    ///
256    /// # Errors
257    ///
258    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
259    /// Also returns an error if `node` is not a memory free node, CUDA cannot query the pointer, or a previous asynchronous launch reports an error.
260    pub unsafe fn memory_free_node_ptr(&self, node: &GraphNode) -> Result<DevicePtr> {
261        self.check_node(node)?;
262        let mut ptr: *mut c_void = ptr::null_mut();
263        // SAFETY: `node` belongs to this live graph, and `ptr` is a valid output location.
264        unsafe {
265            try_ffi!(runtime::cudaGraphMemFreeNodeGetParams(
266                node.as_raw(),
267                (&raw mut ptr).cast(),
268            ))?;
269        }
270        // SAFETY: the address is the one CUDA's free node frees, and the caller must not use it after the graph frees it.
271        Ok(unsafe { DevicePtr::new(ptr.cast()) })
272    }
273
274    /// Returns the attribute `id` of the kernel node `node`.
275    ///
276    /// # Errors
277    ///
278    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
279    /// Also returns an error if `node` is not a kernel node, CUDA cannot query the attribute, or a previous asynchronous launch reports an error.
280    pub fn kernel_node_attribute(
281        &self,
282        node: &GraphNode,
283        id: GraphKernelNodeAttributeId,
284    ) -> Result<GraphKernelNodeAttribute> {
285        self.check_node(node)?;
286        let mut value = runtime::cudaLaunchAttributeValue::default();
287        // SAFETY: `node` belongs to this live graph, and the attribute value is a writable local union sized for every attribute.
288        unsafe {
289            try_ffi!(runtime::cudaGraphKernelNodeGetAttribute(
290                node.as_raw(),
291                id.into(),
292                &raw mut value,
293            ))?;
294
295            Ok(match id {
296                GraphKernelNodeAttributeId::Cooperative => {
297                    GraphKernelNodeAttribute::Cooperative(*value.cooperative.as_ref() != 0)
298                }
299                GraphKernelNodeAttributeId::ClusterDimension => {
300                    let dim = value.clusterDim.as_ref();
301                    GraphKernelNodeAttribute::ClusterDimension(Dim3::new(dim.x, dim.y, dim.z))
302                }
303                GraphKernelNodeAttributeId::Priority => {
304                    GraphKernelNodeAttribute::Priority(*value.priority.as_ref())
305                }
306                GraphKernelNodeAttributeId::PreferredSharedMemoryCarveout => {
307                    GraphKernelNodeAttribute::PreferredSharedMemoryCarveout(
308                        *value.sharedMemCarveout.as_ref(),
309                    )
310                }
311            })
312        }
313    }
314
315    /// Returns the shared memory configuration of the kernel node `node`.
316    ///
317    /// # Errors
318    ///
319    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
320    /// Also propagates CUDA kernel-node attribute errors, including an incompatible node type or unsupported attribute.
321    pub fn kernel_node_shared_memory_mode(&self, node: &GraphNode) -> Result<SharedMemoryMode> {
322        self.check_node(node)?;
323        let mut value = driver::CUlaunchAttributeValue::default();
324        // SAFETY: `node` belongs to this live graph, and `value` is a valid output location.
325        unsafe {
326            try_ffi!(driver::cuGraphKernelNodeGetAttribute(
327                node.as_raw(),
328                driver::CUlaunchAttributeID::CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE,
329                &raw mut value
330            ))?;
331            Ok(value.sharedMemoryMode.try_into()?)
332        }
333    }
334
335    /// Returns the cluster scheduling policy preference of the kernel node `node`.
336    ///
337    /// # Errors
338    ///
339    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
340    /// Also propagates CUDA kernel-node attribute errors, including an incompatible node type or unsupported attribute.
341    pub fn kernel_node_cluster_scheduling_policy(
342        &self,
343        node: &GraphNode,
344    ) -> Result<ClusterSchedulingPolicy> {
345        self.check_node(node)?;
346        let mut value = driver::CUlaunchAttributeValue::default();
347        // SAFETY: `node` belongs to this live graph, and `value` is a valid output location.
348        unsafe {
349            try_ffi!(driver::cuGraphKernelNodeGetAttribute(
350                node.as_raw(),
351                driver::CUlaunchAttributeID::CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE,
352                &raw mut value
353            ))?;
354            Ok(value.clusterSchedulingPolicyPreference.try_into()?)
355        }
356    }
357
358    /// Changes the one-dimensional copy node `node` in the graph definition.
359    /// Existing executable graphs keep their previous parameters until explicitly updated.
360    ///
361    /// # Safety
362    ///
363    /// Source and destination must uphold [`MemoryCopy1DNodeParams::new`] for every affected replay.
364    /// Retain old sources for existing executables.
365    ///
366    /// # Errors
367    ///
368    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
369    /// Also propagates context-binding and CUDA node-parameter update errors, including a node that is not a memory-copy node or invalid copy parameters.
370    pub unsafe fn set_memory_copy_node_1d_params(
371        &mut self,
372        node: &GraphNode,
373        params: &MemoryCopy1DNodeParams,
374    ) -> Result<()> {
375        self.check_node(node)?;
376        // SAFETY: `node` belongs to this exclusively borrowed graph, and the caller vouches for the copy operands.
377        unsafe {
378            try_ffi!(runtime::cudaGraphMemcpyNodeSetParams1D(
379                node.as_raw(),
380                params.dst().cast(),
381                params.src().cast(),
382                params.count() as _,
383                params.kind().into(),
384            ))
385        }
386    }
387
388    /// Replaces the graph embedded in the child graph node `node` with an independent snapshot of `child_graph`.
389    /// Existing executable graphs retain their previous parameters until explicitly updated.
390    /// The node identity and its incoming and outgoing dependencies are preserved.
391    ///
392    /// # Errors
393    ///
394    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph, `Error::ContextMismatch` if `child_graph` has another context, or an error if CUDA rejects the replacement.
395    /// CUDA validates the replacement before changing the node.
396    pub fn set_child_graph(&mut self, node: &GraphNode, child_graph: &Self) -> Result<()> {
397        self.check_node(node)?;
398        if self.context.as_ref() != child_graph.context().as_ref() {
399            return Err(Error::context_mismatch("child graph"));
400        }
401
402        let child_resources = child_graph.retained_resources()?;
403        // Retain both snapshots before publishing native pointers.
404        // A rejected replacement can retain extra owners, but cannot release resources used by an existing graph.
405        self.retained_lock()?.extend(child_resources);
406        let mut params = runtime::cudaGraphNodeParams {
407            type_: GraphNodeType::Graph.into(),
408            ..Default::default()
409        };
410        // SAFETY: the graph tag selects this zero-initialized union member.
411        // Write its fields separately so native-required padding and reserved bytes stay zero.
412        let graph_params = unsafe { &mut params.__bindgen_anon_1.graph };
413        graph_params.graph = child_graph.as_raw();
414        graph_params.ownership =
415            driver::CUgraphChildGraphNodeOwnership::CU_GRAPH_CHILD_GRAPH_OWNERSHIP_CLONE;
416        // SAFETY: `node` belongs to this exclusively borrowed graph, the zero-initialized parameters select a cloned child graph, both graphs stay live through the call, and retained resources cover the copied nodes.
417        unsafe {
418            try_ffi!(runtime::cudaGraphNodeSetParams(
419                node.as_raw(),
420                &raw mut params
421            ))
422        }
423    }
424
425    /// Changes the memset node `node` in the graph definition.
426    /// Existing executables keep their previous parameters until explicitly updated.
427    ///
428    /// # Safety
429    ///
430    /// The destination must uphold [`MemorySetNodeParams::new`] for every affected replay.
431    /// Retain previous destinations through existing executable launches.
432    ///
433    /// # Errors
434    ///
435    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph, or an error if the context cannot bind or CUDA rejects the node parameters.
436    pub unsafe fn set_memory_set_node_params(
437        &mut self,
438        node: &GraphNode,
439        params: &MemorySetNodeParams,
440    ) -> Result<()> {
441        self.check_node(node)?;
442        let params = params.into();
443        // SAFETY: `node` belongs to this exclusively borrowed graph, `params` lives through the call, and the caller vouches for the destination.
444        unsafe {
445            try_ffi!(runtime::cudaGraphMemsetNodeSetParams(
446                node.as_raw(),
447                &raw const params,
448            ))
449        }
450    }
451
452    /// Sets an attribute of the kernel node `node`.
453    ///
454    /// # Errors
455    ///
456    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
457    /// Also returns an error if `node` is not a kernel node, CUDA rejects the attribute update, or a previous asynchronous launch reports an error.
458    pub fn set_kernel_node_attribute(
459        &mut self,
460        node: &GraphNode,
461        attribute: GraphKernelNodeAttribute,
462    ) -> Result<()> {
463        self.check_node(node)?;
464        let (id, value) = match attribute {
465            GraphKernelNodeAttribute::Cooperative(value) => {
466                let mut attr = runtime::cudaLaunchAttributeValue {
467                    cooperative: runtime::__BindgenUnionField::new(),
468                    ..runtime::cudaLaunchAttributeValue::default()
469                };
470                // SAFETY: the attribute id set above selects this union field.
471                unsafe { *attr.cooperative.as_mut() = i32::from(value) };
472                (GraphKernelNodeAttributeId::Cooperative, attr)
473            }
474            GraphKernelNodeAttribute::ClusterDimension(value) => {
475                let mut attr = runtime::cudaLaunchAttributeValue {
476                    clusterDim: runtime::__BindgenUnionField::new(),
477                    ..runtime::cudaLaunchAttributeValue::default()
478                };
479                // SAFETY: the attribute id set above selects this union field.
480                unsafe {
481                    *attr.clusterDim.as_mut() = runtime::cudaLaunchAttributeValue__bindgen_ty_1 {
482                        x: value.x,
483                        y: value.y,
484                        z: value.z,
485                    };
486                }
487                (GraphKernelNodeAttributeId::ClusterDimension, attr)
488            }
489            GraphKernelNodeAttribute::Priority(value) => {
490                let mut attr = runtime::cudaLaunchAttributeValue {
491                    priority: runtime::__BindgenUnionField::new(),
492                    ..runtime::cudaLaunchAttributeValue::default()
493                };
494                // SAFETY: the attribute id set above selects this union field.
495                unsafe { *attr.priority.as_mut() = value };
496                (GraphKernelNodeAttributeId::Priority, attr)
497            }
498            GraphKernelNodeAttribute::PreferredSharedMemoryCarveout(value) => {
499                let mut attr = runtime::cudaLaunchAttributeValue {
500                    sharedMemCarveout: runtime::__BindgenUnionField::new(),
501                    ..runtime::cudaLaunchAttributeValue::default()
502                };
503                // SAFETY: the attribute id set above selects this union field.
504                unsafe { *attr.sharedMemCarveout.as_mut() = value };
505                (
506                    GraphKernelNodeAttributeId::PreferredSharedMemoryCarveout,
507                    attr,
508                )
509            }
510        };
511
512        // SAFETY: `node` belongs to this exclusively borrowed graph, and `value` lives through the call.
513        unsafe {
514            try_ffi!(runtime::cudaGraphKernelNodeSetAttribute(
515                node.as_raw(),
516                id.into(),
517                &raw const value,
518            ))
519        }
520    }
521
522    /// Copies the kernel attributes of `src` to `dst`, both kernel nodes of this graph.
523    ///
524    /// # Errors
525    ///
526    /// Returns `Error::GraphNodeMismatch` if either node belongs to another graph.
527    /// Also returns an error if CUDA rejects the attribute copy or a previous asynchronous launch reported an error.
528    pub fn copy_kernel_node_attributes(&mut self, dst: &GraphNode, src: &GraphNode) -> Result<()> {
529        self.check_node(dst)?;
530        self.check_node(src)?;
531        // SAFETY: both nodes belong to this exclusively borrowed graph.
532        unsafe {
533            try_ffi!(runtime::cudaGraphKernelNodeCopyAttributes(
534                dst.as_raw(),
535                src.as_raw()
536            ))
537        }
538    }
539
540    /// Sets an attribute of the kernel node `node` using the extended launch attribute representation.
541    ///
542    /// # Errors
543    ///
544    /// Returns `Error::GraphNodeMismatch` if `node` belongs to another graph.
545    /// Also propagates context-binding and CUDA kernel-node attribute errors, including an incompatible node type or unsupported attribute.
546    pub fn set_launch_attribute(
547        &mut self,
548        node: &GraphNode,
549        attribute: LaunchAttribute,
550    ) -> Result<()> {
551        self.check_node(node)?;
552        let attribute = attribute.raw();
553        // SAFETY: `node` belongs to this exclusively borrowed graph, and the attribute value lives through the call.
554        unsafe {
555            try_ffi!(driver::cuGraphKernelNodeSetAttribute(
556                node.as_raw(),
557                attribute.id,
558                &raw const attribute.value
559            ))
560        }
561    }
562}