-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeuralNet.go
2025 lines (1762 loc) · 101 KB
/
NeuralNet.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) 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.
// Personality Model
// Currently set up to do separate training of Pavlovian and Instrumental Training.
// Interaction with Environment is still a work in progress
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
"github.com/emer/emergent/emer"
"github.com/emer/emergent/env"
"github.com/emer/emergent/netview"
"github.com/emer/emergent/params"
"github.com/gabetucker2/gogenerics"
. "github.com/gabetucker2/gostack"
// "github.com/emer/emergent/patgen"
"github.com/emer/emergent/prjn"
"github.com/emer/emergent/relpos"
"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" // include to get gui views
"github.com/emer/etable/split"
"github.com/emer/leabra/leabra"
"github.com/goki/gi/gi"
"github.com/goki/gi/gimain"
"github.com/goki/gi/giv"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/mat32"
)
func main() {
SetupModel()
TheSim.New()
TheSim.Config()
if len(os.Args) > 1 {
TheSim.CmdArgs() // simple assumption is that any args = no gui -- could add explicit arg if you want
} else {
gimain.Main( func() {
guirun()
})
}
}
func guirun() {
TheSim.Init()
win := TheSim.ConfigGui()
win.StartEventLoop()
}
// LogPrec is precision for saving float values in logs
const LogPrec = 4
// ParamSets is the default set of parameters -- Base is always applied, and others can be optionally
// selected to apply on top of that
var ParamSets = params.Sets{
{Name: "Base", Desc: "these are the best params", Sheets: params.Sheets{
"Network": ¶ms.Sheet{
{Sel: "Prjn", Desc: "norm and momentum on works better, but wt bal is not better for smaller nets",
Params: params.Params{
"Prjn.Learn.Norm.On": "true",
"Prjn.Learn.Momentum.On": "true",
"Prjn.Learn.WtBal.On": "false",
"Prjn.Learn.Learn": "true",
"Prjn.Learn.Lrate": "0.04",
"Prjn.WtInit.Dist": "Uniform",
"Prjn.WtInit.Mean": "0.5",
"Prjn.WtInit.Var": "0.25",
"Prjn.WtScale.Abs": "1",
}},
{Sel: "#MotiveToApproach", Desc: "Set weight to fixed value of 1",
Params: params.Params{
"Prjn.Learn.Learn": "false",
"Prjn.Learn.Lrate": "0",
"Prjn.WtInit.Dist": "Uniform",
"Prjn.WtInit.Mean": "1",
"Prjn.WtInit.Var": "0",
"Prjn.WtScale.Abs": "1",
}},
{Sel: "#MotiveToAvoid", Desc: "Set weight to fixed value of 1",
Params: params.Params{
"Prjn.Learn.Learn": "false",
"Prjn.Learn.Lrate": "0",
"Prjn.WtInit.Dist": "Uniform",
"Prjn.WtInit.Mean": "1",
"Prjn.WtInit.Var": "0",
"Prjn.WtScale.Abs": "1",
}},
{Sel: "#VTA_DAToApproach", Desc: "Set weight to fixed value of 1, and weight scale of 2",
Params: params.Params{
"Prjn.Learn.Learn": "false",
"Prjn.Learn.Lrate": "0",
"Prjn.WtInit.Dist": "Uniform",
"Prjn.WtInit.Mean": "1",
"Prjn.WtInit.Var": "0",
"Prjn.WtScale.Abs": "2",
}},
{Sel: "#VTA_DAToAvoid", Desc: "Set weight to fixed value of 1, and weight scale of 2, inhibitory connection",
Params: params.Params{
"Prjn.Learn.Learn": "false",
"Prjn.Learn.Lrate": "0",
"Prjn.WtInit.Dist": "Uniform",
"Prjn.WtInit.Mean": "1",
"Prjn.WtInit.Var": "0",
"Prjn.WtScale.Abs": "2",
}},
{Sel: "Layer", Desc: "using 2.3 inhib for all of network -- can explore",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "2.3",
"Layer.Act.Gbar.L": "0.1", // set explictly, new default, a bit better vs 0.2
"Layer.Act.XX1.Gain" : "100",
}},
{Sel: "#Behavior", Desc: "Make Behavior layer selective for 1 behavior",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "2.5",
"Layer.Act.XX1.Gain": "200",
}},
{Sel: "#Approach", Desc: "",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "2.3",
"Layer.Act.XX1.Gain": "400",
}},
{Sel: "#Avoid", Desc: "",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "2.3",
"Layer.Inhib.Layer.FB": "1.2",
"Layer.Act.XX1.Thr": ".49",
"Layer.Act.XX1.Gain": "400",
"Layer.Act.Gbar.I": "1.35",
}},
{Sel: "#Hidden", Desc: "Make Hidden representation a bit sparser",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "2.5",
}},
{Sel: ".Back", Desc: "top-down back-projections MUST have lower relative weight scale, otherwise network hallucinates",
Params: params.Params{
"Prjn.WtScale.Rel": "0.2",
}},
},
"Sim": ¶ms.Sheet{ // sim params apply to sim object
{Sel: "Sim", Desc: "best params always finish in this time",
Params: params.Params{
"Sim.MaxEpcs": "100",
}},
},
}},
{Name: "DefaultInhib", Desc: "output uses default inhib instead of lower", Sheets: params.Sheets{
"Network": ¶ms.Sheet{
{Sel: "#Behavior", Desc: "go back to default",
Params: params.Params{
"Layer.Inhib.Layer.Gi": "1.8",
}},
},
"Sim": ¶ms.Sheet{ // sim params apply to sim object
{Sel: "Sim", Desc: "takes longer -- generally doesn't finish..",
Params: params.Params{
"Sim.MaxEpcs": "100",
}},
},
}},
{Name: "NoMomentum", Desc: "no momentum or normalization", Sheets: params.Sheets{
"Network": ¶ms.Sheet{
{Sel: "Prjn", Desc: "no norm or momentum",
Params: params.Params{
"Prjn.Learn.Norm.On": "false",
"Prjn.Learn.Momentum.On": "false",
}},
},
}},
{Name: "WtBalOn", Desc: "try with weight bal on", Sheets: params.Sheets{
"Network": ¶ms.Sheet{
{Sel: "Prjn", Desc: "weight bal on",
Params: params.Params{
"Prjn.Learn.WtBal.On": "true",
}},
},
}},
}
// 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 *leabra.Network `view:"no-inline" desc:"the network -- click to view / edit parameters for layers, prjns, etc"`
Instr *etable.Table `view:"no-inline" desc:"Training pattern for Instrumental Learning"`
Pvlv *etable.Table `view:"no-inline" desc:"Training pattern for Pavlovian Learning"`
Trn *etable.Table `view:"no-inline" desc:"Table that controls type of training and number of Epochs of training"`
Training string `view:"no-inline" desc:"Type of training: Pavlovian or Instrumental"`
World *etable.Table `view:"no-inline" desc:"Table that represents starting state and then each new state of the Internal and External world"`
// WorldChanges *etable.Table `view:"no-inline" desc:"Table that represents change in External world at each time step"`
TrnEpcLog *etable.Table `view:"no-inline" desc:"training epoch-level log data"`
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"`
TstErrStats *etable.Table `view:"no-inline" desc:"stats on 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)"`
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 env.FixedTable `desc:"Training environment -- contains everything about iterating over input / output patterns over training"`
TestEnv env.FixedTable `desc:"Testing environment -- manages iterating over testing"`
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 -- can use 0 or -1 for no testing"`
LayStatNms []string `desc:"names of layers to collect more detailed stats on (avg act, etc)"`
// statistics: note use float64 as that is best for etable.Table
TrlErr float64 `inactive:"+" desc:"1 if trial was error, 0 if correct -- based on SSE = 0 (subject to .5 unit-wise tolerance)"`
TrlSSE float64 `inactive:"+" desc:"current trial's sum squared error"`
TrlAvgSSE float64 `inactive:"+" desc:"current trial's average sum squared error"`
TrlCosDiff float64 `inactive:"+" desc:"current trial's cosine difference"`
EpcSSE float64 `inactive:"+" desc:"last epoch's total sum squared error"`
EpcAvgSSE float64 `inactive:"+" desc:"last epoch's average sum squared error (average over trials, and over units within layer)"`
EpcPctErr float64 `inactive:"+" desc:"last epoch's average TrlErr"`
EpcPctCor float64 `inactive:"+" desc:"1 - last epoch's average TrlErr"`
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)"`
EpcPerTrlMSec float64 `inactive:"+" desc:"how long did the epoch take per trial in wall-clock milliseconds"`
FirstZero int `inactive:"+" desc:"epoch at when SSE first went to zero"`
NZero int `inactive:"+" desc:"number of epochs in a row with zero SSE"`
// internal state - view:"-"
SumErr float64 `view:"-" inactive:"+" desc:"sum to increment as we go through epoch"`
SumSSE float64 `view:"-" inactive:"+" desc:"sum to increment as we go through epoch"`
SumAvgSSE 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"`
Win *gi.Window `view:"-" desc:"main GUI window"`
NetView *netview.NetView `view:"-" desc:"the network viewer"`
ToolBar *gi.ToolBar `view:"-" desc:"the master toolbar"`
TrnEpcPlot *eplot.Plot2D `view:"-" desc:"the training epoch 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"`
ValsTsrs map[string]*etensor.Float32 `view:"-" desc:"map tensor for holding layer values"`
tsrsStack *Stack `view:"-" desc:"gostack map structure containing the keys and values for each stack"`
SaveWts bool `view:"-" desc:"for command-line run only, auto-save final weights after each run"`
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"`
LastEpcTime time.Time `view:"-" desc:"timer for last epoch"`
}
// 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 = &leabra.Network{}
ss.Instr = &etable.Table{}
ss.Pvlv = &etable.Table{}
ss.Trn = &etable.Table{}
ss.World = &etable.Table{}
// ss.WorldChanges = &etable.Table{}
ss.TrnEpcLog = &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.AlphaCycle
ss.TestUpdt = leabra.Cycle
ss.TestInterval = -1
ss.LayStatNms = []string{"Approach", "Avoid", "Hidden", "Behavior"}
}
////////////////////////////////////////////////////////////////////////////////////////////
// Configs
// Config configures all the elements using the standard functions
func (ss *Sim) Config() {
//ss.ConfigPats()
ss.OpenPats()
ss.ConfigEnv()
ss.ConfigNet(ss.Net)
ss.ConfigTrnEpcLog(ss.TrnEpcLog)
ss.ConfigTstEpcLog(ss.TstEpcLog)
ss.ConfigTstTrlLog(ss.TstTrlLog)
ss.ConfigTstCycLog(ss.TstCycLog)
ss.ConfigRunLog(ss.RunLog)
}
// are all of these tensors used/needed??
func (ss *Sim) ConfigEnv() {
if ss.MaxRuns == 0 { // allow user override
ss.MaxRuns = 10
}
if ss.MaxEpcs == 0 { // allow user override
ss.MaxEpcs = 50
ss.NZeroStop = 5
}
ss.TrainEnv.Nm = "TrainEnv"
ss.TrainEnv.Dsc = "training params and state"
ss.TrainEnv.Table = etable.NewIdxView(ss.Instr)
ss.TrainEnv.Validate()
ss.TrainEnv.Run.Max = ss.MaxRuns // note: we are not setting epoch max -- do that manually
ss.TestEnv.Nm = "TestEnv"
ss.TestEnv.Dsc = "testing params and state"
ss.TestEnv.Table = etable.NewIdxView(ss.Instr)
ss.TestEnv.Sequential = true
ss.TestEnv.Validate()
// note: to create a train / test split of pats, do this:
// all := etable.NewIdxView(ss.Pats)
// splits, _ := split.Permuted(all, []float64{.8, .2}, []string{"Train", "Test"})
// ss.TrainEnv.Table = splits.Splits[0]
// ss.TestEnv.Table = splits.Splits[1]
ss.TrainEnv.Init(0)
ss.TestEnv.Init(0)
}
func (ss *Sim) ConfigNet(net *leabra.Network) {
net.InitName(net, "Dynamic Personality Model")
enviro := net.AddLayer2D("Enviro", 1, 7, emer.Input)
intero := net.AddLayer2D("Intero", 1, 7, emer.Input) // TODO: @@@@ fix Parameters.Size
app := net.AddLayer2D("Approach", 1, 5, emer.Target)
av := net.AddLayer2D("Avoid", 1, 2, emer.Target)
hid := net.AddLayer2D("Hidden", 3, 7, emer.Hidden)
beh := net.AddLayer2D("Behavior", 1, 12, emer.Target)
motb := net.AddLayer2D("MotiveBias", 1, 7, emer.Input)
vta := net.AddLayer2D("VTA_DA", 1, 1, emer.Input)
// use this to position layers relative to each other
// default is Above, YAlign = Front, XAlign = Center
av.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Avoid", YAlign: relpos.Front, Space: 2})
// note: see emergent/prjn module for all the options on how to connect
// NewFull returns a new prjn.Full connectivity pattern
full := prjn.NewFull()
motb2app := prjn.NewOneToOne()
motb2av := prjn.NewOneToOne()
motb2av.SendStart = 5
net.ConnectLayers(enviro, app, full, emer.Forward)
net.ConnectLayers(enviro, av, full, emer.Forward)
net.ConnectLayers(intero, app, full, emer.Forward)
net.ConnectLayers(intero, av, full, emer.Forward)
net.ConnectLayers(vta, app, full, emer.Forward)
net.ConnectLayers(vta, av, full, emer.Inhib) // Inhibitory connection
net.ConnectLayers(motb, app, motb2app, emer.Forward)
net.ConnectLayers(motb, av, motb2av, emer.Forward)
net.BidirConnectLayers(hid, app, full)
net.BidirConnectLayers(hid, av, full)
net.BidirConnectLayers(hid, beh, full)
// Commands that are used to position the layers in the Netview
// TODO: proceduralize intero and enviro
app.SetRelPos(relpos.Rel{Rel: relpos.Above, Other: "Enviro", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
hid.SetRelPos(relpos.Rel{Rel: relpos.Above, Other: "Approach", YAlign: relpos.Front, XAlign: relpos.Left, YOffset: 0})
beh.SetRelPos(relpos.Rel{Rel: relpos.Above, Other: "Hidden", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
intero.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Enviro", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
av.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Approach", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
motb.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Avoid", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
vta.SetRelPos(relpos.Rel{Rel: relpos.RightOf, Other: "Intero", YAlign: relpos.Front, XAlign: relpos.Right, XOffset: 1})
// note: can set these to do parallel threaded computation across multiple cpus
// not worth it for this small of a model, but definitely helps for larger ones
// if Thread {
// hid2.SetThread(1)
// out.SetThread(1)
// }
// note: if you wanted to change a layer type from e.g., Target to Compare, do this:
// out.SetType(emer.Compare)
// that would mean that the output layer doesn't reflect target values in plus phase
// and thus removes error-driven learning -- but stats are still computed.
net.Defaults()
ss.SetParams("Network", ss.LogSetParams) // only set Network params
err := net.Build()
if err != nil {
log.Println(err)
return
}
net.InitWts()
}
////////////////////////////////////////////////////////////////////////////////
// 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\tTrial:\t%d\tCycle:\t%d\tName:\t%v\t\t\t", ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TrainEnv.Trial.Cur, ss.Time.Cycle, ss.TrainEnv.TrialName)
} else {
return fmt.Sprintf("Run:\t%d\tEpoch:\t%d\tTrial:\t%d\tCycle:\t%d\tName:\t%v\t\t\t", ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TestEnv.Trial.Cur, ss.Time.Cycle, ss.TestEnv.TrialName)
}
}
func (ss *Sim) UpdateView(train bool) {
if ss.NetView != nil && ss.NetView.IsVisible() {
ss.NetView.Record(ss.Counters(train), 0) // TODO: 0 was added arbitrarily to compile, update this later
// note: essential to use Go version of update when called from another goroutine
ss.NetView.GoUpdate() // note: using counters is significantly slower..
}
}
////////////////////////////////////////////////////////////////////////////////
// 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()
}
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:
if cyc != ss.Time.CycPerQtr-1 { // will be updated by quarter
ss.UpdateView(train)
}
case leabra.FastSpike:
if (cyc+1)%10 == 0 {
ss.UpdateView(train)
}
}
}
}
ss.Net.QuarterFinal(&ss.Time)
ss.Time.QuarterInc()
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()
// ss.ViewUpdt.RecordSyns() // critical to update weights // ! @@@@@@@@ error here, outdated vulkan version
ss.Net.WtFmDWt()
}
if ss.ViewOn && viewUpdt == leabra.AlphaCycle {
ss.UpdateView(train)
}
if !train {
ss.TstCycPlot.GoUpdate() // make sure up-to-date at end
}
}
// ApplyInputs applies input patterns from given environment.
// 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(en env.Env) {
ss.Net.InitExt() // clear any existing inputs -- not strictly necessary if always
// going to the same layers, but good practice and cheap anyway
lays := []string{"Enviro", "Intero", "Approach", "Avoid", "Behavior", "VTA_DA", "MotiveBias"}
for _, lnm := range lays {
ly := ss.Net.LayerByName(lnm).(leabra.LeabraLayer).AsLeabra()
pats := en.State(ly.Nm)
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)
if ss.ViewOn && ss.TrainUpdt > leabra.AlphaCycle {
ss.UpdateView(true)
}
if ss.TestInterval > 0 && epc%ss.TestInterval == 0 { // note: epc is *next* so won't trigger first time
ss.TestAll()
}
if epc >= ss.MaxEpcs || (ss.NZeroStop > 0 && ss.NZero >= ss.NZeroStop) {
// 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.TrainEnv)
ss.AlphaCyc(true) // train
ss.TrialStats(true) // accumulate
}
// 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))
}
}
// 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.TrainEnv.Init(run)
ss.TestEnv.Init(run)
ss.Time.Reset()
ss.Net.InitWts()
ss.Net.SaveWtsJSON("data/current/trained.wts")
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.SumErr = 0
ss.SumSSE = 0
ss.SumAvgSSE = 0
ss.SumCosDiff = 0
ss.FirstZero = -1
ss.NZero = 0
// clear rest just to make Sim look initialized
ss.TrlErr = 0
ss.TrlSSE = 0
ss.TrlAvgSSE = 0
ss.EpcSSE = 0
ss.EpcAvgSSE = 0
ss.EpcPctErr = 0
ss.EpcCosDiff = 0
}
// 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) {
out := ss.Net.LayerByName("Behavior").(leabra.LeabraLayer).AsLeabra()
ss.TrlCosDiff = float64(out.CosDiff.Cos)
ss.TrlSSE, ss.TrlAvgSSE = out.MSE(0.5) // 0.5 = per-unit tolerance -- right side of .5
if ss.TrlSSE > 0 {
ss.TrlErr = 1
} else {
ss.TrlErr = 0
}
if accum {
ss.SumErr += ss.TrlErr
ss.SumSSE += ss.TrlSSE
ss.SumAvgSSE += ss.TrlAvgSSE
ss.SumCosDiff += ss.TrlCosDiff
}
}
// 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()
}
// Train runs the full training from this point onward
func (ss *Sim) Train() {
ss.StopNow = false
for {
ss.TrainTrial()
if ss.StopNow {
break
}
}
ss.Stopped()
}
// Stop tells the sim to stop running
func (ss *Sim) Stop() {
ss.StopNow = true
}
// Stopped is called when a run method stops running -- updates the IsRunning flag and toolbar
func (ss *Sim) Stopped() {
ss.IsRunning = false
if ss.Win != nil {
vp := ss.Win.WinViewport2D()
if ss.ToolBar != nil {
ss.ToolBar.UpdateActions()
}
vp.SetNeedsFullRender()
}
}
// SaveWeights saves the network weights -- when called with giv.CallMethod
// it will auto-prompt for filename
func (ss *Sim) SaveWeights(filename gi.FileName) {
ss.Net.SaveWtsJSON(filename)
}
// Following code is for training the network with both Pavlovian training and Instrumental training
// controls order of training and number of Epochs of training by reading in an etable that has that information.
func (ss *Sim) TrainPIT() {
for i := 0; i < 2; i++ {
ss.Training = ss.Trn.CellString("Training", i)
ss.MaxEpcs = int(ss.Trn.CellFloat("MaxEpoch", i))
switch ss.Training {
case "INSTRUMENTAL":
ss.TrainEnv.Epoch.Cur = 0 //set current epoch to 0 so that training starts from 0 epochs
// Need to set up training patterns.
ss.TrainEnv.Table = etable.NewIdxView(ss.Instr)
ss.TestEnv.Table = etable.NewIdxView(ss.Instr)
// Unlesion Hidden and Behavior layer to make sure all layers are unlesioned
ss.Net.LayerByName("Hidden").SetOff(false)
ss.Net.LayerByName("Behavior").SetOff(false)
// Load saved weights
// OpenWtsJSON opens trained weights
ss.Net.OpenWtsJSON("data/current/trained.wts")
// Define Approach and Avoid as Input layers
// Define Behavior as a Target layer
ss.Net.LayerByName("Enviro").SetType(emer.Input)
ss.Net.LayerByName("Intero").SetType(emer.Input)
ss.Net.LayerByName("Approach").SetType(emer.Input)
ss.Net.LayerByName("Avoid").SetType(emer.Input)
ss.Net.LayerByName("Behavior").SetType(emer.Target)
// Lesion Environment and InteroState layers
ss.Net.LayerByName("Enviro").SetOff(true)
ss.Net.LayerByName("Intero").SetOff(true)
ss.Train()
// Unlesion Environment and InteroState layers
ss.Net.LayerByName("Enviro").SetOff(false)
ss.Net.LayerByName("Intero").SetOff(false)
// Save weights
ss.Net.SaveWtsJSON("data/current/trained.wts")
// Define Environment and InteroState as Input layers
// Define Approach and Avoid as Target layers
// Define Behavior as a Target layer
// Makes sure that layers are set to default.
ss.Net.LayerByName("Enviro").SetType(emer.Input)
ss.Net.LayerByName("Intero").SetType(emer.Input)
ss.Net.LayerByName("Approach").SetType(emer.Target)
ss.Net.LayerByName("Avoid").SetType(emer.Target)
ss.Net.LayerByName("Behavior").SetType(emer.Target)
case "PAVLOV":
ss.TrainEnv.Epoch.Cur = 0 //set current epoch to 0 so that training starts from 0 epochs
// Pavlovian Training
// Need to set up training patterns.
ss.TrainEnv.Table = etable.NewIdxView(ss.Pvlv)
ss.TestEnv.Table = etable.NewIdxView(ss.Pvlv)
// Define Environment and InteroState as Input layers
// Define Approach and Avoid as Target layers
// Define Behavior as a Compare layer
ss.Net.LayerByName("Enviro").SetType(emer.Input)
ss.Net.LayerByName("Intero").SetType(emer.Input)
ss.Net.LayerByName("Approach").SetType(emer.Target)
ss.Net.LayerByName("Avoid").SetType(emer.Target)
ss.Net.LayerByName("Behavior").SetType(emer.Target)
// Load saved weights
ss.Net.OpenWtsJSON("data/current/trained.wts")
// Lesion Hidden layer and Behavior layer
ss.Net.LayerByName("Hidden").SetOff(true)
ss.Net.LayerByName("Behavior").SetOff(true)
// Train until number of Epochs of training reached
ss.Train()
//Unlesion Hidden Layer and Behavior layer
ss.Net.LayerByName("Hidden").SetOff(false)
ss.Net.LayerByName("Behavior").SetOff(false)
// Save weights
ss.Net.SaveWtsJSON("data/current/trained.wts")
// Define Environment and InteroState as Input layers
// Define Approach and Avoid as Target layers
// Define Behavior as a Target layer
// Makes sure that layers are set to default.
ss.Net.LayerByName("Enviro").SetType(emer.Input)
ss.Net.LayerByName("Intero").SetType(emer.Input)
ss.Net.LayerByName("Approach").SetType(emer.Target)
ss.Net.LayerByName("Avoid").SetType(emer.Target)
ss.Net.LayerByName("Behavior").SetType(emer.Target)
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////
// Testing
// TestTrial runs one trial of testing -- always sequentially presented inputs
func (ss *Sim) TestTrial(returnOnChg bool) {
ss.TestEnv.Step()
// Query counters FIRST
_, _, chg := ss.TestEnv.Counter(env.Epoch)
if chg {
if ss.ViewOn && ss.TestUpdt > leabra.AlphaCycle {
ss.UpdateView(false)
}
ss.LogTstEpc(ss.TstEpcLog)
if returnOnChg {
return
}
}
ss.ApplyInputs(&ss.TestEnv)
ss.AlphaCyc(false) // !train
ss.TrialStats(false) // !accumulate
ss.LogTstTrl(ss.TstTrlLog)
}
// This function has been heavily modified from the TestTrial function to dynamically change the External and Internal world state as a function of the model's behavior and exogenous changes.
// WARNING!!! THIS CODE IS A WORK IN PROGRESS. IT HAS NOT BEEN FINISHED OR TESTED.
// World file: first row represents initial State of the World. Subsequent rows initially represent Exogenous Changes to the world.
// Will calculate new state of the world (next row, t) by recording: 1) previous Environment, previous Interostate, (t-1)
// 2) Behavior (t-1), then 3) calculate new Environment and Interostate (t) by calculating a) changes in both Environment and Interostate
// due to behavior, b) changes over time (e.g., getting hungry), and c) exogenous changes in the world represented in row t of World, and
// 4) write all of this into row t of World.
//
//
// WARNING!! Dynamics only runs one trial. Need to have something like TestAll call Dynamics until stopping point reached.
//
//
func (ss *Sim) Dynamics(returnOnChg bool) {
ss.TestEnv.Step()
// TestTrial is called periodically during training, by default. TestInterval is currently set to -1 to turn that off.
if ss.TestEnv.Trial.Cur == 0 {
ss.TestEnv.Table = etable.NewIdxView(ss.World) // define a World Struc item and then use "ss.World"
// datatable for World is read in by OpenPats function
// row 0 of World is initial state of World (Enviro and Interostate)
// subsequent rows will initially have Changes, and these Changes will be used in conjunction with other info
// to calculate new state of the World
ss.TestEnv.NewOrder()
// basic idea is to call this if you read in a new testing file and then have it update the indexes and the order
// so that they will correspond to the size of the new file
// does ss.TestEnv.NewOrder() work properly as long as sequential is set in the ConfigEnv function?
}
// Query counters FIRST
_, _, chg := ss.TestEnv.Counter(env.Epoch)
if chg {
if ss.ViewOn && ss.TestUpdt > leabra.AlphaCycle {
ss.UpdateView(false)
}
ss.LogTstEpc(ss.TstEpcLog)
if returnOnChg {
return
}
}
en := ss.TestEnv // would this line be correct? should this be set up with the &
// should we put the if statement here and then the function call that updates the WorldState?
if ss.TestEnv.Trial.Cur < 1 {
// Code to read input values for Environment and Interoceptive State
// ss.ValsTsr("Envp") = en.State("Enviro") // previous Environment
// ss.ValsTsr("Intp") = en.State("Intero") // previous InteroState
// TODO: proceduralize this section. shouldn't be too hard once you finish figuring out how you are going to order the layer arrays.
ss.tsrsStack.Update(REPLACE_Val, en.State("Enviro").(*etensor.Float32), FIND_Key, "EnvpTsr") // previous Environment
ss.tsrsStack.Update(REPLACE_Val, en.State("Intero").(*etensor.Float32), FIND_Key, "IntpTsr") // previous Intero
ss.ApplyInputs(&ss.TestEnv)
ss.AlphaCyc(false) // !train
// Code to read Behavior activations after AlphaCyc applied
beh := ss.Net.LayerByName("Behavior").(leabra.LeabraLayer).AsLeabra()
bh := ss.ValsTsr("Behavior") // see ra25 example for this method for a reusable map of tensors
beh.UnitValsTensor(bh, "ActM") // read the actMs into tensor
ss.TrialStats(false) // !accumulate
ss.LogTstTrl(ss.TstTrlLog)
} else {
// ! main emergentstack section:
// take previous inputs (cur-1), retrieve current values(cur) and behavior activations (see below)
// calculate new state of Environment and InteroState and put in TestEnv Table
// do below
// NEED TO READ UP ON APPROPRIATE WAY TO USE ASSIGNMENT STATEMENTS VERSUS =
// take envp, intp, and beh and then with the following, calculate new World State
// en := &ss.TestEnv // already assigned in "if statement"
// envc := en.State("Enviro").(*etensor.Float32) // exogenous Changes to current Environment
// intc := en.State("Intero").(*etensor.Float32) // exogenous Changes to current InteroState
// Are there exogenous changes to Interostate? maybe we don't need intc.
// TODO: discuss envp and intp tensors: do we need them if we're plotting to a csv each frame?
// TODO: discuss role of envc/intc vs EnviroTsr and InteroTsr
// envp := ss.EnvpTsr
// intp := ss.IntpTsr
// TODO: replace this with layerTensors; see EnviroTsr initialization to-do comment
enviro := ss.tsrsStack.Get(FIND_Key, "Enviro").Val.(*etensor.Float32) // This is used to create new Environment representation
intero := ss.tsrsStack.Get(FIND_Key, "Intero").Val.(*etensor.Float32) // This is used to create new InteroState representation
layerTensors := MakeStack(Layers.ToArray(RETURN_Keys), []*etensor.Float32{enviro, intero}) // * dummy stack until you can figure out how to procedurally add EnviroTsr and InteroTsr
// Then calculate new enviro and new intero which will be written to the World datatable
// This code takes the tensor from the Behavior layer and then finds the index of the most strongly activated behavior.
bh := ss.ValsTsr("Behavior")
_, _, _, maxBHIdx := bh.Range() // TODO: have behavior-generating minimum threshold, rather than just grab the max
// then set the Behavior tensor to all zeros and then set the value at the index to 1.
// so this tensor identifies which behavior is Performed or Enacted
bh.SetZeros()
bh.SetFloat1D(maxBHIdx, 1.0) // selected behavior => 1, rest are set to 0, found from idx "maxBHIdx"
// * Update Parameters
for _, card := range Parameters.Cards {
// initialize variables
parameterName := card.Key.(string)
parameterData := card.Val.(*Stack)
layers := parameterData.Get(FIND_Key, "layerValues").Val.(*Stack)
initialLayers := MakeStack()
dx_ui := parameterData.Get(FIND_Key, "dx_ui").Val.(float32)
tprev_s := parameterData.Get(FIND_Key, "tprev_s").Val.(float32)
tcur_s := parameterData.Get(FIND_Key, "tcur_s").Val.(float32)
dt_s := parameterData.Get(FIND_Key, "dt_s").Val.(float32)
timeIncrements := parameterData.Get(FIND_Key, "timeIncrements").Val.(*Stack) // get a stack containing each timeincrement function, corresponding to the desired incremented layer
actions := parameterData.Get(FIND_Key, "actions").Val.(*Stack)
relations := parameterData.Get(FIND_Key, "relations").Val.(*Stack)
// update time increments
for _, layerName := range layers.ToArray(RETURN_Keys) {
x := layers.Get(FIND_Key, layerName).Val.(*float32)
initialLayers.Add(layerName, gogenerics.CloneObject(*x)) // keep a save of the original layers so you can detect how much they've changed by then end of increments and actions
thisTimeIncrement := timeIncrements.Get(FIND_Key, layerName).Val.(func(float32, float32, float32, float32, float32) float32)
// update x/thisLayerValue to new float32
*x = thisTimeIncrement(*x, dx_ui, tprev_s, tcur_s, dt_s)
}
// perform actions
PerformActions(actions, parameterName)
// update relations
for _, _relation := range relations.ToArray() {
relation := _relation.(*Relation)
deltaX := *initialLayers.Get(FIND_Key, relation.ThisLayer).Val.(*float32) - *layers.Get(FIND_Key, relation.ThisLayer).Val.(*float32)
// multiply the other parameter's value by the rate of change for the other parameter times the amount by which this parameter changed
// TODO: update math, write it out in LaTeX
*Parameters.Get(FIND_Key, relation.OtherParameter).Val.(*Stack).Get(FIND_Key, relation.OtherLayer).Val.(*float32) += (relation.Dx * deltaX)
}
}
// * Perform ComplexActions
PerformActions(ComplexActions, "")
trl := ss.TestEnv.Trial.Cur
row := trl
for _, tsrCard := range layerTensors.Cards {