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
use std::alloc::Layout;
use std::mem::{ManuallyDrop, MaybeUninit};
use strided_basic::StridedViewMut;
use tenferro_tensor::{validate::checked_shape_product, TensorRank, TensorScalar, TypedTensor};
use crate::buffer_pool::{BufferPool, PoolScalar, UninitCheckoutToken};
use crate::{Error, Result};
fn checked_compact_strides(shape: &[usize]) -> Result<Vec<isize>> {
let mut strides = Vec::with_capacity(shape.len());
let mut stride = 1isize;
for &dim in shape {
strides.push(stride);
let dim = isize::try_from(dim).map_err(|_| {
Error::invalid_argument("pooled_uninit_output", "shape", "dimension exceeds isize")
})?;
stride = stride.checked_mul(dim).ok_or_else(|| {
Error::invalid_argument("pooled_uninit_output", "shape", "compact stride overflow")
})?;
}
Ok(strides)
}
#[derive(Debug)]
/// Owns a pooled full-overwrite destination until initialization is proven.
///
/// This type is public because `tenferro-cpu` is a sibling crate and must use
/// the same canonical owner; `pub(crate)` would prevent that cross-crate
/// ownership. Before the unsafe completion handoff, callers receive only
/// `MaybeUninit` storage.
pub struct PooledUninitOutput<'pool, T: PoolScalar> {
pool: &'pool mut BufferPool,
shape: Vec<usize>,
strides: Vec<isize>,
data: Vec<std::mem::MaybeUninit<T>>,
checkout: Option<UninitCheckoutToken>,
byte_len: usize,
}
impl<'pool, T: PoolScalar> PooledUninitOutput<'pool, T> {
/// Creates a compact, pooled full-overwrite destination.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let output = PooledUninitOutput::<f32>::new(&mut pool, vec![2, 3]).unwrap();
/// drop(output);
/// ```
/// # Errors
/// Returns `Error::Validation` for shape-product, layout, or stride
/// validation failures, or `Error::BackendSource` if allocation
/// reservation fails. No pool accounting is changed before validation.
pub fn new(pool: &'pool mut BufferPool, shape: Vec<usize>) -> Result<Self> {
let len = checked_shape_product("pooled_uninit_output", "shape", &shape)?;
let layout = Layout::array::<T>(len).map_err(|_| {
Error::invalid_argument(
"pooled_uninit_output",
"shape",
"element byte layout exceeds allocation limits",
)
})?;
let byte_len = layout.size();
let strides = checked_compact_strides(&shape)?;
let (data, checkout) =
<T as crate::buffer_pool::private::Sealed>::pool_acquire_uninit_tracked(pool, len)?;
debug_assert!(match checkout {
UninitCheckoutToken::Fresh { actual_capacity }
| UninitCheckoutToken::Reused { actual_capacity } => {
data.capacity() == actual_capacity
}
});
Ok(Self {
pool,
shape,
strides,
data,
checkout: Some(checkout),
byte_len,
})
}
/// Borrows the destination as `MaybeUninit` elements.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<i32>::new(&mut pool, vec![1]).unwrap();
/// output.as_uninit_slice_mut()[0].write(7);
/// ```
///
pub fn as_uninit_slice_mut(&mut self) -> &mut [MaybeUninit<T>] {
self.data.as_mut_slice()
}
/// Borrows the validated compact destination for typed uninitialized kernels.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<f32>::new(&mut pool, vec![2]).unwrap();
/// let view = output.as_uninit_view_mut().unwrap();
/// assert_eq!(view.dims(), &[2]);
/// ```
/// # Errors
/// Returns `Error::BackendSource` if validated strided-view metadata is
/// rejected.
pub fn as_uninit_view_mut(&mut self) -> Result<StridedViewMut<'_, MaybeUninit<T>>> {
let shape = &self.shape;
let strides = &self.strides;
let data = &mut self.data;
StridedViewMut::new(data, shape, strides, 0)
.map_err(|err| Error::backend_source("pooled_uninit_output", err))
}
#[cfg(test)]
pub(crate) fn token_is_reused_with_capacity(&self, capacity: usize) -> bool {
matches!(self.checkout, Some(UninitCheckoutToken::Reused { actual_capacity }) if actual_capacity == capacity)
}
#[cfg(test)]
pub(crate) fn token_is_fresh(&self) -> bool {
matches!(
self.checkout,
Some(UninitCheckoutToken::Fresh { actual_capacity })
if self.data.capacity() == actual_capacity
)
}
/// Returns the backing bytes for erased uninitialized kernel descriptors.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<i32>::new(&mut pool, vec![1]).unwrap();
/// assert_eq!(output.as_uninit_bytes_mut().len(), 4);
/// ```
pub fn as_uninit_bytes_mut(&mut self) -> &mut [std::mem::MaybeUninit<u8>] {
let data = self.as_uninit_slice_mut();
// SAFETY: this creates only MaybeUninit byte elements over the same allocation.
unsafe {
std::slice::from_raw_parts_mut(
data.as_mut_ptr().cast::<std::mem::MaybeUninit<u8>>(),
self.byte_len,
)
}
}
/// Converts the allocation after a successful full-overwrite kernel.
///
/// # Safety
/// Every logical element must have been initialized by the completed kernel.
/// The kernel must have completed all validation before writing, and must
/// not retain any destination view after returning.
/// Successful completion transfers success accounting to the owning
/// `BufferPoolLoan` context; direct internal callers must keep that context alive.
/// Completes the handoff as a dynamic-rank typed tensor.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<i32>::new(&mut pool, vec![1]).unwrap();
/// output.as_uninit_slice_mut()[0].write(7);
/// // SAFETY: the preceding write initializes every logical destination element.
/// // SAFETY: the example writes every logical destination element before completion.
/// let tensor = unsafe { output.assume_init() }.unwrap();
/// assert_eq!(tensor.as_slice().unwrap(), &[7]);
/// ```
///
/// # Errors
/// Returns `Error::Validation` if tensor construction rejects the shape or
/// data length. Dynamic-rank conversion itself is infallible, so this
/// method does not produce a rank-conversion `Error::BackendSource`.
pub unsafe fn assume_init(self) -> Result<TypedTensor<T>>
where
T: TensorScalar,
{
// SAFETY: this method has the same full-initialization precondition.
unsafe { self.assume_init_as::<tenferro_tensor::DynRank>() }
}
/// Completes the handoff with an explicitly selected tensor rank.
///
/// # Safety
/// Every logical element must have been initialized by the completed kernel.
/// The destination must be fully initialized before this method is called;
/// otherwise reading or dropping the resulting tensor is undefined behavior.
///
/// # Errors
/// Returns `Error::BackendSource` if rank conversion rejects the shape, or
/// `Error::Validation` if tensor construction rejects the shape or length.
///
/// # Examples
///
/// ```rust
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// use tenferro_tensor::Rank;
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<i32>::new(&mut pool, vec![1]).unwrap();
/// output.as_uninit_slice_mut()[0].write(7);
/// // SAFETY: the preceding write initializes every logical destination element.
/// let tensor = unsafe { output.assume_init_as::<Rank<1>>() }.unwrap();
/// assert_eq!(tensor.as_slice().unwrap(), &[7]);
/// ```
pub unsafe fn assume_init_as<R: TensorRank>(self) -> Result<TypedTensor<T, R>>
where
T: TensorScalar,
{
// SAFETY: the caller guarantees complete initialization.
unsafe { self.finish(false) }
}
/// Transfer a fully initialized output with automatic original-pool return.
/// The pool is retained weakly; dropping the pool first frees later outputs
/// normally. Dropping an output never acquires a CPU session lock.
///
/// # Safety
/// Every logical element must be initialized and no kernel may retain a
/// destination view. This is the same full-overwrite contract as assume_init.
///
/// # Errors
/// Returns [`Error::Validation`] if the output shape and initialized buffer
/// length disagree, or [`Error::RuntimeState`] if recycler attachment cannot
/// obtain the host allocation. Shape conversion failures retain their typed
/// source as [`Error::BackendSource`].
///
/// # Examples
/// ```
/// use tenferro_cpu_basic::{buffer_pool::BufferPool, PooledUninitOutput};
/// let mut pool = BufferPool::new();
/// let mut output = PooledUninitOutput::<f64>::new(&mut pool, vec![1])?;
/// output.as_uninit_slice_mut()[0].write(2.0);
/// // SAFETY: the only element has been initialized.
/// let tensor = unsafe { output.assume_init_recycled() }?;
/// assert_eq!(tensor.as_slice()?, &[2.0]);
/// drop(tensor);
/// assert_eq!(pool.len(), 1);
/// # Ok::<(), tenferro_tensor::Error>(())
/// ```
pub unsafe fn assume_init_recycled(self) -> Result<TypedTensor<T>> {
// SAFETY: the caller guarantees complete initialization.
unsafe { self.finish(true) }
}
unsafe fn finish<R: TensorRank>(mut self, recycle: bool) -> Result<TypedTensor<T, R>> {
let shape = R::shape_from_vec(std::mem::take(&mut self.shape).into())
.map_err(|err| Error::backend_source("pooled_uninit_output", err))?;
let data = std::mem::take(&mut self.data);
let mut data = ManuallyDrop::new(data);
// SAFETY: caller proves initialization and MaybeUninit<T> has identical layout.
let data = unsafe {
Vec::from_raw_parts(data.as_mut_ptr().cast::<T>(), data.len(), data.capacity())
};
if recycle {
// INVARIANT: only successful completion takes the checkout, and this
// method consumes self, so a live output always owns its token here.
let Some(checkout) = self.checkout.take() else {
unreachable!("a live pooled output owns its checkout");
};
let recycler = <T as crate::buffer_pool::private::Sealed>::pool_finish_recycled(
self.pool, checkout,
);
TypedTensor::from_vec_col_major_with_recycler(shape, data, recycler)
} else {
let tensor = TypedTensor::from_vec_col_major(shape, data)?;
self.checkout = None;
Ok(tensor)
}
}
}
impl<T: PoolScalar> Drop for PooledUninitOutput<'_, T> {
fn drop(&mut self) {
let Some(checkout) = self.checkout.take() else {
return;
};
let data = std::mem::take(&mut self.data);
<T as crate::buffer_pool::private::Sealed>::pool_discard_uninit(
&mut *self.pool,
data,
checkout,
);
}
}
#[cfg(test)]
mod tests;