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
298
299
300
301
302
303
304
305
306
307
308
309
310
use crate::internal::*;
use downcast_rs::Downcast;
use std::fmt;
#[derive(Clone, PartialEq, Hash)]
pub struct ShapeFact {
dims: TVec<TDim>,
concrete: Option<TVec<usize>>,
}
impl ShapeFact {
pub fn rank(&self) -> usize {
self.dims.len()
}
fn compute_concrete(&mut self) {
self.concrete =
self.dims.iter().map(|d| d.to_usize()).collect::<TractResult<TVec<_>>>().ok()
}
pub fn as_concrete(&self) -> Option<&[usize]> {
self.concrete.as_deref()
}
pub fn is_concrete(&self) -> bool {
self.concrete.is_some()
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item = TDim> + 'a {
self.dims.iter().cloned()
}
pub fn to_tvec(&self) -> TVec<TDim> {
self.dims.clone()
}
pub fn eval_to_usize(&self, values: &SymbolValues) -> TractResult<Cow<TVec<usize>>> {
if let Some(c) = &self.concrete {
Ok(Cow::Borrowed(c))
} else {
Ok(Cow::Owned(
self.iter()
.map(|d| d.eval(&values).to_usize())
.collect::<TractResult<TVec<_>>>()?,
))
}
}
pub fn eval_to_isize(&self, values: &SymbolValues) -> TractResult<TVec<isize>> {
self.iter().map(|d| d.eval(&values).to_isize()).collect::<TractResult<_>>()
}
pub fn from_dims<D: ToDim, T: IntoIterator<Item = D>>(it: T) -> ShapeFact {
let mut dims = ShapeFact { dims: it.into_iter().map(|d| d.to_dim()).collect(), concrete: None };
dims.compute_concrete();
dims
}
pub fn set(&mut self, ix: usize, dim: TDim) {
self.dims[ix] = dim;
self.compute_concrete();
}
pub fn insert_axis(&mut self, axis: usize) -> TractResult<()> {
self.dims.insert(axis, 1.into());
if let Some(concrete) = &mut self.concrete {
concrete.insert(axis, 1);
}
Ok(())
}
pub fn remove_axis(&mut self, axis: usize) -> TractResult<()> {
self.dims.remove(axis);
if let Some(concrete) = &mut self.concrete {
concrete.remove(axis);
}
Ok(())
}
}
impl std::ops::Deref for ShapeFact {
type Target = [TDim];
fn deref(&self) -> &[TDim] {
&self.dims
}
}
impl<D: ToDim, T: IntoIterator<Item = D>> From<T> for ShapeFact {
fn from(it: T) -> ShapeFact {
ShapeFact::from_dims(it)
}
}
pub trait Fact: std::fmt::Debug + Downcast + dyn_clone::DynClone + Send + Sync + 'static {
fn to_typed_fact(&self) -> TractResult<TypedFact>;
fn matches(&self, t: &Tensor, symbols: Option<&SymbolValues>) -> TractResult<bool> {
self.to_typed_fact()?.matches(t, symbols)
}
fn same_as(&self, _other: &dyn Fact) -> bool;
fn compatible_with(&self, _other: &dyn Fact) -> bool;
}
impl_downcast!(Fact);
dyn_clone::clone_trait_object!(Fact);
impl<D: ToDim> std::iter::FromIterator<D> for ShapeFact {
fn from_iter<T: IntoIterator<Item = D>>(iter: T) -> Self {
ShapeFact::from_dims(iter.into_iter().map(|d| d.to_dim()))
}
}
impl fmt::Debug for ShapeFact {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use tract_itertools::Itertools;
write!(fmt, "{}", self.iter().join(","))
}
}
impl AsRef<[TDim]> for ShapeFact {
fn as_ref(&self) -> &[TDim] {
&self.dims
}
}
#[derive(Clone, PartialEq, Hash)]
pub struct TypedFact {
pub datum_type: DatumType,
pub shape: ShapeFact,
pub konst: Option<Arc<Tensor>>,
pub uniform: Option<Arc<Tensor>>,
}
impl_dyn_hash!(TypedFact);
impl TypedFact {
pub fn scalar<T>() -> TypedFact
where
T: Datum,
{
let foo: &[usize] = &[];
Self::dt_shape(T::datum_type(), foo)
}
pub fn shape<T, S>(shape: S) -> TypedFact
where
T: Datum,
S: Into<ShapeFact>,
{
Self::dt_shape(T::datum_type(), shape)
}
pub fn dt_scalar(datum_type: DatumType) -> TypedFact {
let foo: &[usize] = &[];
TypedFact { datum_type, shape: ShapeFact::from(foo), konst: None, uniform: None }
}
pub fn dt_shape<S>(datum_type: DatumType, shape: S) -> TypedFact
where
S: Into<ShapeFact>,
{
TypedFact { datum_type, shape: shape.into(), konst: None, uniform: None }
}
pub fn rank(&self) -> usize {
if cfg!(debug_assertions) {
self.consistent().unwrap();
}
self.shape.rank()
}
fn format_dt_shape_nocheck(&self) -> String {
if self.shape.rank() > 0 {
format!("{:?},{:?}", self.shape, self.datum_type)
} else {
format!("{:?}", self.datum_type)
}
}
pub fn format_dt_shape(&self) -> String {
if cfg!(debug_assertions) {
self.consistent().unwrap()
}
self.format_dt_shape_nocheck()
}
pub fn consistent(&self) -> TractResult<()> {
if let Some(k) = &self.konst {
if !self.matches(k.as_ref(), None)? {
bail!("fact says {}, constant is {:?}", self.format_dt_shape_nocheck(), k);
}
}
if let Some(u) = &self.uniform {
if self.datum_type != u.datum_type() {
bail!("fact as uniform value {:?}, but is of type {:?}", u, self.datum_type);
}
}
if let (Some(u), Some(k)) = (self.uniform.as_deref(), self.konst.as_deref()) {
if let Some(k) = k.as_uniform() {
if &k != u {
bail!("Uniform value and uniform constant mismatch: {:?}, {:?}", u, k);
}
} else {
bail!("Fact said to be uniform ({:?}) and equal to {:?} which is not.", u, k);
}
}
Ok(())
}
pub fn without_value(&self) -> Self {
Self::dt_shape(self.datum_type, self.shape.clone())
}
}
impl Fact for TypedFact {
fn to_typed_fact(&self) -> TractResult<TypedFact> {
if cfg!(debug_assertions) {
self.consistent()?
}
Ok(self.clone())
}
fn matches(&self, t: &Tensor, symbols: Option<&SymbolValues>) -> TractResult<bool> {
let shape = self.shape.eval_to_usize(symbols.unwrap_or(&SymbolValues::default()))?;
Ok(self.datum_type == t.datum_type() && &**shape == t.shape())
}
fn same_as(&self, other: &dyn Fact) -> bool {
if cfg!(debug_assertions) {
self.consistent().unwrap()
}
if let Some(other) = other.downcast_ref::<Self>() {
if cfg!(debug_assertions) {
other.consistent().unwrap()
}
self == other
} else {
false
}
}
fn compatible_with(&self, other: &dyn Fact) -> bool {
if cfg!(debug_assertions) {
self.consistent().unwrap()
}
if let Some(other) = other.downcast_ref::<Self>() {
if cfg!(debug_assertions) {
other.consistent().unwrap()
}
self.without_value().same_as(&other.without_value())
} else {
false
}
}
}
impl From<Tensor> for TypedFact {
fn from(t: Tensor) -> TypedFact {
TypedFact::from(t.into_arc_tensor())
}
}
impl<'t> From<&'t Tensor> for TypedFact {
fn from(t: &'t Tensor) -> TypedFact {
TypedFact::from(t.clone())
}
}
impl From<Arc<Tensor>> for TypedFact {
fn from(t: Arc<Tensor>) -> TypedFact {
TypedFact {
datum_type: t.datum_type(),
shape: ShapeFact::from_dims(t.shape().iter().map(TDim::from)),
uniform: t.as_uniform().map(Arc::new),
konst: Some(t),
}
}
}
impl<'a> From<&'a TypedFact> for TypedFact {
fn from(fact: &TypedFact) -> TypedFact {
fact.clone()
}
}
impl fmt::Debug for TypedFact {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.konst {
Some(ref k) => write!(fmt, "{:?}", k),
None if self.rank() > 0 => write!(fmt, "{:?},{:?}", self.shape, self.datum_type),
None => write!(fmt, "{:?}", self.datum_type),
}
}
}