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
use std::collections::BTreeMap;

use crate::{transforms::Func, Tensor};

pub trait Module {
    fn forward(&self, input: &Tensor) -> Tensor;
    fn parameters(&self) -> Vec<Tensor>;
    fn update(&mut self, params: &BTreeMap<usize, Tensor>);
}

impl<T> Func<Tensor, Tensor> for T
where
    T: Module,
{
    type Tangent = BTreeMap<usize, Tensor>;
    type Cotangent = BTreeMap<usize, Tensor>;

    fn call(&self, input: Tensor) -> Tensor {
        self.forward(&input)
    }

    fn capture_inputs(&self, _input: &Tensor) -> Vec<Tensor> {
        self.parameters()
    }
}

// for loss fn (module, input) -> loss
impl<M, F> Func<(&M, &Tensor), Tensor> for F
where
    M: Module,
    F: Fn(&M, &Tensor) -> Tensor,
{
    type Tangent = BTreeMap<usize, Tensor>;
    type Cotangent = BTreeMap<usize, Tensor>;
    fn call(&self, input: (&M, &Tensor)) -> Tensor {
        self(input.0, input.1)
    }

    fn capture_inputs(&self, input: &(&M, &Tensor)) -> Vec<Tensor> {
        input.0.parameters()
    }
}

// for loss fn (module, input, label) -> loss
impl<M, F> Func<(&M, &Tensor, &Tensor), Tensor> for F
where
    M: Module,
    F: Fn(&M, &Tensor, &Tensor) -> Tensor,
{
    type Tangent = BTreeMap<usize, Tensor>;
    type Cotangent = BTreeMap<usize, Tensor>;
    fn call(&self, input: (&M, &Tensor, &Tensor)) -> Tensor {
        self(input.0, input.1, input.2)
    }

    fn capture_inputs(&self, input: &(&M, &Tensor, &Tensor)) -> Vec<Tensor> {
        input.0.parameters()
    }
}

// for loss fn  (module, input) -> (loss, logits)
impl<M, F> Func<(&M, &Tensor), (Tensor, Tensor)> for F
where
    M: Module,
    F: Fn(&M, &Tensor) -> (Tensor, Tensor),
{
    type Tangent = BTreeMap<usize, Tensor>;
    type Cotangent = BTreeMap<usize, Tensor>;
    fn call(&self, input: (&M, &Tensor)) -> (Tensor, Tensor) {
        self(input.0, input.1)
    }

    fn capture_inputs(&self, input: &(&M, &Tensor)) -> Vec<Tensor> {
        input.0.parameters()
    }
}

// for loss fn (module, input, label) -> loss
impl<M, F> Func<(&M, &Tensor, &Tensor), (Tensor, Tensor)> for F
where
    M: Module,
    F: Fn(&M, &Tensor, &Tensor) -> (Tensor, Tensor),
{
    type Tangent = BTreeMap<usize, Tensor>;
    type Cotangent = BTreeMap<usize, Tensor>;
    fn call(&self, input: (&M, &Tensor, &Tensor)) -> (Tensor, Tensor) {
        self(input.0, input.1, input.2)
    }

    fn capture_inputs(&self, input: &(&M, &Tensor, &Tensor)) -> Vec<Tensor> {
        input.0.parameters()
    }
}