singe_cuda/graph/buffer.rs
1use std::{mem::MaybeUninit, result::Result as StdResult, sync::Arc};
2
3use crate::{
4 context::Context,
5 error::Result,
6 graph::{GraphBuffer, RetainedAllocation},
7 memory::{DeviceAllocation, DeviceMemory, transfer},
8 view::{
9 AnyBitPatternDeviceRepr, DeviceOutputView, DeviceRepr, DeviceSlice, DeviceView,
10 DeviceViewMut, NoUninitDeviceRepr,
11 },
12};
13
14impl<T> GraphBuffer<T>
15where
16 T: DeviceRepr,
17{
18 pub(crate) fn from_memory(memory: DeviceMemory<T>) -> Self {
19 Self { memory }
20 }
21
22 pub(crate) fn retained(&self) -> RetainedAllocation {
23 let memory = Arc::clone(self.memory.allocation());
24 RetainedAllocation(memory)
25 }
26
27 /// Returns the number of exposed elements.
28 #[must_use]
29 pub fn len(&self) -> usize {
30 self.memory.len()
31 }
32
33 /// Returns whether the exposed element range is empty.
34 #[must_use]
35 pub fn is_empty(&self) -> bool {
36 self.memory.is_empty()
37 }
38
39 /// Returns the byte length of the exposed element range.
40 #[must_use]
41 pub fn byte_len(&self) -> usize {
42 self.memory.byte_len()
43 }
44
45 /// Returns the context retained by the buffer allocation.
46 #[must_use]
47 pub fn context(&self) -> &Arc<Context> {
48 self.memory.context()
49 }
50
51 /// Returns the CUDA-accessible element pointer without synchronizing graph work.
52 #[must_use]
53 pub fn as_ptr(&self) -> *const T {
54 self.memory.as_ptr()
55 }
56
57 /// Returns the CUDA-accessible mutable element pointer.
58 ///
59 /// The caller must order raw accesses against graph launches using this allocation.
60 pub fn as_mut_ptr(&mut self) -> *mut T {
61 self.memory.as_mut_ptr()
62 }
63
64 /// Copies a host slice into this graph-retained device buffer.
65 ///
66 /// This updates the stable allocation used by graph-buffer node APIs.
67 /// The caller is still responsible for ordering this copy against graph launches that read or write the same allocation.
68 ///
69 /// # Errors
70 ///
71 /// Returns an error if `host_slice` does not have the same length as this buffer or if CUDA rejects the copy.
72 pub fn copy_from_host(&mut self, host_slice: &[T]) -> Result<()> {
73 transfer::copy_from_host(self, host_slice)
74 }
75
76 /// Copies this graph-retained device buffer into a host slice.
77 ///
78 /// # Errors
79 ///
80 /// Returns an error if `host_slice` does not have the same length as this buffer or if CUDA rejects the copy.
81 pub fn copy_to_host(&self, host_slice: &mut [T]) -> Result<()>
82 where
83 T: AnyBitPatternDeviceRepr,
84 {
85 let () = T::LAYOUT;
86 // SAFETY: `T: AnyBitPatternDeviceRepr`, so any device bytes are valid `T` values.
87 unsafe { self.copy_to_host_unchecked(host_slice) }
88 }
89
90 /// Copies graph-buffer values whose validity follows from the graph's kernels.
91 ///
92 /// # Safety
93 ///
94 /// Every copied element must be initialized and valid for `T`.
95 /// The copy must be ordered after all graph writes to this buffer.
96 ///
97 /// # Errors
98 ///
99 /// Returns an error for unequal element counts or byte-size overflow.
100 /// Also propagates context-binding, stream-capture, CUDA copy, and stream synchronization errors.
101 pub unsafe fn copy_to_host_unchecked(&self, host_slice: &mut [T]) -> Result<()> {
102 // SAFETY: the caller guarantees every element is initialized, valid for `T`, and written before this copy, which is all the owned memory's copy requires.
103 unsafe { self.memory.copy_to_host_unchecked(host_slice) }
104 }
105
106 /// Copies another graph-retained buffer into this buffer.
107 ///
108 /// # Errors
109 ///
110 /// Returns an error if the buffers have different lengths or if CUDA rejects the copy.
111 pub fn copy_from_buffer<S: DeviceSlice<T> + ?Sized>(&mut self, src: &S) -> Result<()> {
112 transfer::copy_device(self, src)
113 }
114
115 /// Copies every element into a new host vector and waits for completion.
116 ///
117 /// # Errors
118 ///
119 /// Propagates byte-size, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
120 /// No initialized vector is returned unless the transfer completes.
121 pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
122 where
123 T: AnyBitPatternDeviceRepr,
124 {
125 self.memory.copy_to_host_vec()
126 }
127
128 /// Reads graph output values whose validity follows from the producing kernels.
129 ///
130 /// # Safety
131 ///
132 /// All elements must be initialized and valid for `T`, and graph writes must finish before this readback.
133 ///
134 /// # Errors
135 ///
136 /// Propagates byte-size, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
137 /// No initialized vector is returned unless the transfer completes.
138 pub unsafe fn copy_to_host_vec_unchecked(&self) -> Result<Vec<T>> {
139 // SAFETY: the caller guarantees every element is initialized, valid for `T`, and written before this readback.
140 unsafe { self.memory.copy_to_host_vec_unchecked() }
141 }
142
143 /// Returns the allocation retained by graph definitions, executables, and foreign owners.
144 #[must_use]
145 pub fn allocation(&self) -> &Arc<DeviceAllocation> {
146 self.memory.allocation()
147 }
148
149 /// Borrows the initialized buffer as a shared device view.
150 #[must_use]
151 pub fn view(&self) -> DeviceView<'_, T> {
152 DeviceView::from_buffer(self)
153 }
154
155 /// Borrows the initialized buffer as an exclusive device view.
156 pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
157 DeviceViewMut::from_buffer(self)
158 }
159
160 /// Reinterprets initialized bytes without changing graph-retained allocation ownership.
161 ///
162 /// # Errors
163 ///
164 /// Returns the original buffer if the destination type is zero-sized, its size does not divide the exposed byte length, or a nonempty range is not aligned for the destination type.
165 pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<GraphBuffer<U>, Self>
166 where
167 T: NoUninitDeviceRepr,
168 {
169 self.memory
170 .cast()
171 .map(GraphBuffer::from_memory)
172 .map_err(Self::from_memory)
173 }
174
175 /// Erases initialization while preserving graph-retained allocation ownership.
176 #[must_use]
177 pub fn into_uninit(self) -> GraphBuffer<MaybeUninit<T>> {
178 GraphBuffer::from_memory(self.memory.into_uninit())
179 }
180}
181
182impl<T: DeviceRepr> GraphBuffer<MaybeUninit<T>> {
183 /// Borrows the uninitialized buffer as a write-only destination of `T` values.
184 pub fn output(&mut self) -> DeviceOutputView<'_, T> {
185 DeviceOutputView::from_output(self)
186 }
187
188 /// Marks all values initialized after their producing work completes.
189 ///
190 /// # Safety
191 ///
192 /// Every element must be valid, and producing work must complete or be ordered before every consumer.
193 /// Recording a graph does not establish initialization; only its successful execution can do so.
194 #[must_use]
195 pub unsafe fn assume_init(self) -> GraphBuffer<T> {
196 // SAFETY: the caller guarantees every element is valid and its producing work is ordered before every consumer.
197 GraphBuffer::from_memory(unsafe { self.memory.assume_init() })
198 }
199
200 /// Exposes only a produced prefix while retaining the full graph allocation.
201 ///
202 /// # Safety
203 ///
204 /// Every prefix element must be valid, with producer completion and ordering satisfying `assume_init`.
205 ///
206 /// # Errors
207 ///
208 /// Returns an error if `length` exceeds the currently exposed element count.
209 pub unsafe fn assume_init_prefix(self, length: usize) -> Result<GraphBuffer<T>> {
210 // SAFETY: the caller guarantees the first `length` elements are valid and ordered as `assume_init` requires; the length itself is checked by the callee.
211 unsafe { self.memory.assume_init_prefix(length) }.map(GraphBuffer::from_memory)
212 }
213}