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
use crate::{backend::Backend, Tensor};
use std::{any::Any, collections::HashMap};
#[derive(Debug)]
pub struct TensorContainer<B: Backend, ID> {
tensors: HashMap<ID, Box<dyn Any + Send + Sync>>,
_b: B,
}
impl<B, ID> Default for TensorContainer<B, ID>
where
B: Backend,
ID: std::hash::Hash + PartialEq + Eq,
{
fn default() -> Self {
Self::new()
}
}
impl<B, ID> TensorContainer<B, ID>
where
B: Backend,
ID: std::hash::Hash + PartialEq + Eq,
{
pub fn new() -> Self {
Self {
tensors: HashMap::new(),
_b: B::default(),
}
}
pub fn get<const D: usize>(&self, id: &ID) -> Option<Tensor<B, D>> {
let grad = match self.tensors.get(id) {
Some(grad) => grad,
None => return None,
};
let tensor = grad
.downcast_ref()
.map(|primitive: &B::TensorPrimitive<D>| Tensor::from_primitive(primitive.clone()));
tensor
}
pub fn register<const D: usize>(&mut self, id: ID, value: Tensor<B, D>) {
self.tensors.insert(id, Box::new(value.into_primitive()));
}
pub fn remove<const D: usize>(&mut self, id: &ID) -> Option<Tensor<B, D>> {
self.tensors
.remove(id)
.map(|item| item.downcast::<B::TensorPrimitive<D>>().unwrap())
.map(|primitive| Tensor::from_primitive(*primitive))
}
pub fn len(&self) -> usize {
self.tensors.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}