-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfixed_stack_models.py
More file actions
1668 lines (1403 loc) · 70 KB
/
Copy pathfixed_stack_models.py
File metadata and controls
1668 lines (1403 loc) · 70 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
from venv import logger
import torch
import torch.nn.functional as F
from action_dict import GeneralizedActionDict
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from utils import *
class NoValidNextActionError(Exception):
pass
class StackIndexError(Exception):
pass
class MultiLayerLSTMCell(nn.Module):
def __init__(
self,
input_size: int,
hidden_size: int,
num_layers: int,
bias: bool = False,
dropout: float = 0.0,
layernorm: bool = True,
):
super(MultiLayerLSTMCell, self).__init__()
self.lstm = nn.ModuleList()
self.lstm.append(nn.LSTMCell(input_size, hidden_size))
for i in range(num_layers - 1):
self.lstm.append(nn.LSTMCell(hidden_size, hidden_size))
self.regularizer = nn.ModuleList()
if layernorm:
# Set layernorm as regularizer.
for _ in range(num_layers):
self.regularizer.append(nn.LayerNorm(normalized_shape=hidden_size))
else:
# Set dropout as regularizer.
dropout_layer = nn.Dropout(dropout, inplace=True)
for _ in range(num_layers):
self.regularizer.append(dropout_layer)
self.num_layers = num_layers
def forward(self, input, prev):
"""
:param input: (batch_size, input_size)
:param prev: tuple of (h0, c0), each has size (batch, hidden_size, num_layers)
"""
next_hidden = []
next_cell = []
if prev is None:
prev = (
input.new(input.size(0), self.lstm[0].hidden_size, self.num_layers).fill_(0),
input.new(input.size(0), self.lstm[0].hidden_size, self.num_layers).fill_(0),
)
for i in range(self.num_layers):
prev_hidden_i = prev[0][:, :, i]
prev_cell_i = prev[1][:, :, i]
if i == 0:
next_hidden_i, next_cell_i = self.lstm[i](input, (prev_hidden_i, prev_cell_i))
else:
# Only apply regularizer to hidden state (but not the cell state)
input_im1 = self.regularizer[i](input_im1)
next_hidden_i, next_cell_i = self.lstm[i](input_im1, (prev_hidden_i, prev_cell_i))
next_hidden += [next_hidden_i]
next_cell += [next_cell_i]
input_im1 = next_hidden_i
next_hidden = torch.stack(next_hidden).permute(1, 2, 0)
next_cell = torch.stack(next_cell).permute(1, 2, 0)
return next_hidden, next_cell
class LSTMComposition(nn.Module):
def __init__(self, dim: int, dropout: float, layernorm: bool):
super(LSTMComposition, self).__init__()
self.dim = dim
self.rnn = nn.LSTM(dim, dim, bidirectional=True, batch_first=True)
if layernorm:
self.output = nn.Sequential(
nn.LayerNorm(normalized_shape=dim * 2),
nn.Linear(dim * 2, dim),
# nn.LayerNorm(normalized_shape=dim),
nn.ReLU(),
)
else:
self.output = nn.Sequential(nn.Dropout(dropout, inplace=True), nn.Linear(dim * 2, dim), nn.ReLU())
# memo: not sure why this is necessary.
self.cache_size: int = 10000
self.batch_index = torch.arange(0, self.cache_size, dtype=torch.long) # cache with sufficient number.
def forward(self, children, ch_lengths, nt, nt_id, stack_state):
"""
:param children: (batch_size, max_num_children, input_dim)
:param ch_lengths: (batch_size)
:param nt: (batch_size, input_dim)
:param nt_id: (batch_size)
"""
lengths = ch_lengths + 2
nt = nt.unsqueeze(1)
elems = torch.cat([nt, children, torch.zeros_like(nt)], dim=1)
# elems[self.batch_index[: elems.size(0)], lengths - 1] = nt.squeeze(1)
if elems.size(0) < self.cache_size:
elems[self.batch_index[: elems.size(0)], lengths - 1] = nt.squeeze(1)
else:
elems[torch.arange(0, elems.size(0), dtype=torch.long, device=children.device), lengths - 1] = nt.squeeze(1)
packed = pack_padded_sequence(elems, lengths.int().cpu(), batch_first=True, enforce_sorted=False)
h, _ = self.rnn(packed)
h, _ = pad_packed_sequence(h, batch_first=True)
gather_idx = (lengths - 2).unsqueeze(1).expand(-1, h.size(-1)).unsqueeze(1)
fwd = h.gather(1, gather_idx).squeeze(1)[:, : self.dim]
bwd = h[:, 1, self.dim :]
c = torch.cat([fwd, bwd], dim=1)
return self.output(c), None, None
class AttentionComposition(nn.Module):
def __init__(self, w_dim: int, dropout: float, layernorm: bool, num_labels: int = 10):
super(AttentionComposition, self).__init__()
self.w_dim = w_dim
self.num_labels = num_labels
# Set regularizer:
if layernorm:
self.nt_emb2_regularizer = nn.LayerNorm(normalized_shape=w_dim * 2)
self.weighted_child_regularizer = nn.LayerNorm(normalized_shape=w_dim * 2)
else:
dropout_layer = nn.Dropout(dropout, inplace=True)
self.nt_emb2_regularizer = dropout_layer
self.weighted_child_regularizer = dropout_layer
self.rnn = nn.LSTM(w_dim, w_dim, bidirectional=True, batch_first=True)
self.V = nn.Linear(2 * w_dim, 2 * w_dim, bias=False)
self.nt_emb = nn.Embedding(num_labels, w_dim) # o_nt in the Kuncoro et al. (2017)
self.nt_emb2 = nn.Sequential(
nn.Embedding(num_labels, w_dim * 2), self.nt_emb2_regularizer
) # t_nt in the Kuncoro et al. (2017)
self.gate = nn.Sequential(nn.Linear(w_dim * 4, w_dim * 2), nn.Sigmoid())
self.output = nn.Sequential(nn.Linear(w_dim * 2, w_dim), nn.ReLU())
def forward(self, children, ch_lengths, nt, nt_id, stack_state): # children: (batch_size, n_children, w_dim)
packed = pack_padded_sequence(children, ch_lengths.int().cpu(), batch_first=True, enforce_sorted=False)
h, _ = self.rnn(packed)
h, _ = pad_packed_sequence(h, batch_first=True) # (batch, n_children, 2*w_dim)
rhs = torch.cat([self.nt_emb(nt_id), stack_state], dim=1) # (batch_size, w_dim*2, 1)
logit = (self.V(h) * rhs.unsqueeze(1)).sum(-1) # equivalent to bmm(self.V(h), rhs.unsqueeze(-1)).squeeze(-1)
len_mask = (
ch_lengths.new_zeros(children.size(0), 1) + torch.arange(children.size(1), device=children.device)
) >= ch_lengths.unsqueeze(1)
logit[len_mask] = -float("inf")
attn = F.softmax(logit, -1)
weighted_child = (h * attn.unsqueeze(-1)).sum(1)
weighted_child = self.weighted_child_regularizer(weighted_child)
nt2 = self.nt_emb2(nt_id) # (batch_size, w_dim)
gate_input = torch.cat([nt2, weighted_child], dim=-1)
g = self.gate(gate_input) # (batch_size, w_dim)
c = g * nt2 + (1 - g) * weighted_child # (batch_size, w_dim)
return self.output(c), attn, g
class GeneralizedActionFixedStack:
def __init__(
self,
initial_hidden: tuple[torch.Tensor, torch.Tensor],
stack_size: int,
input_size: int,
batch_size: int,
beam_size: int,
sample_size: int,
):
"""
initial_hidden: pair of next_hidden and next_cell of size [(batch_size, hidden_size, layer), (batch_size, hidden_size, layer)]
"""
super(GeneralizedActionFixedStack, self).__init__()
device = initial_hidden[1].device
hidden_size = initial_hidden[0].size(-2)
num_layers = initial_hidden[0].size(-1)
assert initial_hidden[0].size(0) == batch_size
parallel_size = (batch_size, sample_size, beam_size)
self.batch_index = (
(
torch.arange(0, batch_size, dtype=torch.long, device=device)
.unsqueeze(1)
.expand(-1, sample_size * beam_size)
.reshape(-1)
),
torch.cat(
[
torch.arange(0, sample_size, dtype=torch.long, device=device)
.unsqueeze(1)
.expand(-1, beam_size)
.reshape(-1)
for _ in range(batch_size)
]
),
torch.cat(
[torch.arange(0, beam_size, dtype=torch.long, device=device) for _ in range(batch_size * sample_size)]
),
)
# self.batch_size = initial_hidden[0].size(0)
self.batch_size = batch_size
self.beam_size = beam_size
self.sample_size = sample_size
self.stack_size = stack_size
self.input_size = input_size
# self.max_comp_nodes = max_comp_nodes
self.hidden_size = hidden_size
self.num_layers = num_layers
self.pointer = torch.zeros(parallel_size, dtype=torch.long, device=device) # word pointer
self.top_position = torch.zeros(parallel_size, dtype=torch.long, device=device) # stack top position
self.hiddens = initial_hidden[0].new_zeros(
parallel_size + (stack_size + 1, hidden_size, num_layers), device=device
)
self.cells = initial_hidden[0].new_zeros(
parallel_size + (stack_size + 1, hidden_size, num_layers), device=device
)
self.trees = initial_hidden[0].new_zeros(parallel_size + (stack_size, input_size), device=device)
# self.hiddens[:, :, 0, 0] = initial_hidden[0]
# self.cells[:, :, 0, 0] = initial_hidden[1]
self.hiddens[:, :, 0, 0] = initial_hidden[0].unsqueeze(1) # Need to add sample dimension.
self.cells[:, :, 0, 0] = initial_hidden[1].unsqueeze(1) # Need to add sample dimension.
self.nt_index = torch.zeros(parallel_size + (stack_size,), dtype=torch.long, device=device)
self.nt_ids = torch.zeros(parallel_size + (stack_size,), dtype=torch.long, device=device)
self.nt_index_pos = (
torch.tensor([-1], dtype=torch.long, device=device).expand(parallel_size).clone()
) # default is -1 (0 means zero-dim exists)
self.attrs = [
"pointer",
"top_position",
"hiddens",
"cells",
"trees",
"nt_index",
"nt_ids",
"nt_index_pos",
]
# TODO: deal with beam width for efficiency...?
def hidden_head(self, offset: int = 0, batches: tuple[torch.Tensor, ...] | None = None) -> torch.Tensor:
assert offset >= 0
if batches is None:
return self.hiddens[
self.batch_index + (self.top_position.view(-1) - offset,)
] # (batches, hidden_size, num_layers)
else:
return self.hiddens[batches + (self.top_position[batches] - offset,)] # (batches, hidden_size, num_layers)
def cell_head(self, offset: int = 0, batches: tuple[torch.Tensor, ...] | None = None) -> torch.Tensor:
assert offset >= 0
if batches is None:
return self.cells[self.batch_index + ((self.top_position.view(-1) - offset),)]
else:
return self.cells[batches + (self.top_position[batches] - offset,)]
def do_shift(
self,
shift_batches: tuple[torch.Tensor, ...], # (batch, sample, beam)
shifted_embs: torch.Tensor, # (batches, input_size)
):
# First check if stack size is enough.
if (self.top_position[shift_batches] >= self.stack_size).any():
# stack.top_position is equall to the number of elements on the stack.
logger.warning("Stack is already full!!!! Cannot SHIFT anymore!!!!")
raise StackIndexError
assert shifted_embs.size() == (shift_batches[0].size(0), self.input_size)
# Update stack-like structures.
# top_position here is the position to be inserted.
self.trees[shift_batches + (self.top_position[shift_batches],)] = shifted_embs
self.pointer[shift_batches] = self.pointer[shift_batches] + 1
# top_position here is the position to be inserted next.
self.top_position[shift_batches] = self.top_position[shift_batches] + 1
def do_nt(
self,
nt_batches: tuple[torch.Tensor, ...],
nt_embs: torch.Tensor,
nt_ids: torch.Tensor,
nt_pos: torch.Tensor,
):
# First check if stack size is enough.
if (self.top_position[nt_batches] >= self.stack_size).any():
# stack.top_position is equall to the number of elements on the stack.
logger.warning("Stack is already full!!!! Cannot NT anymore!!!!")
print(f"{nt_batches=}")
raise StackIndexError
# Update stack-like structures.
# Update stack tree.
# Note the offset of stack.top_position; top_position is equall to the number of elements on the stack.
insert_nt_idx = self.top_position[nt_batches] - nt_pos
assert insert_nt_idx.size() == (nt_batches[0].size(0),)
num_elems_to_move = nt_pos
max_num_elems = num_elems_to_move.max().item()
elem_idx_order = (
torch.arange(max_num_elems, device=insert_nt_idx.device)
.unsqueeze(0)
# .repeat(insert_nt_idx.size(0), 1)
.expand(
insert_nt_idx.size(0), -1
) # Since elem_idx_order is only used for reference (i.e., not written to), expand can be used (without cloning) instead of repeat to avoid memory copying.
) # (nt_batch_size, max_num_elems)
assert elem_idx_order.size() == (nt_batches[0].size(0), max_num_elems)
nt_batches_for_move = convert_to_advanced_index(
batch_index=nt_batches,
mask=elem_idx_order < num_elems_to_move.unsqueeze(-1),
start_idx=insert_nt_idx,
)
nt_batches_for_move_tgt = nt_batches_for_move[:-1] + (nt_batches_for_move[-1] + 1,)
# First, shift.
self.trees[nt_batches_for_move_tgt] = self.trees[nt_batches_for_move]
# Then, insert.
self.trees[nt_batches + (insert_nt_idx,)] = nt_embs
self.nt_index_pos[nt_batches] = self.nt_index_pos[nt_batches] + 1
self.nt_ids[nt_batches + (self.nt_index_pos[nt_batches],)] = nt_ids
self.top_position[nt_batches] = self.top_position[nt_batches] + 1
self.nt_index[nt_batches + (self.nt_index_pos[nt_batches],)] = insert_nt_idx + 1
def do_reduce(self, reduce_batches, new_child):
# Update stack-like structures.
prev_nt_position = self.nt_index[reduce_batches + (self.nt_index_pos[reduce_batches],)]
child_length = self.top_position[reduce_batches] - prev_nt_position
self.trees[reduce_batches + (prev_nt_position - 1,)] = new_child
# Update pointers/positions.
# +1 is for the reduced nt.
self.nt_index_pos[reduce_batches] = self.nt_index_pos[reduce_batches] - 1
self.top_position[reduce_batches] = prev_nt_position
def collect_reduced_children(self, reduce_batches):
"""
:param reduce_batches: Tuple of idx tensors (output of non_zero()).
"""
nt_index_pos = self.nt_index_pos[reduce_batches]
prev_nt_position = self.nt_index[reduce_batches + (nt_index_pos,)]
reduced_nt_ids = self.nt_ids[reduce_batches + (nt_index_pos,)]
reduced_nts = self.trees[reduce_batches + (prev_nt_position - 1,)]
child_length = self.top_position[reduce_batches] - prev_nt_position
max_ch_length = child_length.max()
child_idx = prev_nt_position.unsqueeze(1) + torch.arange(max_ch_length, device=prev_nt_position.device)
child_idx[child_idx >= self.stack_size] = (
self.stack_size - 1
) # ceiled at maximum stack size (exceeding this may occur for some batches, but those should be ignored safely.)
child_idx = child_idx.unsqueeze(-1).expand(
-1, -1, self.trees.size(-1)
) # (num_reduced_batch, max_num_child, input_dim)
reduced_children = torch.gather(self.trees[reduce_batches], 1, child_idx)
return reduced_children, child_length, reduced_nts, reduced_nt_ids
def update_hidden(self, new_hidden, new_cell, no_nop_batches):
# debug
# print(f"{self.hiddens.size()=}")
# print(f"{no_nop_batches=}")
# print(f"{new_hidden.size()=}")
# debug
# Do nothing for nop actions (e.g., PAD).
self.hiddens[no_nop_batches + (self.top_position[no_nop_batches],)] = new_hidden
self.cells[no_nop_batches + (self.top_position[no_nop_batches],)] = new_cell
def move_beams(self, self_move_idxs, other: "GeneralizedActionFixedStack", move_idxs):
self.pointer[self_move_idxs] = other.pointer[move_idxs]
self.top_position[self_move_idxs] = other.top_position[move_idxs]
self.hiddens[self_move_idxs] = other.hiddens[move_idxs]
self.cells[self_move_idxs] = other.cells[move_idxs]
self.trees[self_move_idxs] = other.trees[move_idxs]
self.nt_index[self_move_idxs] = other.nt_index[move_idxs]
self.nt_ids[self_move_idxs] = other.nt_ids[move_idxs]
self.nt_index_pos[self_move_idxs] = other.nt_index_pos[move_idxs]
class ActionPath:
def __init__(
self,
batch_size: int,
beam_size: int,
sample_size: int,
max_actions: torch.Tensor, # (batch_size,) maximum number of actions allowed for each batch.
padding_idx: int,
device: str,
):
super(ActionPath, self).__init__()
self.padding_idx = padding_idx
parallel_size = (batch_size, sample_size, beam_size)
max_actions_max = max_actions.max()
self.max_actions = max_actions # (batch_size,)
self.actions = torch.full(
parallel_size
+ (
max_actions_max + 1,
), # +1 is for the first <PAD> action to deal with existence of prev_actions for the first time step.
padding_idx,
dtype=torch.long,
device=device,
)
self.actions_pos = self.actions.new_zeros(parallel_size)
self.attrs = ["actions", "actions_pos"]
def move_beams(self, self_idxs, source, source_idxs):
self.actions[self_idxs] = source.actions[source_idxs]
self.actions_pos[self_idxs] = source.actions_pos[source_idxs]
def add(self, actions, active_idxs):
# action_pos should be updated before actions to correctly hold prev_actions.
self.actions_pos[active_idxs] += 1
self.actions[active_idxs + (self.actions_pos[active_idxs],)] = actions[active_idxs]
class BeamItems:
def __init__(
self,
stack: GeneralizedActionFixedStack,
max_actions: torch.Tensor, # (batch_size,)
padding_idx: int, # idx for <PAD> action.
start_empty: bool,
):
super(BeamItems, self).__init__()
self.batch_size = stack.batch_size
self.beam_size = stack.beam_size
self.sample_size = stack.sample_size
self.stack = stack
self.scores = (
torch.tensor([-float("inf")], device=stack.hiddens.device)
.expand(self.batch_size, self.sample_size, self.beam_size)
.clone()
)
# Log probs of lastly shifted token.
self.last_token_log_probs = (
torch.tensor([-float("inf")], device=stack.hiddens.device)
.expand(self.batch_size, self.sample_size, self.beam_size)
.clone()
)
# Fill the first element with 0.
if not start_empty:
self.scores[..., 0] = 0
self.last_token_log_probs[..., 0] = 0
self.action_path = ActionPath(
batch_size=self.batch_size,
beam_size=self.beam_size,
sample_size=self.sample_size,
max_actions=max_actions,
padding_idx=padding_idx,
device=stack.hiddens.device,
)
# Beams should not be empty at first (i.e., must have at least size 1).
if not start_empty:
self.active_widths = self.scores.new_ones((self.batch_size, self.sample_size), dtype=torch.long)
else:
self.active_widths = self.scores.new_zeros((self.batch_size, self.sample_size), dtype=torch.long)
@property
def actions(self):
return self.action_path.actions
@property
def actions_pos(self):
return self.action_path.actions_pos
def active_idxs(self) -> tuple[torch.Tensor, ...]:
"""
:return (batch_idxs, sample_idxs, beam_idxs): All active idxs according to active beam sizes for each batch and sample defined by self.beam_widths.
"""
return self.active_idx_mask().nonzero(as_tuple=True)
def active_idx_mask(self) -> torch.Tensor:
order = torch.arange(self.beam_size, device=self.active_widths.device)
return order < self.active_widths.unsqueeze(-1)
def move_elements(
self,
source: "BeamItems",
self_idxs: tuple[
torch.Tensor,
torch.Tensor,
torch.Tensor,
], # (batch_indices, sample_indicies, beam_indices)
source_idxs: tuple[
torch.Tensor,
torch.Tensor,
torch.Tensor,
],
# new_scores=None,
):
self.scores[self_idxs] = source.scores[source_idxs]
self.last_token_log_probs[self_idxs] = source.last_token_log_probs[source_idxs]
self.stack.move_beams(self_idxs, source.stack, source_idxs)
self.action_path.move_beams(self_idxs, source.action_path, source_idxs)
def do_action(
self,
actions: torch.Tensor, # (batch_size, sample_size, beam_size)
):
# Update action_path.
self.action_path.add(actions, self.active_idxs())
def get_best_item_mask(
self,
) -> torch.Tensor: # (batch_size, sample_size, beam_size)
inactive_mask = torch.arange(self.beam_size, dtype=torch.long, device=self.scores.device).unsqueeze(0).expand(
self.batch_size, self.sample_size, -1
) >= self.active_widths.unsqueeze(-1)
scores = self.scores.clone().detach()
# Set -inf for inactive and inactive beam items.
scores[inactive_mask] = -float("inf")
best_beam_item_idxs = scores.argmax(dim=-1, keepdim=True)
assert best_beam_item_idxs.size() == (self.batch_size, self.sample_size, 1)
# Calculate best action mask.
best_beam_item_mask = (
torch.arange(self.beam_size, device=self.scores.device).view(1, 1, self.beam_size) == best_beam_item_idxs
)
assert best_beam_item_mask.size() == (
self.batch_size,
self.sample_size,
self.beam_size,
)
# debug
# logger.warning(f"{self.scores=}")
# logger.warning(f"{best_beam_item_mask=}")
# debug
return best_beam_item_mask
# Mainly for debug.
def get_beam_actions(self, action_dict: GeneralizedActionDict) -> list[list[list[list[str]]]]:
beam_actions = [
[
[
[
action_dict.i2a(a_id)
for a_id in self.actions[
batch_i,
sample_i,
beam_i,
: self.actions_pos[batch_i, sample_i, beam_i] + 1,
]
]
for beam_i in range(self.beam_size)
]
for sample_i in range(self.sample_size)
]
for batch_i in range(self.batch_size)
]
return beam_actions
class GeneralizedActionRNNGCell(nn.Module):
"""
RNNGCell receives next action and input word embedding, do action, and returns next updated hidden states.
"""
def __init__(
self,
input_size: int,
hidden_size: int,
num_layers: int,
vocab_size: int,
vocab_padding_idx: int,
dropout: float,
layernorm: bool,
action_dict: GeneralizedActionDict,
attention_composition: bool,
):
super(GeneralizedActionRNNGCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
# Set regularizer.
if layernorm:
self.initial_emb_regularizer = nn.LayerNorm(normalized_shape=input_size)
self.nt_emb_regularizer = nn.LayerNorm(normalized_shape=input_size)
self.token_emb_regularizer = nn.LayerNorm(normalized_shape=input_size)
self.output_regularizer = nn.LayerNorm(normalized_shape=hidden_size)
else:
dropout_layer = nn.Dropout(dropout, inplace=True)
self.initial_emb_regularizer = dropout_layer
self.nt_emb_regularizer = dropout_layer
self.token_emb_regularizer = dropout_layer
self.output_regularizer = dropout_layer
self.nt_emb = nn.Sequential(nn.Embedding(action_dict.num_nts, input_size), self.nt_emb_regularizer)
self.token_emb = nn.Sequential(
nn.Embedding(
vocab_size,
input_size,
padding_idx=vocab_padding_idx,
),
self.token_emb_regularizer,
)
self.stack_rnn = MultiLayerLSTMCell(input_size, hidden_size, num_layers, dropout=dropout, layernorm=layernorm)
self.output = nn.Sequential(self.output_regularizer, nn.Linear(hidden_size, input_size), nn.ReLU())
self.composition = (
AttentionComposition(
w_dim=input_size,
dropout=dropout,
layernorm=layernorm,
num_labels=action_dict.num_nts,
)
if attention_composition
else LSTMComposition(dim=input_size, dropout=dropout, layernorm=layernorm)
)
self.initial_emb = nn.Sequential(nn.Embedding(1, input_size), self.initial_emb_regularizer)
self.action_dict = action_dict
def get_initial_hidden(self, x) -> torch.Tensor:
"""
x: (batch_size, sent_len?)
Return: hidden and cell: [(batch_size, hidden_size, num_layers), (batch_size, hidden_size, num_layers)]
Note that the returned hidden_states do not need sample/beam dimension because the same values are used.
"""
iemb = self.initial_emb(x.new_zeros(x.size(0), dtype=torch.long)) # (batch_size, input_size)
return self.stack_rnn(iemb, None)
def forward(
self,
x: torch.Tensor, # (batch_size, sent_len)
actions: torch.Tensor, # (batch_size, sample_size, beam_size)
stack: GeneralizedActionFixedStack,
):
"""
Similar to update_stack_rnn.
:param word_vecs: (batch_size, sent_len, input_size)
:param actions: (batch_size, 1)
"""
reduce_batches = (actions == self.action_dict.reduce_idx).nonzero(as_tuple=True)
nt_batches = ((self.action_dict.nt_begin_idx <= actions) * (actions <= self.action_dict.nt_end_idx)).nonzero(
as_tuple=True
)
shift_batches = (actions == self.action_dict.shift_idx).nonzero(as_tuple=True)
no_nop_batches = (actions != self.action_dict.padding_idx).nonzero(as_tuple=True)
# debug
# logger.warning(f"{actions.size()=}")
# logger.warning(f"{no_nop_batches=}")
# debug
new_input = stack.trees.new_zeros(
stack.hiddens.size()[:-3] + (self.input_size,)
) # (batch_size, sample_size, beam_size, input_size)
# First fill in trees. Then, gather those added elements in a column, which become
# the input to stack_rnn.
if shift_batches[0].size(0) > 0:
token_ids = x[shift_batches[:1] + (stack.pointer[shift_batches],)]
token_embs = self.token_emb(token_ids).to(new_input.dtype)
stack.do_shift(shift_batches, token_embs)
new_input[shift_batches] = token_embs
if nt_batches[0].size(0) > 0:
nt_ids = (actions[nt_batches] - self.action_dict.nt_begin_idx) // (self.action_dict.num_actions_for_each_nt)
nt_pos = (actions[nt_batches] - self.action_dict.nt_begin_idx) % (self.action_dict.num_actions_for_each_nt)
nt_embs = self.nt_emb(nt_ids).to(new_input.dtype)
stack.do_nt(nt_batches, nt_embs, nt_ids, nt_pos)
new_input[nt_batches] = nt_embs
if reduce_batches[0].size(0) > 0:
children, ch_lengths, reduced_nt, reduced_nt_ids = stack.collect_reduced_children(reduce_batches)
if isinstance(self.composition, AttentionComposition):
hidden_head = stack.hidden_head(batches=reduce_batches)[
:, :, -1
] # The return of stack.hidden_head has the size (batches, hidden_size, num_layers)
stack_h = self.output(hidden_head)
else:
stack_h = None
new_child, _, _ = self.composition(children, ch_lengths, reduced_nt, reduced_nt_ids, stack_h)
stack.do_reduce(reduce_batches, new_child)
new_input[reduce_batches] = new_child.to(new_input.dtype)
# Input for rnn should be (beam_size, input_size). During beam search, new_input has different size.
new_hidden, new_cell = self.stack_rnn(
new_input[no_nop_batches],
(stack.hidden_head(offset=1, batches=no_nop_batches), stack.cell_head(offset=1, batches=no_nop_batches)),
)
# Do nothing for nop actions (e.g., PAD).
stack.update_hidden(new_hidden, new_cell, no_nop_batches)
# The shape of stack.hidden_head() is (batch_size, hidden_size, num_layers)
return stack.hidden_head()[..., -1] # (batch_size, hidden_size)
# Deterministic version of sample_beam_items.
def sample_beam_items_deterministic(
flattened_logits: torch.Tensor, # (B*, M) where M is the number of all candidates.
max_num_to_sample: int,
) -> torch.Tensor: # Ordered idices of sampled items of size (B*, N) where N <= num_to_sample (N < num_to_sample if there are few candidates).
# Get sizes.
# Sample top-k.
# Simply deterministically take the top-k largetst items.
sampled_items = flattened_logits.topk(k=max_num_to_sample, dim=-1).indices
return sampled_items
@torch.compile
def get_until_kth_mask(
input: torch.Tensor, # (*, N)
k_tensor: torch.Tensor, # (*,)
) -> torch.Tensor: # (*, N)
""""""
int_input = input.int() * 2
count_so_far = int_input.cumsum_(dim=-1)
added_count_so_far = torch.where(
condition=input, input=count_so_far, other=count_so_far + 1
) # This is necessary to avoid giving True to the elements on the right of k-th True element in input.
return added_count_so_far <= (k_tensor.unsqueeze(-1) * 2)
def get_finished_word_sync_step_batches(
open_beam: BeamItems,
step_complete_beam: BeamItems,
word_sync_step_limit: int,
tmp_step_count: int,
) -> torch.Tensor:
finished_word_sync_step_batches = (
(open_beam.active_widths == 0) # In case there is no candidates.
+ (
step_complete_beam.active_widths >= step_complete_beam.beam_size
) # In case the step_complete_beam is already full.
+ (tmp_step_count + 1 >= word_sync_step_limit)
* (
step_complete_beam.active_widths > 0
) # In case inner steps exceeds the limit and step_complete_beam is not empty except when all tokens are already shifted (i.e., the step complete action is FINISH).
)
return finished_word_sync_step_batches
class GeneralizedActionFixedStackRNNG(nn.Module):
def __init__(
self,
action_dict: GeneralizedActionDict,
vocab_size: int = 100,
vocab_padding_idx: int = 0,
w_dim: int = 20,
h_dim: int = 20,
num_layers: int = 1,
dropout: float = 0.0,
layernorm: bool = True,
attention_composition: bool = False,
):
super(GeneralizedActionFixedStackRNNG, self).__init__()
self.action_dict = action_dict
self.vocab_padding_idx = vocab_padding_idx
# Set regularizer.
if layernorm:
self.emb_regularizer = nn.LayerNorm(normalized_shape=w_dim)
else:
dropout_layer = nn.Dropout(dropout, inplace=True)
self.emb_regularizer = dropout_layer
self.vocab_size = vocab_size
self.rnng = GeneralizedActionRNNGCell(
input_size=w_dim,
hidden_size=h_dim,
num_layers=num_layers,
vocab_size=vocab_size,
vocab_padding_idx=vocab_padding_idx,
dropout=dropout,
layernorm=layernorm,
action_dict=self.action_dict,
attention_composition=attention_composition,
)
self.vocab_mlp = nn.Linear(w_dim, vocab_size)
self.num_layers = num_layers
self.action_size = action_dict.action_size
self.action_mlp = nn.Linear(w_dim, self.action_size)
self.input_size = w_dim
self.hidden_size = h_dim
self.vocab_mlp.weight = self.rnng.token_emb[0].weight
def get_next_action_candidates(
self,
beam: BeamItems,
sent_lengths: torch.Tensor, # (batch_size,)
token_ids: torch.Tensor, # (batch_size, sent_len)
finished_word_sync_step_batches: torch.Tensor, # (batch_size, sample_size) this is necessary to avoid applying word_sync_step_limit to FINISH step.
word_sync_step: int,
) -> tuple[
torch.Tensor, # (batch_size, sample_size, beam_size, action_size) each entry has the score (log probs) for next actions.
torch.Tensor, # (batch_size, sample_size, beam_size, action_size) token log probs.
]:
# Calculate scores for next action candidates.
# Take the hidden vector of the last layer.
# Note that the size of hidden_head() is (batches, hidden_size, num_layers).
# Here, batches is the same as batch_size * sample_size * beam_size.
# TODO: deal with beam width for efficiency...?
# But in practice, almost all of the beams are filled by just after one inference step (because there are many possible next actions).
hiddens = self.rnng.output(beam.stack.hidden_head()[:, :, -1])
# Calculate invalid action masks.
invalid_action_mask = self.get_invalid_action_mask(
beam=beam,
sent_lengths=sent_lengths,
) # (batch_size, sample_size, beam_size, num_actions)
# Calcualte action logits.
action_logits: torch.Tensor = (
self.action_mlp(hiddens).view(beam.batch_size, beam.sample_size, beam.beam_size, -1)
# .float()
)
# This is necessary since the log_softmax of inactive beams would be NAN (because all actions are invalid and comes with -inf logits)
# Somehow, we need to use torch.where because the gradint calculation does not work when the output of log_soft_max is overwritten(?) (not really sure though).
# Here, to align with supervised training loss, we apply invalid_action_mask after calculating log probs.
next_action_log_probs = torch.where(
condition=(
finished_word_sync_step_batches.logical_not().view(beam.batch_size, beam.sample_size, 1)
* beam.active_idx_mask()
)
.unsqueeze(-1)
.expand(-1, -1, -1, self.action_dict.action_size)
* invalid_action_mask.logical_not(),
input=torch.nn.functional.log_softmax(input=action_logits, dim=-1),
other=-float("inf"),
)
# debug
assert (
finished_word_sync_step_batches.logical_not().view(beam.batch_size, beam.sample_size, 1)
* beam.active_idx_mask()
).unsqueeze(-1).expand(-1, -1, -1, self.action_dict.action_size).size() == invalid_action_mask.size()
# debug
# Next, calcualte token prediction log probs.
# Calculate token probabilities.
assert word_sync_step < token_ids.size(1)
next_tokens = token_ids[:, word_sync_step]
# Simply inserting -inf to padding_idx does not work because the substitution blocks the gradient flow.
token_logits = self.vocab_mlp(hiddens).view(beam.batch_size, beam.sample_size, beam.beam_size, -1)
token_logits[..., self.vocab_padding_idx] = -float("inf")
token_neg_ll = torch.nn.functional.cross_entropy(
input=token_logits.view(beam.batch_size * beam.sample_size * beam.beam_size, self.vocab_size),
target=next_tokens.view(beam.batch_size, 1, 1).repeat(1, beam.sample_size, beam.beam_size).view(-1),
reduction="none",
ignore_index=self.vocab_padding_idx,
).view(beam.batch_size, beam.sample_size, beam.beam_size)
token_log_probs = -token_neg_ll
# In-place operation.
next_action_log_probs.index_add_(
dim=-1,
index=torch.tensor(
[self.action_dict.shift_idx], dtype=torch.long, device=token_ids.device
), # BTW, this index must not be a scalar tensor (but a single dimension tensor) when one wants to compile a function containing this part.
source=token_log_probs.unsqueeze(-1),
)
# return next_action_log_probs, token_log_probs, torch.tensor([])
return next_action_log_probs, token_log_probs
def step_word_sync_beam_search(
self,
x: torch.Tensor, # (batch_size, sent_len)
open_beam: BeamItems,
step_complete_beam: BeamItems,
sent_lengths: torch.Tensor, # (batch_size,)
min_shift_size: int,
finished_word_sync_step_batches: torch.Tensor, # (batch_size, sample_size) this is necessary to avoid applying word_sync_step_limit to FINISH step.
word_sync_step: int,
):
# TODO: only consider unfinished items (i.e., step_completed_beam.active_widths < beam_widths) for efficiency.
# Only use step_not_completed_beam here (because next action candidates are only taken from the items in step_not_completed_beam).
next_action_log_probs, token_log_probs = self.get_next_action_candidates(
beam=open_beam,
sent_lengths=sent_lengths,
token_ids=x,
finished_word_sync_step_batches=finished_word_sync_step_batches,
word_sync_step=word_sync_step,
)
assert next_action_log_probs.size() == (
open_beam.batch_size,
open_beam.sample_size,
open_beam.beam_size,
self.action_dict.action_size,
)
# Calcualte the scores used for beam transition (current beam item score + next action score).
next_beam_item_candidate_logits = open_beam.scores.unsqueeze(dim=-1) + next_action_log_probs
assert next_beam_item_candidate_logits.size() == (
open_beam.batch_size,
open_beam.sample_size,
open_beam.beam_size,
self.action_dict.action_size,
)
# Choose next beam items.
# Next, enumerate and sample only SHIFT actions.
# No need to explicitly flatten the candidates, because each beam item can have at most one shift action.
flattened_complete_action_candidate_logits = next_beam_item_candidate_logits[..., self.action_dict.shift_idx]
assert flattened_complete_action_candidate_logits.size() == (
open_beam.batch_size,
open_beam.sample_size,
open_beam.beam_size,
)
# Calculate number of shift actions forced to sample.
num_force_sample = torch.minimum(
torch.minimum(
step_complete_beam.beam_size - step_complete_beam.active_widths,
torch.tensor(min_shift_size, dtype=torch.long, device=x.device),
),
# Need to use the logits before clamp.
(next_beam_item_candidate_logits[..., self.action_dict.shift_idx] != -float("inf")).count_nonzero(dim=-1),
)
max_num_force_sample = num_force_sample.max().item()
# Force to sample actions to complete word sync beam step.
tmp_force_sampled_items = sample_beam_items_deterministic(
flattened_logits=flattened_complete_action_candidate_logits, max_num_to_sample=max_num_force_sample
)
# Recover the idxs for the full flattened candidates.
force_sampled_items = self.action_dict.shift_idx + tmp_force_sampled_items * self.action_dict.action_size
# Next, sample from remaining candidates.
# First, disable the logits for already sampled complete actions.
# TODO: this can be simpler by counting scores not equal to -float('inf')...?
force_num_sampled_mask = torch.arange(max_num_force_sample, device=next_action_log_probs.device).view(
1, 1, max_num_force_sample
) < num_force_sample.unsqueeze(-1)
force_sampled_batches = force_num_sampled_mask.nonzero(as_tuple=True)[:-1] + (
tmp_force_sampled_items[force_num_sampled_mask],
)
# TODO: this clone may not be necessary; this can be made simpler by using torch.scatter?