/
test_autodiffcomposition.py
2335 lines (1814 loc) · 93.9 KB
/
test_autodiffcomposition.py
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
import logging
import timeit as timeit
import numpy as np
import pytest
import psyneulink as pnl
from psyneulink.core.components.functions.transferfunctions import Logistic
from psyneulink.core.components.mechanisms.processing.compositioninterfacemechanism import CompositionInterfaceMechanism
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.components.process import Process
from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection
from psyneulink.core.components.system import System
try:
import torch
from psyneulink.library.compositions.autodiffcomposition import AutodiffComposition
torch_available = True
except ImportError:
torch_available = False
logger = logging.getLogger(__name__)
# All tests are set to run. If you need to skip certain tests,
# see http://doc.pytest.org/en/latest/skipping.html
# Unit tests for functions of AutodiffComposition class that are new (not in Composition)
# or override functions in Composition
@pytest.mark.skipif(
not torch_available,
reason='Pytorch python module (torch) is not installed. Please install it with '
'`pip install torch` or `pip3 install torch`'
)
@pytest.mark.acconstructor
class TestACConstructor:
def test_no_args(self):
comp = AutodiffComposition()
assert isinstance(comp, AutodiffComposition)
def test_two_calls_no_args(self):
comp = AutodiffComposition()
comp_2 = AutodiffComposition()
assert isinstance(comp, AutodiffComposition)
assert isinstance(comp_2, AutodiffComposition)
# KAM removed this pytest 10/30 after removing target_CIM
# def test_target_CIM(self):
# comp = AutodiffComposition()
# assert isinstance(comp.target_CIM, CompositionInterfaceMechanism)
# assert comp.target_CIM.composition == comp
# assert comp.target_CIM_states == {}
def test_pytorch_representation(self):
comp = AutodiffComposition()
assert comp.pytorch_representation == None
def test_report_prefs(self):
comp = AutodiffComposition()
assert comp.input_CIM.reportOutputPref == False
assert comp.output_CIM.reportOutputPref == False
# assert comp.target_CIM.reportOutputPref == False
def test_patience(self):
comp = AutodiffComposition(patience=10)
assert comp.patience == 10
@pytest.mark.skipif(
not torch_available,
reason='Pytorch python module (torch) is not installed. Please install it with '
'`pip install torch` or `pip3 install torch`'
)
@pytest.mark.acmisc
class TestMiscTrainingFunctionality:
# test whether pytorch parameters are initialized to be identical to the Autodiff Composition's
# projections when AC is initialized with the "param_init_from_pnl" argument set to True
def test_param_init_from_pnl(self):
# create xor model mechanisms and projections
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection(matrix=np.random.rand(2,10))
out_map = MappingProjection(matrix=np.random.rand(10,1))
# put the mechanisms and projections together in an autodiff composition (AC)
xor = AutodiffComposition(param_init_from_pnl=True)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
# mini version of xor.execute just to build up pytorch representation
xor._analyze_graph()
xor._build_pytorch_representation(execution_id=xor.default_execution_id)
# check whether pytorch parameters are identical to projections
assert np.allclose(hid_map.parameters.matrix.get(None),
xor.parameters.pytorch_representation.get(xor).params[0].detach().numpy())
assert np.allclose(out_map.parameters.matrix.get(None),
xor.parameters.pytorch_representation.get(xor).params[1].detach().numpy())
# test whether processing doesn't interfere with pytorch parameters after training
def test_training_then_processing(self):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection()
out_map = MappingProjection()
xor = AutodiffComposition(param_init_from_pnl=True)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
# train model for a few epochs
# results_before_proc = xor.run(inputs={xor_in:xor_inputs},
# targets={xor_out:xor_targets},
# epochs=10)
results_before_proc = xor.run(inputs = {"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
# get weight parameters from pytorch
pt_weights_hid_bp = xor.parameters.pytorch_representation.get(xor).params[0].detach().numpy().copy()
pt_weights_out_bp = xor.parameters.pytorch_representation.get(xor).params[1].detach().numpy().copy()
#KAM temporarily removed -- will reimplement when pytorch weights can be used in pure PNL execution
# do processing on a few inputs
# results_proc = xor.run(inputs={xor_in:xor_inputs})
# results_proc = xor.run(inputs={"inputs": {xor_in:xor_inputs}})
#
# # get weight parameters from pytorch
# pt_weights_hid_ap = xor.parameters.pytorch_representation.get(xor).params[0].detach().numpy().copy()
# pt_weights_out_ap = xor.parameters.pytorch_representation.get(xor).params[1].detach().numpy().copy()
#
# # check that weight parameters before and after processing are the same
# assert np.allclose(pt_weights_hid_bp, pt_weights_hid_ap)
# assert np.allclose(pt_weights_out_bp, pt_weights_out_ap)
@pytest.mark.parametrize(
'loss', ['l1', 'poissonnll']
)
def test_various_loss_specs(self, loss):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection()
out_map = MappingProjection()
xor = AutodiffComposition(param_init_from_pnl=True, loss_spec=loss)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
xor.run(inputs = {"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
def test_pytorch_loss_spec(self):
ls = torch.nn.SoftMarginLoss(reduction='sum')
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection()
out_map = MappingProjection()
xor = AutodiffComposition(param_init_from_pnl=True, loss_spec=ls)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
xor.run(inputs={"inputs": {xor_in: xor_inputs},
"targets": {xor_out: xor_targets},
"epochs": 10})
@pytest.mark.parametrize(
'learning_rate, weight_decay, optimizer_type', [
(10, 0, 'sgd'), (1.5, 1, 'sgd'), (1.5, 1, 'adam'),
]
)
def test_optimizer_specs(self, learning_rate, weight_decay, optimizer_type):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection()
out_map = MappingProjection()
xor = AutodiffComposition(param_init_from_pnl=True,
learning_rate=learning_rate,
optimizer_type=optimizer_type,
weight_decay=weight_decay)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
# train model for a few epochs
# results_before_proc = xor.run(inputs={xor_in:xor_inputs},
# targets={xor_out:xor_targets},
# epochs=10)
results_before_proc = xor.run(inputs = {"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
# test whether pytorch parameters and projections are kept separate (at diff. places in memory)
def test_params_stay_separate(self):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_m = np.random.rand(2,10)
out_m = np.random.rand(10,1)
hid_map = MappingProjection(name='hid_map',
matrix=hid_m.copy(),
sender=xor_in,
receiver=xor_hid)
out_map = MappingProjection(name='out_map',
matrix=out_m.copy(),
sender=xor_hid,
receiver=xor_out)
xor = AutodiffComposition(param_init_from_pnl=True,
learning_rate=10.0,
optimizer_type="sgd")
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
# train the model for a few epochs
result = xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
# get weight parameters from pytorch
pt_weights_hid = xor.parameters.pytorch_representation.get(xor).params[0].detach().numpy().copy()
pt_weights_out = xor.parameters.pytorch_representation.get(xor).params[1].detach().numpy().copy()
# assert that projections are still what they were initialized as
assert np.allclose(hid_map.parameters.matrix.get(None), hid_m)
assert np.allclose(out_map.parameters.matrix.get(None), out_m)
# assert that projections didn't change during training with the pytorch
# parameters (they should now be different)
assert not np.allclose(pt_weights_hid, hid_map.parameters.matrix.get(None))
assert not np.allclose(pt_weights_out, out_map.parameters.matrix.get(None))
# test whether the autodiff composition's get_parameters method works as desired
def test_get_params(self):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection(matrix=np.random.rand(2,10))
out_map = MappingProjection(matrix=np.random.rand(10,1))
xor = AutodiffComposition(param_init_from_pnl=True,
learning_rate=1.0)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
# call run to only process the inputs, so that pytorch representation of AC gets created
# results = xor.run(inputs={xor_in:xor_inputs})
#KAM Changed 11/1/18
# mini version of xor.execute just to build up pytorch representation
xor._analyze_graph()
# CW changed 12/3/18
xor._build_pytorch_representation(xor.default_execution_id)
# OLD
# xor._build_pytorch_representation()
# call get_parameters to obtain a copy of the pytorch parameters in numpy arrays,
# and get the parameters straight from pytorch
weights_get_params = xor.get_parameters()[0]
weights_straight_1 = xor.parameters.pytorch_representation.get(xor).params[0]
weights_straight_2 = xor.parameters.pytorch_representation.get(xor).params[1]
# check that parameter copies obtained from get_parameters are the same as the
# projections and parameters from pytorch
assert np.allclose(hid_map.parameters.matrix.get(None), weights_get_params[hid_map])
assert np.allclose(weights_straight_1.detach().numpy(), weights_get_params[hid_map])
assert np.allclose(out_map.parameters.matrix.get(None), weights_get_params[out_map])
assert np.allclose(weights_straight_2.detach().numpy(), weights_get_params[out_map])
# call run to train the pytorch parameters
results = xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 10})
# check that the parameter copies obtained from get_parameters have not changed with the
# pytorch parameters during training (and are thus at a different memory location)
assert not np.allclose(weights_straight_1.detach().numpy(), weights_get_params[hid_map])
assert not np.allclose(weights_straight_2.detach().numpy(), weights_get_params[out_map])
@pytest.mark.skipif(
not torch_available,
reason='Pytorch python module (torch) is not installed. Please install it with '
'`pip install torch` or `pip3 install torch`'
)
@pytest.mark.accorrectness
class TestTrainingCorrectness:
# test whether xor model created as autodiff composition learns properly
@pytest.mark.parametrize(
'eps, calls, opt, from_pnl_or_no', [
(2000, 'single', 'adam', True),
# (6000, 'multiple', 'adam', True),
(2000, 'single', 'adam', False),
# (6000, 'multiple', 'adam', False)
]
)
def test_xor_training_correctness(self, eps, calls, opt, from_pnl_or_no):
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
hid_map = MappingProjection(matrix=np.random.rand(2,10), sender=xor_in, receiver=xor_hid)
out_map = MappingProjection(matrix=np.random.rand(10,1))
xor = AutodiffComposition(param_init_from_pnl=from_pnl_or_no,
optimizer_type=opt,
learning_rate=0.1)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
if calls == 'single':
results = xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": eps}
)
for i in range(len(results[0])):
assert np.allclose(np.round(results[0][i][0]), xor_targets[i])
else:
results = xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 1}
)
for i in range(eps-1):
results = xor.run(inputs={"inputs": {xor_in:xor_inputs},
"targets": {xor_out:xor_targets},
"epochs": 1}
)
for i in range(len(results[eps-1])):
assert np.allclose(np.round(results[eps-1][i][0]), xor_targets[i])
# tests whether semantic network created as autodiff composition learns properly
@pytest.mark.parametrize(
'eps, opt, from_pnl_or_no', [
(1000, 'adam', True),
# (1000, 'adam', False)
]
)
def test_semantic_net_training_correctness(self, eps, opt, from_pnl_or_no):
# MECHANISMS FOR SEMANTIC NET:
nouns_in = TransferMechanism(name="nouns_input",
default_variable=np.zeros(8))
rels_in = TransferMechanism(name="rels_input",
default_variable=np.zeros(3))
h1 = TransferMechanism(name="hidden_nouns",
default_variable=np.zeros(8),
function=Logistic())
h2 = TransferMechanism(name="hidden_mixed",
default_variable=np.zeros(15),
function=Logistic())
out_sig_I = TransferMechanism(name="sig_outs_I",
default_variable=np.zeros(8),
function=Logistic())
out_sig_is = TransferMechanism(name="sig_outs_is",
default_variable=np.zeros(12),
function=Logistic())
out_sig_has = TransferMechanism(name="sig_outs_has",
default_variable=np.zeros(9),
function=Logistic())
out_sig_can = TransferMechanism(name="sig_outs_can",
default_variable=np.zeros(9),
function=Logistic())
# SET UP PROJECTIONS FOR SEMANTIC NET
map_nouns_h1 = MappingProjection(matrix=np.random.rand(8,8),
name="map_nouns_h1",
sender=nouns_in,
receiver=h1)
map_rels_h2 = MappingProjection(matrix=np.random.rand(3,15),
name="map_relh2",
sender=rels_in,
receiver=h2)
map_h1_h2 = MappingProjection(matrix=np.random.rand(8,15),
name="map_h1_h2",
sender=h1,
receiver=h2)
map_h2_I = MappingProjection(matrix=np.random.rand(15,8),
name="map_h2_I",
sender=h2,
receiver=out_sig_I)
map_h2_is = MappingProjection(matrix=np.random.rand(15,12),
name="map_h2_is",
sender=h2,
receiver=out_sig_is)
map_h2_has = MappingProjection(matrix=np.random.rand(15,9),
name="map_h2_has",
sender=h2,
receiver=out_sig_has)
map_h2_can = MappingProjection(matrix=np.random.rand(15,9),
name="map_h2_can",
sender=h2,
receiver=out_sig_can)
# COMPOSITION FOR SEMANTIC NET
sem_net = AutodiffComposition(param_init_from_pnl=from_pnl_or_no,
optimizer_type=opt, learning_rate=0.001)
sem_net.add_node(nouns_in)
sem_net.add_node(rels_in)
sem_net.add_node(h1)
sem_net.add_node(h2)
sem_net.add_node(out_sig_I)
sem_net.add_node(out_sig_is)
sem_net.add_node(out_sig_has)
sem_net.add_node(out_sig_can)
sem_net.add_projection(sender=nouns_in, projection=map_nouns_h1, receiver=h1)
sem_net.add_projection(sender=rels_in, projection=map_rels_h2, receiver=h2)
sem_net.add_projection(sender=h1, projection=map_h1_h2, receiver=h2)
sem_net.add_projection(sender=h2, projection=map_h2_I, receiver=out_sig_I)
sem_net.add_projection(sender=h2, projection=map_h2_is, receiver=out_sig_is)
sem_net.add_projection(sender=h2, projection=map_h2_has, receiver=out_sig_has)
sem_net.add_projection(sender=h2, projection=map_h2_can, receiver=out_sig_can)
# INPUTS & OUTPUTS FOR SEMANTIC NET:
nouns = ['oak', 'pine', 'rose', 'daisy', 'canary', 'robin', 'salmon', 'sunfish']
relations = ['is', 'has', 'can']
is_list = ['living', 'living thing', 'plant', 'animal', 'tree', 'flower', 'bird', 'fish', 'big', 'green', 'red',
'yellow']
has_list = ['roots', 'leaves', 'bark', 'branches', 'skin', 'feathers', 'wings', 'gills', 'scales']
can_list = ['grow', 'move', 'swim', 'fly', 'breathe', 'breathe underwater', 'breathe air', 'walk', 'photosynthesize']
nouns_input = np.identity(len(nouns))
rels_input = np.identity(len(relations))
truth_nouns = np.identity(len(nouns))
truth_is = np.zeros((len(nouns), len(is_list)))
truth_is[0, :] = [1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0]
truth_is[1, :] = [1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0]
truth_is[2, :] = [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0]
truth_is[3, :] = [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]
truth_is[4, :] = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1]
truth_is[5, :] = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
truth_is[6, :] = [1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
truth_is[7, :] = [1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0]
truth_has = np.zeros((len(nouns), len(has_list)))
truth_has[0, :] = [1, 1, 1, 1, 0, 0, 0, 0, 0]
truth_has[1, :] = [1, 1, 1, 1, 0, 0, 0, 0, 0]
truth_has[2, :] = [1, 1, 0, 0, 0, 0, 0, 0, 0]
truth_has[3, :] = [1, 1, 0, 0, 0, 0, 0, 0, 0]
truth_has[4, :] = [0, 0, 0, 0, 1, 1, 1, 0, 0]
truth_has[5, :] = [0, 0, 0, 0, 1, 1, 1, 0, 0]
truth_has[6, :] = [0, 0, 0, 0, 0, 0, 0, 1, 1]
truth_has[7, :] = [0, 0, 0, 0, 0, 0, 0, 1, 1]
truth_can = np.zeros((len(nouns), len(can_list)))
truth_can[0, :] = [1, 0, 0, 0, 0, 0, 0, 0, 1]
truth_can[1, :] = [1, 0, 0, 0, 0, 0, 0, 0, 1]
truth_can[2, :] = [1, 0, 0, 0, 0, 0, 0, 0, 1]
truth_can[3, :] = [1, 0, 0, 0, 0, 0, 0, 0, 1]
truth_can[4, :] = [1, 1, 0, 1, 1, 0, 1, 1, 0]
truth_can[5, :] = [1, 1, 0, 1, 1, 0, 1, 1, 0]
truth_can[6, :] = [1, 1, 1, 0, 1, 1, 0, 0, 0]
truth_can[7, :] = [1, 1, 1, 0, 1, 1, 0, 0, 0]
# SETTING UP DICTIONARY OF INPUTS/OUTPUTS FOR SEMANTIC NET
inputs_dict = {}
inputs_dict[nouns_in] = []
inputs_dict[rels_in] = []
targets_dict = {}
targets_dict[out_sig_I] = []
targets_dict[out_sig_is] = []
targets_dict[out_sig_has] = []
targets_dict[out_sig_can] = []
for i in range(len(nouns)):
for j in range(len(relations)):
inputs_dict[nouns_in].append(nouns_input[i])
inputs_dict[rels_in].append(rels_input[j])
targets_dict[out_sig_I].append(truth_nouns[i])
targets_dict[out_sig_is].append(truth_is[i])
targets_dict[out_sig_has].append(truth_has[i])
targets_dict[out_sig_can].append(truth_can[i])
# TRAIN THE MODEL
result = sem_net.run(inputs=[{'inputs': inputs_dict,
'targets': targets_dict,
'epochs': eps}])
# CHECK CORRECTNESS
for i in range(len(result[0])): # go over trial outputs in the single results entry
for j in range(len(result[0][i])): # go over outputs for each output layer
# get target for terminal node whose output state corresponds to current output
correct_value = None
curr_CIM_input_state = sem_net.output_CIM.input_states[j]
for output_state in sem_net.output_CIM_states.keys():
if sem_net.output_CIM_states[output_state][0] == curr_CIM_input_state:
node = output_state.owner
correct_value = targets_dict[node][i]
# compare model output for terminal node on current trial with target for terminal node on current trial
assert np.allclose(np.round(result[0][i][j]), correct_value)
@pytest.mark.skipif(
not torch_available,
reason='Pytorch python module (torch) is not installed. Please install it with '
'`pip install torch` or `pip3 install torch`'
)
@pytest.mark.actime
class TestTrainingTime:
@pytest.mark.skip
@pytest.mark.parametrize(
'eps, opt', [
(1, 'sgd'),
(10, 'sgd'),
(100, 'sgd')
]
)
def test_and_training_time(self, eps, opt):
# SET UP MECHANISMS FOR COMPOSITION
and_in = TransferMechanism(name='and_in',
default_variable=np.zeros(2))
and_out = TransferMechanism(name='and_out',
default_variable=np.zeros(1),
function=Logistic())
# SET UP MECHANISMS FOR SYSTEM
and_in_sys = TransferMechanism(name='and_in_sys',
default_variable=np.zeros(2))
and_out_sys = TransferMechanism(name='and_out_sys',
default_variable=np.zeros(1),
function=Logistic())
# SET UP PROJECTIONS FOR COMPOSITION
and_map = MappingProjection(name='and_map',
matrix=np.random.rand(2, 1),
sender=and_in,
receiver=and_out)
# SET UP PROJECTIONS FOR SYSTEM
and_map_sys = MappingProjection(name='and_map_sys',
matrix=and_map.matrix.copy(),
sender=and_in_sys,
receiver=and_out_sys)
# SET UP COMPOSITION
and_net = AutodiffComposition(param_init_from_pnl=True)
and_net.add_node(and_in)
and_net.add_node(and_out)
and_net.add_projection(sender=and_in, projection=and_map, receiver=and_out)
# SET UP INPUTS AND TARGETS
and_inputs = np.zeros((4,2))
and_inputs[0] = [0, 0]
and_inputs[1] = [0, 1]
and_inputs[2] = [1, 0]
and_inputs[3] = [1, 1]
and_targets = np.zeros((4,1))
and_targets[0] = [0]
and_targets[1] = [1]
and_targets[2] = [1]
and_targets[3] = [0]
# TIME TRAINING FOR COMPOSITION
start = timeit.default_timer()
result = and_net.run(inputs={and_in:and_inputs},
targets={and_out:and_targets},
epochs=eps,
learning_rate=0.1,
controller=opt)
end = timeit.default_timer()
comp_time = end - start
# SET UP SYSTEM
and_process = Process(pathway=[and_in_sys,
and_map_sys,
and_out_sys],
learning=pnl.LEARNING)
and_sys = System(processes=[and_process],
learning_rate=0.1)
# TIME TRAINING FOR SYSTEM
start = timeit.default_timer()
results_sys = and_sys.run(inputs={and_in_sys:and_inputs},
targets={and_out_sys:and_targets},
num_trials=(eps*and_inputs.shape[0]+1))
end = timeit.default_timer()
sys_time = end - start
# LOG TIMES, SPEEDUP PROVIDED BY COMPOSITION OVER SYSTEM
msg = 'Training XOR model as AutodiffComposition for {0} epochs took {1} seconds'.format(eps, comp_time)
print(msg)
print("\n")
logger.info(msg)
msg = 'Training XOR model as System for {0} epochs took {1} seconds'.format(eps, sys_time)
print(msg)
print("\n")
logger.info(msg)
speedup = np.round((sys_time/comp_time), decimals=2)
msg = ('Training XOR model as AutodiffComposition for {0} epochs was {1} times faster than '
'training it as System for {0} epochs.'.format(eps, speedup))
print(msg)
logger.info(msg)
@pytest.mark.skip
@pytest.mark.parametrize(
'eps, opt', [
(1, 'sgd'),
(10, 'sgd'),
(100, 'sgd')
]
)
def test_xor_training_time(self, eps, opt):
# SET UP MECHANISMS FOR COMPOSITION
xor_in = TransferMechanism(name='xor_in',
default_variable=np.zeros(2))
xor_hid = TransferMechanism(name='xor_hid',
default_variable=np.zeros(10),
function=Logistic())
xor_out = TransferMechanism(name='xor_out',
default_variable=np.zeros(1),
function=Logistic())
# SET UP MECHANISMS FOR SYSTEM
xor_in_sys = TransferMechanism(name='xor_in_sys',
default_variable=np.zeros(2))
xor_hid_sys = TransferMechanism(name='xor_hid_sys',
default_variable=np.zeros(10),
function=Logistic())
xor_out_sys = TransferMechanism(name='xor_out_sys',
default_variable=np.zeros(1),
function=Logistic())
# SET UP PROJECTIONS FOR COMPOSITION
hid_map = MappingProjection(name='hid_map',
matrix=np.random.rand(2,10),
sender=xor_in,
receiver=xor_hid)
out_map = MappingProjection(name='out_map',
matrix=np.random.rand(10,1),
sender=xor_hid,
receiver=xor_out)
# SET UP PROJECTIONS FOR SYSTEM
hid_map_sys = MappingProjection(name='hid_map_sys',
matrix=hid_map.matrix.copy(),
sender=xor_in_sys,
receiver=xor_hid_sys)
out_map_sys = MappingProjection(name='out_map_sys',
matrix=out_map.matrix.copy(),
sender=xor_hid_sys,
receiver=xor_out_sys)
# SET UP COMPOSITION
xor = AutodiffComposition(param_init_from_pnl=True)
xor.add_node(xor_in)
xor.add_node(xor_hid)
xor.add_node(xor_out)
xor.add_projection(sender=xor_in, projection=hid_map, receiver=xor_hid)
xor.add_projection(sender=xor_hid, projection=out_map, receiver=xor_out)
# SET UP INPUTS AND TARGETS
xor_inputs = np.array( # the inputs we will provide to the model
[[0, 0],
[0, 1],
[1, 0],
[1, 1]])
xor_targets = np.array( # the outputs we wish to see from the model
[[0],
[1],
[1],
[0]])
# TIME TRAINING FOR COMPOSITION
start = timeit.default_timer()
result = xor.run(inputs={xor_in:xor_inputs},
targets={xor_out:xor_targets},
epochs=eps,
learning_rate=0.1,
controller=opt)
end = timeit.default_timer()
comp_time = end - start
# SET UP SYSTEM
xor_process = Process(pathway=[xor_in_sys,
hid_map_sys,
xor_hid_sys,
out_map_sys,
xor_out_sys],
learning=pnl.LEARNING)
xor_sys = System(processes=[xor_process],
learning_rate=0.1)
# TIME TRAINING FOR SYSTEM
start = timeit.default_timer()
results_sys = xor_sys.run(inputs={xor_in_sys:xor_inputs},
targets={xor_out_sys:xor_targets},
num_trials=(eps*xor_inputs.shape[0]+1))
end = timeit.default_timer()
sys_time = end - start
# LOG TIMES, SPEEDUP PROVIDED BY COMPOSITION OVER SYSTEM
msg = 'Training XOR model as AutodiffComposition for {0} epochs took {1} seconds'.format(eps, comp_time)
print(msg)
print("\n")
logger.info(msg)
msg = 'Training XOR model as System for {0} epochs took {1} seconds'.format(eps, sys_time)
print(msg)
print("\n")
logger.info(msg)
speedup = np.round((sys_time/comp_time), decimals=2)
msg = ('Training XOR model as AutodiffComposition for {0} epochs was {1} times faster than '
'training it as System for {0} epochs.'.format(eps, speedup))
print(msg)
logger.info(msg)
@pytest.mark.skip
@pytest.mark.parametrize(
'eps, opt', [
(1, 'sgd'),
(10, 'sgd'),
(100, 'sgd')
]
)
def test_semantic_net_training_time(self, eps, opt):
# SET UP MECHANISMS FOR COMPOSITION: