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};

/// Contains tensor of arbitrary dimension.
#[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,
{
    /// Create an empty container.
    pub fn new() -> Self {
        Self {
            tensors: HashMap::new(),
            _b: B::default(),
        }
    }

    /// Get a tensor with the given ID.
    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
    }

    /// Register a new tensor for the given ID.
    ///
    /// # Notes
    ///
    /// If a tensor is already registered for the given ID, it will be replaced.
    pub fn register<const D: usize>(&mut self, id: ID, value: Tensor<B, D>) {
        self.tensors.insert(id, Box::new(value.into_primitive()));
    }

    /// Remove a tensor for the given ID and returns it.
    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))
    }

    /// The number of tensors registered.
    pub fn len(&self) -> usize {
        self.tensors.len()
    }

    /// If any tensor is contained.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}