-
Notifications
You must be signed in to change notification settings - Fork 13
/
dreamcoder.py
1694 lines (1558 loc) · 86.7 KB
/
dreamcoder.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 datetime
import dill
import gc
from dreamcoder.compression import induceGrammar
from dreamcoder.recognition import *
from dreamcoder.enumeration import *
from dreamcoder.fragmentGrammar import *
from dreamcoder.taskBatcher import *
from dreamcoder.primitiveGraph import graphPrimitives
from dreamcoder.dreaming import backgroundHelmholtzEnumeration
from dreamcoder.parser import *
from dreamcoder.languageUtilities import *
from dreamcoder.translation import *
class ECResult():
def __init__(self, _=None,
frontiersOverTime=None,
testingSearchTime=None,
learningCurve=None,
grammars=None,
taskSolutions=None,
averageDescriptionLength=None,
parameters=None,
models=None,
recognitionModel=None,
searchTimes=None,
recognitionTaskMetrics=None,
numTestingTasks=None,
sumMaxll=None,
testingSumMaxll=None,
hitsAtEachWake=None,
timesAtEachWake=None,
allFrontiers=None,
taskLanguage=None,
tasksAttempted=None,):
self.frontiersOverTime = {} # Map from task to [frontier at iteration 1, frontier at iteration 2, ...]
self.hitsAtEachWake = hitsAtEachWake or []
self.timesAtEachWake = timesAtEachWake or []
self.testingSearchTime = testingSearchTime or []
self.searchTimes = searchTimes or []
self.trainSearchTime = {} # map from task to search time
self.testSearchTime = {} # map from task to search time
self.recognitionTaskMetrics = recognitionTaskMetrics or {}
self.recognitionModel = recognitionModel
self.averageDescriptionLength = averageDescriptionLength or []
self.parameters = parameters
self.learningCurve = learningCurve or []
self.grammars = grammars or []
self.taskSolutions = taskSolutions or {}
self.numTestingTasks = numTestingTasks
self.sumMaxll = sumMaxll or [] #TODO name change
self.testingSumMaxll = testingSumMaxll or [] #TODO name change
self.allFrontiers = allFrontiers or {}
self.taskLanguage = taskLanguage or {} # Maps from task names to language.
self.models = models or [] # List of recognition models.
self.tasksAttempted = tasksAttempted or set() # Tasks we have attempted so far.
def __repr__(self):
attrs = ["{}={}".format(k, v) for k, v in self.__dict__.items()]
return "ECResult({})".format(", ".join(attrs))
def getTestingTasks(self):
testing = []
training = self.taskSolutions.keys()
for t in self.recognitionTaskMetrics:
if isinstance(t, Task) and t not in training: testing.append(t)
return testing
def recordFrontier(self, frontier):
t = frontier.task
if t not in self.frontiersOverTime: self.frontiersOverTime[t] = []
self.frontiersOverTime[t].append(frontier)
# Linux does not like files that have more than 256 characters
# So when exporting the results we abbreviate the parameters
abbreviations = {"frontierSize": "fs",
"useDSL": "DSL",
"matrixRank": "MR",
"reuseRecognition": "RR",
"ensembleSize": "ES",
"recognitionTimeout": "RT",
"recognitionSteps": "RS",
"recognitionEpochs": "RE",
'useWakeLanguage' : "LANG",
"iterations": "it",
"maximumFrontier": "MF",
"pseudoCounts": "pc",
"auxiliaryLoss": "aux",
"structurePenalty": "L",
"helmholtzRatio": "HR",
"biasOptimal": "BO",
"contextual": "CO",
"topK": "K",
"enumerationTimeout": "ET",
"recognition_0": "rec",
"use_ll_cutoff": "llcut",
"topk_use_only_likelihood": "topLL",
"activation": "act",
"storeTaskMetrics": 'STM',
"topkNotMAP": "tknm",
"rewriteTaskMetrics": "RW",
'taskBatchSize': 'batch',
'language_encoder' : 'lang_ft',
'noConsolidation': 'no_dsl'}
@staticmethod
def abbreviate(parameter): return ECResult.abbreviations.get(parameter, parameter)
@staticmethod
def abbreviate_value(value):
if type(value) == bool:
return str(value)[0]
else:
return value
@staticmethod
def parameterOfAbbreviation(abbreviation):
return ECResult.abbreviationToParameter.get(abbreviation, abbreviation)
@staticmethod
def clearRecognitionModel(path):
SUFFIX = '.pickle'
assert path.endswith(SUFFIX)
with open(path,'rb') as handle:
result = dill.load(handle)
result.models = []
result.recognitionModel = None
result.parser = None
clearedPath = path[:-len(SUFFIX)] + "_graph=True" + SUFFIX
with open(clearedPath,'wb') as handle:
result = dill.dump(result, handle)
eprint(" [+] Cleared recognition models from:")
eprint(" %s"%path)
eprint(" and exported to:")
eprint(" %s"%clearedPath)
eprint(" Use this one for graphing.")
ECResult.abbreviationToParameter = {
v: k for k, v in ECResult.abbreviations.items()}
def explorationCompression(*arguments, **keywords):
for r in ecIterator(*arguments, **keywords):
pass
return r
def ecIterator(grammar, tasks,
_=None,
useDSL=True,
noConsolidation=False,
mask=False,
seed=0,
addFullTaskMetrics=False,
matrixRank=None,
solver='ocaml',
compressor="ocaml",
biasOptimal=True,
contextual=True,
testingTasks=[],
iterations=None,
resume=None,
initialTimeout=None,
initialTimeoutIterations=None,
enumerationTimeout=None,
testingTimeout=None,
testEvery=1,
skip_first_test=False,
test_only_after_recognition=False,
test_dsl_only=False,
reuseRecognition=False,
ensembleSize=1,
# Recognition parameters.
recognition_0=["examples"],
recognition_1=[],
# SMT parameters.
moses_dir=None,
smt_phrase_length=None,
pretrained_word_embeddings=False,
smt_pseudoalignments=0,
finetune_1=False,
helmholtz_nearest_language=0,
language_encoder=None,
featureExtractor=None,
languageDataset=None,
condition_independently_on_language_descriptions=False,
recognitionEpochs=None,
recognitionTimeout=None,
recognitionSteps=None,
helmholtzRatio=0.,
activation='relu',
topK=1,
topk_use_only_likelihood=False,
use_map_search_times=True,
maximumFrontier=None,
pseudoCounts=1.0, aic=1.0,
structurePenalty=0.001, arity=0,
evaluationTimeout=1.0, # seconds
taskBatchSize=None,
taskReranker='default',
CPUs=1,
cuda=False,
message="",
outputPrefix=None,
storeTaskMetrics=False,
rewriteTaskMetrics=True,
auxiliaryLoss=False,
custom_wake_generative=None,
interactive=False,
parser=None,
interactiveTasks=None,
taskDataset=None,
languageDatasetDir=None,
useWakeLanguage=False,
debug=False,
synchronous_grammar=False,
language_compression=False,
lc_score=False,
max_compression=0,
max_mem_per_enumeration_thread=1000000,
# Entrypoint flags for integration tests. If these are set, we return early at semantic breakpoints in the iteration.
test_task_language=False, # Integration test on the language we add to tasks.
test_background_helmholtz=False, # Integration test for enumerating Helmholtz frontiers in the background.
test_wake_generative_enumeration=False, # Integration test for enumeration.
test_sleep_recognition_0=False, # Integration test for the examples-only recognizer.
test_sleep_recognition_1=False, # Integration test for the language-based recognizer.
test_next_iteration_settings=False, # Integration test for the second iteration.
):
if enumerationTimeout is None:
eprint(
"Please specify an enumeration timeout:",
"explorationCompression(..., enumerationTimeout = ..., ...)")
assert False
if iterations is None:
eprint(
"Please specify a iteration count: explorationCompression(..., iterations = ...)")
assert False
if (("examples" in recognition_0) or ("examples" in recognition_1)) and featureExtractor is None:
eprint("Warning: Recognition models need examples feature extractor, but none found")
assert False
if (("language" in recognition_0) or ("language" in recognition_1)) and language_encoder is None:
eprint("Warning: Recognition models need language encoder, but none found")
assert False
if matrixRank is not None and not contextual:
eprint("Matrix rank only applies to contextual recognition models, aborting")
assert False
if testingTimeout > 0 and len(testingTasks) == 0:
eprint("You specified a testingTimeout, but did not provide any held out testing tasks, aborting.")
assert False
model_inputs = [recognition_0, recognition_1]
n_models = len([m for m in model_inputs if len(m) > 0])
if len(recognitionEpochs) == 1 and len(recognitionEpochs) < len(model_inputs):
recognitionEpochs = recognitionEpochs * len(model_inputs)
def print_recognition_model_summary():
eprint("-------------------Recognition Model Summary-------------------")
eprint(f"Found n=[{n_models}] recognition models.")
for i, model in enumerate(model_inputs):
if len(model) < 1: continue
eprint(f"Model {i}: {model}")
if "examples" in model:
eprint(f"Examples encoder: {str(featureExtractor.__name__)}")
if "language" in model:
eprint(f"Language encoder: {language_encoder}")
eprint(f"Language dataset or datasets: {languageDataset}")
if recognitionEpochs is not None:
eprint(f"Epochs: [{recognitionEpochs[i]}]; contextual: {contextual}")
elif recognitionSteps is not None:
eprint(f"Steps: [{recognitionSteps}]; contextual: {contextual}")
elif recognitionTimeout is not None:
eprint(f"Timeout: [{recognitionTimeout}]; contextual: {contextual}")
if synchronous_grammar:
eprint(f"Incuding synchronous grammar to train recognition model with language.")
if language_compression:
eprint(f"Using a synchronous grammar during compression.")
if i > 0:
eprint(f"Use n={helmholtz_nearest_language} nearest language examples for Helmholtz")
eprint(f"Finetune from examples: {finetune_1}")
print("\n")
eprint("--------------------------------------")
print_recognition_model_summary()
# TODO: figure out how to save the parameters without removing them here.
# We save the parameters that were passed into EC
# This is for the purpose of exporting the results of the experiment
parameters = {
k: v for k,
v in locals().items() if k not in {
"taskReranker",
"languageDatasetDir",
"tasks",
"use_map_search_times",
"seed",
"activation",
"grammar",
"cuda",
"_",
"testingTimeout",
"testEvery",
"message",
"CPUs",
"outputPrefix",
"resume",
"resumeFrontierSize",
"addFullTaskMetrics",
"featureExtractor",
"evaluationTimeout",
"testingTasks",
"compressor",
"custom_wake_generative",
"interactive",
"interactiveTasks",
"parser",
"print_recognition_model_summary",
"condition_independently_on_language_descriptions",
"solver"} and v is not None}
if not recognition_0:
for k in {"helmholtzRatio", "recognitionTimeout", "biasOptimal", "mask",
"contextual", "matrixRank", "reuseRecognition", "auxiliaryLoss", "ensembleSize"}:
if k in parameters: del parameters[k]
else: del parameters["recognition_0"];
if recognition_0 and not contextual:
if "matrixRank" in parameters:
del parameters["matrixRank"]
if "mask" in parameters:
del parameters["mask"]
if not mask and 'mask' in parameters: del parameters["mask"]
if not auxiliaryLoss and 'auxiliaryLoss' in parameters: del parameters['auxiliaryLoss']
if not useDSL:
for k in {"structurePenalty", "pseudoCounts", "aic"}:
del parameters[k]
else: del parameters["useDSL"]
if languageDataset:
parameters["languageDataset"] = ",".join([os.path.basename(d).split(".")[0] for d in languageDataset])
# Uses `parameters` to construct the checkpoint path
def checkpointPath(iteration, extra=""):
# Exclude from path, but not from saving in parameters.
exclude_from_path = [
"model_inputs",
"language_encoder",
"recognition_0",
"recognition_1",
"helmholtz_nearest_language",
"taskDataset",
"finetune_1",
"recognitionEpochs",
"languageDataset",
"moses_dir",
"debug",
"smt_phrase_length",
"pretrained_word_embeddings",
"smt_pseudoalignments",
"synchronous_grammar",
"language_compression",
"lc_score",
"max_compression",
"skip_first_test",
"test_only_after_recognition",
"n_models",
"test_dsl_only",
"initialTimeout",
"initialTimeoutIterations"
]
parameters["iterations"] = iteration
checkpoint_params = [k for k in sorted(parameters.keys()) if k not in exclude_from_path and not k.startswith('test_')]
kvs = [
"{}={}".format(
ECResult.abbreviate(k),
ECResult.abbreviate_value(parameters[k])) for k in checkpoint_params]
return "{}_{}{}.pickle".format(outputPrefix, "_".join(kvs), extra)
print(f"Checkpoints will be written to [{checkpointPath('iter')}]")
print(f"Checkpoint path len = [{len(checkpointPath('iter'))}]")
assert(len(checkpointPath('iter')) < 256)
if message:
message = " (" + message + ")"
eprint("Running EC%s on %s @ %s with %d CPUs and parameters:" %
(message, os.uname()[1], datetime.datetime.now(), CPUs))
for k, v in parameters.items():
eprint("\t", k, " = ", v)
eprint("\t", "evaluationTimeout", " = ", evaluationTimeout)
eprint("\t", "cuda", " = ", cuda)
eprint()
if addFullTaskMetrics:
assert resume is not None, "--addFullTaskMetrics requires --resume"
def reportMemory():
eprint(f"Currently using this much memory: {getThisMemoryUsage()}")
# Restore checkpoint
if resume is not None:
try:
resume = int(resume)
path = checkpointPath(resume)
except ValueError:
path = resume
with open(path, "rb") as handle:
result = dill.load(handle)
resume = len(result.grammars) - 1
eprint("Loaded checkpoint from", path)
grammar = result.grammars[-1] if result.grammars else grammar
# Backward compatability if we weren't tracking attempted tasks.
if not hasattr(result, 'tasksAttempted'): result.tasksAttempted = set()
# Use any new tasks.
numTestingTasks = len(testingTasks) if len(testingTasks) != 0 else None
result.numTestingTasks = numTestingTasks
new_tasks = [t for t in tasks if t not in result.allFrontiers]
new_testing = [t for t in testingTasks if t.name not in result.taskLanguage]
print(f"Found {len(new_tasks)} new tasks and {len(new_testing)} new testing tasks")
for t in tasks:
if t not in result.taskSolutions:
result.taskSolutions[t] = Frontier([],
task=t)
if t not in result.allFrontiers:
result.allFrontiers[t] = Frontier([],task=t)
for t in tasks + testingTasks:
if t.name not in result.taskLanguage:
result.taskLanguage[t.name] = []
else: # Start from scratch
#for graphing of testing tasks
numTestingTasks = len(testingTasks) if len(testingTasks) != 0 else None
result = ECResult(parameters=parameters,
grammars=[grammar],
taskSolutions={
t: Frontier([],
task=t) for t in tasks},
models=[],
recognitionModel=None, # Backwards compatability
numTestingTasks=numTestingTasks,
allFrontiers={
t: Frontier([],
task=t) for t in tasks},
taskLanguage={
t.name: [] for t in tasks + testingTasks},
tasksAttempted=set())
# Preload language dataset if avaiable.
if languageDataset is not None:
result.languageDatasetPath = languageDatasetDir
# TODO: figure out how to specify which tasks to load for.
# May need to separately specify train and test.
result.taskLanguage, result.vocabularies = languageForTasks(languageDataset, languageDatasetDir, result.taskLanguage)
if condition_independently_on_language_descriptions:
tasks, testingTasks = generate_independent_tasks_for_language_descriptions(result, tasks, testingTasks)
eprint("Loaded language dataset from ", languageDataset)
if test_task_language:
yield result # Integration test outpoint.
if parser == 'loglinear':
parserModel = LogLinearBigramTransitionParser
else:
eprint("Invalid parser: " + parser + ", aborting.")
assert False
if language_encoder is not None:
if language_encoder == 'ngram':
language_encoder = NgramFeaturizer
elif language_encoder == 'recurrent':
language_encoder = TokenRecurrentFeatureExtractor
else:
eprint("Invalid language encoder: " + language_encoder + ", aborting.")
assert False
# Check if we are just updating the full task metrics
# TODO: this no longer applies (Cathy Wong)
if addFullTaskMetrics:
if testingTimeout is not None and testingTimeout > enumerationTimeout:
enumerationTimeout = testingTimeout
if result.recognitionModel is not None:
_enumerator = lambda *args, **kw: result.recognitionModel.enumerateFrontiers(*args, **kw)
else: _enumerator = lambda *args, **kw: multicoreEnumeration(result.grammars[-1], *args, **kw)
enumerator = lambda *args, **kw: _enumerator(*args,
maximumFrontier=maximumFrontier,
CPUs=CPUs, evaluationTimeout=evaluationTimeout,
solver=solver,
**kw)
trainFrontiers, _, trainingTimes = enumerator(tasks, enumerationTimeout=enumerationTimeout)
testFrontiers, _, testingTimes = enumerator(testingTasks, enumerationTimeout=testingTimeout, testing=True)
recognizer = result.recognitionModel
updateTaskSummaryMetrics(result.recognitionTaskMetrics, trainingTimes, 'recognitionBestTimes')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarLogProductions(tasks), 'taskLogProductions')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarEntropies(tasks), 'taskGrammarEntropies')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, result.recognitionModel.taskAuxiliaryLossLayer(tasks), 'taskAuxiliaryLossLayer')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, testingTimes, 'heldoutTestingTimes')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarLogProductions(testingTasks), 'heldoutTaskLogProductions')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarEntropies(testingTasks), 'heldoutTaskGrammarEntropies')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, result.recognitionModel.taskAuxiliaryLossLayer(testingTasks), 'heldoutAuxiliaryLossLayer')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, {f.task: f
for f in trainFrontiers + testFrontiers
if len(f) > 0},
'frontier')
SUFFIX = ".pickle"
assert path.endswith(SUFFIX)
path = path[:-len(SUFFIX)] + "_FTM=True" + SUFFIX
with open(path, "wb") as handle: dill.dump(result, handle)
if recognition_0: ECResult.clearRecognitionModel(path)
sys.exit(0)
# Preload any supervision if available into the all frontiers.
print(f"Found n={len([t for t in tasks if t.add_as_supervised])} supervised tasks; initializing frontiers.")
for t in tasks:
if t.add_as_supervised:
result.allFrontiers[t] = result.allFrontiers[t].combine(Frontier.makeFrontierFromSupervised(t)).topK(maximumFrontier)
# Set up the task batcher.
if taskReranker == 'default':
taskBatcher = DefaultTaskBatcher()
elif taskReranker == 'random':
taskBatcher = RandomTaskBatcher()
elif taskReranker == 'randomShuffle':
taskBatcher = RandomShuffleTaskBatcher(seed)
elif taskReranker == 'unsolved':
taskBatcher = UnsolvedTaskBatcher()
elif taskReranker == 'unsolvedEntropy':
taskBatcher = UnsolvedEntropyTaskBatcher()
elif taskReranker == 'unsolvedRandomEntropy':
taskBatcher = UnsolvedRandomEntropyTaskBatcher()
elif taskReranker == 'randomkNN':
taskBatcher = RandomkNNTaskBatcher()
elif taskReranker == 'randomLowEntropykNN':
taskBatcher = RandomLowEntropykNNTaskBatcher()
elif taskReranker == 'curriculum':
taskBatcher = CurriculumTaskBatcher()
elif taskReranker == 'sentence_length':
taskBatcher = SentenceLengthTaskBatcher(tasks, result.taskLanguage)
else:
eprint("Invalid task reranker: " + taskReranker + ", aborting.")
assert False
######## Test Evaluation and background Helmholtz enumeration.
for j in range(resume or 0, iterations):
# Clean up -- at each iteration, remove Helmholtz from the task language dictionary.
for key_name in list(result.taskLanguage.keys()):
if "Helmholtz" in key_name:
result.taskLanguage.pop(key_name)
print(f"After removing Helmholtz frontiers, task language length is back to {len(result.taskLanguage)} tasks.")
if storeTaskMetrics and rewriteTaskMetrics:
eprint("Resetting task metrics for next iteration.")
result.recognitionTaskMetrics = {}
reportMemory()
# Evaluate on held out tasks if we have them
should_skip_test = False
if testingTimeout > 0 and j == 0 and skip_first_test:
eprint("SKIPPING FIRST TESTING FOR NOW")
should_skip_test = True
elif j == resume and skip_first_test:
eprint("SKIPPING FIRST TESTING FOR NOW")
should_skip_test = True
if (not should_skip_test) and testingTimeout > 0 and ((j % testEvery == 0) or (j == iterations - 1)):
eprint("Evaluating on held out testing tasks for iteration: %d" % (j))
evaluateOnTestingTasks(result, testingTasks, grammar,
CPUs=CPUs, maximumFrontier=maximumFrontier,
solver=solver,
enumerationTimeout=testingTimeout, evaluationTimeout=evaluationTimeout,
test_dsl_only=test_dsl_only,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
# If we have to also enumerate Helmholtz frontiers,
# do this extra sneaky in the background
if n_models > 0 and biasOptimal and helmholtzRatio > 0 and \
all( str(p) != "REAL" for p in grammar.primitives ): # real numbers don't support this
# the DSL is fixed, so the dreams are also fixed. don't recompute them.
if useDSL or 'helmholtzFrontiers' not in locals():
serialize_special = featureExtractor.serialize_special if hasattr(featureExtractor, 'serialize_special') else None
maximum_helmholtz = featureExtractor.maximum_helmholtz if hasattr(featureExtractor, 'maximum_helmholtz') else None
helmholtzFrontiers = backgroundHelmholtzEnumeration(tasks, grammar, enumerationTimeout,
evaluationTimeout=evaluationTimeout,
special=featureExtractor.special,
executable='helmholtz',
serialize_special=serialize_special,
maximum_size=maximum_helmholtz)
if test_background_helmholtz: # Integration test exitpoint for testing frontiers.
yield helmholtzFrontiers
else:
print("Reusing dreams from previous iteration.")
else:
helmholtzFrontiers = lambda: []
reportMemory()
wakingTaskBatch = taskBatcher.getTaskBatch(result, tasks, taskBatchSize, j)
eprint("Using a waking task batch of size: " + str(len(wakingTaskBatch)))
# WAKING UP
if useDSL:
enumeration_time = enumerationTimeout
if initialTimeout is not None and initialTimeoutIterations is not None:
if j < initialTimeoutIterations:
eprint(f"Found an annealing schedule; using {initialTimeout}s enumeration.")
enumeration_time = initialTimeout
result.tasksAttempted.update(wakingTaskBatch)
wake_generative = custom_wake_generative if custom_wake_generative is not None else default_wake_generative
topDownFrontiers, times = wake_generative(grammar, wakingTaskBatch,
solver=solver,
maximumFrontier=maximumFrontier,
enumerationTimeout=enumeration_time,
CPUs=CPUs,
evaluationTimeout=evaluationTimeout,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
result.trainSearchTime = {t: tm for t, tm in times.items() if tm is not None}
else:
eprint("Skipping top-down enumeration because we are not using the generative model")
topDownFrontiers, times = [], {t: None for t in wakingTaskBatch }
tasksHitTopDown = {f.task for f in topDownFrontiers if not f.empty}
result.hitsAtEachWake.append(len(tasksHitTopDown))
reportMemory()
# Combine topDownFrontiers from this task batch with all frontiers.
for f in topDownFrontiers:
if f.task not in result.allFrontiers: continue # backward compatibility with old checkpoints
result.allFrontiers[f.task] = result.allFrontiers[f.task].combine(f).topK(maximumFrontier)
eprint("Frontiers discovered top down: " + str(len(tasksHitTopDown)))
eprint("Total frontiers: " + str(len([f for f in result.allFrontiers.values() if not f.empty])))
if test_wake_generative_enumeration: yield result
#### Recognition model round 0. No language.
result.models = [] # Reset the list of models at each iteration.
if len(recognition_0) > 0:
result.tasksAttempted.update(wakingTaskBatch)
recognition_iteration = 0
# Should we initialize the weights to be what they were before?
previousRecognitionModel = None
if reuseRecognition and result.recognitionModel is not None:
previousRecognitionModel = result.recognitionModel
thisRatio = helmholtzRatio
if j == 0 and not biasOptimal: thisRatio = 0
if all( f.empty for f in result.allFrontiers.values() ): thisRatio = 1.
enumeration_time = enumerationTimeout
if initialTimeout is not None and initialTimeoutIterations is not None:
if j < initialTimeoutIterations:
eprint(f"Found an annealing schedule; using {initialTimeout}s enumeration.")
enumeration_time = initialTimeout
tasks_hit_recognition_0 = \
sleep_recognition(result, grammar, wakingTaskBatch, tasks, testingTasks, result.allFrontiers.values(),
ensembleSize=ensembleSize,
mask=mask,
activation=activation, contextual=contextual, biasOptimal=biasOptimal,
previousRecognitionModel=previousRecognitionModel, matrixRank=matrixRank,
timeout=recognitionTimeout, evaluationTimeout=evaluationTimeout,
enumerationTimeout=enumeration_time,
helmholtzRatio=thisRatio, helmholtzFrontiers=helmholtzFrontiers(),
auxiliaryLoss=auxiliaryLoss, cuda=cuda, CPUs=CPUs, solver=solver,
recognitionSteps=recognitionSteps, maximumFrontier=maximumFrontier,
featureExtractor=featureExtractor,
language_encoder=language_encoder,
recognitionEpochs=recognitionEpochs[recognition_iteration],
recognition_iteration=recognition_iteration,
recognition_inputs=model_inputs[recognition_iteration],
finetune_from_example_encoder=finetune_1,
language_data=None,
language_lexicon=None,
test_only_after_recognition=test_only_after_recognition,
pretrained_word_embeddings=pretrained_word_embeddings,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
showHitMatrix(tasksHitTopDown, tasks_hit_recognition_0, wakingTaskBatch)
# Record the new topK solutions
result.taskSolutions = {f.task: f.topK(topK)
for f in result.allFrontiers.values()}
for f in result.allFrontiers.values(): result.recordFrontier(f)
result.learningCurve += [
sum(f is not None and not f.empty for f in result.taskSolutions.values())]
updateTaskSummaryMetrics(result.recognitionTaskMetrics, {f.task: f
for f in result.allFrontiers.values()
if len(f) > 0},
'frontier')
if test_sleep_recognition_0: yield result
### Induce synchronous grammar for generative model with language.
# We use this to pre-generate information that can be used to label the Helmholtz samples.
translation_info = None
if "language" in recognition_1 and synchronous_grammar:
if all( f.empty for f in result.allFrontiers.values() ):
eprint("No non-empty frontiers to train a translation model, skipping.")
else:
translation_info = induce_synchronous_grammar(frontiers=result.allFrontiers.values(),
tasks=tasks, testingTasks=testingTasks, tasksAttempted=result.tasksAttempted,
grammar=grammar,
language_encoder=language_encoder,
language_data=result.taskLanguage,
language_lexicon=result.vocabularies["train"],
output_prefix=outputPrefix,
moses_dir=moses_dir,
max_phrase_length=smt_phrase_length,
pseudoalignments=smt_pseudoalignments,
debug=debug,
iteration=j)
#### Recognition model round 1. With language, using the joint generative model to label the Helmholtz samples.
if len(recognition_1) > 0:
result.tasksAttempted.update(wakingTaskBatch)
recognition_iteration = 1
thisRatio = helmholtzRatio
if j == 0 and not biasOptimal: thisRatio = 0
if all( f.empty for f in result.allFrontiers.values() ): thisRatio = 1.
enumeration_time = enumerationTimeout
if initialTimeout is not None and initialTimeoutIterations is not None:
if j < initialTimeoutIterations:
eprint(f"Found an annealing schedule; using {initialTimeout}s enumeration.")
enumeration_time = initialTimeout
tasks_hit_recognition_1 = \
sleep_recognition(result, grammar, wakingTaskBatch, tasks, testingTasks, result.allFrontiers.values(),
ensembleSize=ensembleSize,
mask=mask,
activation=activation, contextual=contextual, biasOptimal=biasOptimal,
previousRecognitionModel=None, matrixRank=matrixRank,
timeout=recognitionTimeout, evaluationTimeout=evaluationTimeout,
enumerationTimeout=enumeration_time,
helmholtzRatio=thisRatio, helmholtzFrontiers=helmholtzFrontiers(),
auxiliaryLoss=auxiliaryLoss, cuda=cuda, CPUs=CPUs, solver=solver,
recognitionSteps=recognitionSteps, maximumFrontier=maximumFrontier,
featureExtractor=featureExtractor,
language_encoder=language_encoder,
recognitionEpochs=recognitionEpochs[recognition_iteration],
recognition_iteration=recognition_iteration,
recognition_inputs=model_inputs[recognition_iteration],
finetune_from_example_encoder=finetune_1,
language_data=result.taskLanguage,
language_lexicon=result.vocabularies["train"],
helmholtz_nearest_language=helmholtz_nearest_language,
helmholtz_translation_info=translation_info,
test_only_after_recognition=test_only_after_recognition,
pretrained_word_embeddings=pretrained_word_embeddings,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
showHitMatrix(tasksHitTopDown, tasks_hit_recognition_1, wakingTaskBatch)
# Record the new topK solutions
result.taskSolutions = {f.task: f.topK(topK)
for f in result.allFrontiers.values()}
for f in result.allFrontiers.values(): result.recordFrontier(f)
result.learningCurve += [
sum(f is not None and not f.empty for f in result.taskSolutions.values())]
updateTaskSummaryMetrics(result.recognitionTaskMetrics, {f.task: f
for f in result.allFrontiers.values()
if len(f) > 0},
'frontier')
if test_sleep_recognition_1: yield result
# Interactive mode.
if interactive or useWakeLanguage:
tasks_hit_parser = default_wake_language(grammar, wakingTaskBatch,
testingTasks=testingTasks,
maximumFrontier=maximumFrontier,
enumerationTimeout=enumerationTimeout,
CPUs=CPUs,
solver=solver,
parser=parserModel,
interactiveTasks=interactiveTasks,
evaluationTimeout=evaluationTimeout,
currentResult=result,
interactive=interactive,
language_encoder=language_encoder,
cuda=cuda,
epochs=recognitionEpochs)
for task in tasks_hit_parser:
if task not in result.allFrontiers: continue
result.allFrontiers[task] = result.allFrontiers[task].\
combine(grammar.rescoreFrontier(tasks_hit_parser[task])).\
topK(maximumFrontier)
eprint("Frontiers discovered with parser: " + str(len(tasks_hit_parser)))
eprint("Total frontiers: " + str(len([f for f in result.allFrontiers.values() if not f.empty])))
eprint(Frontier.describe([f for f in tasks_hit_parser.values() if not f.empty]))
showHitMatrix(tasksHitTopDown, set(tasks_hit_parser.keys()), wakingTaskBatch)
# Sleep-G
if useDSL and not(noConsolidation) or debug:
eprint(f"Currently using this much memory: {getThisMemoryUsage()}")
## Language for compression
language_alignments = []
if language_compression:
eprint(f"Using language alignments for compression.")
if debug:
eprint(f"Running in debug -- using an old checkpoint for alignments.")
output_dir = "experimentOutputs/clevr/2020-05-21T17-56-08-470454/moses_corpus_1"
else:
eprint(f"Reading alignments from the Moses dir.")
if translation_info is None:
eprint(f"No translation info found; setting output dir to None.")
output_dir = None
else:
output_dir = translation_info["output_dir"]
language_alignments = get_alignments(grammar=grammar, output_dir=output_dir)
grammar = consolidate(result, grammar, topK=topK, pseudoCounts=pseudoCounts, arity=arity, aic=aic,
structurePenalty=structurePenalty, compressor=compressor, CPUs=CPUs,
iteration=j, language_alignments=language_alignments,
lc_score=lc_score,
max_compression=max_compression)
eprint(f"Currently using this much memory: {getThisMemoryUsage()}")
else:
eprint("Skipping consolidation.")
result.grammars.append(grammar)
if outputPrefix is not None:
path = checkpointPath(j + 1)
with open(path, "wb") as handle:
try:
dill.dump(result, handle)
except TypeError as e:
eprint(result)
assert(False)
eprint("Exported checkpoint to", path)
if recognition_0:
ECResult.clearRecognitionModel(path)
graphPrimitives(result, "%s_primitives_%d_"%(outputPrefix,j))
yield result
def showHitMatrix(top, bottom, tasks):
tasks = set(tasks)
total = bottom | top
eprint(len(total), "/", len(tasks), "total hit tasks")
bottomMiss = tasks - bottom
topMiss = tasks - top
eprint("{: <13s}{: ^13s}{: ^13s}".format("", "bottom miss", "bottom hit"))
eprint("{: <13s}{: ^13d}{: ^13d}".format("top miss",
len(bottomMiss & topMiss),
len(bottom & topMiss)))
eprint("{: <13s}{: ^13d}{: ^13d}".format("top hit",
len(top & bottomMiss),
len(top & bottom)))
def evaluateOnTestingTasks(result, testingTasks, grammar, _=None,
CPUs=None, solver=None, maximumFrontier=None, enumerationTimeout=None, evaluationTimeout=None,
test_dsl_only= False,max_mem_per_enumeration_thread=1000000):
if len(result.models) > 0 and not test_dsl_only:
eprint("Evaluating on testing tasks using the recognizer.")
recognizer = result.models[-1]
testingFrontiers, times = \
recognizer.enumerateFrontiers(testingTasks,
CPUs=CPUs,
solver=solver,
maximumFrontier=maximumFrontier,
enumerationTimeout=enumerationTimeout,
evaluationTimeout=evaluationTimeout,
testing=True,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarLogProductions(testingTasks), 'heldoutTaskLogProductions')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarEntropies(testingTasks), 'heldoutTaskGrammarEntropies')
updateTaskSummaryMetrics(result.recognitionTaskMetrics, recognizer.taskGrammarEntropies(testingTasks), 'heldoutTaskGrammarEntropies')
else:
if test_dsl_only:
eprint("Evaluating on testing tasks using the following DSL:")
testingFrontiers, times = multicoreEnumeration(grammar, testingTasks,
solver=solver,
maximumFrontier=maximumFrontier,
enumerationTimeout=enumerationTimeout,
CPUs=CPUs,
evaluationTimeout=evaluationTimeout,
testing=True,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
updateTaskSummaryMetrics(result.recognitionTaskMetrics, times, 'heldoutTestingTimes')
updateTaskSummaryMetrics(result.recognitionTaskMetrics,
{f.task: f for f in testingFrontiers if len(f) > 0 },
'frontier')
for f in testingFrontiers: result.recordFrontier(f)
result.testSearchTime = {t: tm for t, tm in times.items() if tm is not None}
times = [t for t in times.values() if t is not None ]
eprint("\n".join(f.summarize() for f in testingFrontiers))
summaryStatistics("Testing tasks", times)
eprint("Hits %d/%d testing tasks" % (len(times), len(testingTasks)))
result.testingSearchTime.append(times)
def default_wake_language(grammar, tasks,
testingTasks,
maximumFrontier=None,
enumerationTimeout=None,
CPUs=None,
solver=None,
parser=None,
interactiveTasks=None,
evaluationTimeout=None,
currentResult=None,
get_language_fn=None,
interactive=None,
language_encoder=None,
program_featurizer=None,
epochs=None,
cuda=False,
max_mem_per_enumeration_thread=1000000):
# Get interactive descriptions for all solutions.
if get_language_fn is not None:
solutions = [f for f in currentResult.allFrontiers.values() if not f.empty]
solutions_language = get_language_fn(solutions)
for t in solutions_language:
currentResult.taskLanguage[t].append(solutions_language[t])
# Retrain the parser.
parser_model = parser(grammar,
language_data=currentResult.taskLanguage,
frontiers=currentResult.allFrontiers,
tasks=tasks,
testingTasks=testingTasks,
cuda=cuda,
language_feature_extractor=language_encoder)
parser_model.train(epochs=epochs)
if interactive:
eprint("Not yet implemented: interactive mode.")
assert False
else:
# Enumerative search using the retrained parser.
eprint("Enumerating from the trained parser.")
enumerated_frontiers, recognition_times = parser_model.enumerateFrontiers(tasks=tasks,
enumerationTimeout=enumerationTimeout,
solver=solver,
CPUs=CPUs,
maximumFrontier=maximumFrontier,
evaluationTimeout=evaluationTimeout)
tasks_hit = {f.task : f for f in enumerated_frontiers if not f.empty}
currentResult.parser = parser_model
return tasks_hit
def default_wake_generative(grammar, tasks,
maximumFrontier=None,
enumerationTimeout=None,
CPUs=None,
solver=None,
evaluationTimeout=None,
max_mem_per_enumeration_thread=1000000):
topDownFrontiers, times = multicoreEnumeration(grammar, tasks,
maximumFrontier=maximumFrontier,
enumerationTimeout=enumerationTimeout,
CPUs=CPUs,
solver=solver,
evaluationTimeout=evaluationTimeout,
max_mem_per_enumeration_thread=max_mem_per_enumeration_thread)
eprint("Generative model enumeration results:")
eprint(Frontier.describe(topDownFrontiers))
summaryStatistics("Generative model", [t for t in times.values() if t is not None])
return topDownFrontiers, times
def induce_synchronous_grammar(frontiers, tasks, testingTasks, tasksAttempted, grammar,
language_encoder=None, language_data=None, language_lexicon=None,
output_prefix=None,
moses_dir=None,
max_phrase_length=None,
pseudoalignments=None,
debug=None,
iteration=None):
encoder = language_encoder(tasks, testingTasks=testingTasks, cuda=False, language_data=language_data, lexicon=language_lexicon)
n_frontiers = len([f for f in frontiers if not f.empty])
eprint(f"Inducing synchronous grammar. Using n=[{n_frontiers} frontiers],")
if n_frontiers == 0:
return None
if debug:
# Use the previous iteration so that we can peek into it
debug_iteration = iteration - 1
corpus_dir = os.path.join(os.path.dirname(output_prefix), f'moses_corpus_{debug_iteration}')
# eprint(f"Running in non-debug mode, writing corpus files to {corpus_dir}.")
# eprint("Running in debug mode, writing corpus files to tmp.")
# corpus_dir = os.path.split(os.path.dirname(output_prefix))[0] # Remove timestamp and type prefix on checkpoint
# corpus_dir = os.path.join(corpus_dir, 'corpus_tmp')
else:
corpus_dir = os.path.join(os.path.dirname(output_prefix), f'moses_corpus_{iteration}')
eprint(f"Running in non-debug mode, writing corpus files to {corpus_dir}.")
alignment_outputs = smt_alignment(tasks, tasksAttempted, frontiers, grammar, encoder, corpus_dir, moses_dir, phrase_length=max_phrase_length, n_pseudo=pseudoalignments)
return alignment_outputs