1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Graph nodes with explicit normal or green execution contexts.
use std::{ptr, rc::Rc, slice, sync::Arc};
use singe_core::{impl_enum_display, report_cleanup_failure};
use singe_cuda_sys::driver as sys;
use crate::{
context::Context,
driver::entry_points::{cuGraphAddNode_v3, cuGraphNodeSetParams_v2},
error::{Error, Result},
event::Event,
graph::{ExecutableGraph, Graph, GraphInstantiateFlags, GraphNode, raw::HostNodeParams},
green::{GreenContext, GreenStream},
module::{KernelLaunchArgs, LaunchConfig},
semaphore::ExternalSemaphore,
stream::Stream,
try_ffi,
types::DeviceFunction,
};
/// Preferred execution context of a graph node.
#[derive(Debug, Clone)]
pub enum ExecutionContext {
/// An ordinary CUDA context.
Context(Arc<Context>),
/// A green context with provisioned GPU resources.
Green(Rc<GreenContext>),
}
impl ExecutionContext {
fn raw(&self) -> sys::CUcontext {
match self {
Self::Context(context) => context.as_raw(),
Self::Green(context) => context.as_raw().cast(),
}
}
fn kernel_context(&self) -> Result<sys::CUcontext> {
match self {
Self::Context(context) => Ok(context.as_raw()),
Self::Green(context) => context.context_handle(),
}
}
}
/// Node parameters whose resources are retained by contextual graphs.
#[derive(Debug, Clone)]
pub enum NodeParameters {
/// Function and user data to call when the node executes.
Host {
/// Native callback and borrowed user-data pointer.
parameters: HostNodeParams,
/// Blocking or spinning behavior of the host-task execution thread.
synchronization_mode: HostTaskSyncMode,
},
/// Event to record when the node executes.
EventRecord(Rc<Event>),
/// External semaphore and fence value to signal.
SemaphoreSignal {
/// External semaphore retained through graph execution.
semaphore: Rc<ExternalSemaphore>,
/// Timeline fence value to signal.
value: u64,
},
/// External semaphore and fence value to wait for.
SemaphoreWait {
/// External semaphore retained through graph execution.
semaphore: Rc<ExternalSemaphore>,
/// Timeline fence value required before dependent graph work can proceed.
value: u64,
},
}
impl NodeParameters {
fn with_raw<T>(
&self,
context: &ExecutionContext,
f: impl FnOnce(&mut sys::CUgraphNodeParams) -> Result<T>,
) -> Result<T> {
let mut raw = sys::CUgraphNodeParams::default();
let mut semaphore_handle;
let mut signal = sys::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::default();
let mut wait = sys::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::default();
match self {
Self::Host {
parameters,
synchronization_mode,
} => {
raw.type_ = sys::CUgraphNodeType::CU_GRAPH_NODE_TYPE_HOST;
raw.__bindgen_anon_1.host = sys::CUDA_HOST_NODE_PARAMS_v2 {
fn_: parameters.function().as_raw(),
userData: parameters.user_data().cast(),
syncMode: *synchronization_mode as u32,
__bindgen_anon_1: sys::CUDA_HOST_NODE_PARAMS_v2_st__bindgen_ty_1 {
ctx: context.raw(),
},
};
}
Self::EventRecord(event) => {
raw.type_ = sys::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EVENT_RECORD;
raw.__bindgen_anon_1.eventRecord = sys::CUDA_EVENT_RECORD_NODE_PARAMS {
event: event.as_raw(),
__bindgen_anon_1: sys::CUDA_EVENT_RECORD_NODE_PARAMS_st__bindgen_ty_1 {
ctx: context.raw(),
},
};
}
Self::SemaphoreSignal { semaphore, value } => {
semaphore_handle = semaphore.as_raw();
signal.params.fence.value = *value;
raw.type_ = sys::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL;
raw.__bindgen_anon_1.extSemSignal = sys::CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 {
extSemArray: &raw mut semaphore_handle,
paramsArray: &raw const signal,
numExtSems: 1,
__bindgen_anon_1: sys::CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2_st__bindgen_ty_1 {
ctx: context.raw(),
},
};
}
Self::SemaphoreWait { semaphore, value } => {
semaphore_handle = semaphore.as_raw();
wait.params.fence.value = *value;
raw.type_ = sys::CUgraphNodeType::CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT;
raw.__bindgen_anon_1.extSemWait = sys::CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 {
extSemArray: &raw mut semaphore_handle,
paramsArray: &raw const wait,
numExtSems: 1,
__bindgen_anon_1: sys::CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2_st__bindgen_ty_1 {
ctx: context.raw(),
},
};
}
}
f(&mut raw)
}
}
/// A node retaining its chosen context and external resources.
#[derive(Debug, Clone)]
pub struct ContextNode {
node: GraphNode,
context: ExecutionContext,
parameters: Option<NodeParameters>,
}
impl ContextNode {
/// Returns the borrowed native node handle without independently retaining its graph.
#[must_use]
pub fn as_raw(&self) -> sys::CUgraphNode {
self.node.as_raw()
}
}
/// A graph that may retain thread-affine green contexts.
#[derive(Debug)]
pub struct ContextGraph {
graph: Graph,
nodes: Vec<ContextNode>,
}
impl ContextGraph {
/// Creates an empty graph in `context` for nodes with explicit ordinary or green execution contexts.
///
/// # Errors
///
/// Propagates context binding and native graph creation errors from [`Context::create_graph`].
pub fn create(context: &Arc<Context>) -> Result<Self> {
Ok(Self {
graph: context.create_graph()?,
nodes: Vec::new(),
})
}
/// Creates a new node described by its type-specific parameters.
///
/// # Safety
///
/// Host callbacks and their data must remain valid for every execution.
/// Callbacks must not call CUDA.
/// External resources must not be destroyed or manipulated through raw handles while referenced by the graph.
///
/// # Errors
///
/// Returns an error for dependencies belonging to another graph, an unavailable driver entry point, or a native node-creation failure such as incompatible parameters or execution context.
/// Context and resource owners are retained only after creation succeeds.
pub unsafe fn add_node(
&mut self,
context: ExecutionContext,
dependencies: &[ContextNode],
parameters: NodeParameters,
) -> Result<ContextNode> {
let dependencies = dependencies
.iter()
.map(|n| n.node.clone())
.collect::<Vec<_>>();
self.graph.check_nodes(&dependencies)?;
let handles = dependencies
.iter()
.map(GraphNode::as_raw)
.collect::<Vec<_>>();
let mut handle = ptr::null_mut();
// SAFETY: `handle` is a local output, `handles` lives across the call with its length passed alongside, `&mut self` gives exclusive access to the graph, and the caller keeps the callbacks and external resources in `raw` valid for every execution.
parameters.with_raw(&context, |raw| unsafe {
cuGraphAddNode_v3(
&raw mut handle,
self.graph.as_raw(),
handles.as_ptr(),
ptr::null(),
handles.len() as _,
raw,
)
})?;
let node = ContextNode {
node: self.graph.node_from_raw(handle),
context,
parameters: Some(parameters),
};
self.nodes.push(node.clone());
Ok(node)
}
/// Updates a node's type-specific parameters and preferred context.
///
/// # Safety
///
/// The callback and data lifetime requirements of `add_node` also apply.
///
/// # Errors
///
/// Returns an error if `node` belongs to another graph, the driver entry point is unavailable, or CUDA rejects the parameter or execution-context change.
/// Retained node parameters change only after native success.
pub unsafe fn set_node_parameters(
&mut self,
node: &mut ContextNode,
context: ExecutionContext,
parameters: NodeParameters,
) -> Result<()> {
self.graph.check_nodes(slice::from_ref(&node.node))?;
// SAFETY: `check_nodes` confirmed `node` belongs to this graph, `&mut self` gives exclusive access to it, and the caller keeps the callbacks and external resources in `raw` valid for every execution.
parameters.with_raw(&context, |raw| unsafe {
cuGraphNodeSetParams_v2(node.as_raw(), raw)
})?;
node.context = context;
node.parameters = Some(parameters);
if let Some(retained) = self.nodes.iter_mut().find(|n| n.node == node.node) {
*retained = node.clone();
}
Ok(())
}
/// Adds a kernel node with an explicit execution context.
///
/// # Safety
///
/// Arguments must match the function ABI and satisfy its value and access requirements.
/// The function must be valid in `context` and its code owner must outlive every queued execution.
/// Pointed-to storage must remain valid for every execution, with exclusive writable access.
///
/// # Errors
///
/// Returns an error for dependencies belonging to another graph, an unavailable driver entry point, a failed green-context conversion, or CUDA rejecting the kernel node or launch attributes.
/// If setting an attribute fails after creation, cleanup attempts to destroy the new native node.
pub unsafe fn add_kernel<'a, P: KernelLaunchArgs<'a>>(
&mut self,
context: ExecutionContext,
dependencies: &[ContextNode],
function: DeviceFunction,
config: &LaunchConfig,
parameters: P,
) -> Result<ContextNode> {
let dependencies = dependencies
.iter()
.map(|n| n.node.clone())
.collect::<Vec<_>>();
self.graph.check_nodes(&dependencies)?;
let handles = dependencies
.iter()
.map(GraphNode::as_raw)
.collect::<Vec<_>>();
let mut handle = ptr::null_mut();
let kernel_context = context.kernel_context()?;
// SAFETY: `arguments` outlives the call that copies it into the node, `handles` lives across the call with its length passed alongside, `&mut self` gives exclusive access to the graph, and the caller guarantees the function, arguments, and their storage match and stay valid in `context`.
parameters.with_encoded_arguments(|mut arguments| unsafe {
let mut raw = sys::CUgraphNodeParams {
type_: sys::CUgraphNodeType::CU_GRAPH_NODE_TYPE_KERNEL,
..Default::default()
};
raw.__bindgen_anon_1.kernel = sys::CUDA_KERNEL_NODE_PARAMS_v3 {
func: function.as_raw(),
gridDimX: config.grid_dim().x,
gridDimY: config.grid_dim().y,
gridDimZ: config.grid_dim().z,
blockDimX: config.block_dim().x,
blockDimY: config.block_dim().y,
blockDimZ: config.block_dim().z,
sharedMemBytes: config.shared_memory_bytes_u32(),
kernelParams: arguments.as_mut_ptr().cast(),
ctx: kernel_context,
..Default::default()
};
cuGraphAddNode_v3(
&raw mut handle,
self.graph.as_raw(),
handles.as_ptr(),
ptr::null(),
handles.len() as _,
&raw mut raw,
)
})?;
let node = ContextNode {
node: self.graph.node_from_raw(handle),
context,
parameters: None,
};
for attribute in config.attributes() {
if let Err(error) = self.graph.set_launch_attribute(&node.node, *attribute) {
// SAFETY: `handle` is the node just added to this exclusively borrowed graph, and nothing else refers to it yet.
if let Err(destroy_error) = unsafe { try_ffi!(sys::cuGraphDestroyNode(handle)) } {
report_cleanup_failure("destroy", "cuda graph node", &destroy_error);
}
return Err(error);
}
}
self.nodes.push(node.clone());
Ok(node)
}
/// Instantiates the graph, retaining its execution contexts and resources.
///
/// # Errors
///
/// Propagates native graph-instantiation errors from [`Graph::instantiate`], including invalid nodes, incompatible contexts, or unsupported instantiation flags.
pub fn instantiate(&self, flags: GraphInstantiateFlags) -> Result<ContextExecutableGraph> {
Ok(ContextExecutableGraph {
executable: self.graph.instantiate(flags)?,
nodes: self.nodes.clone(),
})
}
}
/// An executable graph retaining thread-affine contexts and external resources.
#[derive(Debug)]
pub struct ContextExecutableGraph {
executable: ExecutableGraph,
nodes: Vec<ContextNode>,
}
impl ContextExecutableGraph {
/// Enqueues the retained executable on an ordinary CUDA stream.
///
/// # Safety
///
/// Retain node storage and exclude conflicting accesses through completion.
///
/// # Errors
///
/// Propagates stream-context validation, context binding, and native launch errors from [`ExecutableGraph::launch_async`].
pub unsafe fn launch_async(&self, stream: &Stream) -> Result<()> {
// SAFETY: the caller retains node storage and excludes conflicting accesses through completion, as `ExecutableGraph::launch_async` requires.
unsafe { self.executable.launch_async(stream) }
}
/// Enqueues the retained executable on a green-context stream.
///
/// # Safety
///
/// Retain node storage and exclude conflicting accesses through completion.
///
/// # Errors
///
/// Returns `Error::StreamContextMismatch` unless the graph belongs to the primary context of the green context's device.
/// Also returns an error if the context cannot be bound or CUDA rejects launching this executable on the supplied green-context stream, including incompatible graph or stream state and prior asynchronous failures.
pub unsafe fn launch_green_async(&self, stream: &GreenStream) -> Result<()> {
if !self
.executable
.context()
.is_primary_for(stream.context().device())?
{
return Err(Error::StreamContextMismatch);
}
self.executable.context().bind()?;
// SAFETY: `self.executable` owns the live executable and `stream` borrows a live green stream; the caller retains node storage and excludes conflicting accesses through completion.
unsafe {
try_ffi!(sys::cuGraphLaunch(
self.executable.as_raw(),
stream.as_raw()
))
}
}
/// Borrows the retained node and resource snapshot from graph instantiation.
#[must_use]
pub fn nodes(&self) -> &[ContextNode] {
&self.nodes
}
}
/// Synchronization mode for a host task's execution thread.
#[derive(Debug, Clone, Copy)]
#[repr(u32)]
#[non_exhaustive]
pub enum HostTaskSyncMode {
/// The execution thread will block until new host tasks are ready to run.
Blocking = sys::CUhostTaskSyncMode::CU_HOST_TASK_BLOCKING.0,
/// The execution thread will spin wait until new host tasks are ready to run.
SpinWait = sys::CUhostTaskSyncMode::CU_HOST_TASK_SPINWAIT.0,
}
impl_enum_display!(HostTaskSyncMode, {
HostTaskSyncMode::Blocking => "CU_HOST_TASK_BLOCKING",
HostTaskSyncMode::SpinWait => "CU_HOST_TASK_SPINWAIT",
});