-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
1517 lines (1327 loc) · 76.6 KB
/
Copy pathmodels.py
File metadata and controls
1517 lines (1327 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from enum import Enum
from typing import Union, Optional
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from nltk import TreePrettyPrinter, Tree
from torch import Tensor
from torch_geometric.utils import coalesce
from TPR_utils import batch_symbols_to_node_tree, build_D, build_E, SparseTPR, SparseTPRBlock
from sparsemax import Sparsemax
from utils import pashamax, sinusoidal_positional_encoding
sparsemax = Sparsemax(dim=-1)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class RootPredictionType(Enum):
"""
Enum for how to generate the cons root argument.
@LINEAR: A linear transformation from d_model->d_filler
@ATTN_OVER_DICT: A linear transformation from d_model->n_fillers followed by a weighted sum over the dictionary of
embeddings
@POSITION_ATTN_OVER_INPUTS: A linear transformation from d_model->input_length followed by a weighted sum over the
input embeddings
@QK_ATTN_OVER_INPUTS: A linear transformation from d_model->d_key followed by query-key attention and a weighted
sum over the input embeddings
"""
LINEAR = 'LINEAR'
ATTN_OVER_DICT = 'ATTN_OVER_DICT'
POSITION_ATTN_OVER_INPUTS = 'POSITION_ATTN_OVER_INPUTS'
QK_ATTN_OVER_INPUTS = 'QK_ATTN_OVER_INPUTS'
def __str__(self):
return self.value
class DiffTreeMachine(nn.Module):
def __init__(self, config):
super().__init__()
d_tpr = config.d_filler * config.d_role
# The number of bits used to store the role index
self.role_bits = int(math.log2(config.tpr.num_roles))
self.filler_map_location = config.filler_map_location
if config.filler_map_location:
self.filler_map = nn.Linear(config.d_filler, config.d_filler)
torch.nn.init.eye_(self.filler_map.weight)
if config.filler_map_location == 'operation':
# self.num_ops = 4
raise NotImplementedError
else:
self.num_ops = 3
if config.filler_map_type != 'linear':
raise NotImplementedError
else:
self.num_ops = 3
# Controls whether roles are summed over before performing the linear transformation for ctrl_type == 'conv'
# This is necessary because the size of the linear layer grows with the role dimension which is too large
# for high depths
self.sum_over_roles = True
self.ctrl_type = config.ctrl_type
if self.ctrl_type == 'linear':
self.ctrl_net = nn.Linear(d_tpr, config.d_model)
elif self.ctrl_type == 'conv_mlp':
self.ctrl_net = nn.Sequential(
nn.Conv1d(in_channels=config.d_filler, out_channels=config.n_conv_kernels, kernel_size=1, stride=1),
nn.GELU(),
nn.Flatten(),
nn.Linear(config.n_conv_kernels * config.d_role, config.d_model)
)
elif self.ctrl_type == 'conv':
self.ctrl_net = nn.Sequential(
nn.Conv1d(
in_channels=config.d_filler,
out_channels=config.n_conv_kernels,
kernel_size=1,
stride=1,
bias=False
),
SumModule(-1) if self.sum_over_roles else nn.Identity(),
nn.Flatten(),
nn.Linear(config.n_conv_kernels, config.d_model) if self.sum_over_roles else nn.Linear(
config.n_conv_kernels * config.d_role,
config.d_model
)
)
elif self.ctrl_type == 'set_transformer':
self.ctrl_net = SetTransformer(
config.d_model,
config.d_filler,
self.role_bits,
config.nhead,
config.dim_feedforward
)
else:
raise RuntimeError('Unsupported ctrl_type: {}'.format(config.ctrl_type))
self.encoding_dropout = nn.Dropout(config.dropout)
self.interpreter = DiffTreeInterpreter(
tpr=config.tpr,
num_ops=self.num_ops,
predefined_operations_are_random=config.predefined_operations_are_random,
sparse=config.sparse,
filler_threshold=config.filler_threshold,
max_filled_roles=config.max_filled_roles,
cons_only=config.cons_only,
new_tree_filler_dropout1d=config.new_tree_filler_dropout1d,
config=config,
)
self.max_filled_roles = config.max_filled_roles
self.max_roles_during_training = config.max_filled_roles
self.max_roles_during_eval = config.tpr.num_roles
self.dtm_layers = config.dtm_layers
config.num_ops = self.num_ops
config.filler_matrix = config.tpr.out.weight
self.nta = NeuralTreeAgent(config)
self.op_logits_token = nn.parameter.Parameter(torch.Tensor(1, config.d_model))
nn.init.normal_(self.op_logits_token)
self.root_filler_token = nn.parameter.Parameter(torch.Tensor(1, config.d_model))
nn.init.normal_(self.root_filler_token)
# We only need positional embeddings for inputs with multiple trees
if config.max_input_length > 1:
if config.random_positional_max_len > config.max_input_length:
max_len = config.random_positional_max_len
self.random_positional_embedding = True
else:
max_len = config.max_input_length
self.random_positional_embedding = False
uniform_weights = torch.zeros(max_len).softmax(0)
self.register_buffer('uniform_weights', uniform_weights)
if config.positional_embedding_type == 'learned':
# TODO: what should be the scale and initialization of the embeddings?
positional_embeddings = nn.Embedding(max_len, config.d_model)
self.register_parameter('positional_embeddings', positional_embeddings.weight)
elif config.positional_embedding_type == 'sinusoidal':
# TODO: also, check the norm of the positional embeddings. Does the sinusoidal embeddings need to be
# scaled?
positional_embeddings = torch.tensor(
sinusoidal_positional_encoding(max_len, config.d_model),
dtype=torch.float32
)
self.register_buffer('positional_embeddings', positional_embeddings)
else:
raise RuntimeError('Unsupported positional_embedding_type: {}'.format(config.positional_embedding_type))
else:
self.positional_embeddings = None
# input_lang and output_lang will be used for debugging in forward()
self.input_lang = config.input_lang
self.output_lang = config.output_lang
self.tpr = config.tpr
self.include_empty_tpr = config.include_empty_tpr
self.sparse = config.sparse
self.cons_only = config.cons_only
self.filler_dropout_location = config.filler_dropout_location
if config.filler_dropout_location:
self.filler_dropout = nn.Dropout(config.filler_dropout)
self.filler_noise_location = config.filler_noise_location
self.filler_noise_std = config.filler_noise_std
self.root_prediction_type = config.root_prediction_type
def forward(self, input_tpr, bsz, debug=False, calculate_entropy=False, custom_memory_set=False,
decoded_tpr_to_tree_fn=None, vocab_info=None, input_filler_root_embeddings=None,
input_filler_root_mask=None
) -> (Union[SparseTPR, Tensor], Optional[dict], None):
debug_writer = [] if debug else None
if not self.sparse:
has_multiple_input_tprs = input_tpr.dim() == 4
if self.filler_dropout_location == 'input':
input_tpr = SparseTPRBlock(input_tpr.indices(), self.filler_dropout(input_tpr.values()))
# TODO: Question, dropout rescales the values during training to keep the same magnitude. Should we do
# something similar when we add noise?
if self.filler_noise_location == 'input' and self.training:
# We don't want to add noise to the padding embeddings
if self.sparse:
pad_mask = (input_tpr.values() == 0).all(dim=1)
noisy_values = input_tpr.values() + torch.randn_like(input_tpr.values()) * self.filler_noise_std
noisy_values.masked_fill_(pad_mask.unsqueeze(1), 0)
input_tpr = SparseTPRBlock(input_tpr.indices(), noisy_values)
else:
pad_mask = (input_tpr == 0).all(dim=-1)
noisy_values = input_tpr + torch.randn_like(input_tpr) * self.filler_noise_std
noisy_values.masked_fill_(pad_mask.unsqueeze(-1), 0)
input_tpr = noisy_values
# We need to convert indices to words for printing
if debug:
assert self.input_lang
assert self.output_lang
if self.filler_map_location == 'pre_dtm':
if self.sparse:
input_fillers = self.apply_sparse_filler_transformation(input_tpr.values())
input_tpr = torch.sparse_coo_tensor(indices=input_tpr.indices(), values=input_fillers,
size=input_tpr.shape).coalesce()
else:
input_tpr = self.apply_dense_filler_transformation(input_tpr)
if self.sparse:
step_offset = input_tpr.memory_slot_indices().max() + 1 if self.include_empty_tpr \
else input_tpr.memory_slot_indices().max()
else:
step_offset = input_tpr.shape[1] - 1
if custom_memory_set:
# Add 1 for the input TPR
memory_slots = self.dtm_layers + 1 + step_offset
if self.sparse:
values_storage = torch.zeros((bsz * memory_slots * self.max_filled_roles, self.tpr.d_filler),
device=input_tpr.device)
# The 3 indices are batch, memory slot, role
indices_storage = torch.zeros((3, bsz * memory_slots * self.max_filled_roles),
device=input_tpr.device, dtype=torch.int32)
# The start and end indices for each storage slot. For example, if the first layer writes to memory
# index 0 in dimensions 0-71, the second memory slot would write from 71 onwards. This tensor keeps
# track of where each memory slot starts and ends in order to know where to write the next TPR as
# well as how to retrieve the TPRs from storage.
# We add 2 to the number of dtm_layers because we need to include a starting index (index 0) and the input
# TPRs which end at index 1.
storage_start_end_indices = torch.zeros(self.dtm_layers + 2, device=input_tpr.device, dtype=torch.long)
indices_storage, values_storage = sparse_storage_block_set(
indices_storage,
values_storage,
input_tpr.indices(),
input_tpr.values(),
0,
storage_start_end_indices
)
if self.include_empty_tpr:
raise NotImplementedError('include_empty_tpr does not work with sparse and custom_memory_set yet')
else:
# Include one extra for the input TPR and a potential extra for the 0 TPR
memory = torch.zeros((bsz, memory_slots, input_tpr.shape[-2], input_tpr.shape[-1]),
device=input_tpr.device, layout=torch.sparse_coo if self.sparse else torch.strided)
memory = memory_set(memory, input_tpr, 0)
if self.include_empty_tpr:
memory = memory_set(memory, self.tpr.empty_tpr(input_tpr.device), 1)
else:
if self.sparse:
memory = torch.sparse_coo_tensor(indices=torch.stack((
input_tpr.indices()[0],
torch.zeros(input_tpr.values().shape[0], device=input_tpr.device),
input_tpr.indices()[1]
)), values=input_tpr.values(), size=(
bsz, 2 if self.include_empty_tpr else 1, self.tpr.num_roles, self.tpr.d_filler)
).coalesce()
else:
memory = input_tpr.unsqueeze(1) # the dtm_layers dimension
# TODO: if self.cons_only==True, we don't need the operation token
# Setup the encodings for the NTA
op_logits_token = self.op_logits_token.repeat(bsz, 1, 1)
root_filler_token = self.root_filler_token.repeat(bsz, 1, 1)
encodings = torch.cat((op_logits_token, root_filler_token), dim=1)
# Encode the trees that initialize the memory
if self.sparse:
# The input trees always have root nodes, so we can count the number of root nodes to get the number of trees
trees_encoding, agent_pad_mask = self.ctrl_net(input_tpr, bsz, num_trees=(input_tpr.role_indices() == 1).sum())
else:
if has_multiple_input_tprs:
trees_encoding = self.ctrl_net(input_tpr.view(input_tpr.shape[0], input_tpr.shape[1], -1))
agent_pad_mask = (input_tpr == 0).all(dim=-1).all(dim=-1)
else:
trees_encoding = self.ctrl_net(input_tpr.view(input_tpr.shape[0], -1))
agent_pad_mask = (input_tpr == 0).all(dim=-1)
# Add two non-padding tokens to the agent pad mask for the op logits and root filler tokens
agent_pad_mask = torch.cat((torch.zeros((bsz, 2), device=agent_pad_mask.device, dtype=torch.bool),
agent_pad_mask), dim=1)
# TODO: technically, I don't think we need to add positional_embeddings to the <EOB> token
if self.positional_embeddings is not None:
if self.random_positional_embedding:# and self.training:
positional_indices = torch.multinomial(self.uniform_weights, trees_encoding.shape[1], replacement=False)
positional_indices = positional_indices.sort()[0]
else:
positional_indices = torch.arange(trees_encoding.shape[1], device=trees_encoding.device)
positional_embeddings = torch.index_select(self.positional_embeddings, 0, positional_indices).unsqueeze(0)
else:
positional_embeddings = torch.tensor([0], device=trees_encoding.device)
encodings = torch.cat(
(
encodings,
self.encoding_dropout(trees_encoding + positional_embeddings)
),
dim=1
)
# Step offset will cause us to skip shrinking the input TPR in the first loop, so we encode that here if we
# include the empty TPR
if self.include_empty_tpr:
raise RuntimeError('I need to rethink how empty TPRs work, maybe replace it with a root node with the EOB'
'filler?')
if self.filler_map_location == 'pre_shrink':
# Remove the memory slot dimension
if self.sparse:
transformed_fillers = self.apply_sparse_filler_transformation(input_tpr.values())
tree_to_shrink = torch.sparse_coo_tensor(indices=memory.indices()[[0, 2]],
values=transformed_fillers,
size=(memory.shape[0], memory.shape[2],
memory.shape[3])).coalesce()
else:
tree_to_shrink = self.apply_dense_filler_transformation(memory[:, 0])
else:
if self.sparse:
tree_to_shrink = input_tpr
else:
tree_to_shrink = memory.select(1, 0)
if self.ctrl_type == 'linear':
tree_encoding = self.ctrl_net(tree_to_shrink.flatten(1))
elif self.ctrl_type == 'conv_mlp' or self.ctrl_type == 'conv' or self.ctrl_type == 'set_transformer':
tree_encoding = self.ctrl_net(tree_to_shrink)
else:
raise RuntimeError('Unsupported ctrl_type: {}'.format(self.ctrl_type))
encodings = torch.cat((encodings, self.encoding_dropout(tree_encoding).unsqueeze(1)), dim=1)
cons_arg1_entropies = torch.empty(self.dtm_layers, device=input_tpr.device)
cons_arg2_entropies = torch.empty(self.dtm_layers, device=input_tpr.device)
for step in range(self.dtm_layers):
# logger.verbose(f'Layer {step} allocated memory {torch.cuda.memory_allocated() / 1024 ** 2} mb')
# Encode the most recent TPR in memory except at step 0 where we encoded the inputs above
if step > 0:
if self.filler_map_location == 'pre_shrink':
if self.sparse:
most_recent_mask = memory.indices()[1] == step + step_offset
transformed_fillers = self.apply_sparse_filler_transformation(memory.values()[most_recent_mask])
tree_to_shrink = torch.sparse_coo_tensor(indices=memory.indices()[[0, 2]][:, most_recent_mask],
values=transformed_fillers,
size=(memory.shape[0], memory.shape[2],
memory.shape[3])).coalesce()
else:
tree_to_shrink = self.apply_dense_filler_transformation(memory[:, step + step_offset])
else:
if self.sparse:
if custom_memory_set:
tree_to_shrink = get_sparse_tpr_from_storage(
indices_storage,
values_storage,
step,
storage_start_end_indices
)
else:
most_recent_memory_mask = memory.indices()[1] == step + step_offset
tree_to_shrink = torch.sparse_coo_tensor(indices=torch.stack(
(memory.indices()[0][most_recent_memory_mask], memory.indices()[-1][most_recent_memory_mask])),
values=memory.values()[most_recent_memory_mask], size=(bsz, self.tpr.num_roles,
self.tpr.d_filler)).coalesce()
else:
tree_to_shrink = memory.select(1, step + step_offset)
if self.ctrl_type == 'linear':
tree_encoding = self.ctrl_net(tree_to_shrink.flatten(1))
pad = torch.zeros((bsz, 1), dtype=torch.bool, device=tree_encoding.device)
elif self.ctrl_type == 'conv_mlp' or self.ctrl_type == 'conv':
if self.sparse:
# The output of the conv layer is batch_size, n_kernels, n_roles. As n_roles gets very large,
# this can be very memory intensive. We can avoid this by summing over the role dimension first
# so that the output is batch_size, n_kernels. TODO: look into using SetTransformer with a learned
# query vector to perform weighted summing over the roles
if self.sum_over_roles:
summed_over_roles = torch.sparse.sum(tree_to_shrink, dim=1).to_dense()
num_filled_roles = torch.bincount(tree_to_shrink.indices()[0])
# Normalize the result by dividing by the number of filled roles
normalized = torch.div(summed_over_roles, num_filled_roles[None].T)
conv_results = normalized @ self.ctrl_net[0].weight.transpose(0, 1).squeeze()
tree_encoding = self.ctrl_net[3](conv_results)
else:
conv_results = tree_to_shrink.values() @ self.ctrl_net[0].weight.transpose(0, 1).squeeze()
# sparse_indices[0] is the batch index, sparse_indices[1] is the role index
sparse_indices = tree_to_shrink.indices()
# batch_size, n_kernels, n_roles
dense_conv_results = torch.zeros((bsz, self.ctrl_net[0].out_channels, input_tpr.shape[1]),
device=input_tpr.device)
dense_conv_results[sparse_indices[0], ..., sparse_indices[1]] = conv_results
flat = self.ctrl_net[2](dense_conv_results)
tree_encoding = self.ctrl_net[3](flat)
else:
tree_encoding = self.ctrl_net(tree_to_shrink)
elif self.ctrl_type == 'set_transformer':
if self.sparse:
tree_encoding, pad = self.ctrl_net.single_tree_forward(tree_to_shrink, bsz)
else:
raise RuntimeError('Set Transformer shrink only implemented for sparse TPRs.')
else:
raise RuntimeError('Unsupported ctrl_type: {}'.format(self.ctrl_type))
encodings = torch.cat(
(encodings,
self.encoding_dropout(tree_encoding.view(bsz, 1, -1))), dim=1)
agent_pad_mask = torch.cat((agent_pad_mask, pad), dim=1)
op_dist, root_filler, arg_weights, encodings, root_filler_dist = self.nta(
encodings,
step,
agent_pad_mask,
input_filler_root_embeddings=input_filler_root_embeddings,
input_filler_root_mask=input_filler_root_mask
)
# TODO: now that the arg weights are produced by the NTA, we can use them to calculate the entropy of the
# distributions here instead of in the separate car/cdr/cons nets
if self.cons_only:
op_dist = torch.zeros_like(op_dist)
op_dist[:, 2] = 1
cons_arg1_entropies[step] = -torch.sum(
arg_weights[:, :, 2] * torch.log(arg_weights[:, :, 2] + 1e-9),
dim=1
).mean() # Adding a small constant for numerical stability
cons_arg2_entropies[step] = -torch.sum(
arg_weights[:, :, 3] * torch.log(arg_weights[:, :, 3] + 1e-9),
dim=1
).mean() # Adding a small constant for numerical stability
use_checkpoint = False
if use_checkpoint:
new_tree = checkpoint.checkpoint(self.interpreter, memory[:, :step + 1 + step_offset], arg_weights,
root_filler, op_dist)
else:
if custom_memory_set:
if self.sparse:
trees_in_memory = get_sparse_tpr_block_from_storage(
indices_storage,
values_storage,
storage_end_index=step+1,
storage_start_end_indices=storage_start_end_indices
)
new_tree = self.interpreter(
trees_in_memory,
arg_weights,
root_filler,
op_dist,
bsz,
# Don't perform dropout on the last step before the output
skip_dropout=step == self.dtm_layers - 1
)
else:
new_tree = self.interpreter(memory[:, :step + 1 + step_offset], arg_weights, root_filler,
op_dist, bsz)
else:
new_tree = self.interpreter(memory, arg_weights, root_filler, op_dist, bsz)
if debug:
output_string = 'Step {}:\nBlackboard:'.format(step)
debug_writer.append(output_string)
# Use the batch dimension to decode previous layers on the blackboard
if custom_memory_set and self.sparse:
trees_to_decode = trees_in_memory
first_batch_mask = trees_to_decode.batch_indices() == 0
# Ignore the batch index dimension by indexing from [1:]
trees_to_decode = SparseTPR(trees_to_decode.indices()[1:][:, first_batch_mask],
trees_to_decode.values()[first_batch_mask])
else:
trees_to_decode = memory[0, :step + 1 + step_offset]
if self.sparse and not custom_memory_set:
trees_to_decode = trees_to_decode.coalesce()
if self.sparse:
x_decoded = decoded_tpr_to_tree_fn(
self.tpr.unbind(
(SparseTPR(trees_to_decode.indices(), trees_to_decode.values())), decode=True, type_='input'
)
)
else:
x_decoded = decoded_tpr_to_tree_fn(
self.tpr.unbind(trees_to_decode, decode=True, type_='input')
)
x_tree = batch_symbols_to_node_tree(
x_decoded,
self.input_lang.ind2vocab,
terminal_vocab=vocab_info['terminal'],
unary_vocab=vocab_info['unary'],
sparse=self.sparse
)
extra_column_label = ''
is_root_prediction_attn = ((self.root_prediction_type == RootPredictionType.ATTN_OVER_DICT or
self.root_prediction_type == RootPredictionType.QK_ATTN_OVER_INPUTS) and
not self.nta.hardcode_cons_root_index)
if is_root_prediction_attn:
extra_column_label = ', root filler'
if self.cons_only:
debug_writer.append(f'[cons_l, cons_r{extra_column_label}]')
else:
debug_writer.append(f'[car, cdr, cons_l, cons_r{extra_column_label}]')
for i, tree in enumerate(x_tree):
if tree:
if self.cons_only:
weights_string = np.array2string(
arg_weights[0, i, -2:].detach().cpu().numpy(),
formatter={'float_kind': arg_weight_formatter}
)
else:
weights_string = np.array2string(
arg_weights[0, i, :].detach().cpu().numpy(),
formatter={'float_kind': arg_weight_formatter}
)
# Only print the input root attention for valid input fillers in the 0th batch
if (is_root_prediction_attn and input_filler_root_mask and
i < input_filler_root_mask[0].shape[0] and not input_filler_root_mask[0, i]):
root_attn = f'{root_filler_dist[0, i]:.2f}'[1:]
weights_string = weights_string[:-1] + f' {root_attn}' + ']'
if i > step_offset:
debug_writer.append(f'{i:2}\t{weights_string} {i-step_offset-1:2}. {tree.str()}')
else:
debug_writer.append(f'{i:2}\t{weights_string} {tree.str()}')
else:
debug_writer.append('None')
if not self.cons_only:
debug_writer.append(
'car: {:.3f}\tcdr: {:.3f}\tcons: {:.3f}'.format(op_dist[0][0], op_dist[0][1], op_dist[0][2]))
if (not self.nta.hardcode_cons_root_index and self.root_prediction_type ==
RootPredictionType.ATTN_OVER_DICT):
root_filler_dist_str = 'root filler ~ '
for i, filler_weight in enumerate(root_filler_dist[0]):
if filler_weight > .1:
root_filler_dist_str += f'{self.output_lang.ind2vocab[i]}: {filler_weight:.2}\t'
debug_writer.append(root_filler_dist_str)
tree_to_decode = new_tree[0].unsqueeze(0)
if self.sparse:
tree_to_decode = tree_to_decode.coalesce()
fully_decoded = decoded_tpr_to_tree_fn(
self.tpr.unbind(
SparseTPR(tree_to_decode.indices(), tree_to_decode.values()) if self.sparse else tree_to_decode,
decode=True,
type_='output' if step == self.dtm_layers - 1 else 'input'
)
)
debug_tree = batch_symbols_to_node_tree(
fully_decoded,
self.output_lang.ind2vocab if step == self.dtm_layers - 1 else self.input_lang.ind2vocab,
terminal_vocab=vocab_info['terminal'],
unary_vocab=vocab_info['unary'],
sparse=self.sparse
)[0]
debug_writer.append('Output: ')
if not debug_tree:
debug_writer.append('None')
else:
pretty_tree = TreePrettyPrinter(Tree.fromstring(debug_tree.str()))
debug_writer.append('```{}```'.format(pretty_tree.text()))
if custom_memory_set:
if self.sparse:
indices_storage, values_storage = sparse_storage_set(
indices_storage,
values_storage,
new_tree.indices(),
new_tree.values(),
step + 1,
step + 1 + step_offset,
storage_start_end_indices
)
else:
memory = memory_set(memory, new_tree, step + 1 + step_offset)
else:
# LARGE MEMORY USAGE
if self.sparse:
memory = torch.sparse_coo_tensor(indices=torch.stack((
torch.cat((memory.indices()[0], new_tree.indices()[0])),
torch.cat((memory.indices()[1],
torch.tensor(step + step_offset + 1, device=input_tpr.device).repeat(
new_tree._nnz()))),
torch.cat((memory.indices()[2], new_tree.indices()[1])))),
values=torch.cat((memory.values(), new_tree.values())),
size=(memory.shape[0], memory.shape[1] + 1, memory.shape[2], memory.shape[3])).coalesce()
else:
memory = torch.cat([memory, new_tree.unsqueeze(1)], dim=1)
if self.filler_map_location == 'post_dtm' or self.filler_map_location == 'pre_shrink':
if self.sparse:
if custom_memory_set:
output = get_sparse_tpr_from_storage(
indices_storage,
values_storage,
step + 1,
storage_start_end_indices
)
output = SparseTPR(output.indices(), self.apply_sparse_filler_transformation(output.values()))
else:
last_memory_mask = memory.indices()[1] == self.dtm_layers + step_offset
transformed_fillers = self.apply_sparse_filler_transformation(memory.values()[last_memory_mask])
output = torch.sparse_coo_tensor(indices=memory.indices()[[0, 2]][:, last_memory_mask],
values=transformed_fillers,
size=input_tpr.shape).coalesce()
else:
output = self.apply_dense_filler_transformation(memory[:, self.dtm_layers + step_offset])
if debug:
if self.sparse and custom_memory_set:
to_decode = output
first_batch_mask = output.batch_indices() == 0
to_decode = SparseTPR(
to_decode.indices()[:, first_batch_mask],
to_decode.values()[first_batch_mask]
)
else:
to_decode = output[0].unsqueeze(0)
if self.sparse:
to_decode = to_decode.coalesce()
fully_decoded = decoded_tpr_to_tree_fn(self.tpr.unbind(to_decode, decode=True, type_='output'))
debug_tree = batch_symbols_to_node_tree(
fully_decoded,
self.output_lang.ind2vocab,
terminal_vocab=vocab_info['terminal'],
unary_vocab=vocab_info['unary']
)[0]
debug_writer.append('Post-Linear Output: ')
if not debug_tree:
debug_writer.append('None')
else:
pretty_tree = TreePrettyPrinter(Tree.fromstring(debug_tree.str()))
debug_writer.append('```{}```'.format(pretty_tree.text()))
else:
if self.sparse:
if custom_memory_set:
output = get_sparse_tpr_from_storage(indices_storage, values_storage, step + 1,
storage_start_end_indices)
else:
last_memory_mask = memory.indices()[1] == memory.shape[1] - 1
output = torch.sparse_coo_tensor(indices=torch.stack(
(memory.indices()[0][last_memory_mask], memory.indices()[-1][last_memory_mask])),
values=memory.values()[last_memory_mask],
size=(bsz, self.tpr.num_roles, self.tpr.d_filler)).coalesce()
else:
# Select the final TPR in memory
output = memory.select(1, -1)
debug_info = None
if debug:
print('\n'.join(debug_writer))
debug_info = {'text': debug_writer}
entropies = {
'cons_arg1': cons_arg1_entropies,
'cons_arg2': cons_arg2_entropies
}
if self.filler_dropout_location == 'pre_output':
output = SparseTPRBlock(output.indices(), self.filler_dropout(output.values()))
return SparseTPR(output.indices(), output.values()) if self.sparse else output, debug_info, entropies
def set_gumbel_temp(self, temp):
self.interpreter.gumbel_temp = temp
self.nta.gumbel_temp = temp
def apply_sparse_filler_transformation(self, fillers, apply_bias=False):
"""
Apply a linear transformation on the fillers. The bias is turned off by default since the bias will "turn on"
empty fillers by making them not zero.
"""
filler_transformed = fillers @ self.filler_map.weight
if apply_bias:
filler_transformed += self.filler_map.bias
return filler_transformed
def apply_dense_filler_transformation(self, tpr, apply_bias=False):
"""
Apply a linear transformation on the fillers. The bias is turned off by default since the bias will "turn on"
empty fillers by making them not zero.
"""
filler_transformed = torch.einsum('bfr,ft->btr', tpr, self.filler_map.weight)
if apply_bias:
filler_transformed += self.filler_map.bias.unsqueeze(0).unsqueeze(-1)
return filler_transformed
class NeuralTreeAgent(nn.Module):
"""
The Neural Tree Agent
"""
def __init__(self, config):
super().__init__()
# We only need to create a single layer since this layer will be deep copied by nn.TransformerEncoder
transformer_layer = nn.TransformerEncoderLayer(
d_model=config.d_model,
nhead=config.nhead,
dim_feedforward=config.dim_feedforward,
dropout=config.dropout,
activation=config.activation,
layer_norm_eps=config.layer_norm_eps,
batch_first=True,
norm_first=bool(config.transformer_norm_first)
)
self.is_agent_universal = config.is_agent_universal
self.filler_matrix = config.filler_matrix
self.root_prediction_type = config.root_prediction_type
self.hardcode_cons_root_index = config.hardcode_cons_root_index
self.layers = nn.ModuleList()
self.arg_logits_list = nn.ModuleList()
self.root_filler_list = nn.ModuleList()
self.op_logits_list = nn.ModuleList()
self.root_prediction_key_list = nn.ModuleList()
self.root_prediction_query_list = nn.ModuleList()
if self.is_agent_universal:
encoder_norm = nn.LayerNorm(
config.d_model,
eps=config.layer_norm_eps
) if config.transformer_norm_first else None
self.layers.append(
nn.TransformerEncoder(transformer_layer, config.agent_layers_per_step, encoder_norm)
)
# 4 for the 4 arguments, car, cdr, cons1, cons2
arg_logits = nn.Linear(config.d_model, 4)
nn.init.normal_(arg_logits.weight, std=0.02)
nn.init.zeros_(arg_logits.bias)
self.arg_logits_list.append(arg_logits)
if self.root_prediction_type == RootPredictionType.ATTN_OVER_DICT:
root_filler = nn.Linear(config.d_model, config.filler_matrix.shape[0])
nn.init.normal_(root_filler.weight, std=0.02)
nn.init.zeros_(root_filler.bias)
elif self.root_prediction_type == RootPredictionType.POSITION_ATTN_OVER_INPUTS:
# TODO: How should this linear layer be initialized?
root_filler = nn.Linear(config.d_model, config.max_input_length)
self.max_input_length = config.max_input_length
elif self.root_prediction_type == RootPredictionType.QK_ATTN_OVER_INPUTS:
# root_prediction_key converts fillers to keys
self.root_prediction_key = nn.Linear(config.d_filler, config.d_model // config.nhead)
# root_prediction_query converts the root token to a query
self.root_prediction_query = nn.Linear(config.d_model, config.d_model // config.nhead)
# Note, the values are the fillers themselves
root_filler = None
self.root_prediction_key_list.append(self.root_prediction_key)
self.root_prediction_query_list.append(self.root_prediction_query)
elif self.root_prediction_type == RootPredictionType.LINEAR:
root_filler = nn.Linear(config.d_model, config.d_filler)
else:
raise RuntimeError('Unsupported root_prediction_type: {}'.format(self.root_prediction_type))
self.root_filler_list.append(root_filler)
op_logits = nn.Linear(config.d_model, config.num_ops)
nn.init.normal_(op_logits.weight, std=0.02)
nn.init.zeros_(op_logits.bias)
self.op_logits_list.append(op_logits)
else:
for i in range(config.dtm_layers):
encoder_norm = nn.LayerNorm(
config.d_model,
eps=config.layer_norm_eps
) if config.transformer_norm_first else None
self.layers.append(
nn.TransformerEncoder(transformer_layer, config.agent_layers_per_step, encoder_norm)
)
# 4 for the 4 arguments, car, cdr, cons1, cons2
arg_logits = nn.Linear(config.d_model, 4)
nn.init.normal_(arg_logits.weight, std=0.02)
nn.init.zeros_(arg_logits.bias)
self.arg_logits_list.append(arg_logits)
if self.root_prediction_type == RootPredictionType.ATTN_OVER_DICT:
root_filler = nn.Linear(config.d_model, config.filler_matrix.shape[0])
nn.init.normal_(root_filler.weight, std=0.02)
nn.init.zeros_(root_filler.bias)
elif self.root_prediction_type == RootPredictionType.POSITION_ATTN_OVER_INPUTS:
# TODO: How should this linear layer be initialized?
root_filler = nn.Linear(config.d_model, config.max_input_length)
self.max_input_length = config.max_input_length
elif self.root_prediction_type == RootPredictionType.QK_ATTN_OVER_INPUTS:
# root_prediction_key converts fillers to keys
self.root_prediction_key = nn.Linear(config.d_filler, config.d_model // config.nhead)
# root_prediction_query converts the root token to a query
self.root_prediction_query = nn.Linear(config.d_model, config.d_model // config.nhead)
# Note, the values are the fillers themselves
root_filler = None
self.root_prediction_key_list.append(self.root_prediction_key)
self.root_prediction_query_list.append(self.root_prediction_query)
elif self.root_prediction_type == RootPredictionType.LINEAR:
root_filler = nn.Linear(config.d_model, config.d_filler)
else:
raise RuntimeError('Unsupported root_prediction_type: {}'.format(self.root_prediction_type))
self.root_filler_list.append(root_filler)
op_logits = nn.Linear(config.d_model, config.num_ops)
nn.init.normal_(op_logits.weight, std=0.02)
nn.init.zeros_(op_logits.bias)
self.op_logits_list.append(op_logits)
self.op_dist_fn = config.op_dist_fn
self.arg_dist_fn = config.arg_dist_fn
self.pad_idx = config.pad_idx
self.op_token_idx = 0
self.root_filler_token_idx = 1
self.arg_noise_std = config.arg_noise_std
def forward(
self,
encodings,
step,
pad_mask=None,
input_filler_root_embeddings=None,
input_filler_root_mask=None
):
if self.is_agent_universal:
step = 0
encodings = self.layers[step](encodings, src_key_padding_mask=pad_mask)
op_logits = self.op_logits_list[step](encodings[:, self.op_token_idx, :])
if self.op_dist_fn == 'softmax':
op_dist = F.softmax(op_logits, dim=-1)
elif self.op_dist_fn == 'pashamax':
op_dist = pashamax(op_logits, dim=-1)
elif self.op_dist_fn == 'sparsemax':
op_dist = sparsemax(op_logits)
elif self.op_dist_fn == 'gumbel':
op_dist = F.gumbel_softmax(op_logits, tau=self.gumbel_temp, hard=True)
else:
raise ValueError('Unknown op_dist_fn: {}'.format(self.op_dist_fn))
root_filler_dist = None
if self.hardcode_cons_root_index:
if self.hardcode_cons_root_index == -1:
root_filler = torch.zeros((encodings.shape[0], self.filler_matrix.shape[-1]), device=encodings.device)
else:
root_filler = self.filler_matrix[self.hardcode_cons_root_index].expand(encodings.shape[0], -1)
else:
if self.root_prediction_type == RootPredictionType.ATTN_OVER_DICT:
root_filler_logits = self.root_filler_list[step](encodings[:, self.root_filler_token_idx, :])
# We don't ever want to predict the padding token. Also, this prevents gradient from following through the
# padding embedding which would make it non-zero.
root_filler_logits[:, self.pad_idx] = -float('inf')
root_filler_dist = F.softmax(root_filler_logits, dim=-1)
# batch x n_fillers, n_fillers x d_filler
root_filler = torch.einsum('bn,nd->bd', root_filler_dist, self.filler_matrix)
elif self.root_prediction_type == RootPredictionType.POSITION_ATTN_OVER_INPUTS:
root_filler_logits = self.root_filler_list[step](encodings[:, self.root_filler_token_idx, :])
# Mask padding tokens -inf
root_filler_logits.masked_fill_(input_filler_root_mask, -float('inf'))
# Softmax
root_filler_dist = root_filler_logits.softmax(dim=-1)
# batch x max_input_length, batch x max_input_length x d_filler
root_filler = torch.einsum('bm,bmd->bd', root_filler_dist, input_filler_root_embeddings)
elif self.root_prediction_type == RootPredictionType.QK_ATTN_OVER_INPUTS:
# TODO: for a universal agent, the keys can be cached instead of recomputed
keys = self.root_prediction_key_list[step](input_filler_root_embeddings)
query = self.root_prediction_query_list[step](encodings[:, self.root_filler_token_idx, :])
# batch x n_input_fillers x d_key, batch d_query
query_key_match = torch.einsum('blk,bk->bl', keys, query)
query_key_match.masked_fill_(input_filler_root_mask, -float('inf'))
root_filler_dist = F.softmax(query_key_match / np.sqrt(keys.shape[-1]), dim=1)
root_filler = torch.einsum('blv,bl->bv', input_filler_root_embeddings, root_filler_dist)
elif self.root_prediction_type == RootPredictionType.LINEAR:
root_filler = self.root_filler_list[step](encodings[:, self.root_filler_token_idx, :])
else:
raise RuntimeError('Unsupported root_prediction_type: {}'.format(self.root_prediction_type))
arg_logits = self.arg_logits_list[step](encodings[:, 2:, :])
if self.arg_noise_std != 0 and self.training:
arg_logits = arg_logits + torch.randn_like(arg_logits) * self.arg_noise_std
# Pad mask tracks which tokens are padding, so in this case we need to flip the boolean value to keep the
# correct values
arg_logits = torch.where(~pad_mask[:, 2:].unsqueeze(-1), arg_logits, -1e9)
if self.arg_dist_fn == 'softmax':
arg_weights = F.softmax(arg_logits, dim=1)
elif self.arg_dist_fn == 'gumbel':
arg_weights = F.gumbel_softmax(arg_logits, tau=self.gumbel_temp)
else:
raise ValueError('Unknown arg_dist_fn: {}'.format(self.arg_dist_fn))
quantize = False
if quantize:
max_values = arg_weights.max(dim=1, keepdim=True).values
arg_weights = (arg_weights == max_values).float()
return op_dist, root_filler, arg_weights, encodings, root_filler_dist
class DiffTreeInterpreter(nn.Module):
def __init__(self, tpr, num_ops=3, predefined_operations_are_random=False, sparse=False, filler_threshold=None,
max_filled_roles=None, cons_only=False, new_tree_filler_dropout1d=0., config=None):
super().__init__()
role_matrix = tpr.role_matrix
if predefined_operations_are_random:
d_role = role_matrix.shape[1]
D_l = nn.Parameter(role_matrix.new_empty(d_role, d_role))
D_r = nn.Parameter(role_matrix.new_empty(d_role, d_role))
E_l = nn.Parameter(role_matrix.new_empty(d_role, d_role))
E_r = nn.Parameter(role_matrix.new_empty(d_role, d_role))
nn.init.kaiming_uniform_(D_l, a=math.sqrt(5))
nn.init.kaiming_uniform_(D_r, a=math.sqrt(5))
nn.init.kaiming_uniform_(E_l, a=math.sqrt(5))
nn.init.kaiming_uniform_(E_r, a=math.sqrt(5))
else:
D_l, D_r = build_D(role_matrix, sparse=sparse)
E_l, E_r = build_E(role_matrix, sparse=sparse)
self.cons_only = cons_only
if not self.cons_only:
self.car_net = CarNet(D_l, tpr, sparse=sparse)
self.cdr_net = CdrNet(D_r, tpr, sparse=sparse)
root_role = None if sparse else role_matrix[0]
self.cons_net = ConsNet(E_l, E_r, root_role, tpr, sparse=sparse)
self.tpr = tpr
self.num_ops = num_ops
self.sparse = sparse
self.filler_threshold = filler_threshold
self.max_filled_roles = max_filled_roles
self.max_roles_during_training = config.max_filled_roles
self.max_roles_during_eval = config.tpr.num_roles
self.new_tree_filler_dropout1d = None
if new_tree_filler_dropout1d:
self.new_tree_filler_dropout1d = nn.Dropout1d(p=new_tree_filler_dropout1d)
def forward(self, memory, arg_weights, root_filler, op_dist, bsz, calculate_entropy=False, skip_dropout=False):
car_arg_weights = arg_weights[:, :, 0]
cdr_arg_weights = arg_weights[:, :, 1]
cons_arg1_weights = arg_weights[:, :, 2]
cons_arg2_weights = arg_weights[:, :, 3]
# TODO: root_filler is very small, maybe we should normalize it? But why is it small in the first place? It's
# a weighted sum over the filler embeddings....
if self.sparse:
if type(memory) == torch.Tensor:
memory = SparseTPRBlock(memory.indices(), memory.values())
# TODO: large memory usage here
cons_output = self.cons_net(
memory, arg1_weight=cons_arg1_weights,
arg2_weight=cons_arg2_weights, root_filler=root_filler,
calculate_entropy=calculate_entropy
)[0]
if self.cons_only:
output = cons_output
else:
car_output = self.car_net(
memory,
arg1_weight=car_arg_weights,
calculate_entropy=calculate_entropy
)[0]
cdr_output = self.cdr_net(
memory,
arg1_weight=cdr_arg_weights,
calculate_entropy=calculate_entropy
)[0]
indices = torch.stack(
(torch.cat((car_output.indices()[0], cdr_output.indices()[0], cons_output.indices()[0])),
torch.cat((car_output.indices()[1], cdr_output.indices()[1], cons_output.indices()[1])))
)
values = torch.cat(
(op_dist[:, 0][car_output.indices()[0]].unsqueeze(1) * car_output.values(),
op_dist[:, 1][cdr_output.indices()[0]].unsqueeze(1) * cdr_output.values(),
op_dist[:, 2][cons_output.indices()[0]].unsqueeze(1) * cons_output.values())
)
# TODO: figure out why shrinking the norm via op_dist isn't restored when the values are added together.
# For example, the norm of the filler in the root node will be less because it is multiplied by the
# attention weight, but then three values are added together which I would imagine restores the norm?
# Maybe not exactly, the norm of the summation involves cosines between the vectors.
output = SparseTPR(*coalesce(indices, values))
if self.new_tree_filler_dropout1d and not skip_dropout:
values = self.new_tree_filler_dropout1d(output.values())
mask = values.any(dim=-1)
output = SparseTPR(output.indices()[:, mask], values[mask])
# TODO: should we turn off max_filled_roles during evaluation? This leads to a dimension issue where the
# sparse memory expects max_filled_roles but at evaluation time we can have more than max_filled roles.