1pub 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
62 #[repr(u32)]
63 #[non_exhaustive]
64 pub enum GraphKernelNodeAttributeId: runtime::cudaLaunchAttributeID {
65 Cooperative = cudaLaunchAttributeCooperative,
67 ClusterDimension = cudaLaunchAttributeClusterDimension,
69 Priority = cudaLaunchAttributePriority,
71 PreferredSharedMemoryCarveout = cudaLaunchAttributePreferredSharedMemoryCarveout,
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80#[non_exhaustive]
81pub enum GraphKernelNodeAttribute {
82 Cooperative(
84 bool,
86 ),
87 ClusterDimension(
89 Dim3,
91 ),
92 Priority(
94 i32,
96 ),
97 PreferredSharedMemoryCarveout(
99 u32,
101 ),
102}
103
104#[derive(Debug, Clone)]
109pub struct MemoryAllocationNodeInfo {
110 ptr: DevicePtr,
111 pub byte_size: usize,
113 graph_id: Option<GraphId>,
114 _graph: Option<Arc<GraphInner>>,
115 context: Option<Arc<Context>>,
116}
117
118bitflags::bitflags! {
119 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121 pub struct GraphInstantiateFlags: u64 {
122 const AUTO_FREE_ON_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH.0 as u64;
124 const UPLOAD = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD.0 as u64;
128 const DEVICE_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH.0 as u64;
133 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147 pub struct GraphDebugDotFlags: u32 {
148 const VERBOSE = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE.0;
150 const RUNTIME_TYPES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES.0;
152 const KERNEL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS.0;
154 const MEMCPY_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS.0;
156 const MEMSET_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS.0;
158 const HOST_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS.0;
160 const EVENT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EVENT_NODE_PARAMS.0;
162 const EXTERNAL_SEMAPHORE_SIGNAL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_SIGNAL_NODE_PARAMS.0;
164 const EXTERNAL_SEMAPHORE_WAIT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_WAIT_NODE_PARAMS.0;
166 const KERNEL_NODE_ATTRIBUTES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES.0;
168 const HANDLES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES.0;
170 const MEMORY_ALLOC_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS.0;
172 const MEMORY_FREE_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS.0;
174 const BATCH_MEM_OP_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_BATCH_MEM_OP_NODE_PARAMS.0;
176 const EXTRA_TOPOLOGY_INFO = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXTRA_TOPO_INFO.0;
178 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
191#[repr(u32)]
192#[non_exhaustive]
193pub enum GraphNodeType {
194 Kernel = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_KERNEL.0,
196 Memcpy = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMCPY.0,
198 Memset = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMSET.0,
200 Host = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_HOST.0,
202 Graph = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_GRAPH.0,
204 Empty = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EMPTY.0,
206 WaitEvent = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_WAIT_EVENT.0,
208 EventRecord = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EVENT_RECORD.0,
210 ExternalSemaphoresSignal = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL.0,
212 ExternalSemaphoresWait = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT.0,
214 MemoryAlloc = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_ALLOC.0,
216 MemoryFree = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_FREE.0,
218 BatchMemOp = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_BATCH_MEM_OP.0,
220 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
257 #[repr(u8)]
258 #[non_exhaustive]
259 pub enum GraphDependencyType: driver::CUgraphDependencyType {
260 Default = CU_GRAPH_DEPENDENCY_TYPE_DEFAULT,
262 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
289 #[repr(u32)]
290 #[non_exhaustive]
291 pub enum GraphExecUpdateResult: driver::CUgraphExecUpdateResult {
292 Success = CU_GRAPH_EXEC_UPDATE_SUCCESS,
294 Error = CU_GRAPH_EXEC_UPDATE_ERROR,
296 ErrorTopologyChanged = CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED,
298 ErrorNodeTypeChanged = CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED,
300 ErrorFunctionChanged = CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED,
302 ErrorParametersChanged = CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED,
304 ErrorNotSupported = CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED,
306 ErrorUnsupportedFunctionChange = CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE,
308 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354pub struct GraphEdgeAttributes {
355 pub from_port: u8,
357 pub to_port: u8,
359 pub dependency_type: GraphDependencyType,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq, Hash)]
365pub struct GraphDependency {
366 pub node: GraphNode,
368 pub data: GraphEdgeAttributes,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Hash)]
374pub struct GraphEdge {
375 pub from: GraphNode,
377 pub to: GraphNode,
379 pub data: GraphEdgeAttributes,
381}
382
383#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
385pub struct GraphTopologySummary {
386 pub nodes: usize,
388 pub root_nodes: usize,
390 pub edges: usize,
392 pub kernel_nodes: usize,
394 pub memcpy_nodes: usize,
396 pub memset_nodes: usize,
398 pub host_nodes: usize,
400 pub child_graph_nodes: usize,
402 pub empty_nodes: usize,
404 pub wait_event_nodes: usize,
406 pub event_record_nodes: usize,
408 pub external_semaphores_signal_nodes: usize,
410 pub external_semaphores_wait_nodes: usize,
412 pub memory_alloc_nodes: usize,
414 pub memory_free_nodes: usize,
416 pub batch_mem_op_nodes: usize,
418 pub conditional_nodes: usize,
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
426pub struct Position {
427 pub x: usize,
429 pub y: usize,
431 pub z: usize,
433}
434
435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
439pub struct Extent {
440 pub width: usize,
442 pub height: usize,
444 pub depth: usize,
446}
447
448#[derive(Debug, Clone)]
450pub struct MemoryAllocationNodeParams<'a> {
451 pub pool_props: MemoryPoolProps,
453 pub access_descs: &'a [MemoryAccessDescriptor],
455 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 #[must_use]
514 pub const fn ptr(&self) -> DevicePtr {
515 self.ptr
516 }
517
518 #[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#[derive(Debug)]
599pub struct Graph {
600 inner: Arc<GraphInner>,
601 id: GraphId,
602 context: Arc<Context>,
603 _not_sync: PhantomData<Cell<()>>,
604}
605
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
608pub struct GraphId(u64);
609
610#[derive(Debug)]
614pub struct UnboundGraph {
615 inner: Arc<GraphInner>,
616}
617
618#[derive(Debug)]
623pub struct RawGraph {
624 pub handle: runtime::cudaGraph_t,
626 pub context: Arc<Context>,
628 pub retained: RetainedResources,
630 pub id: GraphId,
632}
633
634#[derive(Debug)]
639pub struct RawExecutableGraph {
640 pub handle: runtime::cudaGraphExec_t,
642 pub context: Arc<Context>,
644 pub retained: RetainedResources,
646 pub source_graph: Option<UnboundGraph>,
648 pub source_graph_id: Option<GraphId>,
650}
651
652unsafe impl Send for RawGraph {}
654
655unsafe impl Sync for RawGraph {}
657
658unsafe impl Send for RawExecutableGraph {}
660
661unsafe 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
673unsafe impl Send for GraphInner {}
675
676unsafe 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#[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#[derive(Debug)]
729pub struct BorrowedGraph<'graph> {
730 graph: Graph,
731 _graph: PhantomData<&'graph Graph>,
732}
733
734#[derive(Debug)]
740pub struct GraphBuffer<T: DeviceRepr> {
741 memory: DeviceMemory<T>,
742}
743
744unsafe impl<T: DeviceRepr> DeviceRegionProvider for GraphBuffer<T> {
746 fn region(&self) -> DeviceRegion<'_> {
747 self.memory.region()
748 }
749}
750
751unsafe 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
762unsafe impl<T: DeviceRepr> DeviceSlice<T> for GraphBuffer<T> {}
764
765unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for GraphBuffer<T> {}
767
768unsafe 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
775unsafe impl<T: DeviceRepr> DeviceRange<T> for GraphBuffer<MaybeUninit<T>> {
777 fn len(&self) -> usize {
778 self.memory.len()
779 }
780}
781
782unsafe 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 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 pub unsafe fn create() -> Result<Self> {
830 let mut handle = ptr::null_mut();
831 unsafe {
833 try_ffi!(runtime::cudaGraphCreate(&raw mut handle, 0))?;
834 }
835 unsafe { Self::from_raw(handle) }
837 }
838
839 #[must_use]
841 pub fn as_raw(&self) -> runtime::cudaGraph_t {
842 self.inner.handle
843 }
844
845 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 pub fn generate() -> Self {
868 Self(NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed))
869 }
870
871 #[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 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 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 graph: unsafe { Graph::from_raw_borrowed_in_context(handle, context) },
924 _graph: PhantomData,
925 })
926 }
927
928 #[must_use]
930 pub const fn as_graph(&self) -> &Graph {
931 &self.graph
932 }
933
934 #[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#[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#[derive(Debug)]
963pub struct UnboundExecutableGraph {
964 handle: runtime::cudaGraphExec_t,
965}
966
967impl Drop for UnboundExecutableGraph {
968 fn drop(&mut self) {
969 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
978unsafe 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 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#[derive(Debug, thiserror::Error)]
1002#[non_exhaustive]
1003pub enum GraphUpdateError {
1004 #[error("cuda rejected the executable graph update ({result})")]
1006 Rejected {
1007 result: GraphExecUpdateResult,
1009 error_node: Option<GraphNode>,
1011 error_from_node: Option<GraphNode>,
1013 },
1014 #[error(transparent)]
1016 Cuda(#[from] Error),
1017}
1018
1019#[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 #[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 #[must_use]
1054 pub const fn with_pitch(mut self, pitch: usize) -> Self {
1055 self.pitch = pitch;
1056 self
1057 }
1058
1059 #[must_use]
1061 pub const fn with_value(mut self, value: u32) -> Self {
1062 self.value = value;
1063 self
1064 }
1065
1066 #[must_use]
1068 pub const fn with_height(mut self, height: usize) -> Self {
1069 self.height = height;
1070 self
1071 }
1072
1073 #[must_use]
1075 pub const fn dst(self) -> DevicePtr {
1076 self.dst
1077 }
1078
1079 #[must_use]
1081 pub const fn pitch(self) -> usize {
1082 self.pitch
1083 }
1084
1085 #[must_use]
1087 pub const fn value(self) -> u32 {
1088 self.value
1089 }
1090
1091 #[must_use]
1093 pub const fn element_size(self) -> u32 {
1094 self.element_size
1095 }
1096
1097 #[must_use]
1099 pub const fn width(self) -> usize {
1100 self.width
1101 }
1102
1103 #[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});