-
Notifications
You must be signed in to change notification settings - Fork 5
/
tensor.rs
75 lines (62 loc) · 1.5 KB
/
tensor.rs
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
use std::{borrow::Cow, slice::from_raw_parts};
use ndarray::{ArrayD, ArrayViewD};
use safetensors::{Dtype, View};
pub struct Tensor<'a> {
pub data: ArrayViewD<'a, f32>,
}
impl<'a> Tensor<'a> {
pub fn new(data: ArrayViewD<'a, f32>) -> Self {
Self { data }
}
}
impl<'a> View for Tensor<'a> {
fn dtype(&self) -> Dtype {
Dtype::F32
}
fn shape(&self) -> &[usize] {
self.data.shape()
}
fn data(&self) -> Cow<[u8]> {
let slice = self.data.as_slice().expect("Non contiguous tensors");
let new_slice: &[u8] =
unsafe { from_raw_parts(slice.as_ptr() as *const u8, slice.len() * 4) };
Cow::from(new_slice)
}
fn data_len(&self) -> usize {
self.data.len() * 4
}
}
#[derive(Debug)]
pub struct DenseTensors {
pub weights: ArrayD<f32>,
pub biases: ArrayD<f32>,
}
#[derive(Debug)]
pub struct ConvTensors {
pub weights: ArrayD<f32>,
pub biases: ArrayD<f32>,
}
#[derive(Debug)]
pub struct BatchNormTensors {
pub gamma: ArrayD<f32>,
pub beta: ArrayD<f32>,
pub running_mean: ArrayD<f32>,
pub running_var: ArrayD<f32>,
}
#[derive(Debug)]
pub enum Tensors {
Dense(DenseTensors),
Conv(ConvTensors),
BatchNorm(BatchNormTensors),
}
pub trait GetTensor {
fn get(&mut self) -> Option<Tensors>;
}
impl GetTensor for Option<Vec<Tensors>> {
fn get(&mut self) -> Option<Tensors> {
if let Some(tensors) = self {
return Some(tensors.remove(0));
}
None
}
}