1use super::*;
2use crate::internal::*;
3
4fn any_bit_pattern(dt: DatumType) -> bool {
7 dt.is_copy() && dt != DatumType::Bool
8}
9
10fn check_strides(shape: &[usize], strides: &[isize]) -> TractResult<()> {
13 ensure!(
14 shape.len() == strides.len(),
15 "TensorView shape {shape:?} and strides {strides:?} ranks differ"
16 );
17 ensure!(strides.iter().all(|s| *s >= 0), "TensorView strides {strides:?} must not be negative");
18 Ok(())
19}
20
21fn natural_len(shape: &[usize]) -> usize {
22 shape.iter().product()
23}
24
25fn typed_slice<D: Datum>(dt: DatumType, bytes: &[u8], len: usize) -> TractResult<&[D]> {
26 check_typed::<D>(dt, bytes, len)?;
27 if len == 0 {
28 return Ok(&[]);
29 }
30 Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const D, len) })
32}
33
34fn typed_slice_mut<D: Datum>(dt: DatumType, bytes: &mut [u8], len: usize) -> TractResult<&mut [D]> {
35 check_typed::<D>(dt, bytes, len)?;
36 if len == 0 {
37 return Ok(&mut []);
38 }
39 Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr() as *mut D, len) })
41}
42
43fn check_typed<D: Datum>(dt: DatumType, bytes: &[u8], len: usize) -> TractResult<()> {
44 ensure!(
45 dt.unquantized() == D::datum_type().unquantized(),
46 "Tensor datum type error: tensor is {:?}, accessed as {:?}",
47 dt,
48 D::datum_type(),
49 );
50 ensure!(
51 len.checked_mul(size_of::<D>()).is_some_and(|l| l <= bytes.len()),
52 "TensorView access to {len} {dt:?} overruns its {} bytes",
53 bytes.len()
54 );
55 ensure!(
56 len == 0 || bytes.as_ptr().cast::<D>().is_aligned(),
57 "TensorView data is not aligned for {dt:?}"
58 );
59 Ok(())
60}
61
62fn item_offset(shape: &[usize], strides: &[isize], coords: &[usize]) -> TractResult<usize> {
63 ensure!(
64 coords.len() == shape.len() && coords.iter().zip(shape).all(|(&x, &dim)| x < dim),
65 "Can't access coordinates {coords:?} of TensorView of shape {shape:?}",
66 );
67 Ok(coords.iter().zip(strides).map(|(c, s)| c * *s as usize).sum())
68}
69
70fn axis_offset_bytes(
71 dt: DatumType,
72 shape: &[usize],
73 strides: &[isize],
74 axis: usize,
75 pos: usize,
76) -> TractResult<usize> {
77 ensure!(axis < shape.len(), "Axis {axis} out of TensorView of rank {}", shape.len());
78 Ok(pos * strides[axis] as usize * dt.size_of())
79}
80
81#[derive(Clone, Copy, Debug)]
89pub struct TensorView<'a> {
90 dt: DatumType,
91 bytes: &'a [u8],
92 shape: &'a [usize],
93 strides: &'a [isize],
94}
95
96impl<'a> TensorView<'a> {
97 pub(crate) fn of_tensor(tensor: &'a Tensor) -> TensorView<'a> {
98 TensorView {
99 dt: tensor.dt,
100 bytes: tensor.plain_ram_storage().as_bytes(),
101 shape: &tensor.shape,
102 strides: &tensor.strides,
103 }
104 }
105
106 pub fn from_bytes(
109 tensor: &'a Tensor,
110 offset_bytes: usize,
111 shape: &'a [usize],
112 strides: &'a [isize],
113 ) -> TractResult<TensorView<'a>> {
114 let bytes = tensor
115 .try_as_plain_ram()?
116 .as_bytes()
117 .get(offset_bytes..)
118 .with_context(|| format!("TensorView offset {offset_bytes} out of storage"))?;
119 check_strides(shape, strides)?;
120 Ok(TensorView { dt: tensor.dt, bytes, shape, strides })
121 }
122
123 pub fn from_pod_bytes(
126 dt: DatumType,
127 bytes: &'a [u8],
128 shape: &'a [usize],
129 strides: &'a [isize],
130 ) -> TractResult<TensorView<'a>> {
131 ensure!(any_bit_pattern(dt), "TensorView over raw bytes of {dt:?}");
132 check_strides(shape, strides)?;
133 Ok(TensorView { dt, bytes, shape, strides })
134 }
135
136 pub(crate) fn at_prefix(tensor: &'a Tensor, prefix: &[usize]) -> TractResult<TensorView<'a>> {
137 ensure!(
138 prefix.len() <= tensor.rank() && prefix.iter().zip(tensor.shape()).all(|(p, d)| p < d),
139 "Invalid prefix {:?} for shape {:?}",
140 prefix,
141 tensor.shape()
142 );
143 let mut view = Self::of_tensor(tensor);
144 for (axis, &pos) in prefix.iter().enumerate() {
145 view.offset_axis(axis, pos)?;
146 }
147 view.shape = &tensor.shape[prefix.len()..];
148 view.strides = &tensor.strides[prefix.len()..];
149 Ok(view)
150 }
151
152 #[inline]
153 pub fn datum_type(&self) -> DatumType {
154 self.dt
155 }
156
157 #[inline]
158 pub fn shape(&self) -> &'a [usize] {
159 self.shape
160 }
161
162 #[inline]
163 pub fn strides(&self) -> &'a [isize] {
164 self.strides
165 }
166
167 #[inline]
169 #[allow(clippy::len_without_is_empty)]
170 pub fn len(&self) -> usize {
171 natural_len(self.shape)
172 }
173
174 #[inline]
175 pub fn rank(&self) -> usize {
176 self.shape.len()
177 }
178
179 pub fn offset_axis(&mut self, axis: usize, pos: usize) -> TractResult<()> {
181 let offset = axis_offset_bytes(self.dt, self.shape, self.strides, axis, pos)?;
182 self.bytes = self.bytes.get(offset..).context("TensorView offset out of storage")?;
183 Ok(())
184 }
185
186 #[inline]
188 pub fn as_ptr<D: Datum>(&self) -> TractResult<*const D> {
189 check_typed::<D>(self.dt, self.bytes, 0)?;
190 Ok(self.bytes.as_ptr() as *const D)
191 }
192
193 #[inline]
195 pub unsafe fn as_ptr_unchecked<D: Datum>(&self) -> *const D {
196 self.bytes.as_ptr() as *const D
197 }
198
199 #[inline]
201 pub fn as_slice<D: Datum>(&self) -> TractResult<&'a [D]> {
202 typed_slice(self.dt, self.bytes, self.len())
203 }
204
205 #[inline]
207 pub unsafe fn as_slice_unchecked<D: Datum>(&self) -> &'a [D] {
208 if self.len() == 0 {
209 return &[];
210 }
211 unsafe { std::slice::from_raw_parts(self.as_ptr_unchecked(), self.len()) }
212 }
213
214 pub fn at<D: Datum>(&self, coords: impl AsRef<[usize]>) -> TractResult<&'a D> {
216 let offset = item_offset(self.shape, self.strides, coords.as_ref())?;
217 let bytes = self.bytes.get(offset * self.dt.size_of()..).unwrap_or(&[]);
218 Ok(&typed_slice::<D>(self.dt, bytes, 1)?[0])
219 }
220}
221
222#[derive(Debug)]
226pub struct TensorViewMut<'a> {
227 dt: DatumType,
228 bytes: &'a mut [u8],
229 shape: &'a [usize],
230 strides: &'a [isize],
231}
232
233impl<'a> TensorViewMut<'a> {
234 pub(crate) fn of_tensor(tensor: &'a mut Tensor) -> TensorViewMut<'a> {
235 let Tensor { dt, shape, strides, storage, .. } = tensor;
236 let bytes = storage.as_plain_ram_mut().expect("Non-plain storage").as_bytes_mut();
237 TensorViewMut { dt: *dt, bytes, shape, strides }
238 }
239
240 pub fn from_pod_bytes(
243 dt: DatumType,
244 bytes: &'a mut [u8],
245 shape: &'a [usize],
246 strides: &'a [isize],
247 ) -> TractResult<TensorViewMut<'a>> {
248 ensure!(any_bit_pattern(dt), "TensorViewMut over raw bytes of {dt:?}");
249 check_strides(shape, strides)?;
250 Ok(TensorViewMut { dt, bytes, shape, strides })
251 }
252
253 #[inline]
254 pub fn view(&self) -> TensorView<'_> {
255 TensorView { dt: self.dt, bytes: self.bytes, shape: self.shape, strides: self.strides }
256 }
257
258 #[inline]
259 pub fn datum_type(&self) -> DatumType {
260 self.dt
261 }
262
263 #[inline]
264 pub fn shape(&self) -> &'a [usize] {
265 self.shape
266 }
267
268 #[inline]
269 pub fn strides(&self) -> &'a [isize] {
270 self.strides
271 }
272
273 #[inline]
275 #[allow(clippy::len_without_is_empty)]
276 pub fn len(&self) -> usize {
277 natural_len(self.shape)
278 }
279
280 #[inline]
281 pub fn rank(&self) -> usize {
282 self.shape.len()
283 }
284
285 pub fn offset_axis(&mut self, axis: usize, pos: usize) -> TractResult<()> {
287 let offset = axis_offset_bytes(self.dt, self.shape, self.strides, axis, pos)?;
288 ensure!(offset <= self.bytes.len(), "TensorViewMut offset out of storage");
289 self.bytes = &mut std::mem::take(&mut self.bytes)[offset..];
290 Ok(())
291 }
292
293 #[inline]
295 pub fn as_ptr_mut<D: Datum>(&mut self) -> TractResult<*mut D> {
296 check_typed::<D>(self.dt, self.bytes, 0)?;
297 Ok(self.bytes.as_mut_ptr() as *mut D)
298 }
299
300 #[inline]
302 pub unsafe fn as_ptr_mut_unchecked<D: Datum>(&mut self) -> *mut D {
303 self.bytes.as_mut_ptr() as *mut D
304 }
305
306 #[inline]
308 pub fn as_slice<D: Datum>(&self) -> TractResult<&[D]> {
309 typed_slice(self.dt, self.bytes, self.len())
310 }
311
312 #[inline]
314 pub fn as_slice_mut<D: Datum>(&mut self) -> TractResult<&mut [D]> {
315 let len = self.len();
316 typed_slice_mut(self.dt, self.bytes, len)
317 }
318
319 #[inline]
321 pub unsafe fn as_slice_mut_unchecked<D: Datum>(&mut self) -> &mut [D] {
322 let len = self.len();
323 if len == 0 {
324 return &mut [];
325 }
326 unsafe { std::slice::from_raw_parts_mut(self.as_ptr_mut_unchecked(), len) }
327 }
328
329 pub fn at_mut<D: Datum>(&mut self, coords: impl AsRef<[usize]>) -> TractResult<&mut D> {
331 let offset = item_offset(self.shape, self.strides, coords.as_ref())?;
332 let start = (offset * self.dt.size_of()).min(self.bytes.len());
333 Ok(&mut typed_slice_mut::<D>(self.dt, &mut self.bytes[start..], 1)?[0])
334 }
335}
336
337#[cfg(test)]
338mod test {
339 use super::*;
340
341 #[test]
342 fn test_at_prefix() {
343 let a = Tensor::from_shape(&[2, 2], &[1, 2, 3, 4]).unwrap();
344 let a_view = a.view_at_prefix(&[1]).unwrap();
345 assert_eq!(a_view.shape(), &[2]);
346 assert_eq!(a_view.as_slice::<i32>().unwrap(), &[3, 4]);
347 }
348
349 #[test]
350 fn offsetting_view_stays_in_storage() {
351 let a = Tensor::from_shape(&[4], &[1f32, 2., 3., 4.]).unwrap();
352 let view = a.view_offsetting(&[2]).unwrap();
353 assert!(view.as_slice::<f32>().is_err());
354 assert_eq!(*view.at::<f32>([1]).unwrap(), 4.);
355 assert!(view.at::<f32>([2]).is_err());
356 assert!(a.view_offsetting(&[4]).is_err());
357 assert!(a.view_offsetting(&[]).is_err());
358 }
359
360 #[test]
361 fn empty_view_slices() {
362 let a = Tensor::from_shape::<f32>(&[0, 3], &[]).unwrap();
363 assert!(a.view().as_slice::<f32>().unwrap().is_empty());
364 }
365
366 #[test]
367 fn from_bytes_checks_extent() {
368 let a = Tensor::from_shape(&[4], &[1f32, 2., 3., 4.]).unwrap();
369 assert_eq!(
370 TensorView::from_bytes(&a, 8, &[2], &[1]).unwrap().as_slice::<f32>().unwrap(),
371 &[3., 4.]
372 );
373 assert!(TensorView::from_bytes(&a, 8, &[3], &[1]).unwrap().as_slice::<f32>().is_err());
374 assert!(TensorView::from_bytes(&a, 20, &[0], &[1]).is_err());
375 }
376
377 #[test]
378 fn pod_bytes_refuse_non_pod_types() {
379 let mut bytes = [1u8; 8];
380 assert!(TensorViewMut::from_pod_bytes(DatumType::Bool, &mut bytes, &[8], &[1]).is_err());
381 assert!(TensorViewMut::from_pod_bytes(DatumType::U8, &mut bytes, &[8], &[1]).is_ok());
382 }
383
384 #[test]
385 fn mut_view_writes() {
386 let mut a = Tensor::from_shape(&[2, 2], &[1i32, 2, 3, 4]).unwrap();
387 let mut v = a.view_mut();
388 *v.at_mut::<i32>([1, 0]).unwrap() = 30;
389 v.offset_axis(0, 1).unwrap();
390 assert!(v.as_slice::<i32>().is_err());
391 assert_eq!(*v.at_mut::<i32>([0, 1]).unwrap(), 4);
392 assert_eq!(a.try_as_plain_ram().unwrap().as_slice::<i32>().unwrap(), &[1, 2, 30, 4]);
393 }
394}