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
use super::tensor_collection::*;
use crate::{
    shapes::{Dtype, Shape},
    tensor::{Storage, Tensor},
    tensor_ops::Device,
};

struct Builder<'a, E, D: Storage<E>> {
    device: &'a D,
    dtype: std::marker::PhantomData<E>,
}
impl<'a, E: Dtype, D: Device<E>> TensorVisitor<E, D> for Builder<'a, E, D> {
    type Viewer = ();
    type Err = D::Err;
    type E2 = E;
    type D2 = D;

    fn visit<S: Shape>(
        &mut self,
        opts: TensorOptions<S, E, D>,
        _t: (),
    ) -> Result<Option<Tensor<S, E, D>>, Self::Err> {
        let mut tensor: Tensor<S, E, D> = self.device.try_zeros_like(&opts.shape)?;
        (opts.reset)(&mut tensor)?;
        Ok(Some(tensor))
    }
}

/// Something that can be built. Related to [super::BuildOnDevice]
pub trait BuildModule<D: Device<E>, E: Dtype>:
    Sized + TensorCollection<E, D, To<E, D> = Self>
{
    /// Construct it on the device
    fn build(device: &D) -> Self {
        Self::try_build(device).unwrap()
    }

    /// Fallible version of [BuildModule::build]
    fn try_build(device: &D) -> Result<Self, D::Err> {
        let out = Self::iter_tensors(&mut RecursiveWalker {
            m: (),
            f: &mut Builder {
                device,
                dtype: std::marker::PhantomData,
            },
        })?;

        Ok(out.unwrap())
    }
}

impl<D: Device<E>, E: Dtype, M: Sized + TensorCollection<E, D, To<E, D> = Self>> BuildModule<D, E>
    for M
{
}