This repository has been archived by the owner on Oct 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgograd.go
123 lines (106 loc) · 2.21 KB
/
gograd.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"fmt"
"math"
)
// Var stores a single variable of type float64
type Var struct {
value float64
grad float64
children []*Var
backward func(float64, *Var, *Var)
}
// NewVar creates a new variable of type Var
func NewVar(value float64) (newVar *Var) {
newVar = &Var{value: value}
newVar.children = []*Var{}
newVar.grad = 0
return
}
// Add adds two variables
func (x *Var) Add(y *Var) *Var {
return &Var{
value: x.value + y.value,
children: []*Var{x, y},
backward: func(v float64, x *Var, y *Var) {
x.grad += v
y.grad += v
}}
}
// Mul multiplies two variables
func (x *Var) Mul(y *Var) *Var {
return &Var{
value: x.value * y.value,
children: []*Var{x, y},
backward: func(v float64, x *Var, y *Var) {
x.grad += y.value * v
y.grad += x.value * v
}}
}
// Sub subtracts two variables
func (x *Var) Sub(y *Var) *Var {
return &Var{
value: x.value - y.value,
children: []*Var{x, y},
backward: func(v float64, x *Var, y *Var) {
x.grad += v
y.grad += (v * -1)
}}
}
// Div divides two variables
func (x *Var) Div(y *Var) *Var {
return &Var{
value: x.value / y.value,
children: []*Var{x, y},
backward: func(v float64, x *Var, y *Var) {
x.grad += y.value * v
y.grad += x.value * v
}}
}
// Pow raises one variable to the power of the other
func (x *Var) Pow(y *Var) *Var {
return &Var{
value: math.Pow(x.value, y.value),
children: []*Var{x, y},
backward: func(v float64, x *Var, y *Var) {
x.grad += (y.value * math.Pow(x.value, y.value-1)) * v
}}
}
// Backward reverse accumulates the gradient
func (x *Var) Backward() {
stack := []*Var{}
visited := map[*Var]bool{
x: false,
}
var expand func(x *Var)
expand = func(x *Var) {
if !visited[x] {
visited[x] = true
if len(x.children) > 0 {
for _, c := range x.children {
expand(c)
}
}
stack = append(stack, x)
}
}
expand(x)
x.grad = 1
for i := len(stack) - 1; i >= 0; i-- {
c := stack[i]
if len(c.children) > 0 {
c.backward(c.grad, c.children[0], c.children[1])
}
}
}
func main() {
a := NewVar(4)
b := NewVar(3)
c := a.Add(b)
d := a.Mul(c)
d.Backward()
fmt.Println(d.value)
fmt.Println(a.grad)
fmt.Println(b.grad)
fmt.Println(c.grad)
}