/
ffnet.go
344 lines (263 loc) · 7.45 KB
/
ffnet.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package layers
import (
"errors"
"fmt"
"github.com/gerardabello/weight"
"github.com/gerardabello/weight/debug"
"github.com/gerardabello/weight/tensor"
)
//FFNode is a node to be used with FFNet
type FFNode struct {
layer weight.Layer
parents []*FFNode
//Could be derived from the 'parents' array, but it would be slow to obtain them every time
//Should be buffered channels of size 1
inputs []chan *tensor.Tensor //come from parents
outputs []chan *tensor.Tensor //come from childs
input *tensor.Tensor //tensor to store the sum of incoming inputs on Activate()
gradientError *tensor.Tensor //tensor to store the sum of incoming gradient errors on BackPropagate()
}
func (n *FFNode) ID() string {
return n.layer.ID()
}
//Activate waits for the parent nodes to send its outputs, computes the sum of them and passes it to the underlying layer's Activate, then sends the result to all childs.
func (n *FFNode) Activate() {
np := len(n.inputs)
inputs := make([]*tensor.Tensor, np)
for i := 0; i < np; i++ {
inputs[i] = <-n.inputs[i]
if !inputs[i].HasSize(n.layer.GetInputSize()) {
panic(fmt.Sprintf("One of inputs to node %s has not the correct size. Actual:%v expected:%v \n", n.ID(), inputs[i].Size, n.layer.GetInputSize()))
}
}
//Create a tensor if it doesn't exist
if n.input == nil {
n.input = tensor.NewTensor(n.layer.GetInputSize()...)
} else {
n.input.Zero(0)
}
err := n.input.Add(inputs...)
if err != nil {
panic(err)
}
//The undelying layer does the actual computation
out, err := n.layer.Activate(n.input)
if err != nil {
panic(err)
}
//Send to all childs
for i := 0; i < len(n.outputs); i++ {
n.outputs[i] <- out
}
}
//BackPropagate waits for the child nodes to send its propagated errors, computes the sum of them and passes it to the underlying layer's BackPropagate, then propagates the result to all parents.
func (n *FFNode) BackPropagate() {
nc := len(n.outputs)
gradientErrors := make([]*tensor.Tensor, nc)
for i := 0; i < nc; i++ {
gradientErrors[i] = <-n.outputs[i]
if !gradientErrors[i].HasSize(n.layer.GetOutputSize()) {
panic("One of errors to node has not the correct size")
}
}
//Create a tensor if it doesn't exist
if n.gradientError == nil {
n.gradientError = tensor.NewTensor(n.layer.GetOutputSize()...)
} else {
n.gradientError.Zero(0)
}
err := n.gradientError.Add(gradientErrors...)
if err != nil {
panic(err)
}
//The undelying layer does the actual computation
prop, err := n.layer.(weight.BPLearnerLayer).BackPropagate(n.gradientError)
if err != nil {
panic(err)
}
//Send to all parents
for i := 0; i < len(n.inputs); i++ {
n.inputs[i] <- prop
}
}
//FFNet is a generic feedforward network. It can include any number branches, but they cannot form a loop.
type FFNet struct {
id string
input chan *tensor.Tensor
output chan *tensor.Tensor
startNode *FFNode
endNode *FFNode
nodes []*FFNode
finished bool
}
//NewFFNet returns a new FFNet
func NewFFNet() *FFNet {
net := &FFNet{}
net.id = RandomID(8)
return net
}
func (n *FFNet) ID() string {
return n.id
}
//CreateSlave creates a slave of the FFNet. See EnslaverLayer in package weight for more information on layer slaves.
func (n *FFNet) CreateSlave() weight.Layer {
ng := NewFFNet()
ng.id = n.id
for i := range n.nodes {
var err error
enslaver, ok := n.nodes[i].layer.(weight.EnslaverLayer)
if !ok {
panic("weight.Layer inside Sequential does not implement Enslaver interface")
}
parents := []string{}
for _, parentNode := range n.nodes[i].parents {
parents = append(parents, parentNode.ID())
}
err = ng.AddLayer(enslaver.CreateSlave(), parents...)
if err != nil {
panic(err)
}
}
ng.End()
return ng
}
//Activate takes an input tensor and passes it through all the layers in the netork following the node connections.
func (n *FFNet) Activate(input *tensor.Tensor) (*tensor.Tensor, error) {
if !n.finished {
return nil, errors.New("FFNet is not finished, use End() to finish it before using it")
}
//Call all nodes concurrently
for i := range n.nodes {
go n.nodes[i].Activate()
}
//Send the data to the starting node
n.input <- input
//Wait for the result to be available and return it
return <-n.output, nil
}
func (n *FFNet) BackPropagate(input *tensor.Tensor) (*tensor.Tensor, error) {
if !n.finished {
return nil, errors.New("FFNet is not finished, use End() to finish it before using it")
}
//Call all nodes concurrently
for i := range n.nodes {
go n.nodes[i].BackPropagate()
}
//Send the data to the starting node
n.output <- input
//Wait for the result to be available and return it
return <-n.input, nil
}
func (n *FFNet) AddLayer(layer weight.Layer, parents ...string) error {
if n.finished {
return errors.New("FFNet finished, cannot add more layers")
}
if n.nodes == nil {
n.nodes = []*FFNode{}
}
if n.nodeByID(layer.ID()) != nil {
return errors.New("There's already a layer in the FFNet with the id " + layer.ID())
}
node := &FFNode{layer: layer}
node.outputs = []chan *tensor.Tensor{}
node.inputs = []chan *tensor.Tensor{}
if len(n.nodes) == 0 {
//First node
n.input = make(chan *tensor.Tensor, 1)
n.startNode = node
node.inputs = append(node.inputs, n.input)
} else {
if len(parents) == 0 {
return errors.New("No parent especified")
}
}
for _, parentID := range parents {
parent := n.nodeByID(parentID)
if parent == nil {
return errors.New("Could not find parent layer")
}
err := n.setParent(node, parent)
if err != nil {
return err
}
}
n.nodes = append(n.nodes, node)
return nil
}
func (n *FFNet) nodeByID(id string) *FFNode {
for i := 0; i < len(n.nodes); i++ {
if n.nodes[i].ID() == id {
return n.nodes[i]
}
}
return nil
}
func (n *FFNet) setParent(node *FFNode, parent *FFNode) error {
if node == nil {
return errors.New("FFNode is nil")
}
if parent == nil {
return errors.New("Parent is nil")
}
c := make(chan *tensor.Tensor, 1)
node.parents = append(node.parents, parent)
node.inputs = append(node.inputs, c)
parent.outputs = append(parent.outputs, c)
return nil
}
//End closes the network
func (n *FFNet) End() error {
last := n.nodes[len(n.nodes)-1]
n.output = make(chan *tensor.Tensor, 1)
n.endNode = last
last.outputs = []chan *tensor.Tensor{n.output}
n.finished = true
return nil
}
func (n *FFNet) GetOutputSize() []int {
return n.endNode.layer.GetOutputSize()
}
func (n *FFNet) GetInputSize() []int {
return n.startNode.layer.GetInputSize()
}
func (n *FFNet) GetParamGradPointers() ([]*float64, []*float64) {
params := []*float64{}
grads := []*float64{}
for i := 0; i < len(n.nodes); i++ {
bpLayer, ok := n.nodes[i].layer.(weight.BPLearnerLayer)
if !ok {
panic("weight.Layer inside FFNet does not implement weight.BPLearnerLayer interface")
}
p, g := bpLayer.GetParamGradPointers()
params = append(params, p...)
grads = append(grads, g...)
}
return params, grads
}
func (n *FFNet) GetDebugInfo() []*debug.LayerInfo {
stats := []*debug.LayerInfo{}
for i := 0; i < len(n.nodes); i++ {
dLayer, ok := n.nodes[i].layer.(debug.DebugLayer)
if ok {
stats = append(stats, dLayer.GetDebugInfo()...)
}
}
return stats
}
func NewSequentialNet(layers ...weight.Layer) (*FFNet, error) {
net := NewFFNet()
id := layers[0].ID()
err := net.AddLayer(layers[0])
if err != nil {
return nil, err
}
for i := 1; i < len(layers); i++ {
err := net.AddLayer(layers[i], id)
if err != nil {
return nil, err
}
id = layers[i].ID()
}
net.End()
return net, nil
}