-
Notifications
You must be signed in to change notification settings - Fork 1
/
emery.go
2277 lines (1949 loc) · 75.1 KB
/
emery.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021, 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.
// emery1 is a simulated virtual rat / cat
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
"github.com/emer/emergent/actrf"
"github.com/emer/emergent/emer"
"github.com/emer/emergent/env"
"github.com/emer/emergent/erand"
"github.com/emer/emergent/netview"
"github.com/emer/emergent/params"
"github.com/emer/emergent/prjn"
"github.com/emer/emergent/relpos"
"github.com/emer/empi/mpi"
"github.com/emer/etable/agg"
"github.com/emer/etable/eplot"
"github.com/emer/etable/etable"
"github.com/emer/etable/etensor"
"github.com/emer/etable/etview"
"github.com/emer/etable/metric"
"github.com/emer/etable/split"
"github.com/emer/leabra/deep"
"github.com/emer/leabra/leabra"
"github.com/goki/gi/gi"
"github.com/goki/gi/gimain"
"github.com/goki/gi/gist"
"github.com/goki/gi/giv"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/mat32"
)
func main() {
TheSim.New() // note: not running Config here -- done in CmdArgs for mpi / nogui
if len(os.Args) > 1 {
TheSim.CmdArgs() // simple assumption is that any args = no gui -- could add explicit arg if you want
} else {
TheSim.Config() // for GUI case, config then run..
gimain.Main(func() { // this starts gui -- requires valid OpenGL display connection (e.g., X11)
guirun()
})
}
}
func guirun() {
TheSim.Init()
win := TheSim.ConfigGui()
fwin := TheSim.ConfigWorldGui()
fwin.GoStartEventLoop()
win.StartEventLoop()
}
// LogPrec is precision for saving float values in logs
const LogPrec = 4
// see params_def.go for default params
// Sim encapsulates the entire simulation model, and we define all the
// functionality as methods on this struct. This structure keeps all relevant
// state information organized and available without having to pass everything around
// as arguments to methods, and provides the core GUI interface (note the view tags
// for the fields which provide hints to how things should be displayed).
type Sim struct {
Net *deep.Network `view:"no-inline" desc:"the network -- click to view / edit parameters for layers, prjns, etc"`
PctCortex float64 `desc:"proportion of action driven by the cortex vs. hard-coded reflexive subcortical"`
PctCortexMax float64 `desc:"maximum PctCortex, when running on the schedule"`
ARFs actrf.RFs `view:"no-inline" desc:"activation-based receptive fields"`
TrnEpcLog *etable.Table `view:"no-inline" desc:"training epoch-level log data"`
TrnTrlLog *etable.Table `view:"no-inline" desc:"training trial-level log data"`
TrnErrStats *etable.Table `view:"no-inline" desc:"stats on train trials where errors were made"`
TrnAggStats *etable.Table `view:"no-inline" desc:"stats on all train trials"`
TstEpcLog *etable.Table `view:"no-inline" desc:"testing epoch-level log data"`
TstTrlLog *etable.Table `view:"no-inline" desc:"testing trial-level log data"`
TstErrLog *etable.Table `view:"no-inline" desc:"log of all test trials where errors were made"`
TstCycLog *etable.Table `view:"no-inline" desc:"testing cycle-level log data"`
RunLog *etable.Table `view:"no-inline" desc:"summary log of each run"`
RunStats *etable.Table `view:"no-inline" desc:"aggregate stats on all runs"`
Params params.Sets `view:"no-inline" desc:"full collection of param sets"`
ParamSet string `desc:"which set of *additional* parameters to use -- always applies Base and optionaly this next if set"`
Tag string `desc:"extra tag string to add to any file names output from sim (e.g., weights files, log files, params for run)"`
Prjn4x4Skp2 *prjn.PoolTile `view:"no-inline" desc:"feedforward 4x4 skip 2 topo prjn"`
Prjn4x4Skp2Recip *prjn.PoolTile `view:"no-inline" desc:"feedforward 4x4 skip 2 topo prjn, recip"`
Prjn3x3Skp1 *prjn.PoolTile `view:"no-inline" desc:"feedforward 3x3 skip 1 topo prjn"`
Prjn4x4Skp4 *prjn.PoolTile `view:"no-inline" desc:"feedforward 4x4 skip 4 topo prjn"`
Prjn4x4Skp4Recip *prjn.PoolTile `view:"no-inline" desc:"feedforward 4x4 skip 4 topo prjn, recip"`
MaxRuns int `desc:"maximum number of model runs to perform"`
MaxEpcs int `desc:"maximum number of epochs to run per model run"`
NZeroStop int `desc:"if a positive number, training will stop after this many epochs with zero SSE"`
TrainEnv FWorld `desc:"Training environment -- contains everything about iterating over input / output patterns over training"`
Time leabra.Time `desc:"leabra timing parameters and state"`
ViewOn bool `desc:"whether to update the network view while running"`
TrainUpdt leabra.TimeScales `desc:"at what time scale to update the display during training? Anything longer than Epoch updates at Epoch in this model"`
TestUpdt leabra.TimeScales `desc:"at what time scale to update the display during testing? Anything longer than Epoch updates at Epoch in this model"`
TestInterval int `desc:"how often to run through all the test patterns, in terms of training epochs"`
LayStatNms []string `desc:"names of layers to collect more detailed stats on (avg act, etc)"`
ARFLayers []string `desc:"names of layers to compute position activation fields on"`
// statistics: note use float64 as that is best for etable.Table
RFMaps map[string]*etensor.Float32 `view:"no-inline" desc:"maps for plotting activation-based receptive fields"`
PulvLays []string `view:"-" desc:"pulvinar layers -- for stats"`
HidLays []string `view:"-" desc:"hidden layers: super and CT -- for hogging stats"`
SuperLays []string `view:"-" desc:"superficial layers"`
NetAction string `inactive:"+" desc:"action activated by the cortical network"`
GenAction string `inactive:"+" desc:"action generated by subcortical code"`
ActAction string `inactive:"+" desc:"actual action taken"`
ActMatch float64 `inactive:"+" desc:"1 if net action matches gen action, 0 otherwise"`
TrlCosDiff float64 `inactive:"+" desc:"current trial's overall cosine difference"`
TrlCosDiffTRC []float64 `inactive:"+" desc:"current trial's cosine difference for pulvinar (TRC) layers"`
EpcActMatch float64 `inactive:"+" desc:"last epoch's average act match"`
EpcCosDiff float64 `inactive:"+" desc:"last epoch's average cosine difference for output layer (a normalized error measure, maximum of 1 when the minus phase exactly matches the plus)"`
EpcCosDiffTRC []float64 `inactive:"+" desc:"last epoch's average cosine difference for TRC layers (a normalized error measure, maximum of 1 when the minus phase exactly matches the plus)"`
// internal state - view:"-"
NumTrlStats int `view:"-" inactive:"+" desc:"sum to increment as we go through epoch"`
SumActMatch float64 `view:"-" inactive:"+" desc:"sum to increment as we go through epoch"`
SumCosDiff float64 `view:"-" inactive:"+" desc:"sum to increment as we go through epoch"`
SumCosDiffTRC []float64 `view:"-" inactive:"+" desc:"sum to increment as we go through epoch, per TRC"`
Win *gi.Window `view:"-" desc:"main GUI window"`
NetView *netview.NetView `view:"-" desc:"the network viewer"`
ToolBar *gi.ToolBar `view:"-" desc:"the master toolbar"`
WorldWin *gi.Window `view:"-" desc:"FWorld GUI window"`
WorldTabs *gi.TabView `view:"-" desc:"FWorld TabView"`
MatColors []string `desc:"color strings in material order"`
Trace *etensor.Int `view:"no-inline" desc:"trace of movement for visualization"`
TraceView *etview.TensorGrid `desc:"view of the activity trace"`
WorldView *etview.TensorGrid `desc:"view of the world"`
TrnEpcPlot *eplot.Plot2D `view:"-" desc:"the training epoch plot"`
TrnTrlPlot *eplot.Plot2D `view:"-" desc:"the training trial plot"`
TstEpcPlot *eplot.Plot2D `view:"-" desc:"the testing epoch plot"`
TstTrlPlot *eplot.Plot2D `view:"-" desc:"the test-trial plot"`
TstCycPlot *eplot.Plot2D `view:"-" desc:"the test-cycle plot"`
RunPlot *eplot.Plot2D `view:"-" desc:"the run plot"`
TrnEpcFile *os.File `view:"-" desc:"log file"`
RunFile *os.File `view:"-" desc:"log file"`
PopVals []float32 `view:"-" desc:"tmp pop code values"`
ValsTsrs map[string]*etensor.Float32 `view:"-" desc:"for holding layer values"`
SaveWts bool `view:"-" desc:"for command-line run only, auto-save final weights after each run"`
SaveARFs bool `view:"-" desc:"for command-line run only, auto-save receptive field data"`
NoGui bool `view:"-" desc:"if true, runing in no GUI mode"`
LogSetParams bool `view:"-" desc:"if true, print message for all params that are set"`
IsRunning bool `view:"-" desc:"true if sim is running"`
StopNow bool `view:"-" desc:"flag to stop running"`
NeedsNewRun bool `view:"-" desc:"flag to initialize NewRun if last one finished"`
RndSeed int64 `view:"-" desc:"the current random seed"`
UseMPI bool `view:"-" desc:"if true, use MPI to distribute computation across nodes"`
SaveProcLog bool `view:"-" desc:"if true, save logs per processor"`
Comm *mpi.Comm `view:"-" desc:"mpi communicator"`
AllDWts []float32 `view:"-" desc:"buffer of all dwt weight changes -- for mpi sharing"`
SumDWts []float32 `view:"-" desc:"buffer of MPI summed dwt weight changes"`
}
// this registers this Sim Type and gives it properties that e.g.,
// prompt for filename for save methods.
var KiT_Sim = kit.Types.AddType(&Sim{}, SimProps)
// TheSim is the overall state for this simulation
var TheSim Sim
// New creates new blank elements and initializes defaults
func (ss *Sim) New() {
ss.Net = &deep.Network{}
ss.TrnEpcLog = &etable.Table{}
ss.TrnTrlLog = &etable.Table{}
ss.TstEpcLog = &etable.Table{}
ss.TstTrlLog = &etable.Table{}
ss.TstCycLog = &etable.Table{}
ss.RunLog = &etable.Table{}
ss.RunStats = &etable.Table{}
ss.Params = ParamSets
ss.RndSeed = 1
ss.ViewOn = true
ss.TrainUpdt = leabra.Quarter // leabra.AlphaCycle
ss.TestUpdt = leabra.Cycle
ss.LayStatNms = []string{"MSTd", "MSTdCT", "SMA", "SMACT"}
ss.ARFLayers = []string{"cIPL", "PCC", "PCCCT", "SMA", "SMACT"}
ss.Defaults()
ss.NewPrjns()
}
// Defaults set default param values
func (ss *Sim) Defaults() {
ss.PctCortexMax = 0.9
ss.TestInterval = 50000
}
// NewPrjns creates new projections
func (ss *Sim) NewPrjns() {
ss.Prjn4x4Skp2 = prjn.NewPoolTile()
ss.Prjn4x4Skp2.Size.Set(4, 1)
ss.Prjn4x4Skp2.Skip.Set(2, 1)
ss.Prjn4x4Skp2.Start.Set(-1, -1)
ss.Prjn4x4Skp2Recip = prjn.NewPoolTileRecip(ss.Prjn4x4Skp2)
ss.Prjn3x3Skp1 = prjn.NewPoolTile()
ss.Prjn3x3Skp1.Size.Set(3, 1)
ss.Prjn3x3Skp1.Skip.Set(1, 1)
ss.Prjn3x3Skp1.Start.Set(-1, -1)
ss.Prjn4x4Skp4 = prjn.NewPoolTile()
ss.Prjn4x4Skp4.Size.Set(4, 1)
ss.Prjn4x4Skp4.Skip.Set(4, 1)
ss.Prjn4x4Skp4.Start.Set(0, 0)
ss.Prjn4x4Skp4Recip = prjn.NewPoolTileRecip(ss.Prjn4x4Skp4)
}
////////////////////////////////////////////////////////////////////////////////////////////
// Configs
// Config configures all the elements using the standard functions
func (ss *Sim) Config() {
ss.ConfigEnv()
ss.ConfigNet(ss.Net)
ss.ConfigTrnEpcLog(ss.TrnEpcLog)
ss.ConfigTrnTrlLog(ss.TrnTrlLog)
ss.ConfigTstEpcLog(ss.TstEpcLog)
ss.ConfigTstTrlLog(ss.TstTrlLog)
ss.ConfigTstCycLog(ss.TstCycLog)
ss.ConfigRunLog(ss.RunLog)
}
func (ss *Sim) ConfigEnv() {
if ss.MaxRuns == 0 { // allow user override
ss.MaxRuns = 1
}
if ss.MaxEpcs == 0 { // allow user override
ss.MaxEpcs = 500
ss.NZeroStop = -1
}
ss.TrainEnv.Config(1000) // n trials per epoch
ss.TrainEnv.Nm = "TrainEnv"
ss.TrainEnv.Dsc = "training params and state"
ss.TrainEnv.Run.Max = ss.MaxRuns
ss.TrainEnv.Init(0)
ss.TrainEnv.Validate()
ss.ConfigRFMaps()
}
func (ss *Sim) ConfigRFMaps() {
ss.RFMaps = make(map[string]*etensor.Float32)
mt := &etensor.Float32{}
mt.CopyShapeFrom(ss.TrainEnv.World)
ss.RFMaps["Pos"] = mt
mt = &etensor.Float32{}
mt.SetShape([]int{len(ss.TrainEnv.Acts)}, nil, nil)
ss.RFMaps["Act"] = mt
mt = &etensor.Float32{}
mt.SetShape([]int{ss.TrainEnv.NRotAngles}, nil, nil)
ss.RFMaps["Ang"] = mt
mt = &etensor.Float32{}
mt.SetShape([]int{3}, nil, nil)
ss.RFMaps["Rot"] = mt
}
func (ss *Sim) ConfigNet(net *deep.Network) {
net.InitName(net, "Emery")
ev := &ss.TrainEnv
fsz := 1 + 2*ev.FoveaSize
// popsize = 12
// input / output layers:
v2pd := net.AddLayer4D("V2Pd", 1, ev.NFOVRays, ev.PopSize, 1, emer.Input) // Depth
v2fd := net.AddLayer4D("V2Fd", 1, fsz, ev.PopSize, 1, emer.Input) // FovDepth
v1f := net.AddLayer4D("V1F", 1, fsz, ev.PatSize.Y, ev.PatSize.X, emer.Input) // Fovea
s1s := net.AddLayer4D("S1S", 1, 4, 2, 1, emer.Input) // ProxSoma
s1v := net.AddLayer2D("S1V", ev.PopSize, 1, emer.Input) // Vestibular
ins := net.AddLayer4D("Ins", 1, len(ev.Inters), ev.PopSize, 1, emer.Input) // Inters = Insula
m1 := net.AddLayer2D("M1", 8, 8, emer.Hidden)
vl := net.AddLayer2D("VL", ev.PatSize.Y, ev.PatSize.X, emer.Target) // Action
mstd, mstdct, mstdp := net.AddDeep2D("MSTd", 8, 8) // full field optic flow
mstdp.Shape().SetShape([]int{1, 6, ev.PopSize, 1}, nil, nil)
mstdp.(*deep.TRCLayer).Drivers.Add("V2Pd")
// special soma pulvinars
s1sp := deep.AddTRCLayer4D(net.AsLeabra(), "S1SP", 1, 4, 2, 1)
s1sp.Drivers.Add("S1S")
s1vp := deep.AddTRCLayer2D(net.AsLeabra(), "S1VP", ev.PopSize, 1)
s1vp.Drivers.Add("S1V")
cipl, ciplct, ciplp := net.AddDeep2D("cIPL", 8, 8)
ciplp.Shape().SetShape([]int{8, 8}, nil, nil)
ciplp.(*deep.TRCLayer).Drivers.Add("MSTd")
pcc, pccct, pccp := net.AddDeep2D("PCC", 8, 8)
pccp.Shape().SetShape([]int{8, 8}, nil, nil)
pccp.(*deep.TRCLayer).Drivers.Add("cIPL")
// todo: also try sma driver
sma, smact, smap := net.AddDeep2D("SMA", 8, 8)
smap.Shape().SetShape([]int{8, 8}, nil, nil)
smap.(*deep.TRCLayer).Drivers.Add("M1")
it, itct, itp := net.AddDeep2D("IT", 7, 7)
itp.Shape().SetShape(v1f.Shape().Shp, nil, nil)
itp.(*deep.TRCLayer).Drivers.Add("V1F")
lip, lipct, lipp := net.AddDeep4D("LIP", 1, fsz, 5, 5)
lipp.Shape().SetShape(v2fd.Shape().Shp, nil, nil)
lipp.(*deep.TRCLayer).Drivers.Add("V2Fd")
m1.SetClass("M1")
vl.SetClass("M1")
s1s.SetClass("S1S")
s1sp.SetClass("S1S")
mstd.SetClass("MSTd")
mstdct.SetClass("MSTd")
mstdp.SetClass("MSTd")
cipl.SetClass("cIPL")
ciplct.SetClass("cIPL")
ciplp.SetClass("cIPL")
pcc.SetClass("PCC")
pccct.SetClass("PCC")
pccp.SetClass("PCC")
sma.SetClass("SMA")
smact.SetClass("SMA")
smap.SetClass("SMA")
it.SetClass("IT")
itct.SetClass("IT")
itp.SetClass("IT")
lip.SetClass("LIP")
lipct.SetClass("LIP")
lipp.SetClass("LIP")
v1f.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "V2Pd", YAlign: relpos.Front, Space: 4})
v2fd.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "V1F", XAlign: relpos.Left, Space: 4})
s1s.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "V1F", YAlign: relpos.Front, Space: 4})
s1v.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "S1S", YAlign: relpos.Front, Space: 8})
ins.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "S1V", YAlign: relpos.Front, Space: 4})
s1sp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "S1S", XAlign: relpos.Left, Space: 4})
s1vp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "S1V", XAlign: relpos.Left, Space: 4})
vl.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Ins", YAlign: relpos.Front, Space: 8})
mstd.SetRelPos(relpos.Rel{Rel: relpos.Above, Other: "V2Pd", XAlign: relpos.Left, YAlign: relpos.Front})
mstdct.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "MSTd", XAlign: relpos.Left, Space: 4})
mstdp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "MSTdCT", XAlign: relpos.Left, Space: 4})
cipl.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "MSTd", YAlign: relpos.Front, Space: 4})
ciplct.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "cIPL", XAlign: relpos.Left, Space: 4})
ciplp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "cIPLCT", XAlign: relpos.Left, Space: 4})
pcc.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "cIPL", YAlign: relpos.Front, Space: 6})
pccct.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "PCC", XAlign: relpos.Left, Space: 4})
pccp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "PCCCT", XAlign: relpos.Left, Space: 4})
sma.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "PCC", YAlign: relpos.Front, Space: 6})
smact.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "SMA", XAlign: relpos.Left, Space: 4})
smap.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "SMACT", XAlign: relpos.Left, Space: 4})
m1.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "SMA", YAlign: relpos.Front, Space: 2})
it.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "V2Pd", XAlign: relpos.Left, Space: 4})
itct.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "IT", XAlign: relpos.Left, Space: 4})
itp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "ITCT", XAlign: relpos.Left, Space: 4})
lip.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "V2Fd", YAlign: relpos.Front, Space: 4})
lipct.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "LIP", XAlign: relpos.Left, Space: 4})
lipp.SetRelPos(relpos.Rel{Rel: relpos.Behind, Other: "LIPCT", XAlign: relpos.Left, Space: 4})
full := prjn.NewFull()
sameu := prjn.NewPoolSameUnit()
sameu.SelfCon = false
p1to1 := prjn.NewPoolOneToOne()
////////////////////
// basic super cons
net.ConnectLayers(v2pd, mstd, full, emer.Forward)
// MStd <-> CIPl
net.ConnectLayers(mstd, cipl, full, emer.Forward)
net.ConnectLayers(cipl, mstd, full, emer.Back)
// CIPl <-> PCC
net.ConnectLayers(cipl, pcc, full, emer.Forward)
net.ConnectLayers(pcc, cipl, full, emer.Back)
// PCC <-> SMA
net.ConnectLayers(pcc, sma, full, emer.Forward)
net.ConnectLayers(sma, pcc, full, emer.Back)
// SMA <-> M1
net.ConnectLayers(sma, m1, full, emer.Forward)
net.BidirConnectLayers(m1, vl, full)
net.ConnectLayers(v1f, it, full, emer.Forward)
net.ConnectLayers(v2fd, lip, p1to1, emer.Forward)
////////////////////
// to MSTd
// net.ConnectLayers(mstd, mstd, sameu, emer.Lateral)
net.ConnectLayers(sma, mstd, full, emer.Back)
net.ConnectLayers(s1v, mstd, full, emer.Back)
net.ConnectCtxtToCT(mstdct, mstdct, full).SetClass("CTSelf") // important!
// MSTdCT top-down depth
net.ConnectLayers(ciplct, mstdct, full, emer.Back).SetClass("CTBack")
net.ConnectLayers(pccct, mstdct, full, emer.Back).SetClass("CTBack")
net.ConnectLayers(smact, mstdct, full, emer.Back).SetClass("CTBack") // always need sma to predict action outcome
// // S1 vestibular
// nt.ConnectLayers(mstdct, s1vp, full, emer.Forward)
// nt.ConnectLayers(s1vp, mstdct, full, emer.Back).SetClass("FmPulv")
// nt.ConnectLayers(s1vp, mstd, full, emer.Back).SetClass("FmPulv")
// todo: try S -> CT leak back -- useful in wwi3d
// todo: try higher CT -> mstdp -- useful in wwi3d
////////////////////
// to cIPL
net.ConnectLayers(sma, cipl, full, emer.Back)
net.ConnectLayers(s1s, cipl, full, emer.Back)
net.ConnectLayers(s1v, cipl, full, emer.Back)
net.ConnectLayers(vl, cipl, full, emer.Back) // todo: m1?
net.ConnectCtxtToCT(ciplct, ciplct, full).SetClass("CTSelf")
net.ConnectLayers(pccct, ciplct, full, emer.Back).SetClass("CTBack")
net.ConnectLayers(smact, ciplct, full, emer.Back).SetClass("CTBack")
// net.ConnectLayers(mstdct, ciplp, ss.Prjn4x4Skp2, emer.Forward).SetClass("FwdToPulv")
// todo: try S -> CT leak back -- useful in wwi3d
// todo: try higher CT -> mstdp -- useful in wwi3d
// S1 vestibular
net.ConnectLayers(ciplct, s1vp, full, emer.Forward)
net.ConnectLayers(s1vp, ciplct, full, emer.Back).SetClass("FmPulv")
net.ConnectLayers(s1vp, cipl, full, emer.Back).SetClass("FmPulv")
////////////////////
// to PCC
net.ConnectLayers(s1s, pcc, full, emer.Forward)
net.ConnectLayers(s1v, pcc, full, emer.Forward)
net.ConnectLayers(vl, pcc, full, emer.Back)
net.ConnectCtxtToCT(pccct, pccct, full).SetClass("CTSelf")
net.ConnectLayers(smact, pccct, full, emer.Back).SetClass("CTBack")
// S1 vestibular
net.ConnectLayers(pccct, s1vp, full, emer.Forward)
net.ConnectLayers(s1vp, pccct, full, emer.Back).SetClass("FmPulv")
net.ConnectLayers(s1vp, pcc, full, emer.Back).SetClass("FmPulv")
// S1 soma
net.ConnectLayers(pccct, s1sp, full, emer.Forward)
net.ConnectLayers(s1sp, pccct, full, emer.Back).SetClass("FmPulv")
net.ConnectLayers(s1sp, pcc, full, emer.Back).SetClass("FmPulv")
////////////////////
// to SMA
net.ConnectLayers(it, sma, full, emer.Forward)
net.ConnectLayers(lip, sma, full, emer.Forward)
net.ConnectLayers(cipl, sma, full, emer.Forward) // todo: forward??
net.ConnectLayers(s1s, sma, full, emer.Forward)
net.ConnectLayers(vl, sma, full, emer.Back)
net.ConnectCtxtToCT(smact, smact, full).SetClass("CTSelf")
net.ConnectLayers(vl, smact, full, emer.Back)
// S1 vestibular
net.ConnectLayers(smact, s1vp, full, emer.Forward)
net.ConnectLayers(s1vp, smact, full, emer.Back).SetClass("FmPulv")
net.ConnectLayers(s1vp, sma, full, emer.Back).SetClass("FmPulv")
// S1 soma
net.ConnectLayers(smact, s1sp, full, emer.Forward)
net.ConnectLayers(s1sp, smact, full, emer.Back).SetClass("FmPulv")
net.ConnectLayers(s1sp, sma, full, emer.Back).SetClass("FmPulv")
////////////////////
// to M1
net.ConnectLayers(smact, vl, full, emer.Forward)
net.ConnectLayers(sma, vl, full, emer.Forward)
////////////////////
// to IT
net.ConnectLayers(sma, it, full, emer.Back)
// net.ConnectLayers(pcc, it, full, emer.Back) // not useful
net.ConnectCtxtToCT(itct, itct, full).SetClass("CTSelf")
net.ConnectCtxtToCT(lipct, itp, p1to1).SetClass("CTSelf") // attention
net.ConnectLayers(smact, itct, full, emer.Back).SetClass("CTBack") // needs to know how moving..
// net.ConnectLayers(pccct, itct, full, emer.Back).SetClass("CTBack")
////////////////////
// to LIP
net.ConnectLayers(sma, lip, full, emer.Back)
// net.ConnectLayers(pcc, lip, full, emer.Back) // not useful
net.ConnectCtxtToCT(lipct, lipct, full).SetClass("CTBack")
net.ConnectLayers(smact, lipct, full, emer.Back).SetClass("CTBack") // always need sma to predict action outcome
// net.ConnectLayers(pccct, lipct, full, emer.Back).SetClass("CTBack")
ss.PulvLays = make([]string, 0, 10)
ss.HidLays = make([]string, 0, 10)
ss.SuperLays = make([]string, 0, 10)
for _, ly := range net.Layers {
if ly.IsOff() {
continue
}
switch ly.Type() {
case deep.TRC:
ss.PulvLays = append(ss.PulvLays, ly.Name())
case emer.Hidden:
ss.SuperLays = append(ss.SuperLays, ly.Name())
fallthrough
case deep.CT:
ss.HidLays = append(ss.HidLays, ly.Name())
}
}
ss.PulvLays = append(ss.PulvLays, "VL")
// using 4 total threads -- todo: didn't work
/*
mstd.SetThread(1)
mstdct.SetThread(1)
cipl.SetThread(2)
ciplct.SetThread(2)
pcc.SetThread(3)
pccct.SetThread(3)
sma.SetThread(3)
smact.SetThread(3)
*/
net.Defaults()
ss.SetParams("Network", ss.LogSetParams) // only set Network params
err := net.Build()
if err != nil {
log.Println(err)
return
}
ss.InitWts(net)
}
// Initialize network weights including scales
func (ss *Sim) InitWts(net *deep.Network) {
net.InitTopoScales() // sets all wt scales
net.InitWts()
net.LrateMult(1) // restore initial learning rate value
}
////////////////////////////////////////////////////////////////////////////////
// Init, utils
// Init restarts the run, and initializes everything, including network weights
// and resets the epoch log table
func (ss *Sim) Init() {
rand.Seed(ss.RndSeed)
ss.ConfigEnv() // re-config env just in case a different set of patterns was
// selected or patterns have been modified etc
ss.StopNow = false
ss.SetParams("", ss.LogSetParams) // all sheets
ss.NewRun()
ss.UpdateView(true)
}
// NewRndSeed gets a new random seed based on current time -- otherwise uses
// the same random seed for every run
func (ss *Sim) NewRndSeed() {
ss.RndSeed = time.Now().UnixNano()
}
// Counters returns a string of the current counter state
// use tabs to achieve a reasonable formatting overall
// and add a few tabs at the end to allow for expansion..
func (ss *Sim) Counters(train bool) string {
// if train {
return fmt.Sprintf("Run:\t%d\tEpoch:\t%d\tEvent:\t%d\tCycle:\t%d\tName:\t%v\t\t\t", ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TrainEnv.Event.Cur, ss.Time.Cycle, ss.TrainEnv.Event.Cur)
// } else {
// return fmt.Sprintf("Run:\t%d\tEpoch:\t%d\tEvent:\t%d\tCycle:\t%d\tName:\t%v\t\t\t", ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TestEnv.Event.Cur, ss.Time.Cycle, ss.TrainEnv.Event.Cur)
// }
}
func (ss *Sim) UpdateView(train bool) {
if ss.NetView != nil && ss.NetView.IsVisible() {
ss.NetView.Record(ss.Counters(train))
// note: essential to use Go version of update when called from another goroutine
ss.NetView.GoUpdate() // note: using counters is significantly slower..
}
ss.UpdateWorldGui()
}
////////////////////////////////////////////////////////////////////////////////
// Running the Network, starting bottom-up..
// AlphaCyc runs one alpha-cycle (100 msec, 4 quarters) of processing.
// External inputs must have already been applied prior to calling,
// using ApplyExt method on relevant layers (see TrainTrial, TestTrial).
// If train is true, then learning DWt or WtFmDWt calls are made.
// Handles netview updating within scope of AlphaCycle
func (ss *Sim) AlphaCyc(train bool) {
// ss.Win.PollEvents() // this can be used instead of running in a separate goroutine
viewUpdt := ss.TrainUpdt
if !train {
viewUpdt = ss.TestUpdt
}
// update prior weight changes at start, so any DWt values remain visible at end
// you might want to do this less frequently to achieve a mini-batch update
// in which case, move it out to the TrainTrial method where the relevant
// counters are being dealt with.
if train {
ss.Net.WtFmDWt()
}
ev := &ss.TrainEnv
ss.Net.AlphaCycInit(train)
ss.Time.AlphaCycStart()
for qtr := 0; qtr < 4; qtr++ {
for cyc := 0; cyc < ss.Time.CycPerQtr; cyc++ {
ss.Net.Cycle(&ss.Time)
if !train {
ss.LogTstCyc(ss.TstCycLog, ss.Time.Cycle)
}
ss.Time.CycleInc()
if ss.ViewOn {
switch viewUpdt {
case leabra.Cycle:
ss.UpdateView(train)
case leabra.FastSpike:
if (cyc+1)%10 == 0 {
ss.UpdateView(train)
}
}
}
}
ss.Net.QuarterFinal(&ss.Time)
ss.Time.QuarterInc()
if qtr == 2 {
ss.TakeAction(ss.Net, ev)
}
if ss.ViewOn {
switch {
case viewUpdt <= leabra.Quarter:
ss.UpdateView(train)
case viewUpdt == leabra.Phase:
if qtr >= 2 {
ss.UpdateView(train)
}
}
}
}
if train {
ss.Net.DWt()
}
if ss.ViewOn && viewUpdt == leabra.AlphaCycle {
ss.UpdateView(train)
}
if !train {
ss.TstCycPlot.GoUpdate() // make sure up-to-date at end
}
}
// TakeAction takes action for this step, using either decoded cortical
// or reflexive subcortical action from env.
func (ss *Sim) TakeAction(net *deep.Network, ev *FWorld) {
ly := net.LayerByName("VL").(leabra.LeabraLayer).AsLeabra()
nact := ss.DecodeAct(ly, ev)
gact := ev.ActGen()
ss.NetAction = ev.Acts[nact]
ss.GenAction = ev.Acts[gact]
ss.ActMatch = 0
if nact == gact {
ss.ActMatch = 1
}
if erand.BoolProb(ss.PctCortex, -1) {
ss.ActAction = ss.NetAction
} else {
ss.ActAction = ss.GenAction
}
ly.SetType(emer.Input)
ev.Action(ss.ActAction, nil)
ap, ok := ev.Pats[ss.ActAction]
if ok {
ly.ApplyExt(ap)
}
ly.SetType(emer.Target)
// fmt.Printf("action: %s\n", ev.Acts[act])
}
// DecodeAct decodes the VL ActM state to find closest action pattern
func (ss *Sim) DecodeAct(ly *leabra.Layer, ev *FWorld) int {
vt := ss.ValsTsr("VL")
ly.UnitValsTensor(vt, "ActM")
cnm := ""
dst := float32(0)
for nm, pat := range ev.Pats {
d := metric.Correlation32(vt.Values, pat.Values)
if cnm == "" || d > dst {
cnm = nm
dst = d
}
}
act, ok := ev.ActMap[cnm]
if !ok {
act = rand.Intn(len(ev.Acts))
}
return act
}
// ApplyInputs applies input patterns from given envirbonment.
// It is good practice to have this be a separate method with appropriate
// args so that it can be used for various different contexts
// (training, testing, etc).
func (ss *Sim) ApplyInputs(net *deep.Network, en env.Env) {
net.InitExt() // clear any existing inputs -- not strictly necessary if always
// going to the same layers, but good practice and cheap anyway
states := []string{"Depth", "FovDepth", "Fovea", "ProxSoma", "Vestibular", "Inters", "Action"}
lays := []string{"V2Pd", "V2Fd", "V1F", "S1S", "S1V", "Ins", "VL"}
for i, lnm := range lays {
lyi := ss.Net.LayerByName(lnm)
if lyi == nil {
continue
}
ly := lyi.(leabra.LeabraLayer).AsLeabra()
pats := en.State(states[i])
if pats != nil {
ly.ApplyExt(pats)
}
}
}
// TrainTrial runs one trial of training using TrainEnv
func (ss *Sim) TrainTrial() {
if ss.NeedsNewRun {
ss.NewRun()
}
ss.TrainEnv.Step() // the Env encapsulates and manages all counter state
// Key to query counters FIRST because current state is in NEXT epoch
// if epoch counter has changed
epc, _, chg := ss.TrainEnv.Counter(env.Epoch)
if chg {
ss.LogTrnEpc(ss.TrnEpcLog)
ss.TrainSched(epc)
ss.TrainEnv.Event.Cur = 0
if ss.ViewOn && ss.TrainUpdt > leabra.AlphaCycle {
ss.UpdateView(true)
}
// if epc%ss.TestInterval == 0 { // note: epc is *next* so won't trigger first time
// ss.TestAll()
// }
if epc >= ss.MaxEpcs {
// done with training..
ss.RunEnd()
if ss.TrainEnv.Run.Incr() { // we are done!
ss.StopNow = true
return
} else {
ss.NeedsNewRun = true
return
}
}
}
ss.ApplyInputs(ss.Net, &ss.TrainEnv)
ss.AlphaCyc(true) // train
ss.TrialStats(true) // accumulate
ss.LogTrnTrl(ss.TrnTrlLog)
}
// RunEnd is called at the end of a run -- save weights, record final log, etc here
func (ss *Sim) RunEnd() {
ss.LogRun(ss.RunLog)
if ss.SaveWts {
fnm := ss.WeightsFileName()
fmt.Printf("Saving Weights to: %v\n", fnm)
ss.Net.SaveWtsJSON(gi.FileName(fnm))
}
if ss.SaveARFs {
ss.SaveAllARFs()
}
}
// NewRun intializes a new run of the model, using the TrainEnv.Run counter
// for the new run value
func (ss *Sim) NewRun() {
run := ss.TrainEnv.Run.Cur
ss.PctCortex = 0
ss.TrainEnv.Init(run)
// ss.TestEnv.Init(run)
ss.Time.Reset()
ss.InitWts(ss.Net)
ss.InitStats()
ss.TrnEpcLog.SetNumRows(0)
ss.TstEpcLog.SetNumRows(0)
ss.NeedsNewRun = false
}
// InitStats initializes all the statistics, especially important for the
// cumulative epoch stats -- called at start of new run
func (ss *Sim) InitStats() {
// accumulators
ss.NumTrlStats = 0
ss.SumActMatch = 0
ss.SumCosDiff = 0
// clear rest just to make Sim look initialized
ss.EpcActMatch = 0
ss.EpcCosDiff = 0
}
// TrialStatsTRC computes the trial-level statistics for TRC layers
func (ss *Sim) TrialStatsTRC(accum bool) {
nt := len(ss.PulvLays)
if len(ss.TrlCosDiffTRC) != nt {
ss.TrlCosDiffTRC = make([]float64, nt)
ss.SumCosDiffTRC = make([]float64, nt)
ss.EpcCosDiffTRC = make([]float64, nt)
}
acd := 0.0
for i, ln := range ss.PulvLays {
ly := ss.Net.LayerByName(ln).(leabra.LeabraLayer).AsLeabra()
cd := float64(ly.CosDiff.Cos)
acd += cd
ss.TrlCosDiffTRC[i] = cd
if accum {
ss.SumCosDiffTRC[i] += cd
}
}
ss.TrlCosDiff = acd / float64(len(ss.PulvLays))
if accum {
ss.SumCosDiff += ss.TrlCosDiff
}
}
// TrialStatsTRC computes the trial-level statistics for TRC layers
func (ss *Sim) EpochStatsTRC(nt float64) {
acd := 0.0
for i := range ss.PulvLays {
ss.EpcCosDiffTRC[i] = ss.SumCosDiffTRC[i] / nt
ss.SumCosDiffTRC[i] = 0
acd += ss.EpcCosDiffTRC[i]
}
ss.EpcCosDiff = acd / 3
}
// SetAFMetaData
func (ss *Sim) SetAFMetaData(af etensor.Tensor) {
af.SetMetaData("min", "0")
af.SetMetaData("colormap", "Viridis") // "JetMuted")
af.SetMetaData("grid-fill", "1")
}
// UpdtARFs updates position activation rf's
func (ss *Sim) UpdtARFs() {
for nm, mt := range ss.RFMaps {
mt.SetZeros()
switch nm {
case "Pos":
mt.Set([]int{ss.TrainEnv.PosI.Y, ss.TrainEnv.PosI.X}, 1)
case "Act":
mt.Set1D(ss.TrainEnv.Act, 1)
case "Ang":
mt.Set1D(ss.TrainEnv.Angle/15, 1)
case "Rot":
mt.Set1D(1+ss.TrainEnv.RotAng/15, 1)
}
}
naf := len(ss.ARFLayers) * len(ss.RFMaps)
if len(ss.ARFs.RFs) != naf {
for _, lnm := range ss.ARFLayers {
ly := ss.Net.LayerByName(lnm)
if ly == nil {
continue
}
vt := ss.ValsTsr(lnm)
ly.UnitValsTensor(vt, "ActM")
for nm, mt := range ss.RFMaps {
af := ss.ARFs.AddRF(lnm+"_"+nm, vt, mt)
ss.SetAFMetaData(&af.NormRF)
}
}
}
for _, lnm := range ss.ARFLayers {
ly := ss.Net.LayerByName(lnm)
if ly == nil {
continue
}
vt := ss.ValsTsr(lnm)
ly.UnitValsTensor(vt, "ActM")
for nm, mt := range ss.RFMaps {
ss.ARFs.Add(lnm+"_"+nm, vt, mt, 0.01) // thr prevent weird artifacts
}
}
}
// SaveAllARFs saves all ARFs to files
func (ss *Sim) SaveAllARFs() {
for _, paf := range ss.ARFs.RFs {
fnm := ss.LogFileName(paf.Name)
etensor.SaveCSV(&paf.NormRF, gi.FileName(fnm), '\t')
}
}
// TrialStats computes the trial-level statistics and adds them to the epoch accumulators if
// accum is true. Note that we're accumulating stats here on the Sim side so the
// core algorithm side remains as simple as possible, and doesn't need to worry about
// different time-scales over which stats could be accumulated etc.
// You can also aggregate directly from log data, as is done for testing stats
func (ss *Sim) TrialStats(accum bool) {
ss.TrialStatsTRC(accum)
if accum {
ss.SumActMatch += ss.ActMatch
ss.NumTrlStats++
}
ss.UpdtARFs()
return
}
// TrainEpoch runs training trials for remainder of this epoch
func (ss *Sim) TrainEpoch() {
ss.StopNow = false
curEpc := ss.TrainEnv.Epoch.Cur
for {
ss.TrainTrial()
if ss.StopNow || ss.TrainEnv.Epoch.Cur != curEpc {
break
}
}
ss.Stopped()
}
// TrainRun runs training trials for remainder of run
func (ss *Sim) TrainRun() {
ss.StopNow = false
curRun := ss.TrainEnv.Run.Cur
for {
ss.TrainTrial()
if ss.StopNow || ss.TrainEnv.Run.Cur != curRun {
break
}
}
ss.Stopped()
}
// TrainSched implements the learning rate schedule etc.
func (ss *Sim) TrainSched(epc int) {
if epc > 1 && epc%10 == 0 {
ss.PctCortex = float64(epc) / 100
if ss.PctCortex > ss.PctCortexMax {
ss.PctCortex = ss.PctCortexMax
} else {
fmt.Printf("PctCortex updated to: %g at epoch: %d\n", ss.PctCortex, epc)
}
}
switch epc {
case 50:
ss.ARFs.Reset() // now sufficiently learned to start recording..
case 150:
ss.Net.LrateMult(0.5)
fmt.Printf("dropped lrate 0.5 at epoch: %d\n", epc)
case 250: