forked from emer/leabra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prjn.go
475 lines (440 loc) · 13.7 KB
/
prjn.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (c) 2019, The Emergent Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package leabra
import (
"encoding/json"
"fmt"
"io"
"strings"
"github.com/chewxy/math32"
"github.com/emer/emergent/emer"
"github.com/goki/ki/indent"
)
// leabra.Prjn is a basic Leabra projection with synaptic learning parameters
type Prjn struct {
PrjnStru
WtScale WtScaleParams `desc:"weight scaling parameters: modulates overall strength of projection, using both absolute and relative factors"`
Learn LearnSynParams `desc:"synaptic-level learning parameters"`
Syns []Synapse `desc:"synaptic state values, ordered by the sending layer units which owns them -- one-to-one with SConIdx array"`
// misc state variables below:
GScale float32 `desc:"scaling factor for integrating synaptic input conductances (G's) -- computed in AlphaCycInit, incorporates running-average activity levels"`
GInc []float32 `desc:"local increment accumulator for synaptic conductance from sending units -- goes to either GeInc or GiInc on neuron depending on projection type -- this will be thread-safe"`
WbRecv []WtBalRecvPrjn `desc:"weight balance state variables for this projection, one per recv neuron"`
}
// AsLeabra returns this prjn as a leabra.Prjn -- all derived prjns must redefine
// this to return the base Prjn type, so that the LeabraPrjn interface does not
// need to include accessors to all the basic stuff.
func (pj *Prjn) AsLeabra() *Prjn {
return pj
}
func (pj *Prjn) Defaults() {
pj.WtScale.Defaults()
pj.Learn.Defaults()
pj.GScale = 1
}
// UpdateParams updates all params given any changes that might have been made to individual values
func (pj *Prjn) UpdateParams() {
pj.WtScale.Update()
pj.Learn.Update()
}
// AllParams returns a listing of all parameters in the Layer
func (pj *Prjn) AllParams() string {
str := "///////////////////////////////////////////////////\nPrjn: " + pj.Name() + "\n"
b, _ := json.MarshalIndent(&pj.Learn, "", " ")
str += "Learn: {\n " + strings.Replace(JsonToParams(b), " WtInit: {", "\n WtInit: {", -1)
return str
}
func (pj *Prjn) SynVarNames() []string {
return SynapseVars
}
// SynVals returns values of given variable name on synapses
// for each synapse in the projection using the natural ordering
// of the synapses (sender based for Leabra)
func (pj *Prjn) SynVals(varnm string) []float32 {
vl := make([]float32, len(pj.Syns))
for si := range pj.Syns {
sy := &pj.Syns[si]
sv, ok := sy.VarByName(varnm)
if ok {
vl[si] = sv
}
}
return vl
}
// SynValsTry returns values of given variable name on synapses
// for each synapse in the projection using the natural ordering
// of the synapses (sender based for Leabra)
func (pj *Prjn) SynValsTry(varnm string) ([]float32, error) {
vl := make([]float32, len(pj.Syns))
notOk := false
for si := range pj.Syns {
sy := &pj.Syns[si]
sv, ok := sy.VarByName(varnm)
if ok {
vl[si] = sv
} else {
notOk = true
break
}
}
if notOk {
return vl, fmt.Errorf("leabra.Prjn SynValsTry: variable named: %v not valid", varnm)
}
return vl, nil
}
// SynVal returns value of given variable name on the synapse
// between given send, recv unit indexes (1D, flat indexes)
// returns nil for access errors.
func (pj *Prjn) SynVal(varnm string, sidx, ridx int) float32 {
sv, _ := pj.SynValTry(varnm, sidx, ridx)
return sv
}
// SynValTry returns value of given variable name on the synapse
// between given send, recv unit indexes (1D, flat indexes)
// returns error for access errors.
func (pj *Prjn) SynValTry(varnm string, sidx, ridx int) (float32, error) {
slay := pj.Send.(LeabraLayer).AsLeabra()
rlay := pj.Recv.(LeabraLayer).AsLeabra()
nr := len(rlay.Neurons)
ns := len(slay.Neurons)
if ridx >= nr {
return 0, fmt.Errorf("Prjn.SynVal: recv unit index %v is > size of recv layer: %v", ridx, nr)
}
if sidx >= ns {
return 0, fmt.Errorf("Prjn.SynVal: send unit index %v is > size of send layer: %v", sidx, ns)
}
nc := int(pj.RConN[ridx])
st := int(pj.RConIdxSt[ridx])
for ci := 0; ci < nc; ci++ {
si := int(pj.RConIdx[st+ci])
if si != sidx {
continue
}
rsi := pj.RSynIdx[st+ci]
sy := &pj.Syns[rsi]
sv, ok := sy.VarByName(varnm)
if ok {
return sv, nil
}
}
return 0, fmt.Errorf("Prjn.SynVal: recv unit index %v does not recv from send unit index %v, or variable name: %v not found in synapse", ridx, sidx, varnm)
}
// SetSynVal sets value of given variable name on the synapse
// between given send, recv unit indexes (1D, flat indexes)
// returns error for access errors.
func (pj *Prjn) SetSynVal(varnm string, sidx, ridx int, val float32) error {
slay := pj.Send.(LeabraLayer).AsLeabra()
rlay := pj.Recv.(LeabraLayer).AsLeabra()
nr := len(rlay.Neurons)
ns := len(slay.Neurons)
if ridx >= nr {
return fmt.Errorf("Prjn.SetSynVal: recv unit index %v is > size of recv layer: %v", ridx, nr)
}
if sidx >= ns {
return fmt.Errorf("Prjn.SetSynVal: send unit index %v is > size of send layer: %v", sidx, ns)
}
nc := int(pj.RConN[ridx])
st := int(pj.RConIdxSt[ridx])
for ci := 0; ci < nc; ci++ {
si := int(pj.RConIdx[st+ci])
if si != sidx {
continue
}
rsi := pj.RSynIdx[st+ci]
sy := &pj.Syns[rsi]
ok := sy.SetVarByName(varnm, float64(val))
if ok {
if varnm == "Wt" {
pj.Learn.LWtFmWt(sy)
}
return nil
}
}
return fmt.Errorf("Prjn.SetSynVal: recv unit index %v does not recv from send unit index %v, or variable name: %v not found in synapse", ridx, sidx, varnm)
}
///////////////////////////////////////////////////////////////////////
// Weights File
// WriteWtsJSON writes the weights from this projection from the receiver-side perspective
// in a JSON text format. We build in the indentation logic to make it much faster and
// more efficient.
func (pj *Prjn) WriteWtsJSON(w io.Writer, depth int) {
slay := pj.Send.(LeabraLayer).AsLeabra()
rlay := pj.Recv.(LeabraLayer).AsLeabra()
nr := len(rlay.Neurons)
w.Write(indent.TabBytes(depth))
w.Write([]byte("{\n"))
depth++
w.Write(indent.TabBytes(depth))
w.Write([]byte(fmt.Sprintf("\"GScale\": %v\n", pj.GScale)))
w.Write(indent.TabBytes(depth))
w.Write([]byte(fmt.Sprintf("\"%v\": [\n", slay.Nm)))
depth++
for ri := 0; ri < nr; ri++ {
nc := int(pj.RConN[ri])
st := int(pj.RConIdxSt[ri])
w.Write(indent.TabBytes(depth))
w.Write([]byte(fmt.Sprintf("\"%v\": {\n", ri)))
depth++
w.Write(indent.TabBytes(depth))
w.Write([]byte(fmt.Sprintf("\"n\": %v,\n", nc)))
w.Write(indent.TabBytes(depth))
w.Write([]byte("\"Si\": ["))
for ci := 0; ci < nc; ci++ {
si := pj.RConIdx[st+ci]
w.Write([]byte(fmt.Sprintf("%v ", si)))
}
w.Write([]byte("]\n"))
w.Write(indent.TabBytes(depth))
w.Write([]byte("\"Wt\": ["))
for ci := 0; ci < nc; ci++ {
rsi := pj.RSynIdx[st+ci]
sy := &pj.Syns[rsi]
w.Write([]byte(fmt.Sprintf("%v ", sy.Wt)))
}
w.Write([]byte("]\n"))
depth--
w.Write(indent.TabBytes(depth))
if ri == nr-1 {
w.Write([]byte("}\n"))
} else {
w.Write([]byte("},\n"))
}
}
depth--
w.Write(indent.TabBytes(depth))
w.Write([]byte("]\n"))
depth--
w.Write(indent.TabBytes(depth))
w.Write([]byte("}\n"))
}
// ReadWtsJSON reads the weights for this projection from the receiver-side perspective
// in a JSON text format.
func (pj *Prjn) ReadWtsJSON(r io.Reader) error {
return nil
}
// Build constructs the full connectivity among the layers as specified in this projection.
// Calls PrjnStru.BuildStru and then allocates the synaptic values in Syns accordingly.
func (pj *Prjn) Build() error {
if err := pj.BuildStru(); err != nil {
return err
}
pj.Syns = make([]Synapse, len(pj.SConIdx))
rsh := pj.Recv.Shape()
// ssh := pj.Send.Shape()
rlen := rsh.Len()
pj.GInc = make([]float32, rlen)
pj.WbRecv = make([]WtBalRecvPrjn, rlen)
return nil
}
//////////////////////////////////////////////////////////////////////////////////////
// Init methods
// InitWts initializes weight values according to Learn.WtInit params
func (pj *Prjn) InitWts() {
for si := range pj.Syns {
sy := &pj.Syns[si]
pj.Learn.InitWts(sy)
}
for wi := range pj.WbRecv {
wb := &pj.WbRecv[wi]
wb.Init()
}
pj.LeabraPrj.InitGInc()
}
// InitWtSym initializes weight symmetry -- is given the reciprocal projection where
// the Send and Recv layers are reversed.
func (pj *Prjn) InitWtSym(rpjp LeabraPrjn) {
rpj := rpjp.AsLeabra()
slay := pj.Send.(LeabraLayer).AsLeabra()
ns := len(slay.Neurons)
for si := 0; si < ns; si++ {
nc := int(pj.SConN[si])
st := int(pj.SConIdxSt[si])
for ci := 0; ci < nc; ci++ {
sy := &pj.Syns[st+ci]
ri := pj.SConIdx[st+ci]
// now we need to find the reciprocal synapse on rpj!
// look in ri for sending connections
rsi := ri
rsnc := int(rpj.SConN[rsi])
rsst := int(rpj.SConIdxSt[rsi])
for rci := 0; rci < rsnc; rci++ {
rri := int(rpj.SConIdx[rsst+rci])
if rri == si {
rsy := &rpj.Syns[rsst+rci]
rsy.Wt = sy.Wt
rsy.LWt = sy.LWt
// note: if we support SymFmTop then can have option to go other way
// also for Scale support, copy scales
}
}
}
}
}
// IniteGInc initializes the per-projection GInc threadsafe increment -- not
// typically needed (called during InitWts only) but can be called when needed
func (pj *Prjn) InitGInc() {
for ri := range pj.GInc {
pj.GInc[ri] = 0
}
}
//////////////////////////////////////////////////////////////////////////////////////
// Act methods
// SendGDelta sends the delta-activation from sending neuron index si,
// to integrate synaptic conductances on receivers
func (pj *Prjn) SendGDelta(si int, delta float32) {
scdel := delta * pj.GScale
nc := pj.SConN[si]
st := pj.SConIdxSt[si]
syns := pj.Syns[st : st+nc]
scons := pj.SConIdx[st : st+nc]
for ci := range syns {
ri := scons[ci]
pj.GInc[ri] += scdel * syns[ci].Wt
}
}
// RecvGInc increments the receiver's GeInc or GiInc from that of all the projections.
func (pj *Prjn) RecvGInc() {
rlay := pj.Recv.(LeabraLayer).AsLeabra()
if pj.Typ == emer.Inhib {
for ri := range rlay.Neurons {
rn := &rlay.Neurons[ri]
rn.GiInc += pj.GInc[ri]
pj.GInc[ri] = 0
}
} else {
for ri := range rlay.Neurons {
rn := &rlay.Neurons[ri]
rn.GeInc += pj.GInc[ri]
pj.GInc[ri] = 0
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// Learn methods
// DWt computes the weight change (learning) -- on sending projections
func (pj *Prjn) DWt() {
if !pj.Learn.Learn {
return
}
slay := pj.Send.(LeabraLayer).AsLeabra()
rlay := pj.Recv.(LeabraLayer).AsLeabra()
for si := range slay.Neurons {
sn := &slay.Neurons[si]
if sn.AvgS < pj.Learn.XCal.LrnThr && sn.AvgM < pj.Learn.XCal.LrnThr {
continue
}
nc := int(pj.SConN[si])
st := int(pj.SConIdxSt[si])
syns := pj.Syns[st : st+nc]
scons := pj.SConIdx[st : st+nc]
for ci := range syns {
sy := &syns[ci]
ri := scons[ci]
rn := &rlay.Neurons[ri]
err, bcm := pj.Learn.CHLdWt(sn.AvgSLrn, sn.AvgM, rn.AvgSLrn, rn.AvgM, rn.AvgL)
bcm *= pj.Learn.XCal.LongLrate(rn.AvgLLrn)
err *= pj.Learn.XCal.MLrn
dwt := bcm + err
norm := float32(1)
if pj.Learn.Norm.On {
norm = pj.Learn.Norm.NormFmAbsDWt(&sy.Norm, math32.Abs(dwt))
}
if pj.Learn.Momentum.On {
dwt = norm * pj.Learn.Momentum.MomentFmDWt(&sy.Moment, dwt)
} else {
dwt *= norm
}
sy.DWt += pj.Learn.Lrate * dwt
}
// aggregate max DWtNorm over sending synapses
if pj.Learn.Norm.On {
maxNorm := float32(0)
for ci := range syns {
sy := &syns[ci]
if sy.Norm > maxNorm {
maxNorm = sy.Norm
}
}
for ci := range syns {
sy := &syns[ci]
sy.Norm = maxNorm
}
}
}
}
// WtFmDWt updates the synaptic weight values from delta-weight changes -- on sending projections
func (pj *Prjn) WtFmDWt() {
if !pj.Learn.Learn {
return
}
if pj.Learn.WtBal.On {
for si := range pj.Syns {
sy := &pj.Syns[si]
ri := pj.SConIdx[si]
wb := &pj.WbRecv[ri]
pj.Learn.WtFmDWt(wb.Inc, wb.Dec, &sy.DWt, &sy.Wt, &sy.LWt)
}
} else {
for si := range pj.Syns {
sy := &pj.Syns[si]
pj.Learn.WtFmDWt(1, 1, &sy.DWt, &sy.Wt, &sy.LWt)
}
}
}
// WtBalFmWt computes the Weight Balance factors based on average recv weights
func (pj *Prjn) WtBalFmWt() {
if !pj.Learn.Learn || !pj.Learn.WtBal.On {
return
}
rlay := pj.Recv.(LeabraLayer).AsLeabra()
if rlay.Typ == emer.Target {
return
}
for ri := range rlay.Neurons {
nc := int(pj.RConN[ri])
if nc <= 1 {
continue
}
rn := &rlay.Neurons[ri]
if rn.HasFlag(NeurHasTarg) { // todo: ensure that Pulvinar has this set, or do something else
continue
}
wb := &pj.WbRecv[ri]
st := int(pj.RConIdxSt[ri])
rsidxs := pj.RSynIdx[st : st+nc]
sumWt := float32(0)
sumN := 0
for ci := range rsidxs {
rsi := rsidxs[ci]
sy := &pj.Syns[rsi]
if sy.Wt >= pj.Learn.WtBal.AvgThr {
sumWt += sy.Wt
sumN++
}
}
if sumN > 0 {
sumWt /= float32(sumN)
} else {
sumWt = 0
}
wb.Avg = sumWt
wb.Fact, wb.Inc, wb.Dec = pj.Learn.WtBal.WtBal(sumWt)
}
}
///////////////////////////////////////////////////////////////////////
// WtBalRecvPrjn
// WtBalRecvPrjn are state variables used in computing the WtBal weight balance function
// There is one of these for each Recv Neuron participating in the projection.
type WtBalRecvPrjn struct {
Avg float32 `desc:"average of effective weight values that exceed WtBal.AvgThr across given Recv Neuron's connections for given Prjn"`
Fact float32 `desc:"overall weight balance factor that drives changes in WbInc vs. WbDec via a sigmoidal function -- this is the net strength of weight balance changes"`
Inc float32 `desc:"weight balance increment factor -- extra multiplier to add to weight increases to maintain overall weight balance"`
Dec float32 `desc:"weight balance decrement factor -- extra multiplier to add to weight decreases to maintain overall weight balance"`
}
func (wb *WtBalRecvPrjn) Init() {
wb.Avg = 0
wb.Fact = 0
wb.Inc = 1
wb.Dec = 1
}