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
use crate::tensor::*;
use anyhow::*;
use std::marker::PhantomData;
#[derive(Clone, Debug)]
enum Indexing<'a> {
Prefix(usize),
Custom { shape: &'a [usize], strides: &'a [isize] },
}
#[derive(Clone, Debug)]
pub struct TensorView<'a> {
pub tensor: &'a Tensor,
offset_bytes: isize,
indexing: Indexing<'a>,
phantom: PhantomData<&'a ()>,
}
impl<'a> TensorView<'a> {
pub unsafe fn from_bytes(
tensor: &'a Tensor,
offset_bytes: isize,
shape: &'a [usize],
strides: &'a [isize],
) -> TensorView<'a> {
TensorView {
tensor,
offset_bytes,
indexing: Indexing::Custom { shape, strides },
phantom: PhantomData,
}
}
pub fn at_prefix(tensor: &'a Tensor, prefix: &[usize]) -> anyhow::Result<TensorView<'a>> {
ensure!(
prefix.len() <= tensor.rank() && prefix.iter().zip(tensor.shape()).all(|(p, d)| p < d),
"Invalid prefix {:?} for shape {:?}",
prefix,
tensor.shape()
);
unsafe { Ok(Self::at_prefix_unchecked(tensor, prefix)) }
}
pub unsafe fn at_prefix_unchecked(tensor: &'a Tensor, prefix: &[usize]) -> TensorView<'a> {
let offset_bytes =
prefix.iter().zip(tensor.strides()).map(|(a, b)| *a as isize * b).sum::<isize>()
* tensor.datum_type().size_of() as isize;
TensorView {
tensor,
offset_bytes,
indexing: Indexing::Prefix(prefix.len()),
phantom: PhantomData,
}
}
#[inline]
pub fn datum_type(&self) -> DatumType {
self.tensor.datum_type()
}
pub fn shape(&self) -> &[usize] {
match &self.indexing {
Indexing::Prefix(i) => &self.tensor.shape()[*i..],
Indexing::Custom { shape, .. } => &*shape,
}
}
pub fn strides(&self) -> &[isize] {
match &self.indexing {
Indexing::Prefix(i) => &self.tensor.strides()[*i..],
Indexing::Custom { strides, .. } => &*strides,
}
}
pub fn len(&self) -> usize {
self.shape().iter().product::<usize>()
}
pub fn rank(&self) -> usize {
self.shape().len()
}
fn check_dt<D: Datum>(&self) -> anyhow::Result<()> {
if self.datum_type() != D::datum_type() {
anyhow::bail!(
"TensorView datum type error: tensor is {:?}, accessed as {:?}",
self.datum_type(),
D::datum_type(),
);
}
Ok(())
}
fn check_coords(&self, coords: &[usize]) -> anyhow::Result<()> {
ensure!(
coords.len() == self.rank()
&& coords.iter().zip(self.shape()).all(|(&x, &dim)| x < dim),
"Can't access coordinates {:?} of TensorView of shape {:?}",
coords,
self.shape(),
);
Ok(())
}
pub fn as_ptr<D: Datum>(&self) -> anyhow::Result<*const D> {
self.check_dt::<D>()?;
Ok(unsafe { self.as_ptr_unchecked() })
}
pub unsafe fn as_ptr_unchecked<D: Datum>(&self) -> *const D {
self.tensor.as_ptr_unchecked::<u8>().offset(self.offset_bytes) as *const D
}
pub unsafe fn as_ptr_mut_unchecked<D: Datum>(&mut self) -> *mut D {
self.as_ptr_unchecked::<D>() as *mut D
}
pub fn as_ptr_mut<D: Datum>(&mut self) -> anyhow::Result<*mut D> {
Ok(self.as_ptr::<D>()? as *mut D)
}
pub unsafe fn as_slice_unchecked<D: Datum>(&self) -> &[D] {
std::slice::from_raw_parts::<D>(self.as_ptr_unchecked(), self.len())
}
pub fn as_slice<D: Datum>(&self) -> anyhow::Result<&[D]> {
self.check_dt::<D>()?;
unsafe { Ok(self.as_slice_unchecked()) }
}
pub unsafe fn as_slice_mut_unchecked<D: Datum>(&mut self) -> &mut [D] {
std::slice::from_raw_parts_mut::<D>(self.as_ptr_mut_unchecked(), self.len())
}
pub fn as_slice_mut<D: Datum>(&mut self) -> anyhow::Result<&mut [D]> {
self.check_dt::<D>()?;
unsafe { Ok(self.as_slice_mut_unchecked()) }
}
pub unsafe fn offset_bytes(&mut self, offset: isize) {
self.offset_bytes += offset
}
pub unsafe fn offset_axis_unchecked(&mut self, axis: usize, pos: isize) {
let stride = self.strides()[axis] * self.datum_type().size_of() as isize;
self.offset_bytes(stride * pos)
}
pub unsafe fn offset_axis(&mut self, axis: usize, pos: isize) {
let stride = self.strides()[axis] * self.datum_type().size_of() as isize;
self.offset_bytes(stride * pos)
}
fn offset_for_coords(&self, coords: &[usize]) -> isize {
self.strides()
.iter()
.zip(coords.as_ref())
.map(|(s, c)| *s as isize * *c as isize)
.sum::<isize>()
}
pub unsafe fn at_unchecked<T: Datum>(&self, coords: impl AsRef<[usize]>) -> &T {
self.as_ptr_unchecked::<T>()
.offset(self.offset_for_coords(coords.as_ref()))
.as_ref()
.unwrap()
}
pub unsafe fn at_mut_unchecked<T: Datum>(&mut self, coords: impl AsRef<[usize]>) -> &mut T {
self.as_ptr_mut_unchecked::<T>()
.offset(self.offset_for_coords(coords.as_ref()))
.as_mut()
.unwrap()
}
pub fn at<T: Datum>(&self, coords: impl AsRef<[usize]>) -> anyhow::Result<&T> {
self.check_dt::<T>()?;
let coords = coords.as_ref();
self.check_coords(coords)?;
unsafe { Ok(self.at_unchecked(coords)) }
}
pub fn at_mut<T: Datum>(&mut self, coords: impl AsRef<[usize]>) -> anyhow::Result<&mut T> {
self.check_dt::<T>()?;
let coords = coords.as_ref();
self.check_coords(coords)?;
unsafe { Ok(self.at_mut_unchecked(coords)) }
}
}