-
Notifications
You must be signed in to change notification settings - Fork 0
/
autograd_test.go
76 lines (56 loc) · 1.9 KB
/
autograd_test.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package gosor
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestAutoGradAdd(t *testing.T) {
t.Parallel()
a := Wrap(New(WithValues(2), WithRecordGradients()))
b := Wrap(New(WithValues(3), WithRecordGradients()))
c := Wrap(New(WithValues(9), WithRecordGradients()))
res, err := a.Do(Add, b).Do(Add, c).Value()
require.NoError(t, err)
require.Equal(t, 14., res.Item())
err = res.Backward(nil)
require.NoError(t, err)
require.Equal(t, []float64{1}, res.gradient.Items())
require.Equal(t, []float64{1}, c.MustValue().gradient.Items())
require.Equal(t, []float64{1}, b.MustValue().gradient.Items())
require.Equal(t, []float64{1}, a.MustValue().gradient.Items())
}
func TestAutoGradSub(t *testing.T) {
t.Parallel()
a := Wrap(New(WithValues(4), WithRecordGradients()))
b := Wrap(New(WithValues(2), WithRecordGradients()))
res, err := a.Do(Sub, b).Value()
require.NoError(t, err)
err = res.Backward(nil)
require.NoError(t, err)
require.Equal(t, []float64{2}, res.Items())
require.Equal(t, []float64{1}, a.MustValue().gradient.Items())
require.Equal(t, []float64{-1}, b.MustValue().gradient.Items())
}
func TestAutoGradPow(t *testing.T) {
t.Parallel()
a := Wrap(New(WithValues(4), WithRecordGradients()))
b := Wrap(New(WithValues(2), WithRecordGradients()))
res, err := a.Do(Pow, b).Value()
require.NoError(t, err)
require.Equal(t, []float64{16}, res.Items())
err = res.Backward(nil)
require.NoError(t, err)
require.Equal(t, []float64{8}, a.MustValue().gradient.Items())
}
func TestGradSum(t *testing.T) {
t.Parallel()
a := Wrap(New(WithValues(1, 1, 1, 1), WithRecordGradients()))
b, err := a.DoT(Sum).Value()
require.NoError(t, err)
require.Equal(t, []float64{4}, b.Items())
fmt.Println(b.gradFunc())
err = b.Backward(nil)
require.NoError(t, err)
fmt.Println("ja: ", a.MustValue().gradient)
require.Equal(t, []float64{1, 1, 1, 1}, a.MustValue().gradient.Items())
}