-
Notifications
You must be signed in to change notification settings - Fork 5
/
concept_energy.py
7254 lines (6499 loc) · 323 KB
/
concept_energy.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
# coding: utf-8
# In[ ]:
"""
Script for training EBMs for discovering concepts, relations and operators.
"""
import argparse
from collections import OrderedDict, Iterable
from copy import deepcopy
from datetime import datetime
import itertools
import logging
logging.getLogger('matplotlib.font_manager').disabled = True
from numbers import Number
import os
import pdb
import ipdb
import pickle
import pprint as pp
import random
from typing import Union
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from torch.distributions.normal import Normal
from torch.distributions.one_hot_categorical import OneHotCategorical as cat
from torchvision import datasets, transforms, utils
from torchvision.transforms import functional as F_tr
from torchvision.transforms.functional import InterpolationMode
from einops import rearrange, repeat
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
import sys, os
# sys.path.append(os.path.join(os.path.dirname("__file__"), '..'))
# sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
# from reasoning.concept_env.arc_image import ARCDataset
# from reasoning.slot_attention.models import ClevrImagePreprocessor
# from reasoning.clevr_dataset_gen.dataset import ClevrRelationDataset, create_easy_dataset
# from reasoning.clevr_dataset_gen.generate_concept_dataset import get_clevr_concept_data
# from reasoning.experiments.arguments_EBM import get_args_EBM
# from reasoning.slot_attention.clevr import CLEVR
# from reasoning.slot_attention.multi_dsprites import MultiDsprites
# from reasoning.slot_attention.tetrominoes import Tetrominoes
# from reasoning.experiments.models import get_model_energy, load_model_energy, neg_mask_sgd, neg_mask_sgd_with_kl, id_to_tensor, requires_grad
# from reasoning.experiments.concept_transfer import COLOR_DICT as color_dict_3d
# from reasoning.settings.global_param import REPR_DIM, DEFAULT_OBJ_TYPE
# from reasoning.settings.filepath import REA_PATH, REA_PATH_LOCAL
# from reasoning.experiments.concept_transfer import convert_babyarc
from BabyARC.code.dataset.dataset import *
from reasoning_util import model_parallel, color_dict, clip_grad, identity_fun, seperate_concept, to_one_hot, onehot_to_RGB, get_root_dir, get_module_parameters, assign_embedding_value, get_hashing, to_device_recur, visualize_matrices, repeat_n, mask_iou_score, shrink, get_obj_from_mask
from pytorch_net.util import to_cpu_recur, try_call, Printer, transform_dict, MineDataset, is_diagnose, reduce_tensor, get_hashing, pdump, pload, remove_elements, loss_op_core, filter_kwargs, to_Variable, gather_broadcast, get_pdict, COLOR_LIST, set_seed, Zip, Early_Stopping, init_args, make_dir, str2bool, get_filename_short, get_machine_name, get_device, record_data, plot_matrices, filter_filename, get_next_available_key, to_np_array, to_Variable, get_filename_short, write_to_config, Dictionary, Batch, to_cpu
p = Printer()
REA_PATH = "/dfs/user/tailin/.results"
# ## 1. Dataset:
# ### 1.1 ConceptDataset:
# In[ ]:
class ConceptDataset(Dataset):
"""Concept Dataset for learning basic concepts for ARC.
mode:
Concepts: E(x; a; c)
"Pixel": one or many pixels
"Line": one or many lines
"Rect": hollow rectangles
"{}+{}+...": each "{}" can be a concept.
Symmetries: E(x; a; c)
"hFlip", "vFlip": one image where some object has property of symmetry w.r.t. hflip
"Rotate": one image where some object has property of symmetry w.r.t. rotation.
Relations: E(x; a1, a2; c)
"Vertical": lines where some of them are vertical
"Parallel": lines where some of them are parallel
"Vertical+Parallel": lines where some of them are vertical or parallel
"IsInside": obj_1 is inside obj_2
"SameRow": obj_1 and obj_2 are at the same row
"SameCol": obj_1 and obj_2 are at the same column
Operations: E(x1,x2; a1,a2; c1,c2)
"RotateA+vFlip(Line+Rect)": two images where some object1 in image1 is rotated or vertically-flipped w.r.t. some object2 in image2, and the objects are chosen from Line or Rect.
"hFlip(Lshape)", "vFlip(Lshape+Line)": two images where some object1 in image1 is flipped w.r.t. some object2 in image2.
ARC+:
"arc^{}": ARC images with property "{}" masked as above.
""
"""
def __init__(
self,
mode,
canvas_size=8,
n_examples=10000,
rainbow_prob=0.,
data=None,
idx_list=None,
concept_collection=None,
allowed_shape_concept=None,
w_type="image+mask",
color_avail="-1",
min_n_distractors=0,
max_n_distractors=-1,
n_operators=1,
allow_connect=True,
parsing_check=False,
focus_type=None,
transform=None,
save_interval=-1,
save_filename=None,
):
if allowed_shape_concept is None:
allowed_shape_concept=[
"Line", "Rect", "RectSolid", "Lshape", "Randshape", "ARCshape",
"Tshape", "Eshape",
"Hshape", "Cshape", "Ashape", "Fshape",
"RectE1a", "RectE1b", "RectE1c",
"RectE2a", "RectE2b", "RectE2c",
"RectE3a", "RectE3b", "RectE3c",
"RectF1a", "RectF1b", "RectF1c",
"RectF2a", "RectF2b", "RectF2c",
"RectF3a", "RectF3b", "RectF3c",
]
self.mode = mode
self.canvas_size = canvas_size
self.rainbow_prob = rainbow_prob
self.n_examples = n_examples
self.allowed_shape_concept = allowed_shape_concept
self.min_n_distractors = min_n_distractors
self.max_n_distractors = max_n_distractors
self.n_operators = n_operators
self.w_type = w_type
self.allow_connect = allow_connect
self.parsing_check = parsing_check
self.focus_type = focus_type
if isinstance(color_avail, str):
if color_avail == "-1":
self.color_avail = None
else:
self.color_avail = [int(c) for c in color_avail.split(",")]
for c in self.color_avail:
assert c >= 1 and c <= 9
else:
self.color_avail = color_avail
if idx_list is None:
assert data is None
if mode.startswith("arc^"):
if "(" in mode:
self.data = []
# Operator:
concept_raw = mode.split("(")[0].split("+")
concept_collection = []
for c in concept_raw:
if "^" in c:
concept_collection.append(c.split("^")[1])
else:
concept_collection.append(c)
self.concept_collection = concept_collection
arcDataset = ARCDataset(
n_examples=n_examples*2,
canvas_size=canvas_size,
)
babyArcDataset = BabyARCDataset(
pretrained_obj_cache=os.path.join(get_root_dir(), 'concept_env/datasets/arc_objs.pt'),
save_directory=get_root_dir() + "/concept_env/BabyARCDataset/",
object_limit=None,
noise_level=0,
canvas_size=canvas_size,
)
if set(self.concept_collection).issubset({"RotateA", "RotateB", "RotateC",
"hFlip", "vFlip", "DiagFlipA", "DiagFlipB",
"Identity",
"Move"}):
for arc_example_one_hot in arcDataset:
arc_image = torch.zeros_like(arc_example_one_hot[0])
for i in range(0, 10):
arc_image += arc_example_one_hot[i]*i
arc_image = arc_image.type(torch.int32)
repre_dict = babyArcDataset.sample_task_canvas_from_arc(
arc_image,
color=np.random.choice([True, False], p=[0.6, 0.4]),
is_plot=False,
)
if repre_dict == -1:
continue
in_canvas = Canvas(repre_dict=repre_dict)
# Operate on the input:
if len(list(repre_dict["node_id_map"].keys())) == 0:
continue # empty arc canvas
chosen_obj_key = np.random.choice(list(repre_dict["node_id_map"].keys()))
chosen_obj_id = repre_dict["node_id_map"][chosen_obj_key]
chosen_op = np.random.choice(self.concept_collection)
if chosen_op in ["Identity"]:
inplace = True if random.random() < 0.5 else False
out_canvas_list, concept = OperatorEngine().operator_identity(
[in_canvas],
[[chosen_obj_key]],
inplace=inplace,
)
if out_canvas_list == -1:
continue
elif chosen_op in ["Move"]:
# create operator spec as move is a complex operator
move_spec = OperatorMoveSpec(
autonomous=False,
direction=random.randint(0,3),
distance=-1,
hit_type=None, # either wall, agent or None
linkage_move=False,
linkage_move_distance_ratio=None,
)
out_canvas_list, concept = OperatorEngine().operator_move(
[in_canvas],
[[chosen_obj_key]],
[[move_spec]],
allow_overlap=False,
allow_shape_break=False,
allow_connect=self.allow_connect,
allow_stay=False,
)
if out_canvas_list == -1:
continue
elif chosen_op in ["RotateA", "RotateB", "RotateC", "hFlip", "vFlip", "DiagFlipA", "DiagFlipB"]:
out_canvas_list, concept = OperatorEngine().operate_rotate(
[in_canvas],
[[chosen_obj_key]],
operator_tag=f"#{chosen_op}",
allow_connect=self.allow_connect,
allow_shape_break=False,
)
if out_canvas_list == -1:
continue
else:
raise Exception(f"operator={chosen_op} is not supported!")
# Add to self.data:
in_canvas_dict = in_canvas.repr_as_dict()
out_canvas_dict = out_canvas_list[0].repr_as_dict()
in_mask = in_canvas_dict["id_object_mask"][chosen_obj_id][None]
out_mask = out_canvas_dict["id_object_mask"][chosen_obj_id][None]
self.data.append(
((to_one_hot(in_canvas_dict["image_t"]), to_one_hot(out_canvas_dict["image_t"])),
(in_mask, out_mask),
chosen_op,
Dictionary({}),
)
)
if len(self.data) >= n_examples:
break
if i > n_examples * 2 and len(self.data) < n_examples * 0.05:
raise Exception("Sampled {} times and only {} of them satisfies the specified condition. Try relaxing the condition!".format(i, len(self.data)))
else:
mode_core = mode.split("^")[1]
self.concept_collection = mode_core.split("+")
dataset = ARCDataset(
n_examples=n_examples,
canvas_size=canvas_size,
)
examples_all = []
masks_all = []
concepts_all = []
examples = dataset.data
examples_argmax = examples.argmax(1)
self.data = []
for i in range(len(examples)):
concept_dict = seperate_concept(examples_argmax[i])
masks, concepts = get_masks(concept_dict, allowed_concepts=self.concept_collection, canvas_size=canvas_size)
if masks is not None:
for mask, concept in zip(masks, concepts):
self.data.append((
examples[i],
(mask,),
concept,
Dictionary({}),
)
)
else:
if "(" in mode:
# Operator:
self.concept_collection = mode.split("(")[0].split("+")
input_concepts = mode.split("(")[1][:-1].split("+")
else:
self.concept_collection = mode.split("-")[-1].split("+")
input_concepts = [""]
dataset = BabyARCDataset(
pretrained_obj_cache=os.path.join(get_root_dir(), 'concept_env/datasets/arc_objs.pt'),
save_directory=get_root_dir() + "/concept_env/BabyARCDataset/",
object_limit=None,
noise_level=0,
canvas_size=canvas_size,
)
concept_str_mapping = {
"line": "Line",
"rectangle": "Rect",
"rectangleSolid": "RectSolid",
"Lshape": "Lshape",
"Tshape": "Tshape",
"Eshape": "Eshape",
"Hshape": "Hshape",
"Cshape": "Cshape",
"Ashape": "Ashape",
"Fshape": "Fshape",
"randomShape": "Randshape",
"arcShape": "ARCshape"} # Mapping between two conventions
concept_str_reverse_mapping = {
"Line": "line",
"Rect": "rectangle",
"RectSolid": "rectangleSolid",
"Lshape": "Lshape",
"Tshape": "Tshape",
"Eshape": "Eshape",
"Hshape": "Hshape",
"Cshape": "Cshape",
"Ashape": "Ashape",
"Fshape": "Fshape",
"Randshape": "randomShape",
"ARCshape": "arcShape"} # Mapping between two conventions
composite_concepts = [
"RectE1a", "RectE1b", "RectE1c",
"RectE2a", "RectE2b", "RectE2c",
"RectE3a", "RectE3b", "RectE3c",
"RectF1a", "RectF1b", "RectF1c",
"RectF2a", "RectF2b", "RectF2c",
"RectF3a", "RectF3b", "RectF3c",
]
for c in composite_concepts:
concept_str_mapping[c] = c
concept_str_reverse_mapping[c] = c
if set(get_c_core(self.concept_collection)).issubset({
"Image"
}):
# Image is a collection of all shapes.
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 1 + max_n_distractors # 1 is for the core concept itself.
self.data = generate_samples(
dataset=dataset,
obj_spec_fun=obj_spec_fun,
n_examples=n_examples,
mode="concept-image",
concept_collection=["Line", "Rect", "Lshape",
"RectSolid", "Randshape", "ARCshape",
"Tshape", "Eshape",
"Hshape", "Cshape", "Ashape", "Fshape"],
min_n_objs=1+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
rainbow_prob=rainbow_prob,
concept_str_mapping=concept_str_mapping,
concept_str_reverse_mapping=concept_str_reverse_mapping,
allowed_shape_concept=["Line", "Rect", "Lshape",
"RectSolid", "Randshape", "ARCshape",
"Tshape", "Eshape",
"Hshape", "Cshape", "Ashape", "Fshape"],
color_avail=self.color_avail,
allow_connect=self.allow_connect,
parsing_check=self.parsing_check,
save_interval=10,
save_filename=save_filename,
)
elif set(get_c_core(self.concept_collection)).issubset({
"Line", "Rect", "Lshape",
"RectSolid", "Randshape", "ARCshape",
"Tshape", "Eshape",
"Hshape", "Cshape", "Ashape", "Fshape",
"RectE1a", "RectE1b", "RectE1c",
"RectE2a", "RectE2b", "RectE2c",
"RectE3a", "RectE3b", "RectE3c",
"RectF1a", "RectF1b", "RectF1c",
"RectF2a", "RectF2b", "RectF2c",
"RectF3a", "RectF3b", "RectF3c",
}):
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 1 + max_n_distractors # 1 is for the core concept itself.
self.data = generate_samples(
dataset=dataset,
obj_spec_fun=obj_spec_fun,
n_examples=n_examples,
mode="concept",
concept_collection=self.concept_collection,
min_n_objs=1+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
rainbow_prob=rainbow_prob,
concept_str_mapping=concept_str_mapping,
concept_str_reverse_mapping=concept_str_reverse_mapping,
allowed_shape_concept=self.allowed_shape_concept,
color_avail=self.color_avail,
allow_connect=self.allow_connect,
parsing_check=self.parsing_check,
focus_type=self.focus_type,
save_interval=10,
save_filename=save_filename,
)
elif set(self.concept_collection).issubset({
"RectE1a", "RectE1b", "RectE1c",
"RectE2a", "RectE2b", "RectE2c",
"RectE3a", "RectE3b", "RectE3c",
"RectF1a", "RectF1b", "RectF1c",
"RectF2a", "RectF2b", "RectF2c",
"RectF3a", "RectF3b", "RectF3c",
}):
max_n_objs = 1 # we currently don't allow distractors to be sampled.
self.data = generate_samples(
dataset=dataset,
obj_spec_fun=obj_spec_fun,
n_examples=n_examples,
mode="compositional-concept",
concept_collection=self.concept_collection,
min_n_objs=1+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
rainbow_prob=rainbow_prob,
concept_str_mapping=concept_str_mapping,
concept_str_reverse_mapping=concept_str_reverse_mapping,
allowed_shape_concept=self.allowed_shape_concept,
color_avail=self.color_avail,
allow_connect=self.allow_connect,
parsing_check=self.parsing_check,
focus_type=self.focus_type,
save_interval=10,
save_filename=save_filename,
)
elif set(self.concept_collection).issubset({"Vertical", "Parallel"}):
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 2 + max_n_distractors # 2 is for the core concept itself.
def obj_spec_fun_re(concept_collection, min_n_objs, max_n_objs, canvas_size, allowed_shape_concept=None, color_avail=None, focus_type=None):
n_objs = np.random.randint(min_n_objs, max_n_objs+1)
obj_spec = [(('obj_{}'.format(k), 'line_[-1,1,-1]'), 'Attr') for k in range(n_objs)]
return obj_spec
self.data = generate_samples(
dataset=dataset,
obj_spec_fun=obj_spec_fun_re,
n_examples=n_examples,
mode="relation",
concept_collection=self.concept_collection,
min_n_objs=2+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
rainbow_prob=rainbow_prob,
concept_str_mapping=concept_str_mapping,
concept_str_reverse_mapping=concept_str_reverse_mapping,
allowed_shape_concept=self.allowed_shape_concept,
color_avail=self.color_avail,
allow_connect=self.allow_connect,
parsing_check=self.parsing_check,
save_interval=10,
save_filename=save_filename,
)
elif set(self.concept_collection).issubset({"VerticalMid", "VerticalEdge", "VerticalSepa", "Parallel"}):
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 2 + max_n_distractors # 2 is for the core concept itself.
self.data = generate_lines_full_vertical_parallel(
n_examples=n_examples,
concept_collection=self.concept_collection,
min_n_objs=2+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
min_size=3,
max_size=canvas_size-2,
color_avail=self.color_avail,
isplot=False,
)
elif set(self.concept_collection).issubset({
"SameAll", "SameShape", "SameColor",
"SameRow", "SameCol", "IsInside",
"IsTouch", "IsNonOverlapXY",
"IsEnclosed",
}):
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 2 + max_n_distractors # 2 is for the core relation itself.
def obj_spec_fun_re(
concept_collection, min_n_objs, max_n_objs,
canvas_size, allowed_shape_concept=None,
color_avail=None,
focus_type=None,
):
assert allowed_shape_concept != None
n_objs = np.random.randint(min_n_objs, max_n_objs+1)
# two slots are for the relation
sampled_relation = np.random.choice(concept_collection)
obj_spec = [(('obj_0', 'obj_1'), sampled_relation)]
max_rect_size = canvas_size//2
# choose distractors
for k in range(2, n_objs):
# choose a distractor shape
distractor_shape = np.random.choice(allowed_shape_concept)
if distractor_shape == "Line":
obj_spec += [(('obj_{}'.format(k), 'line_[-1,-1,-1]'), 'Attr')]
elif distractor_shape == "Rect":
obj_spec += [(('obj_{}'.format(k), 'rectangle_[-1,-1]'), 'Attr')]
elif distractor_shape == "RectSolid":
obj_spec += [(('obj_{}'.format(k), 'rectangleSolid_[-1,-1]'), 'Attr')]
elif distractor_shape == "Lshape":
obj_spec += [(('obj_{}'.format(k), 'Lshape_[-1,-1,-1]'), 'Attr')]
elif distractor_shape == "Tshape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Tshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Eshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(5, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Eshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Hshape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Hshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Cshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Cshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Ashape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(4, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Ashape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Fshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(4, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Fshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Randshape":
max_rect_size = canvas_size // 2
w, h = np.random.randint(2, max_rect_size+1, size=2) # hard-code for the size
obj_spec += [(('obj_{}'.format(k), f'randomShape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "ARCshape":
max_rect_size = canvas_size // 2
w, h = np.random.randint(2, max_rect_size+1, size=2) # hard-code for the size
obj_spec += [(('obj_{}'.format(k), f'arcShape_[{w},{h}]'), 'Attr')]
return obj_spec
if len(input_concepts) == 1 and input_concepts[0] == "":
_shape_concept=[c for c in self.allowed_shape_concept]
else:
_shape_concept=[c for c in input_concepts]
self.data = generate_samples(
dataset=dataset,
obj_spec_fun=obj_spec_fun_re,
n_examples=n_examples,
mode="relation",
concept_collection=self.concept_collection,
min_n_objs=2+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
rainbow_prob=rainbow_prob,
concept_str_mapping=concept_str_mapping,
concept_str_reverse_mapping=concept_str_reverse_mapping,
allowed_shape_concept=_shape_concept,
color_avail=self.color_avail,
allow_connect=self.allow_connect,
parsing_check=self.parsing_check,
)
elif set(self.concept_collection).issubset({
"RotateA", "RotateB", "RotateC",
"hFlip", "vFlip", "DiagFlipA",
"DiagFlipB", "Identity", "Move"
}):
if max_n_distractors == -1:
max_n_objs = 3
else:
max_n_objs = 1 + max_n_distractors # 1 is for the core operator itself.
self.data = []
for i in range(self.n_examples * 5):
# Initialize input concept instance:
obj_spec = obj_spec_fun(
concept_collection=input_concepts,
min_n_objs=1+self.min_n_distractors,
max_n_objs=max_n_objs,
canvas_size=canvas_size,
)
# get the number of the objects
operatable_obj_set = set([])
for spec in obj_spec:
if spec[1] == "Attr":
operatable_obj_set.add(spec[0][0])
else:
operatable_obj_set.add(spec[0][0])
operatable_obj_set.add(spec[0][1])
operatable_obj_set = list(operatable_obj_set)
# let us enable distractors
if set(input_concepts).issubset({"SameColor", "IsTouch"}):
n_distractors = np.random.randint(0, max_n_distractors+1)
max_rect_size = canvas_size//2
for i in range(n_distractors):
k = i+len(operatable_obj_set)
distractor_shape = np.random.choice(self.allowed_shape_concept)
if distractor_shape == "Line":
obj_spec += [(('obj_{}'.format(k), 'line_[-1,-1,-1]'), 'Attr')]
elif distractor_shape == "Rect":
obj_spec += [(('obj_{}'.format(k), 'rectangle_[-1,-1]'), 'Attr')]
elif distractor_shape == "RectSolid":
obj_spec += [(('obj_{}'.format(k), 'rectangleSolid_[-1,-1]'), 'Attr')]
elif distractor_shape == "Lshape":
obj_spec += [(('obj_{}'.format(k), 'Lshape_[-1,-1,-1]'), 'Attr')]
elif distractor_shape == "Tshape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Tshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Eshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(5, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Eshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Hshape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Hshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Cshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(3, max_rect_size+2)
obj_spec += [(('obj_{}'.format(k), f'Cshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Ashape":
w = np.random.randint(3, max_rect_size+2)
h = np.random.randint(4, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Ashape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Fshape":
w = np.random.randint(3, max_rect_size+1)
h = np.random.randint(4, max_rect_size+3)
obj_spec += [(('obj_{}'.format(k), f'Fshape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "Randshape":
max_rect_size = canvas_size // 2
w, h = np.random.randint(2, max_rect_size+1, size=2) # hard-code for the size
obj_spec += [(('obj_{}'.format(k), f'randomShape_[{w},{h}]'), 'Attr')]
elif distractor_shape == "ARCshape":
max_rect_size = canvas_size // 2
w, h = np.random.randint(2, max_rect_size+1, size=2) # hard-code for the size
obj_spec += [(('obj_{}'.format(k), f'arcShape_[{w},{h}]'), 'Attr')]
# get all objects include distractors
all_obj_set = set([])
for spec in obj_spec:
if spec[1] == "Attr":
all_obj_set.add(spec[0][0])
else:
all_obj_set.add(spec[0][0])
all_obj_set.add(spec[0][1])
repre_dict = dataset.sample_single_canvas_by_core_edges(
OrderedDict(obj_spec),
allow_connect=self.allow_connect,
rainbow_prob=rainbow_prob,
is_plot=False,
color_avail=self.color_avail,
)
if repre_dict == -1:
continue
in_canvas = Canvas(repre_dict=repre_dict)
# Operate on the input:
chosen_obj_id = np.random.choice(len(operatable_obj_set))
chosen_obj_name = operatable_obj_set[chosen_obj_id]
chosen_op = np.random.choice(self.concept_collection)
if chosen_op in ["Identity"]:
inplace = True if random.random() < 0.5 else False
out_canvas_list, concept = OperatorEngine().operator_identity(
[in_canvas],
[[chosen_obj_name]],
inplace=inplace,
)
if out_canvas_list == -1:
continue
elif chosen_op in [
"RotateA", "RotateB", "RotateC",
"hFlip", "vFlip", "DiagFlipA", "DiagFlipB"
]:
out_canvas_list, concept = OperatorEngine().operate_rotate(
[in_canvas],
[[chosen_obj_name]],
operator_tag=f"#{chosen_op}",
allow_connect=self.allow_connect,
allow_shape_break=False,
)
if out_canvas_list == -1:
continue
elif chosen_op in ["Move"]:
# create operator spec as move is a complex operator
move_spec = OperatorMoveSpec(
autonomous=False,
direction=random.randint(0,3),
distance=-1,
hit_type=None, # either wall, agent or None
linkage_move=False,
linkage_move_distance_ratio=None,
)
out_canvas_list, concept = OperatorEngine().operator_move(
[in_canvas],
[[chosen_obj_name]],
[[move_spec]],
allow_overlap=False,
allow_shape_break=False,
allow_connect=self.allow_connect,
allow_stay=False,
)
if out_canvas_list == -1:
continue
else:
raise Exception(f"operator={chosen_op} is not supported!")
if n_operators > 1:
# operator distractor can act on all objects
addition_operators = min(len(all_obj_set)-1,n_operators-1) # we need to have minimum number of objs
operated_obj_name = set([])
operated_obj_name.add(chosen_obj_name)
exclude_ops = set([chosen_op])
# we need to operate on other objects.
for _ in range(n_operators-1):
addition_obj_set = set(all_obj_set) - operated_obj_name
addition_obj_name = np.random.choice(list(addition_obj_set))
addition_ops = set(self.concept_collection) - exclude_ops
addition_op = np.random.choice(list(addition_ops))
exclude_ops.add(addition_op)
# operate the the previous ouput canvas
if addition_op in ["Identity"]:
inplace = True if random.random() < 0.5 else False
out_canvas_list, concept = OperatorEngine().operator_identity(
[out_canvas_list[0]],
[[addition_obj_name]],
inplace=inplace,
)
if out_canvas_list == -1:
break
elif addition_op in ["RotateA", "RotateB", "RotateC", "hFlip", "vFlip", "DiagFlipA", "DiagFlipB"]:
out_canvas_list, concept = OperatorEngine().operate_rotate(
[out_canvas_list[0]],
[[addition_obj_name]],
operator_tag=f"#{addition_op}",
allow_connect=self.allow_connect,
allow_shape_break=False,
)
if out_canvas_list == -1:
break
elif addition_op in ["Move"]:
# create operator spec as move is a complex operator
move_spec = OperatorMoveSpec(
autonomous=False,
direction=random.randint(0,3),
distance=-1,
hit_type=None, # either wall, agent or None
linkage_move=False,
linkage_move_distance_ratio=None,
)
out_canvas_list, concept = OperatorEngine().operator_move(
[out_canvas_list[0]],
[[addition_obj_name]],
[[move_spec]],
allow_overlap=False,
allow_shape_break=False,
allow_connect=self.allow_connect,
allow_stay=False,
)
if out_canvas_list == -1:
break
else:
raise Exception(f"operator={addition_op} is not supported!")
operated_obj_name.add(addition_obj_name)
if out_canvas_list == -1:
continue
# Add to self.data:
in_canvas_dict = in_canvas.repr_as_dict()
out_canvas_dict = out_canvas_list[0].repr_as_dict()
in_mask = in_canvas_dict["id_object_mask"][in_canvas_dict["node_id_map"][chosen_obj_name]][None]
out_mask = out_canvas_dict["id_object_mask"][in_canvas_dict["node_id_map"][chosen_obj_name]][None]
# TODO: remove deprecated codes.
# in_mask = in_canvas_dict["id_object_mask"][chosen_obj_id][None]
# out_mask = out_canvas_dict["id_object_mask"][chosen_obj_id][None]
info = {"obj_spec": obj_spec}
self.data.append(
((to_one_hot(in_canvas_dict["image_t"]), to_one_hot(out_canvas_dict["image_t"])),
(in_mask, out_mask),
chosen_op,
Dictionary(info),
)
)
if len(self.data) >= n_examples:
break
if i > n_examples * 2 and len(self.data) < n_examples * 0.05:
raise Exception("Sampled {} times and only {} of them satisfies the specified condition. Try relaxing the condition!".format(i, len(self.data)))
else:
raise Exception("concept_collection {} is out of scope!".format(self.concept_collection))
if "obj" in self.w_type and "mask" not in self.w_type:
self.data = mask_to_obj(self.data)
self.idx_list = list(range(len(self.data)))
if len(self.idx_list) < n_examples:
p.print("Dataset created with {} examples, less than {} specified.".format(len(self.idx_list), n_examples))
else:
p.print("Dataset for {} created.".format(mode))
else:
self.data = data
self.idx_list = idx_list
self.concept_collection = concept_collection
self.transform = transform
def __len__(self):
return len(self.idx_list)
def __repr__(self):
return "ConceptDataset({})".format(len(self))
def __getitem__(self, idx):
"""Get data instance, where idx can be a number or a slice."""
if torch.is_tensor(idx):
idx = idx.tolist()
elif isinstance(idx, slice):
return self.__class__(
mode=self.mode,
canvas_size=self.canvas_size,
n_examples=self.n_examples,
rainbow_prob=self.rainbow_prob,
data=self.data,
idx_list=self.idx_list[idx],
concept_collection=self.concept_collection,
w_type=self.w_type,
color_avail=self.color_avail,
max_n_distractors=self.max_n_distractors,
n_operators=self.n_operators,
transform=self.transform,
)
sample = self.data[self.idx_list[idx]]
if self.transform:
sample = self.transform(sample)
return sample
def draw(self, idx):
"""Draw one of multiple data instances."""
if not isinstance(idx, Iterable):
idx = [idx]
for index in idx:
sample = self[index]
if len(sample) == 4:
p.print("example {}, {}:".format(index, sample[2]))
if isinstance(sample[0], tuple):
visualize_matrices([sample[0][0].argmax(0), sample[0][1].argmax(0)])
else:
visualize_matrices([sample[0].argmax(0)])
plot_matrices([sample[1][i].squeeze() for i in range(len(sample[1]))], images_per_row=6)
class ConceptDataset3D(MineDataset):
def draw(self, idx):
"""Draw one of multiple data instances."""
if not isinstance(idx, Iterable):
idx = [idx]
for index in idx:
sample = self[index]
if len(sample) == 4:
p.print("example {}, {}:".format(index, sample[2]))
if isinstance(sample[0], tuple):
visualize_matrices([sample[0][0].argmax(0), sample[0][1].argmax(0)], use_color_dict=False)
else:
visualize_matrices([sample[0]], use_color_dict=False)
visualize_matrices([sample[1][i].squeeze() for i in range(len(sample[1]))])
# ### 1.2 ConceptFewshotDataset:
# In[ ]:
def generate_fewshot_dataset(args, concept_mode="standard", n_shot=1, n_queries_per_class=15):
"""For parsing + classify.
The args.dataset has the format:
f"pc-{concept_1}+{concept_2}+...+{concept_n}"
"""
assert args.dataset.startswith("pc") or args.dataset.startswith("pg") or args.dataset.startswith("yc")
str_split = args.dataset.split("-")[1].split("^")
concept_collection = str_split[-1].split("+")
concept_dict = {}
assert n_shot == 1
# Generate samples for each concept:
for concept in concept_collection:
concept_args = init_args({
"dataset": "c-{}".format(concept),
"seed": args.seed,
"n_examples": args.n_examples * n_shot,
"canvas_size": args.canvas_size,
"rainbow_prob": 0.,
"w_type": "image+mask",
"color_avail": args.color_avail,
"max_n_distractors": 0,
"min_n_distractors": 0,
"allow_connect": True, # No effect
"parsing_check": False,
})
concept_dict[concept] = get_dataset(concept_args, verbose=False)[0]
if args.dataset.startswith("pc"):
example_dict = {}
for concept in concept_collection:
example_args = init_args({
"dataset": "c-{}".format(concept),
"seed": args.seed + 1,
"n_examples": args.n_examples * n_queries_per_class,
"canvas_size": args.canvas_size,
"rainbow_prob": 0.,
"w_type": "image+mask",
"color_avail": args.color_avail,
"max_n_distractors": 0,
"min_n_distractors": 0,
"allow_connect": True,
"parsing_check": False,
})
example_dict[concept] = get_dataset(example_args, verbose=False)[0]
elif args.dataset.startswith("yc"):
example_dict = {}
for concept in concept_collection:
example_args = init_args({
"dataset": "y-{}".format(concept),
"seed_3d": args.seed_3d + args.num_processes_3d,
"num_processes_3d": args.num_processes_3d,
"color_map_3d": args.color_map_3d,
"add_thick_surf": args.add_thick_surf,
"add_thick_depth": args.add_thick_depth,
"image_size_3d": args.image_size_3d,
"n_examples": args.n_examples * n_queries_per_class,
# 2D examples
"seed": args.seed + 1,
"use_seed_2d": args.use_seed_2d,
"canvas_size": args.canvas_size,
"rainbow_prob": 0.,
"w_type": "image+mask",
"color_avail": args.color_avail,
"max_n_distractors": 0,
"min_n_distractors": 0,
"allow_connect": True,
"parsing_check": False,
})
example_dict[concept] = get_dataset(example_args, verbose=False, is_load=True)[0]
elif args.dataset.startswith("pg"):
example_dict = {}
examples_collection = str_split[0].split("+")
# The tasks are split evenly among the possible concepts for demonstration
n_tasks = [args.n_examples // len(concept_collection)] * len(concept_collection)
n_tasks[-1] += args.n_examples % len(concept_collection)
for idx, concept in enumerate(concept_collection):
example_args = init_args({
"dataset": "c-{}+{}^{}".format(concept, str_split[0], concept),
"seed": args.seed + 1,
"n_examples": n_tasks[idx] * n_queries_per_class,
"canvas_size": args.canvas_size,
"rainbow_prob": 0.,
"w_type": "image+mask",
"color_avail": args.color_avail,
"max_n_distractors": 2, # Important: There can be distractors in examples
"parsing_check": False,
})
example_dict[concept] = get_dataset(example_args, verbose=False)[0]
else:
raise
if args.dataset[1] == "c":
if concept_mode == "standard":
dataset = generate_fewshot_dataset_standard(
concept_dict=concept_dict,
example_dict=example_dict,
concept_collection=concept_collection,
n_examples=args.n_examples,
n_shot=n_shot,
n_queries_per_class=n_queries_per_class,
)
elif concept_mode == "random":
dataset = generate_fewshot_dataset_random(
concept_dict=concept_dict,
example_dict=example_dict,
concept_collection=concept_collection,
n_examples=args.n_examples,
n_shot=n_shot,
)
else:
raise Exception("concept_mode '{}' is not valid!".format(concept_mode))
elif args.dataset[1] == "g":
if concept_mode == "standard":
dataset = generate_fewshot_grounding_dataset(
concept_dict=concept_dict,
example_dict=example_dict,
concept_collection=concept_collection,
n_tasks=n_tasks,
n_shot=n_shot,