singe_cuda/graph/executable.rs
1use std::{mem::ManuallyDrop, ptr, result::Result as StdResult, sync::Arc};
2
3use singe_cuda_sys::runtime;
4
5use crate::{
6 context::Context,
7 error::{Error, Result},
8 event::Event,
9 graph::{
10 ExecutableGraph, Graph, GraphBuffer, GraphId, GraphInner, GraphInstantiateFlags, GraphNode,
11 GraphUpdateError, MemorySetNodeParams, RawExecutableGraph, RetainedResources,
12 UnboundExecutableGraph, UnboundGraph,
13 raw::{
14 HostNodeParams, MemoryCopy1DNodeParams, MemoryCopy3DNodeParams,
15 MemoryCopyFromSymbolNodeParams, MemoryCopyToSymbolNodeParams,
16 },
17 },
18 memory::MemoryCopyKind,
19 module::{KernelLaunchArgs, LaunchGeometry, Module},
20 stream::Stream,
21 try_ffi,
22 types::DeviceFunction,
23 view::{DeviceOutput, DeviceRepr, DeviceSlice, DeviceSliceMut},
24};
25
26impl UnboundExecutableGraph {
27 /// Wraps an existing CUDA executable graph handle and takes ownership of it.
28 ///
29 /// # Safety
30 ///
31 /// `handle` must be a valid CUDA executable graph handle.
32 /// Ownership of `handle` is transferred to the returned [`UnboundExecutableGraph`], and the handle must not be destroyed elsewhere after calling this function.
33 ///
34 /// # Errors
35 ///
36 /// Returns an error if the native handle is null.
37 pub unsafe fn from_raw(handle: runtime::cudaGraphExec_t) -> Result<Self> {
38 if handle.is_null() {
39 return Err(Error::NullHandle);
40 }
41
42 Ok(Self { handle })
43 }
44
45 /// Returns the owned native executable handle without transferring ownership.
46 #[must_use]
47 pub const fn as_raw(&self) -> runtime::cudaGraphExec_t {
48 self.handle
49 }
50
51 /// Consumes the executable graph and returns the raw CUDA executable graph handle without destroying it.
52 ///
53 /// The caller becomes responsible for eventually destroying the returned handle with CUDA.
54 #[must_use]
55 pub fn into_raw(self) -> runtime::cudaGraphExec_t {
56 let graph = ManuallyDrop::new(self);
57 graph.as_raw()
58 }
59}
60
61impl ExecutableGraph {
62 pub(crate) fn bind_context(&self) -> Result<()> {
63 self.context.bind()
64 }
65
66 pub(crate) unsafe fn from_raw_with_graph(
67 handle: runtime::cudaGraphExec_t,
68 context: Arc<Context>,
69 source_graph_id: Option<GraphId>,
70 source_graph: Option<Arc<GraphInner>>,
71 retained: RetainedResources,
72 ) -> Result<Self> {
73 if handle.is_null() {
74 return Err(Error::NullHandle);
75 }
76
77 Ok(Self {
78 handle,
79 context,
80 source_graph_id,
81 source_graph,
82 retained,
83 })
84 }
85
86 pub(crate) fn check_node(&self, node: &GraphNode) -> Result<()> {
87 self.bind_context()?;
88 if !matches!((self.source_graph_id, node.graph_id), (Some(source_id), Some(node_id)) if node_id == source_id)
89 {
90 return Err(Error::GraphNodeMismatch);
91 }
92 Ok(())
93 }
94
95 pub(crate) fn retain_module(&mut self, module: &Module) {
96 self.retained.retain_module(module);
97 }
98
99 fn retain_buffer<T>(&mut self, buffer: &GraphBuffer<T>)
100 where
101 T: DeviceRepr,
102 {
103 self.retained.retain_allocation(buffer.retained());
104 }
105
106 /// Returns the flags that were passed to instantiation for the given executable graph.
107 /// [`GraphInstantiateFlags::UPLOAD`] is not returned because it does not affect the resulting executable graph.
108 ///
109 /// Graph objects are not threadsafe.
110 ///
111 /// # Errors
112 ///
113 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
114 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
115 pub fn flags(&self) -> Result<GraphInstantiateFlags> {
116 self.bind_context()?;
117 let mut flags = 0;
118 // SAFETY: `self` owns the live executable, its context is bound above, and `flags` is a local output.
119 unsafe {
120 try_ffi!(runtime::cudaGraphExecGetFlags(
121 self.as_raw(),
122 &raw mut flags
123 ))?;
124 }
125 Ok(GraphInstantiateFlags::from_bits_retain(flags))
126 }
127
128 /// Executes this executable graph in `stream`.
129 /// Only one instance of this executable graph may be executing at a time.
130 /// Each launch is ordered behind both any previous work in `stream` and any previous launches of this executable graph.
131 /// To execute a graph concurrently, it must be instantiated multiple times into multiple executable graphs.
132 ///
133 /// If any allocations created by this executable graph remain unfreed from a previous launch and the graph was not instantiated with [`GraphInstantiateFlags::AUTO_FREE_ON_LAUNCH`], the launch fails with [`crate::error::Status::InvalidValue`].
134 ///
135 /// Graph objects are not threadsafe.
136 ///
137 /// # Safety
138 ///
139 /// Retain every referenced allocation and native owner until execution completes.
140 /// Order conflicting access through external aliases and uphold every node's value contract.
141 ///
142 /// # Errors
143 ///
144 /// Returns `Error::StreamContextMismatch` if `stream` belongs to another context.
145 /// Also returns an error if CUDA rejects the launch or a previous asynchronous launch reported an error.
146 pub unsafe fn launch_async(&self, stream: &Stream) -> Result<()> {
147 if stream.context() != &self.context {
148 return Err(Error::StreamContextMismatch);
149 }
150
151 self.bind_context()?;
152 // SAFETY: `self` owns the live executable and `stream` was checked to share its bound context; the caller retains every referenced allocation and orders conflicting access through completion.
153 unsafe {
154 try_ffi!(runtime::cudaGraphLaunch(self.as_raw(), stream.as_raw()))?;
155 }
156 Ok(())
157 }
158
159 /// Uploads this executable graph to the device in `stream` without executing it.
160 /// Uploads of the same executable graph are serialized.
161 /// Each upload is ordered behind both any previous work in `stream` and any previous launches of this executable graph.
162 /// Uses memory cached by `stream` to back the allocations owned by this executable graph.
163 ///
164 /// # Errors
165 ///
166 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
167 pub fn upload(&self, stream: &Stream) -> Result<()> {
168 if stream.context() != &self.context {
169 return Err(Error::StreamContextMismatch);
170 }
171
172 self.bind_context()?;
173 // SAFETY: `self` owns the live executable and `stream` was checked to share its bound context; uploading runs no node, so no node operand is accessed.
174 unsafe {
175 try_ffi!(runtime::cudaGraphUpload(self.as_raw(), stream.as_raw()))?;
176 }
177 Ok(())
178 }
179
180 /// Updates this executable graph with the node parameters in a topologically identical `graph`.
181 ///
182 /// Limitations:
183 ///
184 /// * Kernel nodes:
185 /// + The owning context of the kernel function cannot change.
186 /// + A node whose kernel function originally did not use CUDA dynamic parallelism cannot be updated to a kernel function that uses CDP.
187 /// + A node whose kernel function originally did not make device-side update calls cannot be updated to a kernel function that makes device-side update calls.
188 /// + A cooperative node cannot be updated to a non-cooperative node, and vice-versa.
189 /// + If the graph was instantiated with [`GraphInstantiateFlags::USE_NODE_PRIORITY`], the priority attribute cannot change.
190 /// Equality is checked on the originally requested priority values, before they are clamped to the device's supported range.
191 /// + If this executable graph was not instantiated for device launch, a node whose kernel function originally did not use device-side [`ExecutableGraph::launch_async`] cannot be updated to a kernel function that uses device-side [`ExecutableGraph::launch_async`] unless the node resides on the same device as nodes which contained such calls at instantiate-time.
192 /// If no such calls were present at instantiation, these updates cannot be performed at all.
193 /// + Neither the source graph nor this executable graph may contain device-updatable kernel nodes.
194 /// * Memset and memcpy nodes:
195 /// + The CUDA device(s) to which the operand(s) was allocated/mapped cannot change.
196 /// + The source/destination memory must be allocated from the same contexts as the original source/destination memory.
197 /// + For 2D memsets, only address and assigned value may be updated.
198 /// + For 1D memsets, updating dimensions is also allowed, but may fail if the resulting operation does not map onto the work resources already allocated for the node.
199 /// * Additional memcpy node restrictions:
200 /// + Changing either the source or destination memory type, such as [`MemoryType::Device`](crate::types::MemoryType::Device) or [`MemoryType::Array`](crate::types::MemoryType::Array), is not supported.
201 /// * Conditional nodes:
202 /// + Changing node parameters is not supported.
203 /// + Changing parameters of nodes within the conditional body graph is subject to the rules above.
204 /// + Conditional handle flags and default values are updated as part of the graph update.
205 ///
206 /// CUDA may add further restrictions in future releases.
207 /// A rejected update returns [`GraphUpdateError::Rejected`], whose result is [`GraphExecUpdateResult::ErrorTopologyChanged`](crate::graph::GraphExecUpdateResult::ErrorTopologyChanged) under the following conditions:
208 ///
209 /// * The count of nodes directly in the executable graph and the source graph differ.
210 /// * The source graph has more exit nodes.
211 /// * A node in the source graph has a different number of dependencies than the paired node from the executable graph.
212 /// * A node in the source graph has a dependency that does not match the corresponding dependency of the paired node from the executable graph.
213 /// The dependencies are paired based on edge order and a dependency does not match when the nodes are already paired based on other edges examined in the graph.
214 ///
215 /// The result of a rejected update is:
216 ///
217 /// * [`GraphExecUpdateResult::Error`](crate::graph::GraphExecUpdateResult::Error) if passed an invalid value.
218 /// * [`GraphExecUpdateResult::ErrorTopologyChanged`](crate::graph::GraphExecUpdateResult::ErrorTopologyChanged) if the graph topology changed.
219 /// * [`GraphExecUpdateResult::ErrorNodeTypeChanged`](crate::graph::GraphExecUpdateResult::ErrorNodeTypeChanged) if the type of a node changed.
220 /// * [`GraphExecUpdateResult::ErrorUnsupportedFunctionChange`](crate::graph::GraphExecUpdateResult::ErrorUnsupportedFunctionChange) if the kernel function changed in an unsupported way.
221 /// * [`GraphExecUpdateResult::ErrorParametersChanged`](crate::graph::GraphExecUpdateResult::ErrorParametersChanged) if any parameters to a node changed in a way that is not supported.
222 /// * [`GraphExecUpdateResult::ErrorAttributesChanged`](crate::graph::GraphExecUpdateResult::ErrorAttributesChanged) if any attributes of a node changed in a way that is not supported.
223 /// * [`GraphExecUpdateResult::ErrorNotSupported`](crate::graph::GraphExecUpdateResult::ErrorNotSupported) if something about a node is unsupported, like the node's type or configuration.
224 ///
225 /// If the update fails for a reason not listed above, the result is [`GraphExecUpdateResult::Error`](crate::graph::GraphExecUpdateResult::Error).
226 /// A rejected update leaves this executable graph unchanged.
227 ///
228 /// # Errors
229 ///
230 /// Returns [`GraphUpdateError::Rejected`] with the result and the nodes CUDA reports if the update violates the constraints above.
231 /// Returns [`GraphUpdateError::Cuda`] holding `Error::ContextMismatch` if `graph` belongs to another context, or holding another error if the context cannot be bound, the graph's retained resources cannot be read, or CUDA fails otherwise, including a previous asynchronous launch reporting an error.
232 pub fn update(&mut self, graph: &Graph) -> StdResult<(), GraphUpdateError> {
233 if self.context.as_ref() != graph.context.as_ref() {
234 return Err(Error::context_mismatch("graph").into());
235 }
236
237 // Read the resources first so a successful update never leaves them unretained.
238 let retained = graph.retained_resources()?;
239 self.bind_context()?;
240 let mut result_info = runtime::cudaGraphExecUpdateResultInfo::default();
241 // SAFETY: `self` owns the live executable, `graph` owns its live graph, `&mut self` excludes other host calls on the executable, and `result_info` is a local output.
242 let status = unsafe {
243 runtime::cudaGraphExecUpdate(self.as_raw(), graph.as_raw(), &raw mut result_info)
244 };
245 if status == runtime::cudaError_t::CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE {
246 let node = |handle: runtime::cudaGraphNode_t| {
247 (!handle.is_null()).then(|| graph.node_from_raw(handle))
248 };
249 return Err(GraphUpdateError::Rejected {
250 result: result_info.result.try_into().map_err(Error::from)?,
251 error_node: node(result_info.errorNode),
252 error_from_node: node(result_info.errorFromNode),
253 });
254 }
255
256 try_ffi!(status)?;
257
258 self.retained.extend(retained);
259 Ok(())
260 }
261
262 /// Sets the parameters of a kernel node in this executable graph.
263 /// The node is identified by the corresponding `node` in the non-executable graph from which this executable graph was instantiated.
264 ///
265 /// `node` must not have been removed from the original graph.
266 /// All node parameters may change, but the following restrictions apply to function updates:
267 ///
268 /// * The owning device of the kernel function cannot change.
269 /// * A node whose kernel function originally did not use CUDA dynamic parallelism cannot be updated to a kernel function that uses CDP
270 /// * A node whose kernel function originally did not make device-side update calls cannot be updated to a kernel function that makes device-side update calls.
271 /// * If this executable graph was not instantiated for device launch, a node whose kernel function originally did not use device-side [`ExecutableGraph::launch_async`] cannot be updated to a kernel function that uses device-side [`ExecutableGraph::launch_async`] unless the node resides on the same device as nodes which contained such calls at instantiate-time.
272 /// If no such calls were present at instantiation, these updates cannot be performed at all.
273 ///
274 /// The modifications only affect future launches of this executable graph.
275 /// Already enqueued or running launches of this executable graph are not affected by this call.
276 /// The original `node` is also not modified by this call.
277 ///
278 /// If `node` is a device-updatable kernel node, the next upload or launch of this executable graph will overwrite any previous device-side updates.
279 /// Additionally, applying host updates to a device-updatable kernel node while it is being updated from the device results in undefined behavior.
280 /// A runtime kernel handle passed as a raw function must come from the same CUDA Runtime instance.
281 /// Passing a symbol that belongs to a different runtime instance results in undefined behavior.
282 /// The only type that can be reliably passed to a different runtime instance is the runtime kernel handle type itself.
283 ///
284 /// Graph objects are not threadsafe.
285 ///
286 /// Launch attributes remain as instantiated; changing them requires a full graph update or re-instantiation.
287 ///
288 /// # Safety
289 ///
290 /// Arguments must match `function`'s ABI and satisfy its value and access requirements.
291 /// The function must belong to the node's execution context.
292 /// Keep its code owner alive until every queued graph execution completes.
293 /// The executable's existing launch attributes must support the new function and geometry.
294 /// CUDA copies the kernel argument values during this call and stores those copied values in the executable graph for future launches.
295 /// If an argument value is itself a pointer, only the pointer address is copied.
296 /// The caller must ensure every copied pointer value remains valid for every future launch that can execute this node.
297 /// Mutable pointer arguments must also remain exclusive for the work ordered by those launches.
298 ///
299 /// # Errors
300 ///
301 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
302 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
303 pub unsafe fn set_kernel_node_params<'a, P>(
304 &mut self,
305 node: &GraphNode,
306 function: DeviceFunction,
307 geometry: &LaunchGeometry,
308 params: P,
309 ) -> Result<()>
310 where
311 P: KernelLaunchArgs<'a>,
312 {
313 self.check_node(node)?;
314 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; CUDA copies `arguments` during the call, and the caller guarantees they match `function` and point to storage valid for every future launch.
315 params.with_encoded_arguments(|mut arguments| unsafe {
316 let params = runtime::cudaKernelNodeParams {
317 func: function.as_raw().cast(),
318 gridDim: geometry.grid_dim().into(),
319 blockDim: geometry.block_dim().into(),
320 sharedMemBytes: geometry.shared_memory_bytes_u32(),
321 kernelParams: arguments.as_mut_ptr().cast(),
322 extra: ptr::null_mut(),
323 };
324 try_ffi!(runtime::cudaGraphExecKernelNodeSetParams(
325 self.as_raw(),
326 node.as_raw(),
327 &raw const params,
328 ))?;
329 Ok(())
330 })
331 }
332
333 /// Updates the work represented by `node` in this executable graph as though `node` had contained the given `params` at instantiation.
334 /// `node` must remain in the graph which was used to instantiate this executable graph.
335 /// Changed edges to and from `node` are ignored.
336 ///
337 /// The source and destination must be allocated from the same contexts as the original source and destination memory.
338 /// The instantiation-time memory operands must be 1-dimensional.
339 /// Zero-length operations are not supported.
340 ///
341 /// The modifications only affect future launches of this executable graph.
342 /// Already enqueued or running launches of this executable graph are not affected by this call.
343 /// The original `node` is also not modified by this call.
344 ///
345 /// Returns [`crate::error::Status::InvalidValue`] if the memory operands' mappings changed or the original memory operands are multidimensional.
346 ///
347 /// Graph objects are not threadsafe.
348 ///
349 /// # Safety
350 ///
351 /// CUDA stores the raw source and destination addresses in the executable graph for future launches.
352 /// The caller must ensure `params` remains valid according to [`MemoryCopy1DNodeParams::new`] for every future launch that can execute this node.
353 ///
354 /// # Errors
355 ///
356 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
357 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
358 pub unsafe fn set_memory_copy_node_1d_params(
359 &mut self,
360 node: &GraphNode,
361 params: &MemoryCopy1DNodeParams,
362 ) -> Result<()> {
363 self.check_node(node)?;
364 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; the caller keeps the copy's addresses valid for every future launch.
365 unsafe {
366 try_ffi!(runtime::cudaGraphExecMemcpyNodeSetParams1D(
367 self.as_raw(),
368 node.as_raw(),
369 params.dst().cast(),
370 params.src().cast(),
371 params.count() as _,
372 params.kind().into(),
373 ))?;
374 }
375 Ok(())
376 }
377
378 /// Updates a memcpy node to copy between typed device byte buffers.
379 ///
380 /// The node copies `src.len()` bytes.
381 /// `dst` must have at least that many bytes.
382 ///
383 /// # Safety
384 ///
385 /// CUDA stores the raw source and destination addresses in the executable graph for future launches.
386 /// The caller must ensure `dst` and `src` remain valid for every future launch that can execute this node.
387 /// `dst` must not be accessed through another mutable path while graph launches using this node can write it.
388 ///
389 /// # Errors
390 ///
391 /// Returns an error if `dst` is smaller than `src`, if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
392 pub unsafe fn set_memory_copy_node_1d_device_to_device<D, S>(
393 &mut self,
394 node: &GraphNode,
395 dst: &mut D,
396 src: &S,
397 ) -> Result<()>
398 where
399 D: DeviceSliceMut<u8> + ?Sized,
400 S: DeviceSlice<u8> + ?Sized,
401 {
402 let count = src.len();
403 if dst.len() < count {
404 return Err(Error::buffer_too_small("destination", count, dst.len()));
405 }
406
407 // SAFETY: `dst` holds at least `count` bytes (checked above) and `src` exactly `count`; the caller keeps both valid for every future launch.
408 let params = unsafe {
409 MemoryCopy1DNodeParams::new(
410 dst.as_mut_ptr().cast(),
411 src.as_device_ptr().cast(),
412 count,
413 MemoryCopyKind::DeviceToDevice,
414 )
415 };
416 // SAFETY: the caller keeps `dst` and `src`, the addresses in `params`, valid and exclusive for every future launch.
417 unsafe { self.set_memory_copy_node_1d_params(node, ¶ms) }
418 }
419
420 /// Updates a memcpy node to copy between graph-retained buffers.
421 ///
422 /// The node copies `src.byte_len()` bytes.
423 /// `dst` must have at least that many bytes.
424 /// The executable graph retains both allocations so future launches cannot outlive the baked CUDA pointer values.
425 ///
426 /// # Safety
427 ///
428 /// Keep source elements valid for every launch, and order their producers before replay.
429 /// Keep destination accesses exclusive through completion, including failed submissions.
430 /// Allocation retention preserves addresses; initialization and access ordering remain caller obligations.
431 ///
432 /// # Errors
433 ///
434 /// Returns an error if `dst` is smaller than `src`, if `node` does not belong to the graph used to instantiate this executable graph, if CUDA rejects the graph update, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
435 pub unsafe fn set_buffer_memory_copy_node_1d_device_to_device<T, D>(
436 &mut self,
437 node: &GraphNode,
438 dst: &mut GraphBuffer<D>,
439 src: &GraphBuffer<T>,
440 ) -> Result<()>
441 where
442 T: DeviceRepr,
443 D: DeviceRepr,
444 GraphBuffer<D>: DeviceOutput<T>,
445 {
446 if &self.context != dst.context() {
447 return Err(Error::MemoryContextMismatch);
448 }
449
450 if &self.context != src.context() {
451 return Err(Error::MemoryContextMismatch);
452 }
453
454 let count = src.byte_len();
455 if dst.byte_len() < count {
456 return Err(Error::buffer_too_small(
457 "destination",
458 count,
459 dst.byte_len(),
460 ));
461 }
462
463 // SAFETY: `dst` holds at least `count` bytes (checked above) and `src` exactly `count`, and the executable retains both allocations below.
464 let params = unsafe {
465 MemoryCopy1DNodeParams::new(
466 dst.as_mut_ptr().cast(),
467 src.as_ptr().cast(),
468 count,
469 MemoryCopyKind::DeviceToDevice,
470 )
471 };
472 // SAFETY: the executable retains both allocations below, so the addresses stay valid; the caller orders producers and keeps destination access exclusive.
473 unsafe { self.set_memory_copy_node_1d_params(node, ¶ms)? };
474 self.retain_buffer(dst);
475 self.retain_buffer(src);
476 Ok(())
477 }
478
479 /// Updates the work represented by `node` in this executable graph as though `node` had contained the given `params` at instantiation.
480 /// `node` must remain in the graph which was used to instantiate this executable graph.
481 /// Changed edges to and from `node` are ignored.
482 ///
483 /// The source and destination memory in `params` must be allocated from the same contexts as the original source and destination memory.
484 /// Both the instantiation-time memory operands and the memory operands in `params` must be 1-dimensional.
485 /// Zero-length operations are not supported.
486 ///
487 /// The modifications only affect future launches of this executable graph.
488 /// Already enqueued or running launches of this executable graph are not affected by this call.
489 /// The original `node` is also not modified by this call.
490 ///
491 /// Returns [`crate::error::Status::InvalidValue`] if the memory operands' mappings changed or either the original or new memory operands are multidimensional.
492 ///
493 /// Graph objects are not threadsafe.
494 ///
495 /// # Safety
496 ///
497 /// CUDA stores the raw source and destination addresses in the executable graph for future launches.
498 /// The caller must ensure `params` remains valid according to [`MemoryCopy3DNodeParams`] for every future launch that can execute this node.
499 ///
500 /// # Errors
501 ///
502 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
503 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
504 pub unsafe fn set_memory_copy_node_params(
505 &mut self,
506 node: &GraphNode,
507 params: &MemoryCopy3DNodeParams,
508 ) -> Result<()> {
509 self.check_node(node)?;
510 let params = params.into();
511 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; `params` is a local read during the call, and the caller keeps its addresses valid for every future launch.
512 unsafe {
513 try_ffi!(runtime::cudaGraphExecMemcpyNodeSetParams(
514 self.as_raw(),
515 node.as_raw(),
516 &raw const params,
517 ))?;
518 }
519 Ok(())
520 }
521
522 /// # Safety
523 ///
524 /// CUDA stores the raw symbol and source pointer in the executable graph for future launches.
525 /// The caller must ensure `params` remains valid according to [`MemoryCopyToSymbolNodeParams::new`] for every future launch that can execute this node.
526 ///
527 /// # Errors
528 ///
529 /// Returns an error if the node does not belong to this executable’s source graph, context binding fails, or CUDA rejects the symbol copy update.
530 pub unsafe fn set_memory_copy_node_to_symbol_params(
531 &mut self,
532 node: &GraphNode,
533 params: &MemoryCopyToSymbolNodeParams,
534 ) -> Result<()> {
535 self.check_node(node)?;
536 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; the caller keeps the symbol and source pointer valid for every future launch.
537 unsafe {
538 try_ffi!(runtime::cudaGraphExecMemcpyNodeSetParamsToSymbol(
539 self.as_raw(),
540 node.as_raw(),
541 params.symbol().cast(),
542 params.src().cast(),
543 params.count() as _,
544 params.offset() as _,
545 params.kind().into(),
546 ))?;
547 }
548 Ok(())
549 }
550
551 /// # Safety
552 ///
553 /// CUDA stores the raw destination and symbol pointer in the executable graph for future launches.
554 /// The caller must ensure `params` remains valid according to [`MemoryCopyFromSymbolNodeParams::new`] for every future launch that can execute this node.
555 ///
556 /// # Errors
557 ///
558 /// Returns an error if the node does not belong to this executable’s source graph, context binding fails, or CUDA rejects the symbol copy update.
559 pub unsafe fn set_memory_copy_node_from_symbol_params(
560 &mut self,
561 node: &GraphNode,
562 params: &MemoryCopyFromSymbolNodeParams,
563 ) -> Result<()> {
564 self.check_node(node)?;
565 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; the caller keeps the symbol and destination pointer valid for every future launch.
566 unsafe {
567 try_ffi!(runtime::cudaGraphExecMemcpyNodeSetParamsFromSymbol(
568 self.as_raw(),
569 node.as_raw(),
570 params.dst().cast(),
571 params.symbol().cast(),
572 params.count() as _,
573 params.offset() as _,
574 params.kind().into(),
575 ))?;
576 }
577 Ok(())
578 }
579
580 /// Updates the work represented by `node` in this executable graph as though `node` had contained the given `params` at instantiation.
581 /// `node` must remain in the graph which was used to instantiate this executable graph.
582 /// Changed edges to and from `node` are ignored.
583 ///
584 /// Zero-sized operations are not supported.
585 ///
586 /// The new destination pointer in `params` must be to the same kind of allocation as the original destination pointer and have the same context association and device mapping as the original destination pointer.
587 ///
588 /// Both the value and pointer address may be updated.
589 /// Changing other aspects of the memset (width, height, element size or pitch) may cause the update to be rejected.
590 /// Specifically, for 2D memsets, all dimension changes are rejected.
591 /// For 1D memsets, changes in height are explicitly rejected and other changes are opportunistically allowed if the resulting work maps onto the work resources already allocated for the node.
592 ///
593 /// The modifications only affect future launches of this executable graph.
594 /// Already enqueued or running launches of this executable graph are not affected by this call.
595 /// The original `node` is also not modified by this call.
596 ///
597 /// Graph objects are not threadsafe.
598 ///
599 /// # Safety
600 ///
601 /// CUDA stores the raw destination address in the executable graph for future launches.
602 /// The caller must ensure `params` remains valid according to [`MemorySetNodeParams::new`] for every future launch that can execute this node.
603 ///
604 /// # Errors
605 ///
606 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
607 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
608 pub unsafe fn set_memory_set_node_params(
609 &mut self,
610 node: &GraphNode,
611 params: &MemorySetNodeParams,
612 ) -> Result<()> {
613 self.check_node(node)?;
614 let params = params.into();
615 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; `params` is a local read during the call, and the caller keeps the destination valid for every future launch.
616 unsafe {
617 try_ffi!(runtime::cudaGraphExecMemsetNodeSetParams(
618 self.as_raw(),
619 node.as_raw(),
620 &raw const params,
621 ))?;
622 }
623 Ok(())
624 }
625
626 /// Updates the work represented by `node` in this executable graph as though `node` had contained the given `params` at instantiation.
627 /// `node` must remain in the graph which was used to instantiate this executable graph.
628 /// Changed edges to and from `node` are ignored.
629 ///
630 /// The modifications only affect future launches of this executable graph.
631 /// Already enqueued or running launches of this executable graph are not affected by this call.
632 /// The original `node` is also not modified by this call.
633 ///
634 /// Graph objects are not threadsafe.
635 ///
636 /// # Safety
637 ///
638 /// CUDA stores the raw callback function and user-data pointer in the executable graph for future launches.
639 /// The caller must ensure `params` remains valid according to [`HostNodeParams::new`] for every future launch that can execute this node.
640 ///
641 /// # Errors
642 ///
643 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
644 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
645 pub unsafe fn set_host_node_params(
646 &mut self,
647 node: &GraphNode,
648 params: &HostNodeParams,
649 ) -> Result<()> {
650 self.check_node(node)?;
651 let params = params.into();
652 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; `params` is a local read during the call, and the caller keeps the callback and user data valid for every future launch.
653 unsafe {
654 try_ffi!(runtime::cudaGraphExecHostNodeSetParams(
655 self.as_raw(),
656 node.as_raw(),
657 &raw const params,
658 ))?;
659 }
660 Ok(())
661 }
662
663 /// Sets the event of an event record node in this executable graph.
664 /// The node is identified by the corresponding `node` in the non-executable graph from which this executable graph was instantiated.
665 ///
666 /// The modifications only affect future launches of this executable graph.
667 /// Already enqueued or running launches of this executable graph are not affected by this call.
668 /// The original `node` is also not modified by this call.
669 /// The executable retains `event`.
670 ///
671 /// Graph objects are not threadsafe.
672 ///
673 /// # Errors
674 ///
675 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
676 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
677 pub fn set_event_record_node_event(
678 &mut self,
679 node: &GraphNode,
680 event: &Arc<Event>,
681 ) -> Result<()> {
682 self.check_node(node)?;
683 if &self.context != event.context() {
684 return Err(Error::context_mismatch("event"));
685 }
686
687 // Retain first, so the executable never references an unretained event.
688 self.retained.retain_event(event);
689
690 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it, and `event` is a live event of the same context (checked above).
691 unsafe {
692 try_ffi!(runtime::cudaGraphExecEventRecordNodeSetEvent(
693 self.as_raw(),
694 node.as_raw(),
695 event.as_raw(),
696 ))?;
697 }
698 Ok(())
699 }
700
701 /// Validates the recorded node identity and context before updating a child graph.
702 /// This lets callers reject an incompatible executable before changing the source graph.
703 /// CUDA determines topology and parameter compatibility when the update is applied.
704 ///
705 /// # Errors
706 ///
707 /// Returns an error if the node does not belong to this executable's source graph, the recorded CUDA contexts differ, or binding the executable's context fails.
708 pub fn validate_child_graph_node_update(
709 &self,
710 node: &GraphNode,
711 child_graph: &Graph,
712 ) -> Result<()> {
713 self.check_node(node)?;
714 if self.context.as_ref() != child_graph.context.as_ref() {
715 return Err(Error::context_mismatch("child graph"));
716 }
717 Ok(())
718 }
719
720 /// Updates the work represented by `node` in this executable graph as though the nodes contained in `node`'s graph had the parameters contained in `child_graph`'s nodes at instantiation.
721 /// `node` must remain in the graph which was used to instantiate this executable graph.
722 /// Changed edges to and from `node` are ignored.
723 ///
724 /// The modifications only affect future launches of this executable graph.
725 /// Already enqueued or running launches of this executable graph are not affected by this call.
726 /// The original `node` is also not modified by this call.
727 ///
728 /// The topology of `child_graph`, as well as the node insertion order, must match that of the graph contained in `node`.
729 /// See [`ExecutableGraph::update`] for a list of restrictions on what can be updated in an instantiated graph.
730 /// The update is recursive, so child graph nodes contained within the top-level child graph are also updated.
731 ///
732 /// Graph objects are not threadsafe.
733 ///
734 /// # Errors
735 ///
736 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
737 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
738 pub fn set_child_graph_node(&mut self, node: &GraphNode, child_graph: &Graph) -> Result<()> {
739 self.validate_child_graph_node_update(node, child_graph)?;
740 // SAFETY: `self` owns the live executable, the validation above confirmed `node` comes from its source graph and `child_graph` shares its context, and the child graph's resources are retained below.
741 unsafe {
742 try_ffi!(runtime::cudaGraphExecChildGraphNodeSetParams(
743 self.as_raw(),
744 node.as_raw(),
745 child_graph.as_raw(),
746 ))?;
747 }
748
749 self.retained.extend(child_graph.retained_resources()?);
750 Ok(())
751 }
752
753 /// Sets the event of an event wait node in this executable graph.
754 /// The node is identified by the corresponding `node` in the non-executable graph from which this executable graph was instantiated.
755 ///
756 /// The modifications only affect future launches of this executable graph.
757 /// Already enqueued or running launches of this executable graph are not affected by this call.
758 /// The original `node` is also not modified by this call.
759 /// The executable retains `event`.
760 ///
761 /// Graph objects are not threadsafe.
762 ///
763 /// # Errors
764 ///
765 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
766 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
767 pub fn set_event_wait_node_event(
768 &mut self,
769 node: &GraphNode,
770 event: &Arc<Event>,
771 ) -> Result<()> {
772 self.check_node(node)?;
773 // Retain first, so the executable never references an unretained event.
774 self.retained.retain_event(event);
775 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it, and `event` borrows a live event.
776 unsafe {
777 try_ffi!(runtime::cudaGraphExecEventWaitNodeSetEvent(
778 self.as_raw(),
779 node.as_raw(),
780 event.as_raw(),
781 ))?;
782 }
783 Ok(())
784 }
785
786 /// Sets `node` to be either enabled or disabled.
787 /// Disabled nodes are functionally equivalent to empty nodes until they are reenabled.
788 /// Existing node parameters are not affected by disabling/enabling the node.
789 ///
790 /// The node is identified by the corresponding `node` in the non-executable graph from which this executable graph was instantiated.
791 ///
792 /// `node` must not have been removed from the original graph.
793 ///
794 /// The modifications only affect future launches of this executable graph.
795 /// Already enqueued or running launches of this executable graph are not affected by this call.
796 /// The original `node` is also not modified by this call.
797 ///
798 /// Currently only kernel, memset and memcpy nodes are supported.
799 ///
800 /// Graph objects are not threadsafe.
801 ///
802 /// # Errors
803 ///
804 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
805 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
806 fn set_node_enabled(&mut self, node: &GraphNode, enabled: bool) -> Result<()> {
807 self.check_node(node)?;
808 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `&mut self` excludes other host calls on it; toggling a node changes no operand.
809 unsafe {
810 try_ffi!(runtime::cudaGraphNodeSetEnabled(
811 self.as_raw(),
812 node.as_raw(),
813 u32::from(enabled),
814 ))?;
815 }
816 Ok(())
817 }
818
819 /// Enables the specified node in this executable graph.
820 ///
821 /// # Errors
822 ///
823 /// Returns an error if the node does not belong to this executable’s source graph, context binding fails, or CUDA rejects changing the node’s enabled state.
824 pub fn enable_node(&mut self, node: &GraphNode) -> Result<()> {
825 self.set_node_enabled(node, true)
826 }
827
828 /// Disables the specified node in this executable graph.
829 ///
830 /// # Errors
831 ///
832 /// Returns an error if the node does not belong to this executable’s source graph, context binding fails, or CUDA rejects changing the node’s enabled state.
833 pub fn disable_node(&mut self, node: &GraphNode) -> Result<()> {
834 self.set_node_enabled(node, false)
835 }
836
837 /// Returns whether `node` is enabled.
838 ///
839 /// The node is identified by the corresponding `node` in the non-executable graph from which this executable graph was instantiated.
840 ///
841 /// `node` must not have been removed from the original graph.
842 ///
843 /// Currently only kernel, memset and memcpy nodes are supported.
844 ///
845 /// Graph objects are not threadsafe.
846 ///
847 /// # Errors
848 ///
849 /// Returns an error if CUDA rejects the graph operation, if a previous asynchronous launch reported an error, or if CUDA reports runtime initialization diagnostics.
850 /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
851 pub fn is_node_enabled(&self, node: &GraphNode) -> Result<bool> {
852 self.check_node(node)?;
853 let mut enabled = 0;
854 // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, and `enabled` is a local output.
855 unsafe {
856 try_ffi!(runtime::cudaGraphNodeGetEnabled(
857 self.as_raw(),
858 node.as_raw(),
859 &raw mut enabled,
860 ))?;
861 }
862 Ok(enabled != 0)
863 }
864
865 /// Returns the native executable handle without transferring ownership.
866 #[must_use]
867 pub const fn as_raw(&self) -> runtime::cudaGraphExec_t {
868 self.handle
869 }
870
871 /// Returns the context this executable graph belongs to.
872 #[must_use]
873 pub fn context(&self) -> &Arc<Context> {
874 &self.context
875 }
876
877 /// Transfers the executable, source graph, context, and retained resource owners without destruction.
878 ///
879 /// Keep the returned parts alive through completed native launches and handle destruction, or re-adopt them.
880 #[must_use]
881 pub fn into_raw(self) -> RawExecutableGraph {
882 let graph = ManuallyDrop::new(self);
883 // SAFETY: ManuallyDrop prevents all fields from being dropped, and each owner is transferred once.
884 unsafe {
885 RawExecutableGraph {
886 handle: graph.handle,
887 context: ptr::read(&raw const graph.context),
888 retained: ptr::read(&raw const graph.retained),
889 source_graph: ptr::read(&raw const graph.source_graph)
890 .map(|inner| UnboundGraph { inner }),
891 source_graph_id: graph.source_graph_id,
892 }
893 }
894 }
895
896 /// Adopts an executable with its original source graph, context, and retained resources.
897 ///
898 /// # Safety
899 ///
900 /// The executable handle must still be live and unchanged and have no other destroying owner.
901 /// Every dependency must remain retained by `raw` or its original unsafe caller contract.
902 ///
903 /// # Errors
904 ///
905 /// Returns an error if the native handle is null.
906 pub unsafe fn from_raw(raw: RawExecutableGraph) -> Result<Self> {
907 // SAFETY: the caller guarantees `raw.handle` is live, unchanged, and solely owned, and `raw` carries the owners its nodes depend on.
908 unsafe {
909 Self::from_raw_with_graph(
910 raw.handle,
911 raw.context,
912 raw.source_graph_id,
913 raw.source_graph.map(|graph| graph.inner),
914 raw.retained,
915 )
916 }
917 }
918}