-
Notifications
You must be signed in to change notification settings - Fork 0
/
gradient.go
60 lines (53 loc) · 1.35 KB
/
gradient.go
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
package gosor
func addAddGradientTrackerToRes(res, t1, t2 *Tensor) {
addGradientTracker(res, []*Tensor{t1, t2}, func() ([]*Tensor, error) {
return []*Tensor{
Wrap(New(WithValues(1))).MustValue(),
Wrap(New(WithValues(1))).MustValue(),
}, nil
})
}
func addSubGradientTrackerToRes(res, t1, t2 *Tensor) {
addGradientTracker(res, []*Tensor{t1, t2}, func() ([]*Tensor, error) {
return []*Tensor{
Wrap(New(WithValues(1))).MustValue(),
Wrap(New(WithValues(-1))).MustValue(),
}, nil
})
}
func addMulGradientTrackerToRes(res, t1, t2 *Tensor) {
addGradientTracker(res, []*Tensor{t1, t2}, func() ([]*Tensor, error) {
t1LocalGrad, err := t2.DeepCopy()
if err != nil {
return nil, err
}
t2LocalGrad, err := t1.DeepCopy()
if err != nil {
return nil, err
}
return []*Tensor{
t1LocalGrad,
t2LocalGrad,
}, nil
})
}
func addPowGradientTrackerToRes(res, t1, t2 *Tensor) {
addGradientTracker(res, []*Tensor{t1, t2}, func() ([]*Tensor, error) {
// localGradient = t2 * t1**(t2-1)
tensor1 := Wrap(t1, nil)
tensor2 := Wrap(t2, nil)
resultGrad := Wrap(res.gradient, nil)
t1Grad, err := resultGrad.Do(Mul, tensor2.Do(
Mul,
tensor1.Do(
Pow,
tensor2.Do(Sub, Wrap(New(WithValues(1)))),
),
)).Value()
if err != nil {
return nil, err
}
// Todo: calculate gradient for t2.
return []*Tensor{t1Grad, nil}, nil
})
}