Skip to main content

tract_data/tensor/
storage.rs

1use std::alloc::Layout;
2use std::fmt;
3use std::hash::Hash;
4
5use crate::TractResult;
6use crate::blob::Blob;
7use crate::datum::DatumType;
8use crate::dyn_eq::DynEq;
9use crate::exotic::ExoticFact;
10use crate::tensor::Tensor;
11use downcast_rs::{Downcast, impl_downcast};
12
13/// Trait abstracting over tensor storage backends.
14///
15/// Two independent axes describe one: layout, `is_exotic`, and placement,
16/// `in_ram`. `PlainStorage` is the primary implementation, plain and in ram by
17/// construction; every other backend is held behind
18/// `StorageKind::Exotic(Box<dyn TensorStorage>)`, whichever pair of answers it
19/// gives.
20pub trait TensorStorage: Send + Sync + fmt::Debug + fmt::Display + DynEq + Downcast {
21    fn byte_len(&self) -> usize;
22    fn is_empty(&self) -> bool;
23    fn deep_clone(&self) -> Box<dyn TensorStorage>;
24    fn as_plain_ram(&self) -> Option<&PlainStorage>;
25    fn as_plain_ram_mut(&mut self) -> Option<&mut PlainStorage>;
26    fn into_plain_ram(self: Box<Self>) -> Option<PlainStorage>;
27    fn dyn_hash(&self, state: &mut dyn std::hash::Hasher);
28    /// Build the `ExoticFact` that describes this storage for use in `TypedFact`.
29    ///
30    /// Plain storage returns `None`. Exotic storages should return the
31    /// appropriate fact so that `From<Arc<Tensor>> for TypedFact` preserves
32    /// exotic-ness.
33    fn exotic_fact(&self, shape: &[usize]) -> TractResult<Option<Box<dyn ExoticFact>>>;
34
35    /// True when the tensor's datum type and shape do not describe it on their
36    /// own, so a fact over it carries an `ExoticFact`.
37    ///
38    /// The layout axis, orthogonal to `in_ram`: all four combinations exist,
39    /// a dense tensor in device memory being plain and out of ram,
40    /// block-quant weights in device memory exotic and out of ram.
41    ///
42    /// Defaults to true: a storage is exotic until it says otherwise, so one
43    /// that forgets is refused where a fact is required rather than silently
44    /// mistyped.
45    fn is_exotic(&self) -> bool {
46        true
47    }
48
49    /// True when the bytes are in host memory, readable without a transfer.
50    ///
51    /// The placement axis. Defaults to true: storage holds its own bytes unless
52    /// it says otherwise. Answers for the bytes in whatever layout the storage
53    /// keeps them -- block-quant storage is in ram while packed -- so it takes
54    /// both axes, `as_plain_ram`, for a plain read to be sure to work.
55    fn in_ram(&self) -> bool {
56        true
57    }
58
59    /// True for storage that is to stay unread inside a model's constants, such
60    /// as a weight known by its name and loaded when the model is ready to run.
61    /// Storage out of ram is otherwise brought into host memory when a constant
62    /// is built from it, so the constant does not hold on to a device buffer.
63    fn stays_lazy(&self) -> bool {
64        false
65    }
66
67    /// Plain storage for the tensor's bytes, producing it if this storage can.
68    ///
69    /// This is the accessor path: `Tensor::as_bytes` and friends go through it,
70    /// so a storage that holds its bytes somewhere else (on a device, say) gets
71    /// a chance to bring them back here, and to keep the result so the next
72    /// access is free. `as_plain_ram` stays the cheap accessor: it answers with
73    /// what is available right now and never produces anything.
74    fn materialize_plain_ram(&self) -> TractResult<&PlainStorage> {
75        self.as_plain_ram().ok_or_else(|| anyhow::anyhow!("Tensor storage is not plain"))
76    }
77
78    /// Slice along `axis`, if this storage can serve it in its own memory --
79    /// for free where the slice is already a range it holds, by a copy it can
80    /// make where it is otherwise.
81    ///
82    /// `None` means "not capable" and the caller falls back to a generic copy
83    /// through host memory, so an implementation is free to refuse any case it
84    /// cannot serve -- but storage whose bytes are not host bytes has no such
85    /// fallback to decline to, and refusing there is a panic. What it must not
86    /// do is return a tensor that is not a valid dense one: `Some` is a claim
87    /// that the result stands on its own everywhere a tensor is accepted.
88    fn slice(
89        &self,
90        _dt: DatumType,
91        _shape: &[usize],
92        _axis: usize,
93        _start: usize,
94        _end: usize,
95    ) -> TractResult<Option<Tensor>> {
96        Ok(None)
97    }
98}
99impl_downcast!(TensorStorage);
100crate::eq_trait_object!(TensorStorage);
101
102/// Plain, contiguous storage backed by a `Blob`: plain in layout and in ram,
103/// which is what every other storage is measured against.
104#[derive(Eq)]
105pub struct PlainStorage(pub(crate) Blob);
106
107impl PlainStorage {
108    #[inline]
109    pub fn layout(&self) -> &Layout {
110        self.0.layout()
111    }
112
113    #[inline]
114    pub fn as_bytes(&self) -> &[u8] {
115        self.0.as_bytes()
116    }
117
118    #[inline]
119    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
120        self.0.as_bytes_mut()
121    }
122
123    #[inline]
124    pub fn as_ptr(&self) -> *const u8 {
125        self.0.as_bytes().as_ptr()
126    }
127
128    #[inline]
129    pub fn as_mut_ptr(&mut self) -> *mut u8 {
130        self.0.as_bytes_mut().as_mut_ptr()
131    }
132
133    #[inline]
134    pub fn into_blob(self) -> Blob {
135        self.0
136    }
137}
138
139impl Default for PlainStorage {
140    #[inline]
141    fn default() -> Self {
142        PlainStorage(Blob::default())
143    }
144}
145
146impl Clone for PlainStorage {
147    #[inline]
148    fn clone(&self) -> Self {
149        PlainStorage(self.0.clone())
150    }
151}
152
153impl Hash for PlainStorage {
154    #[inline]
155    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
156        self.0.hash(state);
157    }
158}
159
160impl PartialEq for PlainStorage {
161    #[inline]
162    fn eq(&self, other: &Self) -> bool {
163        self.0 == other.0
164    }
165}
166
167impl From<Blob> for PlainStorage {
168    #[inline]
169    fn from(blob: Blob) -> Self {
170        PlainStorage(blob)
171    }
172}
173
174impl std::ops::Deref for PlainStorage {
175    type Target = [u8];
176    #[inline]
177    fn deref(&self) -> &[u8] {
178        self.0.as_bytes()
179    }
180}
181
182impl std::ops::DerefMut for PlainStorage {
183    #[inline]
184    fn deref_mut(&mut self) -> &mut [u8] {
185        self.0.as_bytes_mut()
186    }
187}
188
189impl fmt::Debug for PlainStorage {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        fmt::Debug::fmt(&self.0, f)
192    }
193}
194
195impl fmt::Display for PlainStorage {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        fmt::Display::fmt(&self.0, f)
198    }
199}
200
201impl TensorStorage for PlainStorage {
202    #[inline]
203    fn is_empty(&self) -> bool {
204        self.0.is_empty()
205    }
206
207    #[inline]
208    fn byte_len(&self) -> usize {
209        self.0.len()
210    }
211
212    fn deep_clone(&self) -> Box<dyn TensorStorage> {
213        Box::new(PlainStorage(self.0.clone()))
214    }
215
216    fn as_plain_ram(&self) -> Option<&PlainStorage> {
217        Some(self)
218    }
219
220    fn as_plain_ram_mut(&mut self) -> Option<&mut PlainStorage> {
221        Some(self)
222    }
223
224    fn into_plain_ram(self: Box<Self>) -> Option<PlainStorage> {
225        Some(*self)
226    }
227
228    fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
229        state.write_u8(0);
230        state.write(self.0.as_bytes());
231    }
232
233    fn exotic_fact(&self, _shape: &[usize]) -> TractResult<Option<Box<dyn ExoticFact>>> {
234        Ok(None)
235    }
236
237    fn is_exotic(&self) -> bool {
238        false
239    }
240}
241
242/// Inline enum replacing `Box<dyn TensorStorage>`.
243///
244/// The common `Plain` case stays inline (no heap alloc, no vtable indirection).
245/// `Exotic` covers every other backend behind a single Box indirection, whether
246/// or not it is exotic in the fact sense -- `is_exotic` answers that.
247#[derive(Debug, PartialEq, Eq)]
248#[allow(dead_code)]
249pub(crate) enum StorageKind {
250    Plain(PlainStorage),
251    Exotic(Box<dyn TensorStorage>),
252}
253
254impl StorageKind {
255    #[inline]
256    pub fn as_plain_ram(&self) -> Option<&PlainStorage> {
257        match self {
258            StorageKind::Plain(d) => Some(d),
259            StorageKind::Exotic(o) => o.as_plain_ram(),
260        }
261    }
262
263    #[inline]
264    pub fn as_plain_ram_mut(&mut self) -> Option<&mut PlainStorage> {
265        match self {
266            StorageKind::Plain(d) => Some(d),
267            StorageKind::Exotic(o) => o.as_plain_ram_mut(),
268        }
269    }
270
271    #[inline]
272    pub fn into_plain_ram(self) -> Option<PlainStorage> {
273        match self {
274            StorageKind::Plain(d) => Some(d),
275            StorageKind::Exotic(o) => o.into_plain_ram(),
276        }
277    }
278
279    #[inline]
280    pub fn byte_len(&self) -> usize {
281        match self {
282            StorageKind::Plain(d) => d.0.len(),
283            StorageKind::Exotic(o) => o.byte_len(),
284        }
285    }
286
287    #[inline]
288    pub fn is_empty(&self) -> bool {
289        match self {
290            StorageKind::Plain(d) => d.0.is_empty(),
291            StorageKind::Exotic(o) => o.is_empty(),
292        }
293    }
294
295    #[inline]
296    #[allow(dead_code)]
297    pub fn deep_clone(&self) -> StorageKind {
298        match self {
299            StorageKind::Plain(d) => StorageKind::Plain(d.clone()),
300            StorageKind::Exotic(o) => StorageKind::Exotic(o.deep_clone()),
301        }
302    }
303
304    #[inline]
305    pub fn is_exotic(&self) -> bool {
306        match self {
307            StorageKind::Plain(_) => false,
308            StorageKind::Exotic(o) => o.is_exotic(),
309        }
310    }
311
312    #[inline]
313    pub fn in_ram(&self) -> bool {
314        match self {
315            StorageKind::Plain(_) => true,
316            StorageKind::Exotic(o) => o.in_ram(),
317        }
318    }
319
320    #[inline]
321    pub fn materialize_plain_ram(&self) -> TractResult<&PlainStorage> {
322        match self {
323            StorageKind::Plain(d) => Ok(d),
324            StorageKind::Exotic(o) => o.materialize_plain_ram(),
325        }
326    }
327
328    #[inline]
329    pub fn as_storage(&self) -> &dyn TensorStorage {
330        match self {
331            StorageKind::Plain(d) => d,
332            StorageKind::Exotic(o) => o.as_ref(),
333        }
334    }
335
336    #[inline]
337    #[allow(dead_code)]
338    pub fn as_storage_mut(&mut self) -> &mut dyn TensorStorage {
339        match self {
340            StorageKind::Plain(d) => d,
341            StorageKind::Exotic(o) => o.as_mut(),
342        }
343    }
344
345    pub fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
346        match self {
347            StorageKind::Plain(d) => {
348                state.write_u8(0);
349                state.write(d.as_bytes())
350            }
351            StorageKind::Exotic(o) => o.dyn_hash(state),
352        }
353    }
354}