singe_cuda/graph/owned.rs
1//! Owned operation capture and resource-retaining replay.
2
3use std::{
4 mem,
5 sync::{Arc, Mutex},
6};
7
8use singe_core::report_cleanup_failure;
9
10use crate::{
11 error::{Error, Result},
12 graph::{ExecutableGraph, Graph, GraphInstantiateFlags},
13 stream::{Stream, StreamCaptureMode},
14 submission::{DeviceOperation, Execution, Operation, Resources, Submission},
15};
16
17/// Prepared work that can be recorded without allocation, compilation, waits or host readback.
18///
19/// # Safety
20///
21/// Register every owner and byte-range access with `Recording` before recording native work.
22/// Outputs must expose pending storage only; recording does not execute producers.
23/// Native operations and resources must remain valid for every replay.
24pub unsafe trait Recordable: Sized {
25 /// Value produced by recording, without implying producer execution or initialized results.
26 type Output: 'static;
27
28 /// Records this prepared operation and registers its replay resources with `recording`.
29 ///
30 /// # Errors
31 ///
32 /// Returns operation-specific capture or native recording errors.
33 /// Implementations must preserve replay ownership for any nodes recorded before an error is returned.
34 fn record(self, recording: &mut Recording) -> Result<Self::Output>;
35}
36
37/// Resource ledger for one active capture.
38#[derive(Debug)]
39pub struct Recording {
40 stream: Stream,
41 resources: Resources,
42}
43
44impl Recording {
45 /// Returns the stream being captured by this recording.
46 #[must_use]
47 pub fn stream(&self) -> &Stream {
48 &self.stream
49 }
50
51 /// Registers replay resources before recording one native operation.
52 ///
53 /// # Safety
54 ///
55 /// Retain all referenced owners and declare all accessed ranges.
56 /// The closure must be graph-safe and enqueue only on the supplied stream.
57 /// Returned values must not claim that capture initialized their storage.
58 ///
59 /// # Errors
60 ///
61 /// Returns `Error::MemoryContextMismatch` if a nonportable access belongs to another context.
62 /// Otherwise propagates the result of `enqueue`; registered resources remain in the recording ledger even if that callback fails.
63 pub unsafe fn enqueue<T>(
64 &mut self,
65 resources: Resources,
66 enqueue: impl FnOnce(&Stream) -> Result<T>,
67 ) -> Result<T> {
68 for access in &resources.accesses {
69 access.validate_context(self.stream.context())?;
70 }
71
72 self.resources.extend(resources);
73 enqueue(&self.stream)
74 }
75}
76
77impl Drop for Recording {
78 fn drop(&mut self) {
79 // CUDA may still retain captured addresses, so the recorded resources stay retained.
80 if let Err(error) = self.stream.ensure_not_capturing() {
81 mem::forget(mem::take(&mut self.resources));
82 report_cleanup_failure(
83 "release the recorded resources of",
84 "cuda stream capture",
85 &error,
86 );
87 }
88 }
89}
90
91/// A captured graph retaining storage independently of its extracted output.
92#[derive(Debug)]
93pub struct OwnedGraph<T> {
94 graph: Graph,
95 resources: Resources,
96 output: Option<T>,
97}
98
99impl<T> OwnedGraph<T> {
100 /// Takes the value produced during recording, returning `None` after the first successful take.
101 ///
102 /// The value does not establish that recorded producers have executed or completed; their outputs must preserve pending initialization.
103 pub fn take_output(&mut self) -> Option<T> {
104 self.output.take()
105 }
106
107 /// Borrows the recorded graph definition.
108 ///
109 /// The replay resource ledger remains owned by this [`OwnedGraph`].
110 pub fn graph(&self) -> &Graph {
111 &self.graph
112 }
113
114 /// Instantiates replay with independent native execution state and the recorded storage owners.
115 ///
116 /// # Errors
117 ///
118 /// Propagates native graph-instantiation errors from [`Graph::instantiate`].
119 /// No executable or independent resource snapshot is returned if instantiation fails.
120 pub fn instantiate(&self) -> Result<OwnedExecutable> {
121 Ok(OwnedExecutable {
122 executable: Arc::new(Mutex::new(
123 self.graph.instantiate(GraphInstantiateFlags::empty())?,
124 )),
125 resources: self.resources.clone(),
126 })
127 }
128}
129
130/// Reusable replay with common allocation access tracking and independent submission retention.
131#[derive(Debug, Clone)]
132pub struct OwnedExecutable {
133 executable: Arc<Mutex<ExecutableGraph>>,
134 resources: Resources,
135}
136
137impl OwnedExecutable {
138 /// Adopts an existing executable and its complete replay ownership and access declarations.
139 ///
140 /// # Safety
141 ///
142 /// Resources must retain everything referenced by every node, including private scratch.
143 /// Declare writable graph-private storage so shared instances serialize its use.
144 /// Raw mutations must preserve this ownership and access contract.
145 #[must_use]
146 pub unsafe fn from_executable(executable: ExecutableGraph, resources: Resources) -> Self {
147 Self {
148 executable: Arc::new(Mutex::new(executable)),
149 resources,
150 }
151 }
152
153 /// Submits one replay on `stream`, retaining the executable and its resources independently of the returned submission.
154 ///
155 /// Dropping the submission does not cancel queued graph work.
156 ///
157 /// # Errors
158 ///
159 /// Propagates execution setup, access-tracking, dependency-ordering, graph-launch, and completion registration errors.
160 /// Returns `Error::LockPoisoned` if the executable lock is poisoned.
161 /// A failure can occur after native work has been queued; the execution ledger retains resources through cleanup.
162 pub fn launch(&self, stream: &Stream) -> Result<Submission<()>> {
163 self.clone().submit_on(stream)
164 }
165
166 /// Accesses native graph mutation under the replay lock.
167 ///
168 /// # Safety
169 ///
170 /// Complete prior launches before mutation and preserve the retained ownership and access declarations.
171 ///
172 /// # Errors
173 ///
174 /// Returns `Error::LockPoisoned` if the executable lock is poisoned.
175 /// Otherwise propagates errors returned by `access`.
176 pub unsafe fn with_raw<T>(
177 &self,
178 access: impl FnOnce(&mut ExecutableGraph) -> Result<T>,
179 ) -> Result<T> {
180 let mut executable = self
181 .executable
182 .lock()
183 .map_err(|_| Error::lock_poisoned("executable graph"))?;
184 access(&mut executable)
185 }
186}
187
188// SAFETY: `enqueue` registers the replay resources and the executable itself through `Execution::enqueue` before launching, and the unit output exposes no device storage.
189unsafe impl Operation for OwnedExecutable {
190 type Pending = Self::Output;
191
192 type Output = ();
193
194 fn enqueue(self, execution: &mut Execution) -> Result<()> {
195 let mut resources = self.resources;
196 resources.retain(Arc::clone(&self.executable));
197 // SAFETY: `resources` holds every owner and access the replay declared at capture or adoption plus the executable, and the closure only launches on the execution's stream.
198 unsafe {
199 execution.enqueue(resources, |stream| {
200 self.executable
201 .lock()
202 .map_err(|_| Error::lock_poisoned("executable graph"))?
203 .launch_async(stream)
204 })
205 }
206 }
207
208 unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
209 Ok(pending)
210 }
211}
212
213// SAFETY: `Pending` is `Output`, `resolve` returns it unchanged, and `enqueue` schedules the launch without host resolution.
214unsafe impl DeviceOperation for OwnedExecutable {}
215
216impl Stream {
217 /// Captures already prepared owned work; no producer executes during recording.
218 ///
219 /// # Errors
220 ///
221 /// Propagates capture setup, operation recording, and capture finalization errors.
222 /// Resources registered before failure remain retained until capture ends; if cleanup cannot establish that capture ended, the recording preserves those resources.
223 pub fn capture_owned<O: Recordable>(&self, operation: O) -> Result<OwnedGraph<O::Output>> {
224 let mut recording = Recording {
225 stream: self.clone(),
226 resources: Resources::new(),
227 };
228 let mut output = None;
229 let graph = self.capture(StreamCaptureMode::Relaxed, |_| {
230 output = Some(operation.record(&mut recording)?);
231 Ok(())
232 })?;
233 Ok(OwnedGraph {
234 graph,
235 resources: mem::take(&mut recording.resources),
236 output,
237 })
238 }
239}