tract_data/tensor/
named.rs1use std::fmt;
4use std::hash::Hash;
5use std::sync::{Arc, OnceLock};
6
7use crate::TractResult;
8use crate::datum::DatumType;
9use crate::exotic::ExoticFact;
10use crate::internal::*;
11use crate::tensor::storage::{PlainStorage, TensorStorage};
12
13pub trait WeightSource: Send + Sync + fmt::Debug {
16 fn load(&self, name: &str, dt: DatumType, shape: &[usize]) -> TractResult<Tensor>;
17
18 fn contains(&self, _name: &str) -> bool {
21 true
22 }
23}
24
25pub struct NamedStorage {
34 name: String,
35 dt: DatumType,
36 shape: TVec<usize>,
37 source: Option<Arc<dyn WeightSource>>,
38 host: OnceLock<Arc<Tensor>>,
39}
40
41impl NamedStorage {
42 pub fn new(
43 name: impl Into<String>,
44 dt: DatumType,
45 shape: &[usize],
46 source: Option<Arc<dyn WeightSource>>,
47 ) -> NamedStorage {
48 NamedStorage { name: name.into(), dt, shape: shape.into(), source, host: OnceLock::new() }
49 }
50
51 pub fn into_tensor(self) -> Tensor {
53 let dt = self.dt;
54 let shape = self.shape.clone();
55 Tensor::from_storage(dt, &shape, self)
56 }
57
58 pub fn name(&self) -> &str {
59 &self.name
60 }
61
62 pub fn with_source(&self, source: Arc<dyn WeightSource>) -> NamedStorage {
64 NamedStorage::new(self.name.clone(), self.dt, &self.shape, Some(source))
65 }
66
67 pub fn is_materialized(&self) -> bool {
68 self.host.get().is_some()
69 }
70
71 fn materialize(&self) -> TractResult<&Arc<Tensor>> {
72 if let Some(host) = self.host.get() {
73 return Ok(host);
74 }
75 let source = self
76 .source
77 .as_ref()
78 .with_context(|| format!("Weight {:?} has no source to be read from", self.name))?;
79 let tensor = source
80 .load(&self.name, self.dt, &self.shape)
81 .with_context(|| format!("Loading weight {:?}", self.name))?;
82 ensure!(
83 tensor.datum_type() == self.dt && tensor.shape() == &*self.shape,
84 "Weight {:?} loaded as {:?} {:?}, expected {:?} {:?}",
85 self.name,
86 tensor.datum_type(),
87 tensor.shape(),
88 self.dt,
89 self.shape
90 );
91 Ok(self.host.get_or_init(|| tensor.into_arc_tensor()))
92 }
93}
94
95impl PartialEq for NamedStorage {
96 fn eq(&self, other: &Self) -> bool {
97 self.name == other.name && self.dt == other.dt && self.shape == other.shape
98 }
99}
100
101impl Eq for NamedStorage {}
102
103impl fmt::Debug for NamedStorage {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 fmt::Display::fmt(self, f)
106 }
107}
108
109impl fmt::Display for NamedStorage {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 let state = if self.is_materialized() { "loaded" } else { "not loaded" };
112 write!(f, "Named({:?}, {state})", self.name)
113 }
114}
115
116impl TensorStorage for NamedStorage {
117 fn byte_len(&self) -> usize {
118 self.shape.iter().product::<usize>() * self.dt.size_of()
119 }
120
121 fn is_empty(&self) -> bool {
122 self.byte_len() == 0
123 }
124
125 fn deep_clone(&self) -> Box<dyn TensorStorage> {
126 let host = OnceLock::new();
127 if let Some(h) = self.host.get() {
128 let _ = host.set(Arc::clone(h));
129 }
130 Box::new(NamedStorage {
131 name: self.name.clone(),
132 dt: self.dt,
133 shape: self.shape.clone(),
134 source: self.source.clone(),
135 host,
136 })
137 }
138
139 fn as_plain_ram(&self) -> Option<&PlainStorage> {
140 self.host.get().and_then(|h| h.as_plain_ram_storage())
141 }
142
143 fn as_plain_ram_mut(&mut self) -> Option<&mut PlainStorage> {
144 self.materialize().ok()?;
145 Arc::make_mut(self.host.get_mut()?).as_plain_ram_storage_mut()
146 }
147
148 fn into_plain_ram(self: Box<Self>) -> Option<PlainStorage> {
149 let me = *self;
150 me.materialize().ok()?;
151 let host = me.host.into_inner()?;
152 let host = Arc::try_unwrap(host).unwrap_or_else(|shared| (*shared).clone());
153 host.into_blob().ok().map(PlainStorage::from)
154 }
155
156 fn dyn_hash(&self, mut state: &mut dyn std::hash::Hasher) {
157 self.name.hash(&mut state);
158 }
159
160 fn exotic_fact(&self, _shape: &[usize]) -> TractResult<Option<Box<dyn ExoticFact>>> {
161 Ok(None)
162 }
163
164 fn is_exotic(&self) -> bool {
165 false
166 }
167
168 fn in_ram(&self) -> bool {
169 self.is_materialized()
170 }
171
172 fn stays_lazy(&self) -> bool {
173 true
174 }
175
176 fn materialize_plain_ram(&self) -> TractResult<&PlainStorage> {
177 self.materialize()?
178 .as_plain_ram_storage()
179 .context("Weight source did not produce plain storage")
180 }
181}