pub mod contextual;
mod host_data;
pub mod memory;
pub mod owned;
pub mod raw;
mod retained_resource;
mod buffer;
mod definition;
mod executable;
mod node;
use std::{
any::Any,
cell::Cell,
collections::HashMap,
fmt::{self, Display, Formatter},
hash::{Hash, Hasher},
marker::PhantomData,
mem::MaybeUninit,
ops::Deref,
ptr,
result::Result as StdResult,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
};
use bitflags::parser;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use singe_core::{impl_enum_display, report_cleanup_failure};
use singe_cuda_sys::{driver, runtime};
pub use self::{
host_data::GraphHostBuffer,
retained_resource::{
GraphRetainedResource, collect_graph_resources, has_deferred_graph_resources,
},
};
use crate::{
context::Context,
dim::Dim3,
error::{Error, Result},
event::Event,
memory::{DeviceMemory, MemoryAccessDescriptor, MemoryPoolProps},
module::{CodeOwnerId, Module},
try_ffi,
types::DevicePtr,
view::{
DeviceOutput, DeviceRange, DeviceRegion, DeviceRegionProvider, DeviceRepr, DeviceSlice,
DeviceSliceMut,
},
};
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum GraphKernelNodeAttributeId: runtime::cudaLaunchAttributeID {
Cooperative = cudaLaunchAttributeCooperative,
ClusterDimension = cudaLaunchAttributeClusterDimension,
Priority = cudaLaunchAttributePriority,
PreferredSharedMemoryCarveout = cudaLaunchAttributePreferredSharedMemoryCarveout,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GraphKernelNodeAttribute {
Cooperative(
bool,
),
ClusterDimension(
Dim3,
),
Priority(
i32,
),
PreferredSharedMemoryCarveout(
u32,
),
}
#[derive(Debug, Clone)]
pub struct MemoryAllocationNodeInfo {
ptr: DevicePtr,
pub byte_size: usize,
graph_id: Option<GraphId>,
_graph: Option<Arc<GraphInner>>,
context: Option<Arc<Context>>,
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GraphInstantiateFlags: u64 {
const AUTO_FREE_ON_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH.0 as u64;
const UPLOAD = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD.0 as u64;
const DEVICE_LAUNCH = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH.0 as u64;
const USE_NODE_PRIORITY = driver::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY.0 as u64;
}
}
impl Display for GraphInstantiateFlags {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GraphDebugDotFlags: u32 {
const VERBOSE = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE.0;
const RUNTIME_TYPES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES.0;
const KERNEL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS.0;
const MEMCPY_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS.0;
const MEMSET_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS.0;
const HOST_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS.0;
const EVENT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EVENT_NODE_PARAMS.0;
const EXTERNAL_SEMAPHORE_SIGNAL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_SIGNAL_NODE_PARAMS.0;
const EXTERNAL_SEMAPHORE_WAIT_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_WAIT_NODE_PARAMS.0;
const KERNEL_NODE_ATTRIBUTES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES.0;
const HANDLES = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES.0;
const MEMORY_ALLOC_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS.0;
const MEMORY_FREE_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS.0;
const BATCH_MEM_OP_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_BATCH_MEM_OP_NODE_PARAMS.0;
const EXTRA_TOPOLOGY_INFO = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_EXTRA_TOPO_INFO.0;
const CONDITIONAL_NODE_PARAMS = driver::CUgraphDebugDot_flags::CU_GRAPH_DEBUG_DOT_FLAGS_CONDITIONAL_NODE_PARAMS.0;
}
}
impl Display for GraphDebugDotFlags {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum GraphNodeType {
Kernel = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_KERNEL.0,
Memcpy = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMCPY.0,
Memset = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEMSET.0,
Host = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_HOST.0,
Graph = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_GRAPH.0,
Empty = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EMPTY.0,
WaitEvent = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_WAIT_EVENT.0,
EventRecord = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EVENT_RECORD.0,
ExternalSemaphoresSignal = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL.0,
ExternalSemaphoresWait = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT.0,
MemoryAlloc = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_ALLOC.0,
MemoryFree = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_MEM_FREE.0,
BatchMemOp = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_BATCH_MEM_OP.0,
Conditional = driver::CUgraphNodeType::CU_GRAPH_NODE_TYPE_CONDITIONAL.0,
}
impl TryFrom<runtime::cudaGraphNodeType> for GraphNodeType {
type Error = Error;
fn try_from(value: runtime::cudaGraphNodeType) -> Result<Self> {
Self::try_from(value.0)
.map_err(|_| singe_core::UnknownEnumValue::new("GraphNodeType", value.0).into())
}
}
impl From<GraphNodeType> for runtime::cudaGraphNodeType {
fn from(value: GraphNodeType) -> Self {
match value {
GraphNodeType::Kernel => Self::CU_GRAPH_NODE_TYPE_KERNEL,
GraphNodeType::Memcpy => Self::CU_GRAPH_NODE_TYPE_MEMCPY,
GraphNodeType::Memset => Self::CU_GRAPH_NODE_TYPE_MEMSET,
GraphNodeType::Host => Self::CU_GRAPH_NODE_TYPE_HOST,
GraphNodeType::Graph => Self::CU_GRAPH_NODE_TYPE_GRAPH,
GraphNodeType::Empty => Self::CU_GRAPH_NODE_TYPE_EMPTY,
GraphNodeType::WaitEvent => Self::CU_GRAPH_NODE_TYPE_WAIT_EVENT,
GraphNodeType::EventRecord => Self::CU_GRAPH_NODE_TYPE_EVENT_RECORD,
GraphNodeType::ExternalSemaphoresSignal => Self::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL,
GraphNodeType::ExternalSemaphoresWait => Self::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT,
GraphNodeType::MemoryAlloc => Self::CU_GRAPH_NODE_TYPE_MEM_ALLOC,
GraphNodeType::MemoryFree => Self::CU_GRAPH_NODE_TYPE_MEM_FREE,
GraphNodeType::BatchMemOp => Self::CU_GRAPH_NODE_TYPE_BATCH_MEM_OP,
GraphNodeType::Conditional => Self::CU_GRAPH_NODE_TYPE_CONDITIONAL,
}
}
}
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u8)]
#[non_exhaustive]
pub enum GraphDependencyType: driver::CUgraphDependencyType {
Default = CU_GRAPH_DEPENDENCY_TYPE_DEFAULT,
Programmatic = CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC,
}
}
impl_enum_display!(GraphNodeType, {
Self::Kernel => "cudaGraphNodeTypeKernel",
Self::Memcpy => "cudaGraphNodeTypeMemcpy",
Self::Memset => "cudaGraphNodeTypeMemset",
Self::Host => "cudaGraphNodeTypeHost",
Self::Graph => "cudaGraphNodeTypeGraph",
Self::Empty => "cudaGraphNodeTypeEmpty",
Self::WaitEvent => "cudaGraphNodeTypeWaitEvent",
Self::EventRecord => "cudaGraphNodeTypeEventRecord",
Self::ExternalSemaphoresSignal => "cudaGraphNodeTypeExternalSemaphoresSignal",
Self::ExternalSemaphoresWait => "cudaGraphNodeTypeExternalSemaphoresWait",
Self::MemoryAlloc => "cudaGraphNodeTypeMemAlloc",
Self::MemoryFree => "cudaGraphNodeTypeMemFree",
Self::BatchMemOp => "cudaGraphNodeTypeBatchMemOp",
Self::Conditional => "cudaGraphNodeTypeConditional",
});
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum GraphExecUpdateResult: driver::CUgraphExecUpdateResult {
Success = CU_GRAPH_EXEC_UPDATE_SUCCESS,
Error = CU_GRAPH_EXEC_UPDATE_ERROR,
ErrorTopologyChanged = CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED,
ErrorNodeTypeChanged = CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED,
ErrorFunctionChanged = CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED,
ErrorParametersChanged = CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED,
ErrorNotSupported = CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED,
ErrorUnsupportedFunctionChange = CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE,
ErrorAttributesChanged = CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED,
}
}
impl_enum_display!(GraphExecUpdateResult, {
Self::Success => "CU_GRAPH_EXEC_UPDATE_SUCCESS",
Self::Error => "CU_GRAPH_EXEC_UPDATE_ERROR",
Self::ErrorTopologyChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED",
Self::ErrorNodeTypeChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED",
Self::ErrorFunctionChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED",
Self::ErrorParametersChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED",
Self::ErrorNotSupported => "CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED",
Self::ErrorUnsupportedFunctionChange => "CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE",
Self::ErrorAttributesChanged => "CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED",
});
#[derive(Debug, Clone)]
pub struct GraphNode {
handle: runtime::cudaGraphNode_t,
graph_id: Option<GraphId>,
graph: Option<Arc<GraphInner>>,
context: Option<Arc<Context>>,
}
impl PartialEq for GraphNode {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle && self.graph_id == other.graph_id
}
}
impl Eq for GraphNode {}
impl Hash for GraphNode {
fn hash<H: Hasher>(&self, state: &mut H) {
self.handle.hash(state);
self.graph_id.hash(state);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GraphEdgeAttributes {
pub from_port: u8,
pub to_port: u8,
pub dependency_type: GraphDependencyType,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GraphDependency {
pub node: GraphNode,
pub data: GraphEdgeAttributes,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GraphEdge {
pub from: GraphNode,
pub to: GraphNode,
pub data: GraphEdgeAttributes,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct GraphTopologySummary {
pub nodes: usize,
pub root_nodes: usize,
pub edges: usize,
pub kernel_nodes: usize,
pub memcpy_nodes: usize,
pub memset_nodes: usize,
pub host_nodes: usize,
pub child_graph_nodes: usize,
pub empty_nodes: usize,
pub wait_event_nodes: usize,
pub event_record_nodes: usize,
pub external_semaphores_signal_nodes: usize,
pub external_semaphores_wait_nodes: usize,
pub memory_alloc_nodes: usize,
pub memory_free_nodes: usize,
pub batch_mem_op_nodes: usize,
pub conditional_nodes: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
pub x: usize,
pub y: usize,
pub z: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Extent {
pub width: usize,
pub height: usize,
pub depth: usize,
}
#[derive(Debug, Clone)]
pub struct MemoryAllocationNodeParams<'a> {
pub pool_props: MemoryPoolProps,
pub access_descs: &'a [MemoryAccessDescriptor],
pub byte_size: usize,
}
impl Default for GraphEdgeAttributes {
fn default() -> Self {
Self {
from_port: 0,
to_port: 0,
dependency_type: GraphDependencyType::Default,
}
}
}
impl From<runtime::cudaGraphEdgeData> for GraphEdgeAttributes {
fn from(value: runtime::cudaGraphEdgeData) -> Self {
Self {
from_port: value.from_port,
to_port: value.to_port,
dependency_type: GraphDependencyType::try_from(value.type_)
.unwrap_or(GraphDependencyType::Default),
}
}
}
impl From<GraphEdgeAttributes> for runtime::cudaGraphEdgeData {
fn from(value: GraphEdgeAttributes) -> Self {
Self {
from_port: value.from_port,
to_port: value.to_port,
type_: value.dependency_type.into(),
reserved: [0; 5],
}
}
}
impl From<Position> for runtime::cudaPos {
fn from(value: Position) -> Self {
Self {
x: value.x as _,
y: value.y as _,
z: value.z as _,
}
}
}
impl From<Extent> for runtime::cudaExtent {
fn from(value: Extent) -> Self {
Self {
width: value.width as _,
height: value.height as _,
depth: value.depth as _,
}
}
}
impl MemoryAllocationNodeInfo {
#[must_use]
pub const fn ptr(&self) -> DevicePtr {
self.ptr
}
#[must_use]
pub fn context(&self) -> Option<&Arc<Context>> {
self.context.as_ref()
}
fn from_raw_in_graph(
ptr: DevicePtr,
byte_size: usize,
graph_id: GraphId,
graph: Arc<GraphInner>,
context: Option<Arc<Context>>,
) -> Self {
Self::from_raw(ptr, byte_size, Some(graph_id), Some(graph), context)
}
fn from_raw(
ptr: DevicePtr,
byte_size: usize,
graph_id: Option<GraphId>,
graph: Option<Arc<GraphInner>>,
context: Option<Arc<Context>>,
) -> Self {
Self {
ptr,
byte_size,
graph_id,
_graph: graph,
context,
}
}
}
impl PartialEq for MemoryAllocationNodeInfo {
fn eq(&self, other: &Self) -> bool {
self.ptr == other.ptr
&& self.byte_size == other.byte_size
&& self.graph_id == other.graph_id
}
}
impl Eq for MemoryAllocationNodeInfo {}
impl Hash for MemoryAllocationNodeInfo {
fn hash<H: Hasher>(&self, state: &mut H) {
self.ptr.hash(state);
self.byte_size.hash(state);
self.graph_id.hash(state);
}
}
impl GraphTopologySummary {
fn record_node_type(&mut self, node_type: GraphNodeType) {
match node_type {
GraphNodeType::Kernel => self.kernel_nodes += 1,
GraphNodeType::Memcpy => self.memcpy_nodes += 1,
GraphNodeType::Memset => self.memset_nodes += 1,
GraphNodeType::Host => self.host_nodes += 1,
GraphNodeType::Graph => self.child_graph_nodes += 1,
GraphNodeType::Empty => self.empty_nodes += 1,
GraphNodeType::WaitEvent => self.wait_event_nodes += 1,
GraphNodeType::EventRecord => self.event_record_nodes += 1,
GraphNodeType::ExternalSemaphoresSignal => {
self.external_semaphores_signal_nodes += 1;
}
GraphNodeType::ExternalSemaphoresWait => {
self.external_semaphores_wait_nodes += 1;
}
GraphNodeType::MemoryAlloc => self.memory_alloc_nodes += 1,
GraphNodeType::MemoryFree => self.memory_free_nodes += 1,
GraphNodeType::BatchMemOp => self.batch_mem_op_nodes += 1,
GraphNodeType::Conditional => self.conditional_nodes += 1,
}
}
}
#[derive(Debug)]
pub struct Graph {
inner: Arc<GraphInner>,
id: GraphId,
context: Arc<Context>,
_not_sync: PhantomData<Cell<()>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GraphId(u64);
#[derive(Debug)]
pub struct UnboundGraph {
inner: Arc<GraphInner>,
}
#[derive(Debug)]
pub struct RawGraph {
pub handle: runtime::cudaGraph_t,
pub context: Arc<Context>,
pub retained: RetainedResources,
pub id: GraphId,
}
#[derive(Debug)]
pub struct RawExecutableGraph {
pub handle: runtime::cudaGraphExec_t,
pub context: Arc<Context>,
pub retained: RetainedResources,
pub source_graph: Option<UnboundGraph>,
pub source_graph_id: Option<GraphId>,
}
unsafe impl Send for RawGraph {}
unsafe impl Sync for RawGraph {}
unsafe impl Send for RawExecutableGraph {}
unsafe impl Sync for RawExecutableGraph {}
#[derive(Debug)]
pub(crate) struct GraphInner {
handle: runtime::cudaGraph_t,
owns_handle: bool,
context: Option<Arc<Context>>,
retained: Mutex<RetainedResources>,
parent: Option<Arc<Self>>,
}
unsafe impl Send for GraphInner {}
unsafe impl Sync for GraphInner {}
#[derive(Clone)]
pub(crate) struct RetainedAllocation(Arc<dyn Any + Send + Sync>);
impl fmt::Debug for RetainedAllocation {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("RetainedAllocation")
.field("strong_count", &Arc::strong_count(&self.0))
.finish()
}
}
#[derive(Debug, Clone, Default)]
pub struct RetainedResources {
allocations: HashMap<usize, RetainedAllocation>,
modules: HashMap<CodeOwnerId, Module>,
events: HashMap<usize, Arc<Event>>,
}
impl RetainedResources {
fn retain_event(&mut self, event: &Arc<Event>) {
self.events
.entry(Arc::as_ptr(event).addr())
.or_insert_with(|| Arc::clone(event));
}
fn retain_allocation(&mut self, allocation: RetainedAllocation) {
let identity = Arc::as_ptr(&allocation.0).cast::<()>().addr();
self.allocations.entry(identity).or_insert(allocation);
}
fn retain_module(&mut self, module: &Module) {
self.modules
.entry(module.code_owner_id())
.or_insert_with(|| module.clone());
}
fn extend(&mut self, other: Self) {
self.allocations.extend(other.allocations);
self.modules.extend(other.modules);
self.events.extend(other.events);
}
}
#[derive(Debug)]
pub struct BorrowedGraph<'graph> {
graph: Graph,
_graph: PhantomData<&'graph Graph>,
}
#[derive(Debug)]
pub struct GraphBuffer<T: DeviceRepr> {
memory: DeviceMemory<T>,
}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for GraphBuffer<T> {
fn region(&self) -> DeviceRegion<'_> {
self.memory.region()
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for GraphBuffer<T> {
fn as_device_ptr(&self) -> *const T {
self.memory.as_ptr()
}
fn len(&self) -> usize {
self.memory.len()
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for GraphBuffer<T> {}
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for GraphBuffer<T> {}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for GraphBuffer<T> {
fn as_mut_ptr(&mut self) -> *mut T {
self.memory.as_mut_ptr()
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for GraphBuffer<MaybeUninit<T>> {
fn len(&self) -> usize {
self.memory.len()
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for GraphBuffer<MaybeUninit<T>> {
fn as_mut_ptr(&mut self) -> *mut T {
self.memory.as_mut_ptr().cast()
}
}
impl UnboundGraph {
pub unsafe fn from_raw(handle: runtime::cudaGraph_t) -> Result<Self> {
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(Self {
inner: Arc::new(GraphInner {
handle,
owns_handle: true,
context: None,
retained: Mutex::new(RetainedResources::default()),
parent: None,
}),
})
}
pub unsafe fn create() -> Result<Self> {
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(runtime::cudaGraphCreate(&raw mut handle, 0))?;
}
unsafe { Self::from_raw(handle) }
}
#[must_use]
pub fn as_raw(&self) -> runtime::cudaGraph_t {
self.inner.handle
}
pub fn into_raw(self) -> StdResult<runtime::cudaGraph_t, Self> {
match Arc::try_unwrap(self.inner) {
Ok(mut inner) => {
inner.owns_handle = false;
Ok(inner.handle)
}
Err(inner) => Err(Self { inner }),
}
}
}
static NEXT_GRAPH_ID: AtomicU64 = AtomicU64::new(1);
impl GraphId {
pub fn generate() -> Self {
Self(NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed))
}
#[must_use]
pub fn as_u64(self) -> u64 {
self.0
}
}
impl Display for GraphId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl Drop for GraphInner {
fn drop(&mut self) {
if !self.owns_handle {
return;
}
if let Some(context) = &self.context
&& let Err(error) = context.bind()
{
report_cleanup_failure("bind the cuda context to destroy", "cuda graph", &error);
return;
}
unsafe {
if let Err(error) = try_ffi!(runtime::cudaGraphDestroy(self.handle)) {
report_cleanup_failure("destroy", "cuda graph", &error);
}
}
}
}
impl BorrowedGraph<'_> {
pub unsafe fn from_raw(handle: runtime::cudaGraph_t, context: Arc<Context>) -> Result<Self> {
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(Self {
graph: unsafe { Graph::from_raw_borrowed_in_context(handle, context) },
_graph: PhantomData,
})
}
#[must_use]
pub const fn as_graph(&self) -> &Graph {
&self.graph
}
#[must_use]
pub fn as_raw(&self) -> runtime::cudaGraph_t {
self.graph.as_raw()
}
}
impl Deref for BorrowedGraph<'_> {
type Target = Graph;
fn deref(&self) -> &Self::Target {
self.as_graph()
}
}
#[derive(Debug)]
pub struct ExecutableGraph {
handle: runtime::cudaGraphExec_t,
context: Arc<Context>,
source_graph_id: Option<GraphId>,
source_graph: Option<Arc<GraphInner>>,
retained: RetainedResources,
}
#[derive(Debug)]
pub struct UnboundExecutableGraph {
handle: runtime::cudaGraphExec_t,
}
impl Drop for UnboundExecutableGraph {
fn drop(&mut self) {
unsafe {
if let Err(error) = try_ffi!(runtime::cudaGraphExecDestroy(self.handle)) {
report_cleanup_failure("destroy", "cuda executable graph", &error);
}
}
}
}
unsafe impl Send for ExecutableGraph {}
impl Drop for ExecutableGraph {
fn drop(&mut self) {
if let Err(error) = self.bind_context() {
report_cleanup_failure(
"bind the cuda context to destroy",
"cuda executable graph",
&error,
);
return;
}
unsafe {
if let Err(error) = try_ffi!(runtime::cudaGraphExecDestroy(self.handle)) {
report_cleanup_failure("destroy", "cuda executable graph", &error);
}
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GraphUpdateError {
#[error("cuda rejected the executable graph update ({result})")]
Rejected {
result: GraphExecUpdateResult,
error_node: Option<GraphNode>,
error_from_node: Option<GraphNode>,
},
#[error(transparent)]
Cuda(#[from] Error),
}
#[derive(Debug, Clone, Copy)]
pub struct MemorySetNodeParams {
dst: DevicePtr,
pitch: usize,
value: u32,
element_size: u32,
width: usize,
height: usize,
}
impl MemorySetNodeParams {
#[must_use]
pub const unsafe fn new(dst: DevicePtr, element_size: u32, width: usize) -> Self {
Self {
dst,
pitch: 0,
value: 0,
element_size,
width,
height: 1,
}
}
#[must_use]
pub const fn with_pitch(mut self, pitch: usize) -> Self {
self.pitch = pitch;
self
}
#[must_use]
pub const fn with_value(mut self, value: u32) -> Self {
self.value = value;
self
}
#[must_use]
pub const fn with_height(mut self, height: usize) -> Self {
self.height = height;
self
}
#[must_use]
pub const fn dst(self) -> DevicePtr {
self.dst
}
#[must_use]
pub const fn pitch(self) -> usize {
self.pitch
}
#[must_use]
pub const fn value(self) -> u32 {
self.value
}
#[must_use]
pub const fn element_size(self) -> u32 {
self.element_size
}
#[must_use]
pub const fn width(self) -> usize {
self.width
}
#[must_use]
pub const fn height(self) -> usize {
self.height
}
}
impl From<&MemorySetNodeParams> for driver::CUDA_MEMSET_NODE_PARAMS {
fn from(value: &MemorySetNodeParams) -> Self {
Self {
dst: value.dst().addr() as _,
pitch: value.pitch() as _,
value: value.value(),
elementSize: value.element_size(),
width: value.width() as _,
height: value.height() as _,
}
}
}
impl_enum_display!(GraphKernelNodeAttributeId, {
GraphKernelNodeAttributeId::Cooperative => "cudaLaunchAttributeCooperative",
GraphKernelNodeAttributeId::ClusterDimension => "cudaLaunchAttributeClusterDimension",
GraphKernelNodeAttributeId::Priority => "cudaLaunchAttributePriority",
GraphKernelNodeAttributeId::PreferredSharedMemoryCarveout => "cudaLaunchAttributePreferredSharedMemoryCarveout",
});
impl_enum_display!(GraphDependencyType, {
GraphDependencyType::Default => "CU_GRAPH_DEPENDENCY_TYPE_DEFAULT",
GraphDependencyType::Programmatic => "CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC",
});