File size: 69,238 Bytes
3bdb76c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
from dreamcoder.enumeration import *
from dreamcoder.grammar import *
# luke


import gc

try:
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from torch.autograd import Variable
    from torch.nn.utils.rnn import pack_padded_sequence
except:
    eprint("WARNING: Could not import torch. This is only okay when doing pypy compression.")

try:
    import numpy as np
except:
    eprint("WARNING: Could not import np. This is only okay when doing pypy compression.")
    
import json


def variable(x, volatile=False, cuda=False):
    if isinstance(x, list):
        x = np.array(x)
    if isinstance(x, (np.ndarray, np.generic)):
        x = torch.from_numpy(x)
    if cuda:
        x = x.cuda()
    return Variable(x, volatile=volatile)

def maybe_cuda(x, use_cuda):
    if use_cuda:
        return x.cuda()
    else:
        return x


def is_torch_not_a_number(v):
    """checks whether a tortured variable is nan"""
    v = v.data
    if not ((v == v).item()):
        return True
    return False

def is_torch_invalid(v):
    """checks whether a torch variable is nan or inf"""
    if is_torch_not_a_number(v):
        return True
    a = v - v
    if is_torch_not_a_number(a):
        return True
    return False

def _relu(x): return x.clamp(min=0)

class Entropy(nn.Module):
    """Calculates the entropy of logits"""
    def __init__(self):
        super(Entropy, self).__init__()

    def forward(self, x):
        b = F.softmax(x, dim=0) * F.log_softmax(x, dim=0)
        b = -1.0 * b.sum()
        return b

class GrammarNetwork(nn.Module):
    """Neural network that outputs a grammar"""
    def __init__(self, inputDimensionality, grammar):
        super(GrammarNetwork, self).__init__()
        self.logProductions = nn.Linear(inputDimensionality, len(grammar)+1)
        self.grammar = grammar
        
    def forward(self, x):
        """Takes as input inputDimensionality-dimensional vector and returns Grammar
        Tensor-valued probabilities"""
        logProductions = self.logProductions(x)
        return Grammar(logProductions[-1].view(1), #logVariable
                       [(logProductions[k].view(1), t, program)
                        for k, (_, t, program) in enumerate(self.grammar.productions)],
                       continuationType=self.grammar.continuationType)

    def batchedLogLikelihoods(self, xs, summaries):
        """Takes as input BxinputDimensionality vector & B likelihood summaries;
        returns B-dimensional vector containing log likelihood of each summary"""
        use_cuda = xs.device.type == 'cuda'

        B = xs.size(0)
        assert len(summaries) == B
        logProductions = self.logProductions(xs)

        # uses[b][p] is # uses of primitive p by summary b
        uses = np.zeros((B,len(self.grammar) + 1))
        for b,summary in enumerate(summaries):
            for p, production in enumerate(self.grammar.primitives):
                uses[b,p] = summary.uses.get(production, 0.)
            uses[b,len(self.grammar)] = summary.uses.get(Index(0), 0)

        numerator = (logProductions * maybe_cuda(torch.from_numpy(uses).float(),use_cuda)).sum(1)
        numerator += maybe_cuda(torch.tensor([summary.constant for summary in summaries ]).float(), use_cuda)

        alternativeSet = {normalizer
                          for s in summaries
                          for normalizer in s.normalizers }
        alternativeSet = list(alternativeSet)

        mask = np.zeros((len(alternativeSet), len(self.grammar) + 1))
        for tau in range(len(alternativeSet)):
            for p, production in enumerate(self.grammar.primitives):
                mask[tau,p] = 0. if production in alternativeSet[tau] else NEGATIVEINFINITY
            mask[tau,len(self.grammar)] = 0. if Index(0) in alternativeSet[tau] else NEGATIVEINFINITY
        mask = maybe_cuda(torch.tensor(mask).float(), use_cuda)

        # mask: Rx|G|
        # logProductions: Bx|G|
        # Want: mask + logProductions : BxRx|G| = z
        z = mask.repeat(B,1,1) + logProductions.repeat(len(alternativeSet),1,1).transpose(1,0)
        # z: BxR
        z = torch.logsumexp(z, 2) # pytorch 1.0 dependency

        # Calculate how many times each normalizer was used
        N = np.zeros((B, len(alternativeSet)))
        for b, summary in enumerate(summaries):
            for tau, alternatives in enumerate(alternativeSet):
                N[b, tau] = summary.normalizers.get(alternatives,0.)

        denominator = (maybe_cuda(torch.tensor(N).float(),use_cuda) * z).sum(1)
        return numerator - denominator

        

class ContextualGrammarNetwork_LowRank(nn.Module):
    def __init__(self, inputDimensionality, grammar, R=16):
        """Low-rank approximation to bigram model. Parameters is linear in number of primitives.
        R: maximum rank"""
        
        super(ContextualGrammarNetwork_LowRank, self).__init__()

        self.grammar = grammar

        self.R = R # embedding size

        # library now just contains a list of indicies which go with each primitive
        self.grammar = grammar
        self.library = {}
        self.n_grammars = 0
        for prim in grammar.primitives:
            numberOfArguments = len(prim.infer().functionArguments())
            idx_list = list(range(self.n_grammars, self.n_grammars+numberOfArguments))
            self.library[prim] = idx_list
            self.n_grammars += numberOfArguments
        
        # We had an extra grammar for when there is no parent and for when the parent is a variable
        self.n_grammars += 2
        self.transitionMatrix = LowRank(inputDimensionality, self.n_grammars, len(grammar) + 1, R)
        
    def grammarFromVector(self, logProductions):
        return Grammar(logProductions[-1].view(1),
                       [(logProductions[k].view(1), t, program)
                        for k, (_, t, program) in enumerate(self.grammar.productions)],
                       continuationType=self.grammar.continuationType)

    def forward(self, x):
        assert len(x.size()) == 1, "contextual grammar doesn't currently support batching"

        transitionMatrix = self.transitionMatrix(x)
        
        return ContextualGrammar(self.grammarFromVector(transitionMatrix[-1]), self.grammarFromVector(transitionMatrix[-2]),
                {prim: [self.grammarFromVector(transitionMatrix[j]) for j in js]
                 for prim, js in self.library.items()} )
        
    def vectorizedLogLikelihoods(self, x, summaries):
        B = len(summaries)
        G = len(self.grammar) + 1

        # Which column of the transition matrix corresponds to which primitive
        primitiveColumn = {p: c
                           for c, (_1,_2,p) in enumerate(self.grammar.productions) }
        primitiveColumn[Index(0)] = G - 1
        # Which row of the transition matrix corresponds to which context
        contextRow = {(parent, index): r
                      for parent, indices in self.library.items()
                      for index, r in enumerate(indices) }
        contextRow[(None,None)] = self.n_grammars - 1
        contextRow[(Index(0),None)] = self.n_grammars - 2

        transitionMatrix = self.transitionMatrix(x)

        # uses[b][g][p] is # uses of primitive p by summary b for parent g
        uses = np.zeros((B,self.n_grammars,len(self.grammar)+1))
        for b,summary in enumerate(summaries):
            for e, ss in summary.library.items():
                for g,s in zip(self.library[e], ss):
                    assert g < self.n_grammars - 2
                    for p, production in enumerate(self.grammar.primitives):
                        uses[b,g,p] = s.uses.get(production, 0.)
                    uses[b,g,len(self.grammar)] = s.uses.get(Index(0), 0)
                    
            # noParent: this is the last network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 1, p] = summary.noParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 1, G - 1] = summary.noParent.uses.get(Index(0), 0.)

            # variableParent: this is the penultimate network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 2, p] = summary.variableParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 2, G - 1] = summary.variableParent.uses.get(Index(0), 0.)

        uses = maybe_cuda(torch.tensor(uses).float(),use_cuda)
        numerator = uses.view(B, -1) @ transitionMatrix.view(-1)
        
        constant = np.zeros(B)
        for b,summary in enumerate(summaries):
            constant[b] += summary.noParent.constant + summary.variableParent.constant
            for ss in summary.library.values():
                for s in ss:
                    constant[b] += s.constant
            
        numerator = numerator + maybe_cuda(torch.tensor(constant).float(),use_cuda)

        # Calculate the god-awful denominator
        # Map from (parent, index, {set-of-alternatives}) to [occurrences-in-summary-zero, occurrences-in-summary-one, ...]
        alternativeSet = {}
        for b,summary in enumerate(summaries):
            for normalizer, frequency in summary.noParent.normalizers.items():
                k = (None,None,normalizer)
                alternativeSet[k] = alternativeSet.get(k, np.zeros(B))
                alternativeSet[k][b] += frequency
            for normalizer, frequency in summary.variableParent.normalizers.items():
                k = (Index(0),None,normalizer)
                alternativeSet[k] = alternativeSet.get(k, np.zeros(B))
                alternativeSet[k][b] += frequency
            for parent, ss in summary.library.items():
                for argumentIndex, s in enumerate(ss):
                    for normalizer, frequency in s.normalizers.items():
                        k = (parent, argumentIndex, normalizer)
                        alternativeSet[k] = alternativeSet.get(k, zeros(B))
                        alternativeSet[k][b] += frequency

        # Calculate each distinct normalizing constant
        alternativeNormalizer = {}
        for parent, index, alternatives in alternativeSet:
            r = transitionMatrix[contextRow[(parent, index)]]
            entries = r[ [primitiveColumn[alternative] for alternative in alternatives ]]
            alternativeNormalizer[(parent, index, alternatives)] = torch.logsumexp(entries, dim=0)

        # Concatenate the normalizers into a vector
        normalizerKeys = list(alternativeSet.keys())
        normalizerVector = torch.cat([ alternativeNormalizer[k] for k in normalizerKeys])

        assert False, "This function is still in progress."
        

    def batchedLogLikelihoods(self, xs, summaries):
        """Takes as input BxinputDimensionality vector & B likelihood summaries;
        returns B-dimensional vector containing log likelihood of each summary"""
        use_cuda = xs.device.type == 'cuda'
        
        B = xs.shape[0]
        G = len(self.grammar) + 1
        assert len(summaries) == B

        # logProductions: Bx n_grammars x G
        logProductions = self.transitionMatrix(xs)
        # uses[b][g][p] is # uses of primitive p by summary b for parent g
        uses = np.zeros((B,self.n_grammars,len(self.grammar)+1))
        for b,summary in enumerate(summaries):
            for e, ss in summary.library.items():
                for g,s in zip(self.library[e], ss):
                    assert g < self.n_grammars - 2
                    for p, production in enumerate(self.grammar.primitives):
                        uses[b,g,p] = s.uses.get(production, 0.)
                    uses[b,g,len(self.grammar)] = s.uses.get(Index(0), 0)
                    
            # noParent: this is the last network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 1, p] = summary.noParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 1, G - 1] = summary.noParent.uses.get(Index(0), 0.)

            # variableParent: this is the penultimate network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 2, p] = summary.variableParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 2, G - 1] = summary.variableParent.uses.get(Index(0), 0.)
            
        numerator = (logProductions*maybe_cuda(torch.tensor(uses).float(),use_cuda)).view(B,-1).sum(1)

        constant = np.zeros(B)
        for b,summary in enumerate(summaries):
            constant[b] += summary.noParent.constant + summary.variableParent.constant
            for ss in summary.library.values():
                for s in ss:
                    constant[b] += s.constant
            
        numerator += maybe_cuda(torch.tensor(constant).float(),use_cuda)
        
        if True:

            # Calculate the god-awful denominator
            alternativeSet = set()
            for summary in summaries:
                for normalizer in summary.noParent.normalizers: alternativeSet.add(normalizer)
                for normalizer in summary.variableParent.normalizers: alternativeSet.add(normalizer)
                for ss in summary.library.values():
                    for s in ss:
                        for normalizer in s.normalizers: alternativeSet.add(normalizer)
            alternativeSet = list(alternativeSet)

            mask = np.zeros((len(alternativeSet), G))
            for tau in range(len(alternativeSet)):
                for p, production in enumerate(self.grammar.primitives):
                    mask[tau,p] = 0. if production in alternativeSet[tau] else NEGATIVEINFINITY
                mask[tau, G - 1] = 0. if Index(0) in alternativeSet[tau] else NEGATIVEINFINITY
            mask = maybe_cuda(torch.tensor(mask).float(), use_cuda)

            z = mask.repeat(self.n_grammars,1,1).repeat(B,1,1,1) + \
                logProductions.repeat(len(alternativeSet),1,1,1).transpose(0,1).transpose(1,2)
            z = torch.logsumexp(z, 3) # pytorch 1.0 dependency

            N = np.zeros((B, self.n_grammars, len(alternativeSet)))
            for b, summary in enumerate(summaries):
                for e, ss in summary.library.items():
                    for g,s in zip(self.library[e], ss):
                        assert g < self.n_grammars - 2
                        for r, alternatives in enumerate(alternativeSet):                
                            N[b,g,r] = s.normalizers.get(alternatives, 0.)
                # noParent: this is the last network output
                for r, alternatives in enumerate(alternativeSet):
                    N[b,self.n_grammars - 1,r] = summary.noParent.normalizers.get(alternatives, 0.)
                # variableParent: this is the penultimate network output
                for r, alternatives in enumerate(alternativeSet):
                    N[b,self.n_grammars - 2,r] = summary.variableParent.normalizers.get(alternatives, 0.)
            N = maybe_cuda(torch.tensor(N).float(), use_cuda)
            denominator = (N*z).sum(1).sum(1)
        else:
            gs = [ self(xs[b]) for b in range(B) ]
            denominator = torch.cat([ summary.denominator(g) for summary,g in zip(summaries, gs) ])
            
            

        
        
        ll = numerator - denominator 

        if False: # verifying that batching works correctly
            gs = [ self(xs[b]) for b in range(B) ]
            _l = torch.cat([ summary.logLikelihood(g) for summary,g in zip(summaries, gs) ])
            assert torch.all((ll - _l).abs() < 0.0001)
        return ll
    
class ContextualGrammarNetwork_Mask(nn.Module):
    def __init__(self, inputDimensionality, grammar):
        """Bigram model, but where the bigram transitions are unconditional.
        Individual primitive probabilities are still conditional (predicted by neural network)
        """
        
        super(ContextualGrammarNetwork_Mask, self).__init__()

        self.grammar = grammar

        # library now just contains a list of indicies which go with each primitive
        self.grammar = grammar
        self.library = {}
        self.n_grammars = 0
        for prim in grammar.primitives:
            numberOfArguments = len(prim.infer().functionArguments())
            idx_list = list(range(self.n_grammars, self.n_grammars+numberOfArguments))
            self.library[prim] = idx_list
            self.n_grammars += numberOfArguments
        
        # We had an extra grammar for when there is no parent and for when the parent is a variable
        self.n_grammars += 2
        self._transitionMatrix = nn.Parameter(nn.init.xavier_uniform(torch.Tensor(self.n_grammars, len(grammar) + 1)))
        self._logProductions = nn.Linear(inputDimensionality, len(grammar)+1)

    def transitionMatrix(self, x):
        if len(x.shape) == 1: # not batched
            return self._logProductions(x) + self._transitionMatrix # will broadcast
        elif len(x.shape) == 2: # batched
            return self._logProductions(x).unsqueeze(1).repeat(1,self.n_grammars,1) + \
                self._transitionMatrix.unsqueeze(0).repeat(x.size(0),1,1)
        else:
            assert False, "unknown shape for transition matrix input"
        
    def grammarFromVector(self, logProductions):
        return Grammar(logProductions[-1].view(1),
                       [(logProductions[k].view(1), t, program)
                        for k, (_, t, program) in enumerate(self.grammar.productions)],
                       continuationType=self.grammar.continuationType)

    def forward(self, x):
        assert len(x.size()) == 1, "contextual grammar doesn't currently support batching"

        transitionMatrix = self.transitionMatrix(x)
        
        return ContextualGrammar(self.grammarFromVector(transitionMatrix[-1]), self.grammarFromVector(transitionMatrix[-2]),
                {prim: [self.grammarFromVector(transitionMatrix[j]) for j in js]
                 for prim, js in self.library.items()} )
        
    def batchedLogLikelihoods(self, xs, summaries):
        """Takes as input BxinputDimensionality vector & B likelihood summaries;
        returns B-dimensional vector containing log likelihood of each summary"""
        use_cuda = xs.device.type == 'cuda'
        
        B = xs.shape[0]
        G = len(self.grammar) + 1
        assert len(summaries) == B

        # logProductions: Bx n_grammars x G
        logProductions = self.transitionMatrix(xs)
        # uses[b][g][p] is # uses of primitive p by summary b for parent g
        uses = np.zeros((B,self.n_grammars,len(self.grammar)+1))
        for b,summary in enumerate(summaries):
            for e, ss in summary.library.items():
                for g,s in zip(self.library[e], ss):
                    assert g < self.n_grammars - 2
                    for p, production in enumerate(self.grammar.primitives):
                        uses[b,g,p] = s.uses.get(production, 0.)
                    uses[b,g,len(self.grammar)] = s.uses.get(Index(0), 0)
                    
            # noParent: this is the last network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 1, p] = summary.noParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 1, G - 1] = summary.noParent.uses.get(Index(0), 0.)

            # variableParent: this is the penultimate network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 2, p] = summary.variableParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 2, G - 1] = summary.variableParent.uses.get(Index(0), 0.)
            
        numerator = (logProductions*maybe_cuda(torch.tensor(uses).float(),use_cuda)).view(B,-1).sum(1)

        constant = np.zeros(B)
        for b,summary in enumerate(summaries):
            constant[b] += summary.noParent.constant + summary.variableParent.constant
            for ss in summary.library.values():
                for s in ss:
                    constant[b] += s.constant
            
        numerator += maybe_cuda(torch.tensor(constant).float(),use_cuda)
        
        if True:

            # Calculate the god-awful denominator
            alternativeSet = set()
            for summary in summaries:
                for normalizer in summary.noParent.normalizers: alternativeSet.add(normalizer)
                for normalizer in summary.variableParent.normalizers: alternativeSet.add(normalizer)
                for ss in summary.library.values():
                    for s in ss:
                        for normalizer in s.normalizers: alternativeSet.add(normalizer)
            alternativeSet = list(alternativeSet)

            mask = np.zeros((len(alternativeSet), G))
            for tau in range(len(alternativeSet)):
                for p, production in enumerate(self.grammar.primitives):
                    mask[tau,p] = 0. if production in alternativeSet[tau] else NEGATIVEINFINITY
                mask[tau, G - 1] = 0. if Index(0) in alternativeSet[tau] else NEGATIVEINFINITY
            mask = maybe_cuda(torch.tensor(mask).float(), use_cuda)

            z = mask.repeat(self.n_grammars,1,1).repeat(B,1,1,1) + \
                logProductions.repeat(len(alternativeSet),1,1,1).transpose(0,1).transpose(1,2)
            z = torch.logsumexp(z, 3) # pytorch 1.0 dependency

            N = np.zeros((B, self.n_grammars, len(alternativeSet)))
            for b, summary in enumerate(summaries):
                for e, ss in summary.library.items():
                    for g,s in zip(self.library[e], ss):
                        assert g < self.n_grammars - 2
                        for r, alternatives in enumerate(alternativeSet):                
                            N[b,g,r] = s.normalizers.get(alternatives, 0.)
                # noParent: this is the last network output
                for r, alternatives in enumerate(alternativeSet):
                    N[b,self.n_grammars - 1,r] = summary.noParent.normalizers.get(alternatives, 0.)
                # variableParent: this is the penultimate network output
                for r, alternatives in enumerate(alternativeSet):
                    N[b,self.n_grammars - 2,r] = summary.variableParent.normalizers.get(alternatives, 0.)
            N = maybe_cuda(torch.tensor(N).float(), use_cuda)
            denominator = (N*z).sum(1).sum(1)
        else:
            gs = [ self(xs[b]) for b in range(B) ]
            denominator = torch.cat([ summary.denominator(g) for summary,g in zip(summaries, gs) ])
            
            

        
        
        ll = numerator - denominator

        if False: # verifying that batching works correctly
            gs = [ self(xs[b]) for b in range(B) ]
            _l = torch.cat([ summary.logLikelihood(g) for summary,g in zip(summaries, gs) ])
            assert torch.all((ll - _l).abs() < 0.0001)
        return ll
        
                

class ContextualGrammarNetwork(nn.Module):
    """Like GrammarNetwork but ~contextual~"""
    def __init__(self, inputDimensionality, grammar):
        super(ContextualGrammarNetwork, self).__init__()
        
        # library now just contains a list of indicies which go with each primitive
        self.grammar = grammar
        self.library = {}
        self.n_grammars = 0
        for prim in grammar.primitives:
            numberOfArguments = len(prim.infer().functionArguments())
            idx_list = list(range(self.n_grammars, self.n_grammars+numberOfArguments))
            self.library[prim] = idx_list
            self.n_grammars += numberOfArguments
        
        # We had an extra grammar for when there is no parent and for when the parent is a variable
        self.n_grammars += 2
        self.network = nn.Linear(inputDimensionality, (self.n_grammars)*(len(grammar) + 1))


    def grammarFromVector(self, logProductions):
        return Grammar(logProductions[-1].view(1),
                       [(logProductions[k].view(1), t, program)
                        for k, (_, t, program) in enumerate(self.grammar.productions)],
                       continuationType=self.grammar.continuationType)

    def forward(self, x):
        assert len(x.size()) == 1, "contextual grammar doesn't currently support batching"

        allVars = self.network(x).view(self.n_grammars, -1)
        return ContextualGrammar(self.grammarFromVector(allVars[-1]), self.grammarFromVector(allVars[-2]),
                {prim: [self.grammarFromVector(allVars[j]) for j in js]
                 for prim, js in self.library.items()} )

    def batchedLogLikelihoods(self, xs, summaries):
        use_cuda = xs.device.type == 'cuda'
        """Takes as input BxinputDimensionality vector & B likelihood summaries;
        returns B-dimensional vector containing log likelihood of each summary"""

        B = xs.shape[0]
        G = len(self.grammar) + 1
        assert len(summaries) == B

        # logProductions: Bx n_grammars x G
        logProductions = self.network(xs).view(B, self.n_grammars, G)
        # uses[b][g][p] is # uses of primitive p by summary b for parent g
        uses = np.zeros((B,self.n_grammars,len(self.grammar)+1))
        for b,summary in enumerate(summaries):
            for e, ss in summary.library.items():
                for g,s in zip(self.library[e], ss):
                    assert g < self.n_grammars - 2
                    for p, production in enumerate(self.grammar.primitives):
                        uses[b,g,p] = s.uses.get(production, 0.)
                    uses[b,g,len(self.grammar)] = s.uses.get(Index(0), 0)
                    
            # noParent: this is the last network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 1, p] = summary.noParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 1, G - 1] = summary.noParent.uses.get(Index(0), 0.)

            # variableParent: this is the penultimate network output
            for p, production in enumerate(self.grammar.primitives):            
                uses[b, self.n_grammars - 2, p] = summary.variableParent.uses.get(production, 0.)
            uses[b, self.n_grammars - 2, G - 1] = summary.variableParent.uses.get(Index(0), 0.)
            
        numerator = (logProductions*maybe_cuda(torch.tensor(uses).float(),use_cuda)).view(B,-1).sum(1)

        constant = np.zeros(B)
        for b,summary in enumerate(summaries):
            constant[b] += summary.noParent.constant + summary.variableParent.constant
            for ss in summary.library.values():
                for s in ss:
                    constant[b] += s.constant
            
        numerator += maybe_cuda(torch.tensor(constant).float(),use_cuda)

        # Calculate the god-awful denominator
        alternativeSet = set()
        for summary in summaries:
            for normalizer in summary.noParent.normalizers: alternativeSet.add(normalizer)
            for normalizer in summary.variableParent.normalizers: alternativeSet.add(normalizer)
            for ss in summary.library.values():
                for s in ss:
                    for normalizer in s.normalizers: alternativeSet.add(normalizer)
        alternativeSet = list(alternativeSet)

        mask = np.zeros((len(alternativeSet), G))
        for tau in range(len(alternativeSet)):
            for p, production in enumerate(self.grammar.primitives):
                mask[tau,p] = 0. if production in alternativeSet[tau] else NEGATIVEINFINITY
            mask[tau, G - 1] = 0. if Index(0) in alternativeSet[tau] else NEGATIVEINFINITY
        mask = maybe_cuda(torch.tensor(mask).float(), use_cuda)

        z = mask.repeat(self.n_grammars,1,1).repeat(B,1,1,1) + \
            logProductions.repeat(len(alternativeSet),1,1,1).transpose(0,1).transpose(1,2)
        z = torch.logsumexp(z, 3) # pytorch 1.0 dependency

        N = np.zeros((B, self.n_grammars, len(alternativeSet)))
        for b, summary in enumerate(summaries):
            for e, ss in summary.library.items():
                for g,s in zip(self.library[e], ss):
                    assert g < self.n_grammars - 2
                    for r, alternatives in enumerate(alternativeSet):                
                        N[b,g,r] = s.normalizers.get(alternatives, 0.)
            # noParent: this is the last network output
            for r, alternatives in enumerate(alternativeSet):
                N[b,self.n_grammars - 1,r] = summary.noParent.normalizers.get(alternatives, 0.)
            # variableParent: this is the penultimate network output
            for r, alternatives in enumerate(alternativeSet):
                N[b,self.n_grammars - 2,r] = summary.variableParent.normalizers.get(alternatives, 0.)
        N = maybe_cuda(torch.tensor(N).float(), use_cuda)
        

        
        denominator = (N*z).sum(1).sum(1)
        ll = numerator - denominator

        if False: # verifying that batching works correctly
            gs = [ self(xs[b]) for b in range(B) ]
            _l = torch.cat([ summary.logLikelihood(g) for summary,g in zip(summaries, gs) ])
            assert torch.all((ll - _l).abs() < 0.0001)

        return ll
        

class RecognitionModel(nn.Module):
    def __init__(self,featureExtractor,grammar,hidden=[64],activation="tanh",
                 rank=None,contextual=False,mask=False,
                 cuda=False,
                 previousRecognitionModel=None,
                 id=0):
        super(RecognitionModel, self).__init__()
        self.id = id
        self.trained=False
        self.use_cuda = cuda

        self.featureExtractor = featureExtractor
        # Sanity check - make sure that all of the parameters of the
        # feature extractor were added to our parameters as well
        if hasattr(featureExtractor, 'parameters'):
            for parameter in featureExtractor.parameters():
                assert any(myParameter is parameter for myParameter in self.parameters())

        # Build the multilayer perceptron that is sandwiched between the feature extractor and the grammar
        if activation == "sigmoid":
            activation = nn.Sigmoid
        elif activation == "relu":
            activation = nn.ReLU
        elif activation == "tanh":
            activation = nn.Tanh
        else:
            raise Exception('Unknown activation function ' + str(activation))
        self._MLP = nn.Sequential(*[ layer
                                     for j in range(len(hidden))
                                     for layer in [
                                             nn.Linear(([featureExtractor.outputDimensionality] + hidden)[j],
                                                       hidden[j]),
                                             activation()]])

        self.entropy = Entropy()

        if len(hidden) > 0:
            self.outputDimensionality = self._MLP[-2].out_features
            assert self.outputDimensionality == hidden[-1]
        else:
            self.outputDimensionality = self.featureExtractor.outputDimensionality

        self.contextual = contextual
        if self.contextual:
            if mask:
                self.grammarBuilder = ContextualGrammarNetwork_Mask(self.outputDimensionality, grammar)
            else:
                self.grammarBuilder = ContextualGrammarNetwork_LowRank(self.outputDimensionality, grammar, rank)
        else:
            self.grammarBuilder = GrammarNetwork(self.outputDimensionality, grammar)
        
        self.grammar = ContextualGrammar.fromGrammar(grammar) if contextual else grammar
        self.generativeModel = grammar
        
        self._auxiliaryPrediction = nn.Linear(self.featureExtractor.outputDimensionality, 
                                              len(self.grammar.primitives))
        self._auxiliaryLoss = nn.BCEWithLogitsLoss()

        if cuda: self.cuda()

        if previousRecognitionModel:
            self._MLP.load_state_dict(previousRecognitionModel._MLP.state_dict())
            self.featureExtractor.load_state_dict(previousRecognitionModel.featureExtractor.state_dict())
            
    def auxiliaryLoss(self, frontier, features):
        # Compute a vector of uses
        ls = frontier.bestPosterior.program
        def uses(summary):
            if hasattr(summary, 'uses'): 
                return torch.tensor([ float(int(p in summary.uses))
                                      for p in self.generativeModel.primitives ])
            assert hasattr(summary, 'noParent')
            u = uses(summary.noParent) + uses(summary.variableParent)
            for ss in summary.library.values():
                for s in ss:
                    u += uses(s)
            return u
        u = uses(ls)
        u[u > 1.] = 1.
        if self.use_cuda: u = u.cuda()
        al = self._auxiliaryLoss(self._auxiliaryPrediction(features), u)
        return al
            
    def taskEmbeddings(self, tasks):
        return {task: self.featureExtractor.featuresOfTask(task).data.cpu().numpy()
                for task in tasks}

    def forward(self, features):
        """returns either a Grammar or a ContextualGrammar
        Takes as input the output of featureExtractor.featuresOfTask"""
        features = self._MLP(features)
        return self.grammarBuilder(features)

    def auxiliaryPrimitiveEmbeddings(self):
        """Returns the actual outputDimensionality weight vectors for each of the primitives."""
        auxiliaryWeights = self._auxiliaryPrediction.weight.data.cpu().numpy()
        primitivesDict =  {self.grammar.primitives[i] : auxiliaryWeights[i, :] for i in range(len(self.grammar.primitives))}
        return primitivesDict

    def grammarOfTask(self, task):
        features = self.featureExtractor.featuresOfTask(task)
        if features is None: return None
        return self(features)

    def grammarLogProductionsOfTask(self, task):
        """Returns the grammar logits from non-contextual models."""

        features = self.featureExtractor.featuresOfTask(task)
        if features is None: return None

        if hasattr(self, 'hiddenLayers'):
            # Backward compatability with old checkpoints.
            for layer in self.hiddenLayers:
                features = self.activation(layer(features))
            # return features
            return self.noParent[1](features)
        else:
            features = self._MLP(features)

        if self.contextual:
            if hasattr(self.grammarBuilder, 'variableParent'):
                return self.grammarBuilder.variableParent.logProductions(features)
            elif hasattr(self.grammarBuilder, 'network'):
                return self.grammarBuilder.network(features).view(-1)
            elif hasattr(self.grammarBuilder, 'transitionMatrix'):
                return self.grammarBuilder.transitionMatrix(features).view(-1)
            else:
                assert False
        else:
            return self.grammarBuilder.logProductions(features)

    def grammarFeatureLogProductionsOfTask(self, task):
        return torch.tensor(self.grammarOfTask(task).untorch().featureVector())

    def grammarLogProductionDistanceToTask(self, task, tasks):
        """Returns the cosine similarity of all other tasks to a given task."""
        taskLogits = self.grammarLogProductionsOfTask(task).unsqueeze(0) # Change to [1, D]
        assert taskLogits is not None, 'Grammar log productions are not defined for this task.'
        otherTasks = [t for t in tasks if t is not task] # [nTasks -1 , D]

        # Build matrix of all other tasks.
        otherLogits = torch.stack([self.grammarLogProductionsOfTask(t) for t in otherTasks])
        cos = nn.CosineSimilarity(dim=1, eps=1e-6)
        cosMatrix = cos(taskLogits, otherLogits)
        return cosMatrix.data.cpu().numpy()

    def grammarEntropyOfTask(self, task):
        """Returns the entropy of the grammar distribution from non-contextual models for a task."""
        grammarLogProductionsOfTask = self.grammarLogProductionsOfTask(task)

        if grammarLogProductionsOfTask is None: return None

        if hasattr(self, 'entropy'):
            return self.entropy(grammarLogProductionsOfTask)
        else:
            e = Entropy()
            return e(grammarLogProductionsOfTask)

    def taskAuxiliaryLossLayer(self, tasks):
        return {task: self._auxiliaryPrediction(self.featureExtractor.featuresOfTask(task)).view(-1).data.cpu().numpy()
                for task in tasks}
                
    def taskGrammarFeatureLogProductions(self, tasks):
        return {task: self.grammarFeatureLogProductionsOfTask(task).data.cpu().numpy()
                for task in tasks}

    def taskGrammarLogProductions(self, tasks):
        return {task: self.grammarLogProductionsOfTask(task).data.cpu().numpy()
                for task in tasks}

    def taskGrammarStartProductions(self, tasks):
        return {task: np.array([l for l,_1,_2 in g.productions ])
                for task in tasks
                for g in [self.grammarOfTask(task).untorch().noParent] }

    def taskHiddenStates(self, tasks):
        return {task: self._MLP(self.featureExtractor.featuresOfTask(task)).view(-1).data.cpu().numpy()
                for task in tasks}

    def taskGrammarEntropies(self, tasks):
        return {task: self.grammarEntropyOfTask(task).data.cpu().numpy()
                for task in tasks}

    def frontierKL(self, frontier, auxiliary=False, vectorized=True):
        features = self.featureExtractor.featuresOfTask(frontier.task)
        if features is None:
            return None, None
        # Monte Carlo estimate: draw a sample from the frontier
        entry = frontier.sample()

        al = self.auxiliaryLoss(frontier, features if auxiliary else features.detach())

        if not vectorized:
            g = self(features)
            return - entry.program.logLikelihood(g), al
        else:
            features = self._MLP(features).unsqueeze(0)
            
            ll = self.grammarBuilder.batchedLogLikelihoods(features, [entry.program]).view(-1)
            return -ll, al
            

    def frontierBiasOptimal(self, frontier, auxiliary=False, vectorized=True):
        if not vectorized:
            features = self.featureExtractor.featuresOfTask(frontier.task)
            if features is None: return None, None
            al = self.auxiliaryLoss(frontier, features if auxiliary else features.detach())
            g = self(features)
            summaries = [entry.program for entry in frontier]
            likelihoods = torch.cat([entry.program.logLikelihood(g) + entry.logLikelihood
                                     for entry in frontier ])
            best = likelihoods.max()
            return -best, al
            
        batchSize = len(frontier.entries)
        features = self.featureExtractor.featuresOfTask(frontier.task)
        if features is None: return None, None
        al = self.auxiliaryLoss(frontier, features if auxiliary else features.detach())
        features = self._MLP(features)
        features = features.expand(batchSize, features.size(-1))  # TODO
        lls = self.grammarBuilder.batchedLogLikelihoods(features, [entry.program for entry in frontier])
        actual_ll = torch.Tensor([ entry.logLikelihood for entry in frontier])
        lls = lls + (actual_ll.cuda() if self.use_cuda else actual_ll)
        ml = -lls.max() #Beware that inputs to max change output type
        return ml, al

    def replaceProgramsWithLikelihoodSummaries(self, frontier):
        return Frontier(
            [FrontierEntry(
                program=self.grammar.closedLikelihoodSummary(frontier.task.request, e.program),
                logLikelihood=e.logLikelihood,
                logPrior=e.logPrior) for e in frontier],
            task=frontier.task)

    def train(self, frontiers, _=None, steps=None, lr=0.001, topK=5, CPUs=1,
              timeout=None, evaluationTimeout=0.001,
              helmholtzFrontiers=[], helmholtzRatio=0., helmholtzBatch=500,
              biasOptimal=None, defaultRequest=None, auxLoss=False, vectorized=True):
        """
        helmholtzRatio: What fraction of the training data should be forward samples from the generative model?
        helmholtzFrontiers: Frontiers from programs enumerated from generative model (optional)
        If helmholtzFrontiers is not provided then we will sample programs during training
        """
        assert (steps is not None) or (timeout is not None), \
            "Cannot train recognition model without either a bound on the number of gradient steps or bound on the training time"
        if steps is None: steps = 9999999
        if biasOptimal is None: biasOptimal = len(helmholtzFrontiers) > 0
        
        requests = [frontier.task.request for frontier in frontiers]
        if len(requests) == 0 and helmholtzRatio > 0 and len(helmholtzFrontiers) == 0:
            assert defaultRequest is not None, "You are trying to random Helmholtz training, but don't have any frontiers. Therefore we would not know the type of the program to sample. Try specifying defaultRequest=..."
            requests = [defaultRequest]
        frontiers = [frontier.topK(topK).normalize()
                     for frontier in frontiers if not frontier.empty]
        if len(frontiers) == 0:
            eprint("You didn't give me any nonempty replay frontiers to learn from. Going to learn from 100% Helmholtz samples")
            helmholtzRatio = 1.

        # Should we sample programs or use the enumerated programs?
        randomHelmholtz = len(helmholtzFrontiers) == 0
        
        class HelmholtzEntry:
            def __init__(self, frontier, owner):
                self.request = frontier.task.request
                self.task = None
                self.programs = [e.program for e in frontier]
                self.frontier = Thunk(lambda: owner.replaceProgramsWithLikelihoodSummaries(frontier))
                self.owner = owner

            def clear(self): self.task = None

            def calculateTask(self):
                assert self.task is None
                p = random.choice(self.programs)
                return self.owner.featureExtractor.taskOfProgram(p, self.request)

            def makeFrontier(self):
                assert self.task is not None
                f = Frontier(self.frontier.force().entries,
                             task=self.task)
                return f
        
            
            

        # Should we recompute tasks on the fly from Helmholtz?  This
        # should be done if the task is stochastic, or if there are
        # different kinds of inputs on which it could be run. For
        # example, lists and strings need this; towers and graphics do
        # not. There is no harm in recomputed the tasks, it just
        # wastes time.
        if not hasattr(self.featureExtractor, 'recomputeTasks'):
            self.featureExtractor.recomputeTasks = True
        helmholtzFrontiers = [HelmholtzEntry(f, self)
                              for f in helmholtzFrontiers]
        random.shuffle(helmholtzFrontiers)
        
        helmholtzIndex = [0]
        def getHelmholtz():
            if randomHelmholtz:
                if helmholtzIndex[0] >= len(helmholtzFrontiers):
                    updateHelmholtzTasks()
                    helmholtzIndex[0] = 0
                    return getHelmholtz()
                helmholtzIndex[0] += 1
                return helmholtzFrontiers[helmholtzIndex[0] - 1].makeFrontier()

            f = helmholtzFrontiers[helmholtzIndex[0]]
            if f.task is None:
                with timing("Evaluated another batch of Helmholtz tasks"):
                    updateHelmholtzTasks()
                return getHelmholtz()

            helmholtzIndex[0] += 1
            if helmholtzIndex[0] >= len(helmholtzFrontiers):
                helmholtzIndex[0] = 0
                random.shuffle(helmholtzFrontiers)
                if self.featureExtractor.recomputeTasks:
                    for fp in helmholtzFrontiers:
                        fp.clear()
                    return getHelmholtz() # because we just cleared everything
            assert f.task is not None
            return f.makeFrontier()
            
        def updateHelmholtzTasks():
            updateCPUs = CPUs if hasattr(self.featureExtractor, 'parallelTaskOfProgram') and self.featureExtractor.parallelTaskOfProgram else 1
            if updateCPUs > 1: eprint("Updating Helmholtz tasks with",updateCPUs,"CPUs",
                                      "while using",getThisMemoryUsage(),"memory")
            
            if randomHelmholtz:
                newFrontiers = self.sampleManyHelmholtz(requests, helmholtzBatch, CPUs)
                newEntries = []
                for f in newFrontiers:
                    e = HelmholtzEntry(f,self)
                    e.task = f.task
                    newEntries.append(e)
                helmholtzFrontiers.clear()
                helmholtzFrontiers.extend(newEntries)
                return 

            # Save some memory by freeing up the tasks as we go through them
            if self.featureExtractor.recomputeTasks:
                for hi in range(max(0, helmholtzIndex[0] - helmholtzBatch,
                                    min(helmholtzIndex[0], len(helmholtzFrontiers)))):
                    helmholtzFrontiers[hi].clear()

            if hasattr(self.featureExtractor, 'tasksOfPrograms'):
                eprint("batching task calculation")
                newTasks = self.featureExtractor.tasksOfPrograms(
                    [random.choice(hf.programs)
                     for hf in helmholtzFrontiers[helmholtzIndex[0]:helmholtzIndex[0] + helmholtzBatch] ],
                    [hf.request
                     for hf in helmholtzFrontiers[helmholtzIndex[0]:helmholtzIndex[0] + helmholtzBatch] ])
            else:
                newTasks = [hf.calculateTask() 
                            for hf in helmholtzFrontiers[helmholtzIndex[0]:helmholtzIndex[0] + helmholtzBatch]]

                """
                # catwong: Disabled for ensemble training.
                newTasks = \
                           parallelMap(updateCPUs,
                                       lambda f: f.calculateTask(),
                                       helmholtzFrontiers[helmholtzIndex[0]:helmholtzIndex[0] + helmholtzBatch],
                                       seedRandom=True)
                """
            badIndices = []
            endingIndex = min(helmholtzIndex[0] + helmholtzBatch, len(helmholtzFrontiers))
            for i in range(helmholtzIndex[0], endingIndex):
                helmholtzFrontiers[i].task = newTasks[i - helmholtzIndex[0]]
                if helmholtzFrontiers[i].task is None: badIndices.append(i)
            # Permanently kill anything which failed to give a task
            for i in reversed(badIndices):
                assert helmholtzFrontiers[i].task is None
                del helmholtzFrontiers[i]


        # We replace each program in the frontier with its likelihoodSummary
        # This is because calculating likelihood summaries requires juggling types
        # And type stuff is expensive!
        frontiers = [self.replaceProgramsWithLikelihoodSummaries(f).normalize()
                     for f in frontiers]

        eprint("(ID=%d): Training a recognition model from %d frontiers, %d%% Helmholtz, feature extractor %s." % (
            self.id, len(frontiers), int(helmholtzRatio * 100), self.featureExtractor.__class__.__name__))
        eprint("(ID=%d): Got %d Helmholtz frontiers - random Helmholtz training? : %s"%(
            self.id, len(helmholtzFrontiers), len(helmholtzFrontiers) == 0))
        eprint("(ID=%d): Contextual? %s" % (self.id, str(self.contextual)))
        eprint("(ID=%d): Bias optimal? %s" % (self.id, str(biasOptimal)))
        eprint(f"(ID={self.id}): Aux loss? {auxLoss} (n.b. we train a 'auxiliary' classifier anyway - this controls if gradients propagate back to the future extractor)")

        # The number of Helmholtz samples that we generate at once
        # Should only affect performance and shouldn't affect anything else
        helmholtzSamples = []

        optimizer = torch.optim.Adam(self.parameters(), lr=lr, eps=1e-3, amsgrad=True)
        start = time.time()
        losses, descriptionLengths, realLosses, dreamLosses, realMDL, dreamMDL = [], [], [], [], [], []
        classificationLosses = []
        totalGradientSteps = 0
        epochs = 9999999
        for i in range(1, epochs + 1):
            if timeout and time.time() - start > timeout:
                break

            if totalGradientSteps > steps:
                break

            if helmholtzRatio < 1.:
                permutedFrontiers = list(frontiers)
                random.shuffle(permutedFrontiers)
            else:
                permutedFrontiers = [None]

            finishedSteps = False
            for frontier in permutedFrontiers:
                # Randomly decide whether to sample from the generative model
                dreaming = random.random() < helmholtzRatio
                if dreaming: frontier = getHelmholtz()
                self.zero_grad()
                loss, classificationLoss = \
                        self.frontierBiasOptimal(frontier, auxiliary=auxLoss, vectorized=vectorized) if biasOptimal \
                        else self.frontierKL(frontier, auxiliary=auxLoss, vectorized=vectorized)
                if loss is None:
                    if not dreaming:
                        eprint("ERROR: Could not extract features during experience replay.")
                        eprint("Task is:",frontier.task)
                        eprint("Aborting - we need to be able to extract features of every actual task.")
                        assert False
                    else:
                        continue
                if is_torch_invalid(loss):
                    eprint("Invalid real-data loss!")
                else:
                    (loss + classificationLoss).backward()
                    classificationLosses.append(classificationLoss.data.item())
                    optimizer.step()
                    totalGradientSteps += 1
                    losses.append(loss.data.item())
                    descriptionLengths.append(min(-e.logPrior for e in frontier))
                    if dreaming:
                        dreamLosses.append(losses[-1])
                        dreamMDL.append(descriptionLengths[-1])
                    else:
                        realLosses.append(losses[-1])
                        realMDL.append(descriptionLengths[-1])
                    if totalGradientSteps > steps:
                        break # Stop iterating, then print epoch and loss, then break to finish.
                        
            if (i == 1 or i % 10 == 0) and losses:
                eprint("(ID=%d): " % self.id, "Epoch", i, "Loss", mean(losses))
                if realLosses and dreamLosses:
                    eprint("(ID=%d): " % self.id, "\t\t(real loss): ", mean(realLosses), "\t(dream loss):", mean(dreamLosses))
                eprint("(ID=%d): " % self.id, "\tvs MDL (w/o neural net)", mean(descriptionLengths))
                if realMDL and dreamMDL:
                    eprint("\t\t(real MDL): ", mean(realMDL), "\t(dream MDL):", mean(dreamMDL))
                eprint("(ID=%d): " % self.id, "\t%d cumulative gradient steps. %f steps/sec"%(totalGradientSteps,
                                                                       totalGradientSteps/(time.time() - start)))
                eprint("(ID=%d): " % self.id, "\t%d-way auxiliary classification loss"%len(self.grammar.primitives),sum(classificationLosses)/len(classificationLosses))
                losses, descriptionLengths, realLosses, dreamLosses, realMDL, dreamMDL = [], [], [], [], [], []
                classificationLosses = []
                gc.collect()
        
        eprint("(ID=%d): " % self.id, " Trained recognition model in",time.time() - start,"seconds")
        self.trained=True
        return self

    def sampleHelmholtz(self, requests, statusUpdate=None, seed=None):
        if seed is not None:
            random.seed(seed)
        request = random.choice(requests)

        program = self.generativeModel.sample(request, maximumDepth=6, maxAttempts=100)
        if program is None:
            return None
        task = self.featureExtractor.taskOfProgram(program, request)

        if statusUpdate is not None:
            flushEverything()
        if task is None:
            return None

        if hasattr(self.featureExtractor, 'lexicon'):
            if self.featureExtractor.tokenize(task.examples) is None:
                return None
        
        ll = self.generativeModel.logLikelihood(request, program)
        frontier = Frontier([FrontierEntry(program=program,
                                           logLikelihood=0., logPrior=ll)],
                            task=task)
        return frontier

    def sampleManyHelmholtz(self, requests, N, CPUs):
        eprint("Sampling %d programs from the prior on %d CPUs..." % (N, CPUs))
        flushEverything()
        frequency = N / 50
        startingSeed = random.random()

        # Sequentially for ensemble training.
        samples = [self.sampleHelmholtz(requests,
                                           statusUpdate='.' if n % frequency == 0 else None,
                                           seed=startingSeed + n) for n in range(N)]

        # (cathywong) Disabled for ensemble training. 
        # samples = parallelMap(
        #     1,
        #     lambda n: self.sampleHelmholtz(requests,
        #                                    statusUpdate='.' if n % frequency == 0 else None,
        #                                    seed=startingSeed + n),
        #     range(N))
        eprint()
        flushEverything()
        samples = [z for z in samples if z is not None]
        eprint()
        eprint("Got %d/%d valid samples." % (len(samples), N))
        flushEverything()

        return samples

    def enumerateFrontiers(self,
                           tasks,
                           enumerationTimeout=None,
                           testing=False,
                           solver=None,
                           CPUs=1,
                           frontierSize=None,
                           maximumFrontier=None,
                           evaluationTimeout=None):
        with timing("Evaluated recognition model"):
            grammars = {task: self.grammarOfTask(task)
                        for task in tasks}
            #untorch seperately to make sure you filter out None grammars
            grammars = {task: grammar.untorch() for task, grammar in grammars.items() if grammar is not None}

        return multicoreEnumeration(grammars, tasks,
                                    testing=testing,
                                    solver=solver,
                                    enumerationTimeout=enumerationTimeout,
                                    CPUs=CPUs, maximumFrontier=maximumFrontier,
                                    evaluationTimeout=evaluationTimeout)


class RecurrentFeatureExtractor(nn.Module):
    def __init__(self, _=None,
                 tasks=None,
                 cuda=False,
                 # what are the symbols that can occur in the inputs and
                 # outputs
                 lexicon=None,
                 # how many hidden units
                 H=32,
                 # Should the recurrent units be bidirectional?
                 bidirectional=False,
                 # What should be the timeout for trying to construct Helmholtz tasks?
                 helmholtzTimeout=0.25,
                 # What should be the timeout for running a Helmholtz program?
                 helmholtzEvaluationTimeout=0.01):
        super(RecurrentFeatureExtractor, self).__init__()

        assert tasks is not None, "You must provide a list of all of the tasks, both those that have been hit and those that have not been hit. Input examples are sampled from these tasks."

        # maps from a requesting type to all of the inputs that we ever saw with that request
        self.requestToInputs = {
            tp: [list(map(fst, t.examples)) for t in tasks if t.request == tp ]
            for tp in {t.request for t in tasks}
        }

        inputTypes = {t
                      for task in tasks
                      for t in task.request.functionArguments()}
        # maps from a type to all of the inputs that we ever saw having that type
        self.argumentsWithType = {
            tp: [ x
                  for t in tasks
                  for xs,_ in t.examples
                  for tpp, x in zip(t.request.functionArguments(), xs)
                  if tpp == tp]
            for tp in inputTypes
        }
        self.requestToNumberOfExamples = {
            tp: [ len(t.examples)
                  for t in tasks if t.request == tp ]
            for tp in {t.request for t in tasks}
        }
        self.helmholtzTimeout = helmholtzTimeout
        self.helmholtzEvaluationTimeout = helmholtzEvaluationTimeout
        self.parallelTaskOfProgram = True
        
        assert lexicon
        self.specialSymbols = [
            "STARTING",  # start of entire sequence
            "ENDING",  # ending of entire sequence
            "STARTOFOUTPUT",  # begins the start of the output
            "ENDOFINPUT"  # delimits the ending of an input - we might have multiple inputs
        ]
        lexicon += self.specialSymbols
        encoder = nn.Embedding(len(lexicon), H)
        self.encoder = encoder

        self.H = H
        self.bidirectional = bidirectional

        layers = 1

        model = nn.GRU(H, H, layers, bidirectional=bidirectional)
        self.model = model

        self.use_cuda = cuda
        self.lexicon = lexicon
        self.symbolToIndex = {
            symbol: index for index,
            symbol in enumerate(lexicon)}
        self.startingIndex = self.symbolToIndex["STARTING"]
        self.endingIndex = self.symbolToIndex["ENDING"]
        self.startOfOutputIndex = self.symbolToIndex["STARTOFOUTPUT"]
        self.endOfInputIndex = self.symbolToIndex["ENDOFINPUT"]

        # Maximum number of inputs/outputs we will run the recognition
        # model on per task
        # This is an optimization hack
        self.MAXINPUTS = 100

        if cuda: self.cuda()

    @property
    def outputDimensionality(self): return self.H

    # modify examples before forward (to turn them into iterables of lexicon)
    # you should override this if needed
    def tokenize(self, x): return x

    def symbolEmbeddings(self):
        return {s: self.encoder(variable([self.symbolToIndex[s]])).squeeze(
            0).data.cpu().numpy() for s in self.lexicon if not (s in self.specialSymbols)}

    def packExamples(self, examples):
        """IMPORTANT! xs must be sorted in decreasing order of size because pytorch is stupid"""
        es = []
        sizes = []
        for xs, y in examples:
            e = [self.startingIndex]
            for x in xs:
                for s in x:
                    e.append(self.symbolToIndex[s])
                e.append(self.endOfInputIndex)
            e.append(self.startOfOutputIndex)
            for s in y:
                e.append(self.symbolToIndex[s])
            e.append(self.endingIndex)
            if es != []:
                assert len(e) <= len(es[-1]), \
                    "Examples must be sorted in decreasing order of their tokenized size. This should be transparently handled in recognition.py, so if this assertion fails it isn't your fault as a user of EC but instead is a bug inside of EC."
            es.append(e)
            sizes.append(len(e))

        m = max(sizes)
        # padding
        for j, e in enumerate(es):
            es[j] += [self.endingIndex] * (m - len(e))

        x = variable(es, cuda=self.use_cuda)
        x = self.encoder(x)
        # x: (batch size, maximum length, E)
        x = x.permute(1, 0, 2)
        # x: TxBxE
        x = pack_padded_sequence(x, sizes)
        return x, sizes

    def examplesEncoding(self, examples):
        examples = sorted(examples, key=lambda xs_y: sum(
            len(z) + 1 for z in xs_y[0]) + len(xs_y[1]), reverse=True)
        x, sizes = self.packExamples(examples)
        outputs, hidden = self.model(x)
        # outputs, sizes = pad_packed_sequence(outputs)
        # I don't know whether to return the final output or the final hidden
        # activations...
        return hidden[0, :, :] + hidden[1, :, :]

    def forward(self, examples):
        tokenized = self.tokenize(examples)
        if not tokenized:
            return None

        if hasattr(self, 'MAXINPUTS') and len(tokenized) > self.MAXINPUTS:
            tokenized = list(tokenized)
            random.shuffle(tokenized)
            tokenized = tokenized[:self.MAXINPUTS]
        e = self.examplesEncoding(tokenized)
        # max pool
        # e,_ = e.max(dim = 0)

        # take the average activations across all of the examples
        # I think this might be better because we might be testing on data
        # which has far more o far fewer examples then training
        e = e.mean(dim=0)
        return e

    def featuresOfTask(self, t):
        if hasattr(self, 'useFeatures'):
            f = self(t.features)
        else:
            # Featurize the examples directly.
            f = self(t.examples)
        return f

    def taskOfProgram(self, p, tp):
        # half of the time we randomly mix together inputs
        # this gives better generalization on held out tasks
        # the other half of the time we train on sets of inputs in the training data
        # this gives better generalization on unsolved training tasks
        if random.random() < 0.5:
            def randomInput(t): return random.choice(self.argumentsWithType[t])
            # Loop over the inputs in a random order and pick the first ones that
            # doesn't generate an exception

            startTime = time.time()
            examples = []
            while True:
                # TIMEOUT! this must not be a very good program
                if time.time() - startTime > self.helmholtzTimeout: return None

                # Grab some random inputs
                xs = [randomInput(t) for t in tp.functionArguments()]
                try:
                    y = runWithTimeout(lambda: p.runWithArguments(xs), self.helmholtzEvaluationTimeout)
                    examples.append((tuple(xs),y))
                    if len(examples) >= random.choice(self.requestToNumberOfExamples[tp]):
                        return Task("Helmholtz", tp, examples)
                except: continue

        else:
            candidateInputs = list(self.requestToInputs[tp])
            random.shuffle(candidateInputs)
            for xss in candidateInputs:
                ys = []
                for xs in xss:
                    try: y = runWithTimeout(lambda: p.runWithArguments(xs), self.helmholtzEvaluationTimeout)
                    except: break
                    ys.append(y)
                if len(ys) == len(xss):
                    return Task("Helmholtz", tp, list(zip(xss, ys)))
            return None
                
            
    
class LowRank(nn.Module):
    """
    Module that outputs a rank R matrix of size m by n from input of size i.
    """
    def __init__(self, i, m, n, r):
        """
        i: input dimension
        m: output rows
        n: output columns
        r: maximum rank. if this is None then the output will be full-rank
        """
        super(LowRank, self).__init__()

        self.m = m
        self.n = n
        
        maximumPossibleRank = min(m, n)
        if r is None: r = maximumPossibleRank
        
        if r < maximumPossibleRank:
            self.factored = True
            self.A = nn.Linear(i, m*r)
            self.B = nn.Linear(i, n*r)
            self.r = r
        else:
            self.factored = False
            self.M = nn.Linear(i, m*n)

    def forward(self, x):
        sz = x.size()
        if len(sz) == 1:
            B = 1
            x = x.unsqueeze(0)
            needToSqueeze = True
        elif len(sz) == 2:
            B = sz[0]
            needToSqueeze = False
        else:
            assert False, "LowRank expects either a 1-dimensional tensor or a 2-dimensional tensor"

        if self.factored:
            a = self.A(x).view(B, self.m, self.r)
            b = self.B(x).view(B, self.r, self.n)
            y = a @ b
        else:
            y = self.M(x).view(B, self.m, self.n)
        if needToSqueeze:
            y = y.squeeze(0)
        return y
            
            
            

class DummyFeatureExtractor(nn.Module):
    def __init__(self, tasks, testingTasks=[], cuda=False):
        super(DummyFeatureExtractor, self).__init__()
        self.outputDimensionality = 1
        self.recomputeTasks = False
    def featuresOfTask(self, t):
        return variable([0.]).float()
    def featuresOfTasks(self, ts):
        return variable([[0.]]*len(ts)).float()
    def taskOfProgram(self, p, t):
        return Task("dummy task", t, [])

class RandomFeatureExtractor(nn.Module):
    def __init__(self, tasks):
        super(RandomFeatureExtractor, self).__init__()
        self.outputDimensionality = 1
        self.recomputeTasks = False
    def featuresOfTask(self, t):
        return variable([random.random()]).float()
    def featuresOfTasks(self, ts):
        return variable([[random.random()] for _ in range(len(ts)) ]).float()
    def taskOfProgram(self, p, t):
        return Task("dummy task", t, [])

class Flatten(nn.Module):
    def __init__(self):
        super(Flatten, self).__init__()

    def forward(self, x):
        return x.view(x.size(0), -1)

class ImageFeatureExtractor(nn.Module):
    def __init__(self, inputImageDimension, resizedDimension=None,
                 channels=1):
        super(ImageFeatureExtractor, self).__init__()
        
        self.resizedDimension = resizedDimension or inputImageDimension
        self.inputImageDimension = inputImageDimension
        self.channels = channels

        def conv_block(in_channels, out_channels):
            return nn.Sequential(
                nn.Conv2d(in_channels, out_channels, 3, padding=1),
                # nn.BatchNorm2d(out_channels),
                nn.ReLU(),
                nn.MaxPool2d(2)
            )

        # channels for hidden
        hid_dim = 64
        z_dim = 64

        self.encoder = nn.Sequential(
            conv_block(channels, hid_dim),
            conv_block(hid_dim, hid_dim),
            conv_block(hid_dim, hid_dim),
            conv_block(hid_dim, z_dim),
            Flatten()
        )
        
        # Each layer of the encoder halves the dimension, except for the last layer which flattens
        outputImageDimensionality = self.resizedDimension/(2**(len(self.encoder) - 1))
        self.outputDimensionality = int(z_dim*outputImageDimensionality*outputImageDimensionality)

    def forward(self, v):
        """1 channel: v: BxWxW or v:WxW
        > 1 channel: v: BxCxWxW or v:CxWxW"""

        insertBatch = False
        variabled = variable(v).float()
        if self.channels == 1: # insert channel dimension
            if len(variabled.shape) == 3: # batching
                variabled = variabled[:,None,:,:]
            elif len(variabled.shape) == 2: # no batching
                variabled = variabled[None,:,:]
                insertBatch = True
            else: assert False
        else: # expect to have a channel dimension
            if len(variabled.shape) == 4:
                pass
            elif len(variabled.shape) == 3:
                insertBatch = True
            else: assert False                

        if insertBatch: variabled = torch.unsqueeze(variabled, 0)
        
        y = self.encoder(variabled)
        if insertBatch: y = y[0,:]
        return y

class JSONFeatureExtractor(object):
    def __init__(self, tasks, cudaFalse):
        # self.averages, self.deviations = Task.featureMeanAndStandardDeviation(tasks)
        # self.outputDimensionality = len(self.averages)
        self.cuda = cuda
        self.tasks = tasks

    def stringify(self, x):
        # No whitespace #maybe kill the seperators
        return json.dumps(x, separators=(',', ':'))

    def featuresOfTask(self, t):
        # >>> t.request to get the type
        # >>> t.examples to get input/output examples
        # this might actually be okay, because the input should just be nothing
        #return [(self.stringify(inputs), self.stringify(output))
        #        for (inputs, output) in t.examples]
        return [(list(output),) for (inputs, output) in t.examples]