forked from Tiiiger/templm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_search_bart.py
2055 lines (1898 loc) · 85.7 KB
/
template_search_bart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
import torch.distributed as dist
import warnings
import logging
from tqdm.auto import trange, tqdm
import re
from transformers import BartForConditionalGeneration, BeamSearchScorer
from transformers.generation_beam_search import BeamHypotheses
from dataclasses import dataclass, field
from typing import Optional
from transformers.modeling_outputs import BaseModelOutput, Seq2SeqLMOutput
from transformers.file_utils import is_offline_mode, ModelOutput
from transformers.generation_beam_search import BeamScorer, BeamSearchScorer
from transformers.generation_stopping_criteria import (
MaxLengthCriteria,
MaxNewTokensCriteria,
MaxTimeCriteria,
StoppingCriteriaList,
validate_stopping_criteria,
)
from transformers.generation_logits_process import (
EncoderNoRepeatNGramLogitsProcessor,
ForcedBOSTokenLogitsProcessor,
ForcedEOSTokenLogitsProcessor,
HammingDiversityLogitsProcessor,
InfNanRemoveLogitsProcessor,
LogitsProcessorList,
MinLengthLogitsProcessor,
NoBadWordsLogitsProcessor,
NoRepeatNGramLogitsProcessor,
PrefixConstrainedLogitsProcessor,
RepetitionPenaltyLogitsProcessor,
TemperatureLogitsWarper,
TopKLogitsWarper,
TopPLogitsWarper,
)
from transformers.generation_utils import (
validate_stopping_criteria,
BeamSearchDecoderOnlyOutput,
BeamSearchEncoderDecoderOutput,
)
from collections import defaultdict, UserDict
import utils
logger = logging.getLogger(__name__)
class TemplateSearchBART(BartForConditionalGeneration):
"""
This class is created to modify the `generate` function of BART.
Unfortunately most code is duplicated from the parent class. Changes are marked.
This generate function now:
1. returns the most `num_beams` probable templates computed on all the input_ids
2. computes everything in batches under the hood
"""
def init_for_template_search(
self, tokenizer, full_data_field_dicts, hallucinate_aug
):
self.tokenizer = tokenizer
self.hallucinate_aug = hallucinate_aug
@torch.no_grad()
def generate(
self,
# CHANGE: add in `field_dicts` and `tokenizer` as required arguments
input_ids,
field_dicts,
# CHANGE: add inference batch size for internal batching,
inference_batch_size,
# CHANGE: add option to recompute log probs which save memory
recompute_log_prob,
# CHANGE: add in weighting,
input_weighting,
mode="template_search",
search_crit="prob",
max_length: Optional[int] = None,
min_length: Optional[int] = None,
do_sample: Optional[bool] = None,
early_stopping: Optional[bool] = None,
num_beams: Optional[int] = None,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
repetition_penalty: Optional[float] = None,
bad_words_ids=None,
bos_token_id: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int] = None,
length_penalty: Optional[float] = None,
no_repeat_ngram_size: Optional[int] = None,
encoder_no_repeat_ngram_size: Optional[int] = None,
num_return_sequences: Optional[int] = None,
max_time: Optional[float] = None,
max_new_tokens: Optional[int] = None,
decoder_start_token_id: Optional[int] = None,
use_cache: Optional[bool] = None,
num_beam_groups: Optional[int] = None,
diversity_penalty: Optional[float] = None,
prefix_allowed_tokens_fn=None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
output_scores: Optional[bool] = None,
return_dict_in_generate: Optional[bool] = None,
forced_bos_token_id: Optional[int] = None,
forced_eos_token_id: Optional[int] = None,
remove_invalid_values: Optional[bool] = None,
synced_gpus: Optional[bool] = None,
verbose=False,
**model_kwargs,
):
# set init values
if max_length is None and max_new_tokens is None:
# Both are None, default
max_length = self.config.max_length
elif max_length is not None and max_new_tokens is not None:
# Both are set, this is odd, raise a warning
warnings.warn(
"Both `max_length` and `max_new_tokens` have been set but they serve the same purpose.",
UserWarning,
)
max_length = max_length if max_length is not None else self.config.max_length
num_beams = num_beams if num_beams is not None else self.config.num_beams
num_beam_groups = (
num_beam_groups
if num_beam_groups is not None
else self.config.num_beam_groups
)
do_sample = do_sample if do_sample is not None else self.config.do_sample
num_return_sequences = (
num_return_sequences
if num_return_sequences is not None
else self.config.num_return_sequences
)
pad_token_id = (
pad_token_id if pad_token_id is not None else self.config.pad_token_id
)
bos_token_id = (
bos_token_id if bos_token_id is not None else self.config.bos_token_id
)
eos_token_id = (
eos_token_id if eos_token_id is not None else self.config.eos_token_id
)
output_scores = (
output_scores if output_scores is not None else self.config.output_scores
)
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict_in_generate = (
return_dict_in_generate
if return_dict_in_generate is not None
else self.config.return_dict_in_generate
)
# CHANGE: force `inference_batch_size` to be multiples of `num_beams`
inference_batch_size = (inference_batch_size // num_beams) * num_beams
model_kwargs["output_attentions"] = output_attentions
model_kwargs["output_hidden_states"] = output_hidden_states
if input_ids is None and "inputs_embeds" not in model_kwargs:
# init `input_ids` with bos_token_id
input_ids = self._prepare_input_ids_for_generation(
bos_token_id, model_kwargs.get("encoder_outputs")
)
if model_kwargs.get("attention_mask", None) is None:
# init `attention_mask` depending on `pad_token_id`
model_kwargs[
"attention_mask"
] = self._prepare_attention_mask_for_generation(
input_ids, pad_token_id, eos_token_id
)
# special case if pad_token_id is not defined
if pad_token_id is None and eos_token_id is not None:
logger.warning(
f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation."
)
pad_token_id = eos_token_id
# Storing encoder_input_ids for logits_processor that could use them
encoder_input_ids = input_ids if self.config.is_encoder_decoder else None
if self.config.is_encoder_decoder:
# add encoder_outputs to model_kwargs
# CHANGE: computing the encoder states in batch
all_last_hidden_states = []
encoder = self.get_encoder()
encoder_kwargs = {
argument: value
for argument, value in model_kwargs.items()
if not (
argument.startswith("decoder_") or argument.startswith("cross_attn")
)
}
for batch_start in range(0, input_ids.size(0), inference_batch_size):
batch_attention_mask = encoder_kwargs["attention_mask"][
batch_start : batch_start + inference_batch_size
].cuda()
batch_input_ids = input_ids[
batch_start : batch_start + inference_batch_size
].cuda()
batch_encoder_outputs = encoder(
batch_input_ids,
attention_mask=batch_attention_mask,
return_dict=True,
)
all_last_hidden_states.append(
batch_encoder_outputs.last_hidden_state.cpu()
)
all_last_hidden_states = torch.cat(all_last_hidden_states, dim=0)
batch_encoder_outputs.last_hidden_state = all_last_hidden_states
model_kwargs["encoder_outputs"] = batch_encoder_outputs
# set input_ids as decoder_input_ids
if "decoder_input_ids" in model_kwargs:
input_ids = model_kwargs.pop("decoder_input_ids")
else:
input_ids = self._prepare_decoder_input_ids_for_generation(
input_ids,
decoder_start_token_id=decoder_start_token_id,
bos_token_id=bos_token_id,
)
if "encoder_outputs" not in model_kwargs or not isinstance(
model_kwargs["encoder_outputs"], ModelOutput
):
raise ValueError(
"Make sure that `model_kwargs` include `encoder_outputs` of type `ModelOutput`."
)
if input_ids.shape[-1] >= max_length:
input_ids_string = (
"decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
)
logger.warning(
f"Input length of {input_ids_string} is {input_ids.shape[-1]}, but ``max_length`` is set to {max_length}."
"This can lead to unexpected behavior. You should consider increasing ``config.max_length`` or ``max_length``."
)
# determine generation mode
is_greedy_gen_mode = (
(num_beams == 1) and (num_beam_groups == 1) and do_sample is False
)
is_sample_gen_mode = (
(num_beams == 1) and (num_beam_groups == 1) and do_sample is True
)
is_beam_gen_mode = (
(num_beams > 1) and (num_beam_groups == 1) and do_sample is False
)
is_beam_sample_gen_mode = (
(num_beams > 1) and (num_beam_groups == 1) and do_sample is True
)
is_group_beam_gen_mode = (num_beams > 1) and (num_beam_groups > 1)
if num_beam_groups > num_beams:
raise ValueError(
"`num_beam_groups` has to be smaller or equal to `num_beams`"
)
if is_group_beam_gen_mode and do_sample is True:
raise ValueError(
"Diverse beam search cannot be used in sampling mode. Make sure that `do_sample` is set to `False`."
)
# set model_kwargs
model_kwargs["use_cache"] = use_cache
# get distribution pre_processing samplers
logits_processor = self._get_logits_processor(
repetition_penalty=repetition_penalty,
no_repeat_ngram_size=no_repeat_ngram_size,
encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,
encoder_input_ids=encoder_input_ids,
bad_words_ids=bad_words_ids,
min_length=min_length,
max_length=max_length,
eos_token_id=eos_token_id,
forced_bos_token_id=forced_bos_token_id,
forced_eos_token_id=forced_eos_token_id,
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
num_beams=num_beams,
num_beam_groups=num_beam_groups,
diversity_penalty=diversity_penalty,
remove_invalid_values=remove_invalid_values,
)
cur_len = input_ids.shape[-1]
stopping_criteria = self._get_stopping_criteria(
max_length=max_length,
max_time=max_time,
max_new_tokens=max_new_tokens,
start_length=cur_len,
)
# CHANGE: only support beam search so other modes are invalid
# if is_beam_gen_mode:
batch_size = input_ids.shape[0]
length_penalty = (
length_penalty if length_penalty is not None else self.config.length_penalty
)
early_stopping = (
early_stopping if early_stopping is not None else self.config.early_stopping
)
if num_return_sequences > num_beams:
raise ValueError(
"`num_return_sequences` has to be smaller or equal to `num_beams`."
)
if stopping_criteria.max_length is None:
raise ValueError("`max_length` needs to be a stopping_criteria for now.")
# CHANGE: we only keep one beam for the template on cpu
if mode == "beam_search":
beam_scorer = BeamSearchScorer(
batch_size=input_ids.size(0),
num_beams=num_beams,
device=self.device,
length_penalty=length_penalty,
do_early_stopping=early_stopping,
num_beam_hyps_to_keep=num_return_sequences,
)
elif mode == "template_search":
beam_scorer = TemplateSearchScorer(
batch_size=1,
num_beams=num_beams,
device=self.device,
length_penalty=length_penalty,
do_early_stopping=early_stopping,
num_beam_hyps_to_keep=num_return_sequences,
)
else:
raise ValueError
# interleave with `num_beams`
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids,
expand_size=num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
if mode == "template_search":
return self.template_search(
input_ids,
field_dicts,
inference_batch_size,
recompute_log_prob,
input_weighting,
search_crit,
beam_scorer,
max_length=max_length,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
output_scores=output_scores,
return_dict_in_generate=return_dict_in_generate,
synced_gpus=synced_gpus,
verbose=verbose,
**model_kwargs,
)
elif mode == "beam_search":
return self.beam_search(
input_ids,
beam_scorer,
max_length=max_length,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
output_scores=output_scores,
return_dict_in_generate=return_dict_in_generate,
synced_gpus=synced_gpus,
**model_kwargs,
)
def assign_nonterminal_logits(
self,
next_token_scores,
beam_expanded_last_latent_tokens,
beam_expanded_last_surface_tokens,
beam_expanded_field_dicts,
beam_expanded_field_selection_dicts,
):
# CHANGE: this loops distributes the logits from terminal tokens to non-terminal tokens
for i in range(next_token_scores.size(0)):
last_latent_token = beam_expanded_last_latent_tokens[i].item()
last_surface_token = beam_expanded_last_surface_tokens[i].item()
# CONDITION: this is not None when last_latent_token is a field_token and is not the end of a field
next_special_token = self.tokenizer.next_field_token_map.get(
last_latent_token, None
)
# manually cutoff field tokens that are too long
if last_latent_token in self.tokenizer.field_cutoff_set:
next_special_token = None
sen_field_dict = beam_expanded_field_dicts[i]
sen_field_selection_dict = beam_expanded_field_selection_dicts[i]
assert not self.hallucinate_aug, "Hallucination Aug nor supported yet."
if next_special_token is not None:
# CONDITION: the previous token is not the last non-terminal token of the field
if next_special_token in sen_field_dict:
# We identify the corresponding terminal token and get its logits
if last_latent_token not in sen_field_selection_dict:
raise ValueError(
"Field not selected but appear in previous tokens."
)
previous_selected_indices = sen_field_selection_dict[
last_latent_token
]
temp_selected_indices = [
j
for j in previous_selected_indices
if sen_field_dict[next_special_token][j] != -1
]
candidate_tokens = [
sen_field_dict[next_special_token][j]
for j in temp_selected_indices
]
if len(candidate_tokens) == 0:
# CONDITION: the previous token is the last non-terminal of the field
next_token_scores[i] = -100
next_token_scores[i, next_special_token] = 0
sen_field_selection_dict[next_special_token] = (
previous_selected_indices[0],
)
continue
else:
previous_selected_indices = temp_selected_indices
candidate_scores = next_token_scores[i, candidate_tokens]
field_selected_score, field_selected_idx = candidate_scores.max(
dim=0
)
selected_token = candidate_tokens[field_selected_idx.item()]
selected_indices = []
for j in previous_selected_indices:
if sen_field_dict[next_special_token][j] == selected_token:
selected_indices.append(j)
next_token_scores[i, next_special_token] = (
field_selected_score + 1e-6
) # tie breaking
sen_field_selection_dict[next_special_token] = tuple(
selected_indices
)
# CONDITION: the previous token is the last non-terminal of the field
else:
# We force complete the rest by assigning all probability to the next
# non-terminal token (which doesn't have a corresponding terminal token)
next_token_scores[i] = -100
next_token_scores[i, next_special_token] = 0
# CONDITION: the previous token is a terminal token or is the end of a field (the last non-terminal token)
else:
# We compute the probability of entering each field
for field_start in self.tokenizer.field_start_set:
# CONDITION: input data has this field
if field_start in sen_field_dict:
candidate_scores = next_token_scores[
i, sen_field_dict[field_start]
]
field_selected_score, field_selected_idx = candidate_scores.max(
dim=0
)
next_token_scores[i, field_start] = (
field_selected_score + 1e-6
) # tie breaking
selected_token = sen_field_dict[field_start][
field_selected_idx.item()
]
selected_indices = []
for j in range(len(sen_field_dict[field_start])):
if sen_field_dict[field_start][j] == selected_token:
selected_indices.append(j)
sen_field_selection_dict[field_start] = tuple(selected_indices)
# CONDITION: input data doesn't have this field
else:
pass
return next_token_scores
def _compute_next_token_scores_batched(
self, model_inputs, batch_start, batch_size, logits_processor
):
batch_decoder_input_ids = model_inputs["decoder_input_ids"][
batch_start : batch_start + batch_size
].cuda()
batch_encoder_last_state = (
model_inputs["encoder_outputs"]
.last_hidden_state[batch_start : batch_start + batch_size]
.cuda()
)
batch_encoder_outputs = BaseModelOutput(
last_hidden_state=batch_encoder_last_state
)
batch_attention_mask = model_inputs["attention_mask"][
batch_start : batch_start + batch_size
].cuda()
batch_model_inputs = {
"decoder_input_ids": batch_decoder_input_ids,
"encoder_outputs": batch_encoder_outputs,
"attention_mask": batch_attention_mask,
}
batch_outputs = self(**batch_model_inputs, return_dict=True,)
batch_logprobs = batch_outputs.logits.log_softmax(dim=-1)
last_token_index = (
batch_decoder_input_ids.ne(self.tokenizer.pad_token_id).sum(dim=-1) - 1
)
next_token_scores = torch.stack(
[batch_logprobs[i, j] for i, j in enumerate(list(last_token_index))], dim=0,
)
next_token_scores = logits_processor(batch_decoder_input_ids, next_token_scores)
# next_token_scores[:, self.tokenizer.all_field_tokens_list] = -100
for i, last_token_i in enumerate(list(last_token_index)):
batch_logprobs[i, last_token_i] = 0
surface_sequence_scores = (
batch_logprobs[:, :-1]
.gather(index=batch_decoder_input_ids[:, 1:].unsqueeze(-1), dim=-1)
.squeeze(-1)
)
surface_sequence_scores = surface_sequence_scores * (
batch_decoder_input_ids[:, 1:].ne(self.tokenizer.pad_token_id)
)
surface_sequence_scores = surface_sequence_scores.sum(dim=-1)
last_surface_ids = torch.stack(
[
batch_decoder_input_ids[i, j]
for i, j in enumerate(list(last_token_index))
],
dim=0,
)
return next_token_scores, last_surface_ids, surface_sequence_scores
def compute_next_token_scores_batched(
self,
model_inputs,
latent_input_ids,
beam_expanded_field_dicts,
beam_expanded_field_selection_dicts,
inference_batch_size,
logits_processor,
surface_sequence_scores,
input_weighting,
search_crit,
is_first_step=False,
):
# CHANGE: logits are computed in batches.
num_examples = model_inputs["decoder_input_ids"].size(0)
last_latent_tokens = latent_input_ids[:, -1]
num_beams = last_latent_tokens.size(0)
total_batch_size = num_examples // num_beams
beam_expanded_last_latent_tokens = (
last_latent_tokens.unsqueeze(0)
.expand(total_batch_size, num_beams)
.reshape(-1)
)
all_next_token_scores = []
all_surface_sequence_scores = []
all_surface_sequence_scores_raw = []
latent_sequence_scores = torch.zeros(
num_beams * len(self.tokenizer), device="cuda"
)
# Precondition: inference_batch_size is a multiple of num_beams
for batch_start in range(0, num_examples, inference_batch_size):
(
next_token_scores,
batch_last_surface_ids,
batch_surface_sequence_scores,
) = self._compute_next_token_scores_batched(
model_inputs, batch_start, inference_batch_size, logits_processor
)
batch_last_latent_tokens = beam_expanded_last_latent_tokens[
batch_start : batch_start + inference_batch_size
]
real_batch_size = (
min(batch_start + inference_batch_size, num_examples) - batch_start
)
batch_field_dicts = [
beam_expanded_field_dicts[i]
for i in range(batch_start, batch_start + real_batch_size)
]
batch_field_selection_dicts = [
beam_expanded_field_selection_dicts[i]
for i in range(batch_start, batch_start + real_batch_size)
]
next_token_scores = self.assign_nonterminal_logits(
next_token_scores,
batch_last_latent_tokens,
batch_last_surface_ids,
batch_field_dicts,
batch_field_selection_dicts,
)
if is_first_step:
batch_surface_sequence_scores = surface_sequence_scores[
batch_start : batch_start + inference_batch_size
].cuda()
batch_surface_sequence_scores_raw = batch_surface_sequence_scores
batch_surface_sequence_scores = next_token_scores + batch_surface_sequence_scores.unsqueeze(
1
).expand_as(
next_token_scores
)
if search_crit == "prob_lennorm":
num_non_pad = (
model_inputs["decoder_input_ids"][
batch_start : batch_start + inference_batch_size
]
.ne(self.tokenizer.pad_token_id)
.sum(dim=-1, keepdim=True)
).cuda()
batch_surface_sequence_scores = (
batch_surface_sequence_scores / num_non_pad
)
batch_surface_sequence_scores = batch_surface_sequence_scores.view(
real_batch_size // num_beams, num_beams * next_token_scores.size(-1),
)
batch_input_weighting = (
input_weighting[
batch_start
// num_beams : (batch_start + real_batch_size)
// num_beams
]
.to(latent_sequence_scores.device)
.unsqueeze(1)
)
if search_crit in ["prob", "prob_lennorm"]:
latent_sequence_scores += (
batch_surface_sequence_scores.exp() * batch_input_weighting
).sum(dim=0)
elif search_crit == "log_prob":
latent_sequence_scores += (
batch_surface_sequence_scores * batch_input_weighting
).sum(dim=0)
else:
raise ValueError("invalid search criterion", search_crit)
if search_crit == "prob_lennorm":
batch_surface_sequence_scores = batch_surface_sequence_scores.view(
real_batch_size, next_token_scores.size(-1),
)
batch_surface_sequence_scores = (
batch_surface_sequence_scores * num_non_pad
)
batch_surface_sequence_scores = batch_surface_sequence_scores.view(
real_batch_size // num_beams,
num_beams * next_token_scores.size(-1),
)
all_surface_sequence_scores.append(batch_surface_sequence_scores.cpu())
all_surface_sequence_scores_raw.append(
batch_surface_sequence_scores_raw.cpu()
)
all_next_token_scores.append(next_token_scores.cpu())
surface_sequence_scores = torch.cat(all_surface_sequence_scores, dim=0)
surface_sequence_scores_raw = torch.cat(all_surface_sequence_scores_raw, dim=0)
if search_crit == "prob":
latent_sequence_scores = latent_sequence_scores.log().cpu()
elif search_crit == "log_prob":
latent_sequence_scores = latent_sequence_scores.cpu()
else:
raise ValueError("invalid search criterion", search_crit)
next_token_scores = torch.cat(all_next_token_scores)
return (
next_token_scores,
surface_sequence_scores,
surface_sequence_scores_raw,
latent_sequence_scores,
)
def concat_new_ids(
self,
latent_input_ids,
input_ids,
all_word_log_probs,
beam_idx,
beam_next_tokens,
next_token_scores,
beam_expanded_field_dicts,
beam_expanded_field_selection_dicts,
):
# CHANGE:
# This blocks concats newly generated tokens to existing beams
# for the latent sequence, this is a simple concatenation
# for the surface sequence, it:
# 1. remove pad tokens in previous input_ids
# 2. replace field tokens with the data
# 3. pad to the same length
# Invariance: <pad> only appear from the right
latent_input_ids = torch.cat(
[latent_input_ids[beam_idx], beam_next_tokens.unsqueeze(-1)], dim=-1
)
beam_next_tokens = (
beam_next_tokens.unsqueeze(0)
.expand(
input_ids.size(0) // latent_input_ids.size(0), beam_next_tokens.size(0)
)
.reshape(-1, 1)
)
beam_idx = beam_idx.unsqueeze(0) + torch.arange(
input_ids.size(0) // latent_input_ids.size(0)
).unsqueeze(1) * latent_input_ids.size(0)
beam_idx = beam_idx.reshape(-1)
next_token_scores = next_token_scores.reshape(-1, 1)
all_word_log_probs = torch.cat(
[all_word_log_probs[beam_idx], next_token_scores], dim=-1
)
list_input_ids = []
for sen_ids in input_ids[beam_idx]:
list_input_ids.append(
sen_ids[: sen_ids.ne(self.tokenizer.pad_token_id).sum()]
)
beam_expanded_field_selection_dicts = [
beam_expanded_field_selection_dicts[i].copy() for i in beam_idx.tolist()
]
for i, next_token in enumerate(beam_next_tokens):
sen_field_dict = beam_expanded_field_dicts[i]
sen_field_selection_dict = beam_expanded_field_selection_dicts[i]
int_next_token = next_token.item()
if int_next_token not in self.tokenizer.all_field_tokens:
list_input_ids[i] = torch.cat([list_input_ids[i], next_token])
elif int_next_token in sen_field_dict:
selected_idx = sen_field_selection_dict[int_next_token][0]
int_next_surface_token = sen_field_dict[int_next_token][selected_idx]
if int_next_surface_token != -1:
next_token = torch.LongTensor([int_next_surface_token]).to(
input_ids.device
)
list_input_ids[i] = torch.cat([list_input_ids[i], next_token])
if int_next_token in self.tokenizer.field_cutoff_set:
next_run_over_token = self.tokenizer.next_field_token_map.get(
int_next_token, None
)
run_over_tokens = []
while (
next_run_over_token is not None
and next_run_over_token in sen_field_dict
):
int_next_surface_token = sen_field_dict[
next_run_over_token
][selected_idx]
if int_next_surface_token != -1:
run_over_tokens.append(int_next_surface_token)
next_run_over_token = self.tokenizer.next_field_token_map.get(
next_run_over_token, None
)
else:
break
if len(run_over_tokens) != 0:
next_tokens = torch.LongTensor(run_over_tokens).to(
input_ids.device
)
list_input_ids[i] = torch.cat(
[list_input_ids[i], next_tokens]
)
elif (
int_next_token in self.tokenizer.all_field_tokens
and int_next_token not in self.tokenizer.field_start_set
):
pass
elif (
int_next_token in self.tokenizer.all_field_tokens
and int_next_token in self.tokenizer.field_start_set
):
list_input_ids[i] = torch.cat([list_input_ids[i], next_token])
else:
raise ValueError("Impossible")
# TODO: this syntax is disgusting
input_ids = self.tokenizer.pad([{"input_ids": i} for i in list_input_ids])[
"input_ids"
].to(input_ids.device)
return (
latent_input_ids,
input_ids,
all_word_log_probs,
beam_expanded_field_selection_dicts,
)
def template_search(
self,
input_ids,
field_dicts,
inference_batch_size,
recompute_log_prob,
input_weighting,
search_crit,
beam_scorer,
logits_processor=None,
stopping_criteria=None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
output_scores: Optional[bool] = None,
return_dict_in_generate: Optional[bool] = None,
synced_gpus: Optional[bool] = None,
verbose=False,
**model_kwargs,
):
# init values
logits_processor = (
logits_processor if logits_processor is not None else LogitsProcessorList()
)
stopping_criteria = (
stopping_criteria
if stopping_criteria is not None
else StoppingCriteriaList()
)
if max_length is not None:
stopping_criteria = validate_stopping_criteria(
stopping_criteria, max_length
)
if len(stopping_criteria) == 0:
warnings.warn(
"You don't have defined any stopping_criteria, this will likely loop forever",
UserWarning,
)
pad_token_id = (
pad_token_id if pad_token_id is not None else self.config.pad_token_id
)
eos_token_id = (
eos_token_id if eos_token_id is not None else self.config.eos_token_id
)
output_scores = (
output_scores if output_scores is not None else self.config.output_scores
)
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict_in_generate = (
return_dict_in_generate
if return_dict_in_generate is not None
else self.config.return_dict_in_generate
)
# init attention / hidden states / scores tuples
scores = () if (return_dict_in_generate and output_scores) else None
num_beams = beam_scorer.num_beams
batch_size = input_ids.size(0) // num_beams
batch_beam_size, cur_len = input_ids.shape
assert (
num_beams * batch_size == batch_beam_size
), f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
# CHANGE: we keep track of both the surface sequence scores and the latent sequence scores (after averaging)
surface_sequence_scores = torch.zeros(
(batch_size, num_beams), dtype=torch.float, device=input_ids.device
)
surface_sequence_scores[:, 1:] = -1e9
surface_sequence_scores = surface_sequence_scores.view(
(batch_size * num_beams,)
)
latent_sequence_scores = torch.zeros(
(num_beams,), dtype=torch.float, device=input_ids.device
)
latent_sequence_scores[1:] = -1e9
# Duplicating field dict for each sequence on the beam
beam_expanded_field_dicts = []
for field_dict in field_dicts:
for _ in range(num_beams):
# NOTE: make a copy here so we won't modify real field_dict
# this is used for the hallucination augmentation
beam_expanded_field_dicts.append(field_dict.copy())
# Initializing field selection dictionaries to help keep track
beam_expanded_field_selection_dicts = [
defaultdict(dict) for _ in range(surface_sequence_scores.size(0))
]
latent_input_ids = input_ids[:num_beams]
this_peer_finished = False # used by synced_gpus only
assert max_length is not None
all_word_log_probs = torch.zeros(batch_size * num_beams, 1)
# stats for debugging
cutoff_counts = []
step_input_ids = []
step_latent_input_ids = []
step_scores = []
step_partial_surface_seq_scores = []
step_partial_latent_seq_scores = []
if verbose:
bar = trange(max_length - 1, leave=False)
else:
bar = range(max_length)
for loop_i in bar:
# CHANGE: turning off caching to make implementation simple for now
model_kwargs["past"] = None
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
model_inputs["past_key_values"] = None
(
next_token_scores,
surface_sequence_scores,
surface_sequence_scores_raw,
latent_sequence_scores,
) = self.compute_next_token_scores_batched(
model_inputs,
latent_input_ids,
beam_expanded_field_dicts,
beam_expanded_field_selection_dicts,
inference_batch_size,
logits_processor,
surface_sequence_scores,
input_weighting,
search_crit,
is_first_step=(loop_i == 0),
)
eos_scores = next_token_scores[:, self.tokenizer.eos_token_id]
partial_surface_sequence_scores = eos_scores + surface_sequence_scores_raw
partial_surface_sequence_scores = partial_surface_sequence_scores.view(
-1, num_beams
)
step_partial_surface_seq_scores.append(partial_surface_sequence_scores)
if search_crit == "prob":
step_partial_latent_seq_scores.append(
partial_surface_sequence_scores.view(-1, num_beams)
.exp()
.mean(dim=0)
.log()
)
elif search_crit == "log_prob":
step_partial_latent_seq_scores.append(
partial_surface_sequence_scores.view(-1, num_beams).mean(dim=0)
)
else:
raise ValueError("impossible.")
vocab_size = len(self.tokenizer)
next_token_scores = next_token_scores.view(
batch_size, num_beams * vocab_size
)
latent_sequence_scores, next_tokens = torch.topk(
latent_sequence_scores, 2 * num_beams, dim=0, largest=True, sorted=True,
)
expanded_next_tokens = next_tokens.unsqueeze(0).expand(
surface_sequence_scores.size(0), next_tokens.size(0)
)
surface_sequence_scores = surface_sequence_scores.gather(
index=expanded_next_tokens, dim=-1,
)
next_token_scores = next_token_scores.gather(
index=expanded_next_tokens, dim=-1
)
next_indices = (next_tokens / vocab_size).long()
next_tokens = next_tokens % vocab_size
# stateless
# this block is unmodified from HF.
beam_outputs = beam_scorer.process(
latent_input_ids,
latent_sequence_scores.unsqueeze(0),
next_tokens.unsqueeze(0),
next_indices.unsqueeze(0),
input_ids.view(-1, num_beams, input_ids.size(-1)).transpose(0, 1),
pad_token_id=pad_token_id,