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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! `Tensor` is the main data container for tract
use crate::dim::TDim;
use crate::tensor::litteral::*;
use crate::tensor::Tensor;
use crate::TractResult;
use std::{fmt, ops};
use std::hash::Hash;

use tract_linalg::f16::f16;

mod arrays;
pub use arrays::ArrayDatum;

#[cfg(feature = "serialize")]
use serde::ser::{Serialize, Serializer};

#[derive(Debug, Default, Clone, PartialEq, Eq, Educe)]
#[educe(Hash)]
pub struct Blob(pub Vec<u8>);

impl ops::Deref for Blob {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Display for Blob {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Blob of {} bytes: {}", self.len(), String::from_utf8_lossy(self))
    }
}

impl std::str::FromStr for Blob {
    type Err = ();
    fn from_str(s: &str) -> Result<Blob, ()> {
        Ok(Blob(s.as_bytes().to_vec()))
    }
}

impl tract_linalg::hash::SloppyHash for Blob {
    fn sloppy_hash<S: std::hash::Hasher>(&self, state: &mut S) {
        self.0.hash(state)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub enum DatumType {
    Bool,
    U8,
    U16,
    I8,
    I16,
    I32,
    I64,
    F16,
    F32,
    F64,
    TDim,
    Blob,
    String,
}

impl DatumType {
    pub fn super_types(&self) -> &'static [DatumType] {
        match self {
            DatumType::Bool => &[DatumType::Bool],
            DatumType::U8 => &[
                DatumType::U8,
                DatumType::I16,
                DatumType::I32,
                DatumType::I64,
                DatumType::TDim,
                DatumType::F32,
            ],
            DatumType::U16 => {
                &[DatumType::U16, DatumType::I32, DatumType::I64, DatumType::TDim, DatumType::F32]
            }
            DatumType::I8 => &[
                DatumType::I8,
                DatumType::I16,
                DatumType::I32,
                DatumType::I64,
                DatumType::TDim,
                DatumType::F32,
            ],
            DatumType::I16 => {
                &[DatumType::I16, DatumType::I32, DatumType::I64, DatumType::TDim, DatumType::F32]
            }
            DatumType::I32 => &[DatumType::I32, DatumType::I64, DatumType::TDim, DatumType::F32],
            DatumType::I64 => &[DatumType::I64, DatumType::TDim, DatumType::F32],
            DatumType::F16 => &[DatumType::F16, DatumType::F32, DatumType::F64],
            DatumType::F32 => &[DatumType::F32, DatumType::F64],
            DatumType::F64 => &[DatumType::F64],
            DatumType::String => &[DatumType::String],
            DatumType::Blob => &[DatumType::Blob],
            DatumType::TDim => &[DatumType::TDim],
        }
    }

    pub fn super_type_for(
        i: impl IntoIterator<Item = impl std::borrow::Borrow<DatumType>>,
    ) -> Option<DatumType> {
        let mut iter = i.into_iter();
        let mut current = match iter.next() {
            None => return None,
            Some(it) => *it.borrow(),
        };
        while let Some(n) = iter.next() {
            match current.common_super_type(*n.borrow()) {
                None => return None,
                Some(it) => current = it,
            }
        }
        Some(current)
    }

    pub fn common_super_type(&self, rhs: DatumType) -> Option<DatumType> {
        for mine in self.super_types() {
            for theirs in rhs.super_types() {
                if mine == theirs {
                    return Some(*mine);
                }
            }
        }
        return None;
    }

    pub fn is_integer(&self) -> bool {
        match self {
            DatumType::U8
            | DatumType::U16
            | DatumType::I8
            | DatumType::I16
            | DatumType::I32
            | DatumType::I64 => true,
            _ => false,
        }
    }

    pub fn size_of(&self) -> usize {
        match self {
            DatumType::Bool => std::mem::size_of::<bool>(),
            DatumType::U8 => std::mem::size_of::<u8>(),
            DatumType::U16 => std::mem::size_of::<u16>(),
            DatumType::I8 => std::mem::size_of::<i8>(),
            DatumType::I16 => std::mem::size_of::<i16>(),
            DatumType::I32 => std::mem::size_of::<i32>(),
            DatumType::I64 => std::mem::size_of::<i64>(),
            DatumType::F16 => std::mem::size_of::<f16>(),
            DatumType::F32 => std::mem::size_of::<f32>(),
            DatumType::F64 => std::mem::size_of::<f64>(),
            DatumType::Blob => std::mem::size_of::<Blob>(),
            DatumType::TDim => std::mem::size_of::<TDim>(),
            DatumType::String => std::mem::size_of::<String>(),
        }
    }

    pub fn alignment(&self) -> usize {
        match self {
            DatumType::TDim => std::mem::size_of::<usize>(),
            DatumType::String => std::mem::size_of::<usize>(),
            _ => self.size_of(),
        }
    }
}

pub trait Datum:
    Clone
    + Send
    + Sync
    + fmt::Debug
    + fmt::Display
    + Default
    + 'static
    + PartialEq
    + tract_linalg::hash::SloppyHash
{
    fn name() -> &'static str;
    fn datum_type() -> DatumType;
}

pub(crate) trait TryInto<D> {
    fn try_into(&self) -> TractResult<D>;
}

macro_rules! datum {
    ($t:ty, $v:ident) => {
        impl From<$t> for Tensor {
            fn from(it: $t) -> Tensor {
                tensor0(it)
            }
        }

        impl Datum for $t {
            fn name() -> &'static str {
                stringify!($t)
            }

            fn datum_type() -> DatumType {
                DatumType::$v
            }
        }
    };
}

macro_rules! try_into {
    ($f:ty, $t:ty) => {
        impl TryInto<$t> for $f {
            fn try_into(&self) -> TractResult<$t> {
                Ok(*self as $t)
            }
        }
    };
}

try_into!(i8, i16);
try_into!(i8, i32);
try_into!(i8, i64);
try_into!(i16, i32);
try_into!(i16, i64);
try_into!(i32, i64);

try_into!(i16, i8);
try_into!(i32, i8);
try_into!(i64, i8);
try_into!(i32, i16);
try_into!(i64, i16);
try_into!(i64, i32);

try_into!(f64, f32);
try_into!(f32, f64);

try_into!(i8, f32);
try_into!(i16, f32);
try_into!(i32, f32);
try_into!(i64, f32);

try_into!(u8, f32);
try_into!(u16, f32);

try_into!(u8, i64);

try_into!(u8, i32);
try_into!(u16, i32);

try_into!(i8, f64);
try_into!(i16, f64);
try_into!(i32, f64);
try_into!(i64, f64);

try_into!(f32, i8);
try_into!(f32, i16);
try_into!(f32, i32);
try_into!(f32, i64);

try_into!(f64, i8);
try_into!(f64, i16);
try_into!(f64, i32);
try_into!(f64, i64);

impl TryInto<TDim> for i32 {
    fn try_into(&self) -> TractResult<TDim> {
        Ok((*self).into())
    }
}

impl TryInto<TDim> for i64 {
    fn try_into(&self) -> TractResult<TDim> {
        Ok((*self).into())
    }
}

impl TryInto<i32> for TDim {
    fn try_into(&self) -> TractResult<i32> {
        self.to_integer().map(|i| i as i32)
    }
}

impl TryInto<i64> for TDim {
    fn try_into(&self) -> TractResult<i64> {
        self.to_integer().map(|i| i as i64)
    }
}

impl tract_linalg::hash::SloppyHash for TDim {
    fn sloppy_hash<S: std::hash::Hasher>(&self, state: &mut S) {
        self.hash(state)
    }
}

impl TryInto<bool> for f32 {
    fn try_into(&self) -> TractResult<bool> {
        Ok(*self != 0.0)
    }
}

impl TryInto<f32> for bool {
    fn try_into(&self) -> TractResult<f32> {
        if *self {
            Ok(1.0)
        } else {
            Ok(0.0)
        }
    }
}

impl TryInto<bool> for f64 {
    fn try_into(&self) -> TractResult<bool> {
        Ok(*self != 0.0)
    }
}

impl TryInto<f64> for bool {
    fn try_into(&self) -> TractResult<f64> {
        if *self {
            Ok(1.0)
        } else {
            Ok(0.0)
        }
    }
}

macro_rules! cast_to_and_from_bool {
    ($t: ty) => {
        impl TryInto<bool> for $t {
            fn try_into(&self) -> TractResult<bool> {
                Ok(*self != 0)
            }
        }

        impl TryInto<$t> for bool {
            fn try_into(&self) -> TractResult<$t> {
                Ok(*self as usize as _)
            }
        }
    }
}
cast_to_and_from_bool!(i8);
cast_to_and_from_bool!(i16);
cast_to_and_from_bool!(i32);
cast_to_and_from_bool!(i64);


impl TryInto<f32> for f16 {
    fn try_into(&self) -> TractResult<f32> {
        Ok(self.0.to_f32())
    }
}

impl TryInto<f64> for f16 {
    fn try_into(&self) -> TractResult<f64> {
        Ok(self.0.to_f64())
    }
}

impl TryInto<f16> for f32 {
    fn try_into(&self) -> TractResult<f16> {
        Ok(f16(half::f16::from_f32(*self)))
    }
}

impl TryInto<f16> for f64 {
    fn try_into(&self) -> TractResult<f16> {
        Ok(f16(half::f16::from_f64(*self)))
    }
}

impl TryInto<String> for f32 {
    fn try_into(&self) -> TractResult<String> {
        Ok(self.to_string())
    }
}

impl TryInto<f32> for String {
    fn try_into(&self) -> TractResult<f32> {
        // this is onnx casts
        if self == "INF" || self == "+INF" {
            Ok(std::f32::INFINITY)
        } else if self == "-INF" {
            Ok(-std::f32::INFINITY)
        } else {
            Ok(self.parse::<f32>().map_err(|_| format!("Can not parse {} as f32", self))?)
        }
    }
}

datum!(bool, Bool);
datum!(f16, F16);
datum!(f32, F32);
datum!(f64, F64);
datum!(i8, I8);
datum!(i16, I16);
datum!(i32, I32);
datum!(i64, I64);
datum!(u8, U8);
datum!(u16, U16);
datum!(TDim, TDim);
datum!(String, String);
datum!(Blob, Blob);

#[cfg(test)]
mod tests {
    use crate::internal::*;
    use ndarray::arr1;

    #[test]
    fn test_array_to_tensor_to_array() {
        let array = arr1(&[12i32, 42]);
        let tensor = Tensor::from(array.clone());
        let view = tensor.to_array_view::<i32>().unwrap();
        assert_eq!(array, view.into_dimensionality().unwrap());
    }

    #[test]
    fn test_cast_dim_to_dim() {
        let t_dim: Tensor = tensor1(&[12isize.to_dim(), 42isize.to_dim()]);
        let t_i32 = t_dim.cast_to::<i32>().unwrap();
        let t_dim_2 = t_i32.cast_to::<TDim>().unwrap().into_owned();
        assert_eq!(t_dim, t_dim_2);
    }

    #[test]
    fn test_cast_i32_to_dim() {
        let t_i32: Tensor = tensor1(&[0i32, 0]);
        t_i32.cast_to::<TDim>().unwrap();
    }

    #[test]
    fn test_cast_i64_to_bool() {
        let t_i64: Tensor = tensor1(&[0i64]);
        t_i64.cast_to::<bool>().unwrap();
    }
}