-
Notifications
You must be signed in to change notification settings - Fork 19
/
meta.go
195 lines (170 loc) · 4.86 KB
/
meta.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package dual
import (
"bytes"
"log"
"math/rand"
"time"
"github.com/pkg/errors"
G "gorgonia.org/gorgonia"
"gorgonia.org/tensor"
"gorgonia.org/tensor/native"
)
// Train is a basic trainer.
func Train(d *Dual, Xs, policies, values *tensor.Dense, batches, iterations int) error {
m := G.NewTapeMachine(d.g, G.BindDualValues(d.Model()...))
model := G.NodesToValueGrads(d.Model())
solver := G.NewVanillaSolver(G.WithLearnRate(0.1))
var s slicer
for i := 0; i < iterations; i++ {
// var cost float32
for bat := 0; bat < batches; bat++ {
batchStart := bat * d.Config.BatchSize
batchEnd := batchStart + d.Config.BatchSize
Xs2 := s.Slice(Xs, sli(batchStart, batchEnd))
π := s.Slice(policies, sli(batchStart, batchEnd))
v := s.Slice(values, sli(batchStart, batchEnd))
G.Let(d.planes, Xs2)
G.Let(d.Π, π)
G.Let(d.V, v)
if err := m.RunAll(); err != nil {
return err
}
// cost = d.cost.Data().(float32)
if err := solver.Step(model); err != nil {
return err
}
m.Reset()
tensor.ReturnTensor(Xs2)
tensor.ReturnTensor(π)
tensor.ReturnTensor(v)
}
if err := shuffleBatch(Xs, policies, values); err != nil {
return err
}
// TODO: add a channel to send training cost data down
// log.Printf("%d\t%v", i, cost/float32(batches))
}
return nil
}
// shuffleBatch shuffles the batches.
func shuffleBatch(Xs, π, v *tensor.Dense) (err error) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
oriXs := Xs.Shape().Clone()
oriPis := π.Shape().Clone()
defer func() {
if r := recover(); r != nil {
log.Printf("%v %v", Xs.Shape(), π.Shape())
panic(r)
}
}()
Xs.Reshape(as2D(Xs.Shape())...)
π.Reshape(as2D(π.Shape())...)
var matXs, matPis [][]float32
if matXs, err = native.MatrixF32(Xs); err != nil {
return errors.Wrapf(err, "shuffle batch failed - matX")
}
if matPis, err = native.MatrixF32(π); err != nil {
return errors.Wrapf(err, "shuffle batch failed - pi")
}
vs := v.Data().([]float32)
tmp := make([]float32, Xs.Shape()[1])
for i := range matXs {
j := r.Intn(i + 1)
rowI := matXs[i]
rowJ := matXs[j]
copy(tmp, rowI)
copy(rowI, rowJ)
copy(rowJ, tmp)
piI := matPis[i]
piJ := matPis[j]
copy(tmp, piI)
copy(piI, piJ)
copy(piJ, tmp)
vs[i], vs[j] = vs[j], vs[i]
}
Xs.Reshape(oriXs...)
π.Reshape(oriPis...)
return nil
}
func as2D(s tensor.Shape) tensor.Shape {
retVal := tensor.BorrowInts(2)
retVal[0] = s[0]
retVal[1] = s[1]
for i := 2; i < len(s); i++ {
retVal[1] *= s[i]
}
return retVal
}
// Inferencer is a struct that holds the state for a *Dual and a VM. By using an Inferece struct,
// there is no longer a need to create a VM every time an inference needs to be done.
type Inferencer struct {
d *Dual
m G.VM
input *tensor.Dense
buf *bytes.Buffer
}
// Infer takes a trained *Dual, and creates a interence data structure such that it'd be easy to infer
func Infer(d *Dual, actionSpace int, toLog bool) (*Inferencer, error) {
conf := d.Config
conf.FwdOnly = true
conf.BatchSize = actionSpace
newShape := d.planes.Shape().Clone()
newShape[0] = actionSpace
retVal := &Inferencer{
d: New(conf),
input: tensor.New(tensor.WithShape(newShape...), tensor.Of(Float)),
}
if err := retVal.d.Init(); err != nil {
return nil, err
}
retVal.d.SetTesting()
// G.WithInit(G.Zeroes())(retVal.d.planes)
infModel := retVal.d.Model()
for i, n := range d.Model() {
original := n.Value().Data().([]float32)
cloned := infModel[i].Value().Data().([]float32)
copy(cloned, original)
}
retVal.buf = new(bytes.Buffer)
if toLog {
logger := log.New(retVal.buf, "", 0)
retVal.m = G.NewTapeMachine(retVal.d.g,
G.WithLogger(logger),
G.WithWatchlist(),
G.TraceExec(),
G.WithValueFmt("%+1.1v"),
G.WithNaNWatch(),
)
} else {
retVal.m = G.NewTapeMachine(retVal.d.g)
}
return retVal, nil
}
// Dual implements Dualer
func (m *Inferencer) Dual() *Dual { return m.d }
// Infer takes the board, in form of a []float32, and runs inference, and returns the value
func (m *Inferencer) Infer(board []float32) (policy []float32, value float32, err error) {
m.buf.Reset()
for _, op := range m.d.ops {
op.Reset()
}
// copy board to the provided preallocated input tensor
m.input.Zero()
data := m.input.Data().([]float32)
copy(data, board)
m.m.Reset()
// log.Printf("Let planes %p be input %v", m.d.planes, board)
m.buf.Reset()
G.Let(m.d.planes, m.input)
if err = m.m.RunAll(); err != nil {
return nil, 0, err
}
policy = m.d.policyValue.Data().([]float32)
value = m.d.value.Data().([]float32)[0]
// log.Printf("\t%v", policy)
return policy[:m.d.ActionSpace], value, nil
}
// ExecLog returns the execution log. If Infer was called with toLog = false, then it will return an empty string
func (m *Inferencer) ExecLog() string { return m.buf.String() }
// Close implements a closer, because well, a gorgonia VM is a resource.
func (m *Inferencer) Close() error { return m.m.Close() }