-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
generation_utils.py
1543 lines (1307 loc) Β· 66 KB
/
generation_utils.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
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from abc import ABC
from typing import List
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.common_ops_import import convert_dtype
from paddle.fluid.layers.utils import map_structure
from paddlenlp.utils.log import logger
__all__ = ["GenerationMixin"]
class BeamHypotheses:
def __init__(self, num_beams, length_penalty, early_stopping):
"""
Initialize n-best list of hypotheses.
"""
self.length_penalty = length_penalty
self.early_stopping = early_stopping
self.num_beams = num_beams
self.beams = []
self.worst_score = 1e9
def __len__(self):
"""
Number of hypotheses in the list.
"""
return len(self.beams)
def add(self, hyp, sum_logprobs, origin_len=0):
"""
Add a new hypothesis to the list.
"""
score = sum_logprobs / (((hyp.shape[-1] - origin_len + 5) / 6) ** self.length_penalty)
if len(self) < self.num_beams or score > self.worst_score:
self.beams.append((score, hyp))
if len(self) > self.num_beams:
sorted_next_scores = sorted([(s, idx) for idx, (s, _) in enumerate(self.beams)])
del self.beams[sorted_next_scores[0][1]]
self.worst_score = sorted_next_scores[1][0]
else:
self.worst_score = min(score, self.worst_score)
def is_done(self, best_sum_logprobs, cur_len, origin_len=0):
"""
If there are enough hypotheses and that none of the hypotheses being
generated can become better than the worst one in the heap, then we
are done with this sentence.
"""
if len(self) < self.num_beams:
return False
elif self.early_stopping:
return True
else:
cur_score = best_sum_logprobs / ((cur_len - origin_len + 5) / 6) ** self.length_penalty
ret = self.worst_score >= cur_score
return ret
class BeamSearchScorer(object):
"""
implementing standard beam search decoding.
"""
def __init__(
self,
batch_size,
max_length,
num_beams,
length_penalty=1.0,
do_early_stopping=False,
num_beam_hyps_to_keep=1,
num_beam_groups=1,
):
self.max_length = max_length
self.num_beams = num_beams
self.length_penalty = length_penalty
self.do_early_stopping = do_early_stopping
self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
self.num_beam_groups = num_beam_groups
self.group_size = self.num_beams // self.num_beam_groups
self._is_init = False
self._beam_hyps = [
BeamHypotheses(
num_beams=self.num_beams, length_penalty=self.length_penalty, early_stopping=self.do_early_stopping
)
for _ in range(batch_size)
]
self._done = paddle.to_tensor([0 for _ in range(batch_size)], dtype="int64")
if not isinstance(num_beams, int) or num_beams <= 1:
raise ValueError(
"`num_beams` has to be an integer strictly greater than 1, but "
"received {}. For `num_beams` == 1, one should make use of "
"`greedy_search` instead.".format(num_beams)
)
if not isinstance(num_beam_groups, int) or (num_beam_groups > num_beams) or (num_beams % num_beam_groups != 0):
raise ValueError(
"`num_beam_groups` has to be an integer smaller or equal than "
"`num_beams` and `num_beams` has to be divisible by "
"`num_beam_groups`, but received num_beam_groups={}, num_beams="
"{}.".format(num_beam_groups, num_beams)
)
@property
def is_done(self):
return paddle.min(self._done) == 1
def process(
self, input_ids, next_scores, next_tokens, next_indices, origin_len=0, pad_token_id=None, eos_token_id=None
):
cur_len = input_ids.shape[-1]
batch_size = len(self._beam_hyps)
assert batch_size == (input_ids.shape[0] // self.group_size)
next_beam_scores = paddle.zeros([batch_size, self.group_size], dtype=next_scores.dtype)
next_beam_tokens = paddle.zeros([batch_size, self.group_size], dtype=next_tokens.dtype)
next_beam_indices = paddle.zeros([batch_size, self.group_size], dtype=next_indices.dtype)
for batch_idx, beam_hyp in enumerate(self._beam_hyps):
if self._done[batch_idx] == 1:
assert (
len(beam_hyp) >= self.num_beams
), "Batch can only be done if at least {} beams have been generated".format(self.num_beams)
assert (
eos_token_id is not None and pad_token_id is not None
), "generated beams >= num_beams -> eos_token_id and pad_token have to be defined"
# pad the batch
next_beam_scores[batch_idx, :] = 0
next_beam_tokens[batch_idx, :] = pad_token_id
next_beam_indices[batch_idx, :] = 0
continue
# next tokens for this sentence
beam_idx = 0
for beam_token_rank, (next_token, next_score, next_index) in enumerate(
zip(next_tokens[batch_idx], next_scores[batch_idx], next_indices[batch_idx])
):
batch_beam_idx = batch_idx * self.group_size + next_index
# add to generated hypotheses if end of sentence
if (eos_token_id is not None) and (next_token.numpy().item() == eos_token_id):
# If beam_token does not belong to top num_beams tokens,
# it should not be added
is_beam_token_worse_than_top_num_beams = beam_token_rank >= self.group_size
if is_beam_token_worse_than_top_num_beams:
continue
beam_hyp.add(
input_ids[batch_beam_idx.numpy().item()].clone(), next_score.numpy().item(), origin_len
)
else:
# add next predicted token since it is not eos_token
next_beam_scores[batch_idx, beam_idx] = next_score
next_beam_tokens[batch_idx, beam_idx] = next_token.numpy().item()
next_beam_indices[batch_idx, beam_idx] = batch_beam_idx.numpy().item()
beam_idx += 1
# once the beam for next step is full, don't add more tokens to it.
if beam_idx == self.group_size:
break
if beam_idx < self.group_size:
raise ValueError(
"At most {} tokens in `next_tokens[batch_idx]` can be equal "
"to `eos_token_id: {}`. Make sure `next_tokens[batch_idx]` "
"are corrected.".format(self.group_size, eos_token_id)
)
# Check if we are done so that we can save a pad step if all(done)
if beam_hyp.is_done(next_scores[batch_idx].max().numpy().item(), cur_len, origin_len):
self._done[batch_idx] = 1
return {
"next_beam_scores": next_beam_scores.reshape([-1]),
"next_beam_tokens": next_beam_tokens.reshape([-1]),
"next_beam_indices": next_beam_indices.reshape([-1]),
}
def finalize(
self,
input_ids,
final_beam_scores,
final_beam_tokens,
final_beam_indices,
origin_len=0,
pad_token_id=None,
eos_token_id=None,
):
batch_size = len(self._beam_hyps)
# finalize all open beam hypotheses and add to generated hypotheses
for batch_idx, beam_hyp in enumerate(self._beam_hyps):
if self._done[batch_idx] == 1:
continue
# all open beam hypotheses are added to the beam hypothesis
# beam hypothesis class automatically keeps the best beams
for beam_id in range(self.num_beams):
batch_beam_idx = batch_idx * self.num_beams + beam_id
final_score = final_beam_scores[batch_beam_idx].numpy().item()
final_tokens = input_ids[batch_beam_idx]
beam_hyp.add(final_tokens, final_score, origin_len=origin_len)
# select the best hypotheses
sent_lengths = paddle.zeros([batch_size * self.num_beam_hyps_to_keep], dtype=input_ids.dtype)
best = []
# retrieve best hypotheses
for i, beam_hyp in enumerate(self._beam_hyps):
sorted_hyps = sorted(beam_hyp.beams, key=lambda x: x[0])
for j in range(self.num_beam_hyps_to_keep):
best_score, best_hyp = sorted_hyps.pop()
sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
best.append([best_hyp, best_score])
# prepare for adding eos
sent_max_len = min(sent_lengths.max().numpy().item() + 1, self.max_length)
decoded = paddle.zeros([batch_size * self.num_beam_hyps_to_keep, sent_max_len], dtype=input_ids.dtype)
# shorter batches are padded if needed
if sent_lengths.min().numpy().item() != sent_lengths.max().numpy().item():
assert pad_token_id is not None, "`pad_token_id` has to be defined"
decoded[:, :] = pad_token_id
decoded_score = paddle.zeros([batch_size * self.num_beam_hyps_to_keep, 1])
# fill with hypotheses and eos_token_id if the latter fits in
for i, (hypo, score) in enumerate(best):
decoded[i, : sent_lengths[i].numpy().item()] = hypo.numpy()
decoded_score[i] = score
if sent_lengths[i] < self.max_length:
decoded[i, sent_lengths[i].numpy().item()] = eos_token_id
return decoded, decoded_score
class GenerationMixin(object):
r"""
This class implements the interface for generation task.
It's used as the base class of `paddlenlp.transformers.PretrainedModel
<https://paddlenlp.readthedocs.io/zh/latest/source/paddlenlp.transformers.model_utils.html>`__.
"""
@staticmethod
def prepare_input_ids_for_generation(bos_token_id, encoder_output=None):
batch_size = 1
if bos_token_id is None:
raise ValueError("`bos_token_id` should be defined when no " "`input_ids` are provided.")
if encoder_output is not None:
batch_size = encoder_output.shape[0]
return paddle.ones([batch_size, 1], dtype="int64") * bos_token_id
@staticmethod
def prepare_attention_mask_for_generation(input_ids, pad_token_id, eos_token_id):
is_pad_token_in_inputs_ids = (pad_token_id is not None) and paddle.any(
input_ids == pad_token_id
).numpy().item()
is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or (
(eos_token_id is not None) and (pad_token_id != eos_token_id)
)
if is_pad_token_in_inputs_ids and is_pad_token_not_equal_to_eos_token_id:
attention_mask = (input_ids == pad_token_id).astype(paddle.get_default_dtype()) * -1e9
else:
attention_mask = paddle.zeros_like(input_ids, dtype=paddle.get_default_dtype())
return paddle.unsqueeze(attention_mask, axis=[1, 2])
@staticmethod
def prepare_seq_len_for_generation(input_ids, pad_token_id, eos_token_id):
is_pad_token_in_inputs_ids = (pad_token_id is not None) and paddle.any(
input_ids == pad_token_id
).numpy().item()
is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or (
(eos_token_id is not None) and (pad_token_id != eos_token_id)
)
if is_pad_token_in_inputs_ids and is_pad_token_not_equal_to_eos_token_id:
seq_len = paddle.sum(input_ids != pad_token_id, axis=1).unsqueeze(-1)
else:
seq_len = paddle.full((input_ids.shape[0], 1), input_ids.shape[1], dtype="int64")
return seq_len
def get_logits_processor(
self,
min_length=None,
max_length=None,
eos_token_id=None,
forced_bos_token_id=None,
forced_eos_token_id=None,
num_beams=1,
num_beam_groups=1,
diversity_rate=0.0,
repetition_penalty=None,
no_repeat_ngram_size=None,
logits_processors=None,
):
processors = LogitsProcessorList()
if min_length is not None and eos_token_id is not None and min_length > -1:
processors.append(MinLengthLogitsProcessor(min_length, eos_token_id))
if num_beam_groups > 1 and diversity_rate > 0.0:
processors.append(
HammingDiversityLogitsProcessor(
diversity_rate=diversity_rate, num_beams=num_beams, num_beam_groups=num_beam_groups
)
)
if repetition_penalty is not None and repetition_penalty != 1.0:
processors.append(RepetitionPenaltyLogitsProcessor(penalty=repetition_penalty))
if no_repeat_ngram_size is not None and no_repeat_ngram_size > 0:
processors.append(NoRepeatNGramLogitsProcessor(no_repeat_ngram_size))
if forced_bos_token_id is not None:
processors.append(ForcedBOSTokenLogitsProcessor(forced_bos_token_id))
if forced_eos_token_id is not None:
processors.append(ForcedEOSTokenLogitsProcessor(max_length, forced_eos_token_id))
# TODO
# Add more pre_processing for distribution
if logits_processors is not None:
custom_processors = LogitsProcessorList()
custom_processors_type = [type(lp) for lp in logits_processors]
for processor in processors:
if type(processor) not in custom_processors_type:
custom_processors.append(processor)
custom_processors.extend(logits_processors)
return custom_processors
else:
return processors
@staticmethod
def expand_inputs_for_generation(input_ids, expand_size, attention_mask=None, **model_kwargs):
index = paddle.tile(paddle.arange(paddle.shape(input_ids)[0]).unsqueeze(-1), [1, expand_size]).reshape([-1])
input_ids = paddle.gather(input_ids, index)
if attention_mask is not None:
model_kwargs["attention_mask"] = paddle.gather(attention_mask, index)
if "token_type_ids" in model_kwargs and model_kwargs["token_type_ids"] is not None:
token_type_ids = model_kwargs["token_type_ids"]
model_kwargs["token_type_ids"] = paddle.gather(token_type_ids, index)
if "position_ids" in model_kwargs and model_kwargs["position_ids"] is not None:
position_ids = model_kwargs["position_ids"]
model_kwargs["position_ids"] = paddle.gather(position_ids, index)
if "seq_len" in model_kwargs and model_kwargs["seq_len"] is not None:
seq_len = model_kwargs["seq_len"]
model_kwargs["seq_len"] = paddle.gather(seq_len, index)
if "encoder_output" in model_kwargs and model_kwargs["encoder_output"] is not None:
encoder_output = model_kwargs["encoder_output"]
model_kwargs["encoder_output"] = paddle.gather(encoder_output, index)
if "role_ids" in model_kwargs and model_kwargs["role_ids"] is not None:
role_ids = model_kwargs["role_ids"]
model_kwargs["role_ids"] = paddle.gather(role_ids, index)
return input_ids, model_kwargs
@staticmethod
def update_model_kwargs_for_generation(outputs, model_kwargs, is_encoder_decoder=False):
# Update the model inputs during generation.
# Note that If `token_type_ids` and `attention_mask` in `model_kwargs`
# and they contain pad value, the result vectors updated by this method
# may be different from expected. In this case, you need to rewrite the
# method.
# update cache
if isinstance(outputs, tuple) and len(outputs) > 1 and not isinstance(outputs[1], paddle.Tensor):
model_kwargs["cache"] = outputs[1]
# update token_type_ids with last value
if "token_type_ids" in model_kwargs and model_kwargs["token_type_ids"] is not None:
token_type_ids = model_kwargs["token_type_ids"]
model_kwargs["token_type_ids"] = paddle.concat([token_type_ids, token_type_ids[:, -1:]], axis=-1)
# update position_ids
if "position_ids" in model_kwargs and model_kwargs["position_ids"] is not None:
position_ids = model_kwargs["position_ids"]
model_kwargs["position_ids"] = paddle.concat([position_ids, position_ids[:, -1:] + 1], axis=-1)
# update attention_mask
if not is_encoder_decoder and "attention_mask" in model_kwargs:
attention_mask = model_kwargs["attention_mask"]
# nn.Pad2D don't support the data type `bool`
if convert_dtype(attention_mask.dtype) == "bool":
attention_mask = paddle.cast(attention_mask, "int64")
if len(attention_mask.shape) == 4:
attention_mask = nn.Pad2D([0, 0, 0, 1], mode="replicate")(attention_mask)
attention_mask = nn.Pad2D([0, 1, 0, 0], value=-1e4)(attention_mask)
dtype = convert_dtype(attention_mask.dtype)
if "int" in dtype:
attention_mask[:, :, -1, -1] = 1
elif "float" in dtype:
attention_mask[:, :, -1, -1] = 0.0
else:
raise ValueError("The data type of input `attention_mask` must " "be bool, int or float")
else:
attention_mask = paddle.concat(
[attention_mask, paddle.ones([attention_mask.shape[0], 1], dtype="int64")], axis=-1
)
model_kwargs["attention_mask"] = attention_mask
# update role_ids
if "role_ids" in model_kwargs and model_kwargs["role_ids"] is not None:
role_ids = model_kwargs["role_ids"]
model_kwargs["role_ids"] = paddle.concat([role_ids, role_ids[:, -1:]], axis=-1)
return model_kwargs
@staticmethod
def update_scores_for_generation(scores, next_scores, length, unfinished_flag):
# update scores
unfinished_scores = (scores * length + next_scores) / (length + 1)
scores = paddle.where(unfinished_flag, unfinished_scores, scores)
return scores
def prepare_encoder_decoder_kwargs_for_generation(self, input_ids, model_kwargs):
if "encoder_output" not in model_kwargs:
# retrieve encoder 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") or argument == "use_cache"
)
}
model_kwargs["encoder_output"] = encoder(input_ids, **encoder_kwargs)
return model_kwargs
def prepare_decoder_input_ids_for_generation(self, input_ids, decoder_start_token_id=None, bos_token_id=None):
decoder_start_token_id = (
decoder_start_token_id
if decoder_start_token_id is not None
else getattr(self, "decoder_start_token_id", None)
)
decoder_start_token_id = decoder_start_token_id if decoder_start_token_id is not None else bos_token_id
decoder_input_ids = paddle.ones([input_ids.shape[0], 1], dtype="int64") * decoder_start_token_id
return decoder_input_ids
def get_decoder_start_token_id(self, decoder_start_token_id=None, bos_token_id=None):
decoder_start_token_id = (
decoder_start_token_id
if decoder_start_token_id is not None
else getattr(self, self.base_model_prefix).config.get("decoder_start_token_id", None)
)
bos_token_id = (
bos_token_id if bos_token_id is not None else getattr(self, self.base_model_prefix).config["bos_token_id"]
)
if decoder_start_token_id is not None:
return decoder_start_token_id
elif getattr(self, self.base_model_prefix).config.get("decoder_start_token_id", None) is not None:
return getattr(self, self.base_model_prefix).config["decoder_start_token_id"]
elif bos_token_id is not None:
return bos_token_id
elif getattr(self, self.base_model_prefix).config["bos_token_id"] is not None:
return getattr(self, self.base_model_prefix).config["bos_token_id"]
raise ValueError(
"`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
)
def prepare_inputs_for_generation(self, input_ids, **kwargs):
# Implement in subclasses for custom behavior to prepare inputs in the
# generate method.
return {"input_ids": input_ids}
def adjust_logits_during_generation(self, logits):
# Implement in subclasses for custom behavior to adjust the logits in
# the generate method.
return logits
def prepare_fast_entry(self, kwargs):
return False
def _convert_to_fast(self, kwargs):
# try general convert
pass
def _build_fast(self, kwargs):
self._fast_entry = False
if kwargs["num_beam_groups"] != 1:
# not support for group_beam_search yet in the fast version
raise AttributeError("'num_beam_groups != 1' is not supported yet in the fast version")
if paddle.get_default_dtype() == "float16" and kwargs["use_fp16_decoding"] is False:
logger.info(
"Since the default dtype is float16, float16 would be used " "though 'use_fp16_decoding=False'."
)
kwargs["use_fp16_decoding"] = True
self.prepare_fast_entry(kwargs)
@paddle.no_grad()
def generate(
self,
input_ids=None,
max_length=20,
min_length=0,
decode_strategy="greedy_search",
temperature=1.0,
top_k=0,
top_p=1.0,
repetition_penalty=1.0,
num_beams=1,
num_beam_groups=1,
length_penalty=0.0,
early_stopping=False,
bos_token_id=None,
eos_token_id=None,
pad_token_id=None,
decoder_start_token_id=None,
forced_bos_token_id=None,
forced_eos_token_id=None,
no_repeat_ngram_size=None,
num_return_sequences=1,
diversity_rate=0.0,
use_cache=True,
use_fast=False,
use_fp16_decoding=False,
**model_kwargs
):
r"""
The interface for generation task. This method can generate sequences
by using decoding strategy. Currently, there are three decoding
strategies supported: "greedy_search", "sampling" and "beam_search".
Args:
input_ids (Tensor, optional): The input sequence ids for the
generation. It is a Tensor with shape [batch_size, sequence_length].
The data type should be int32 or int64. Default to None, which
we will initialize it as a Tensor with shape [1, 1], filled
with the value `bos_token_id`.
max_length (int, optional): The maximum length of the sequence to
be generated. Default to 20.
min_length (int, optional): The minimum length of the sequence to
be generated. Default to 0.
decode_strategy (str, optional): The decoding strategy in generation.
Currently, there are three decoding strategies supported:
"greedy_search", "sampling" and "beam_search". Default to
"greedy_search".
temperature (float, optional): The value used to module the next
token probabilities in the "sampling" strategy. Default to 1.0,
which means no effect.
top_k (int, optional): The number of highest probability tokens to
keep for top-k-filtering in the "sampling" strategy. Default to
0, which means no effect.
top_p (float, optional): The cumulative probability for
top-p-filtering in the "sampling" strategy. The value should
satisfy :math:`0 <= top\_p < 1`. Default to 1.0, which means no
effect.
repetition_penalty (float, optional):
The parameter for repetition penalty. 1.0 means no penalty. See `this paper
<https://arxiv.org/pdf/1909.05858.pdf>`__ for more details. Defaults to 1.0.
num_beams (int, optional): The number of beams in the "beam_search"
strategy. Default to 1.
num_beam_groups (int, optional):
Number of groups to divide `num_beams` into in order to use DIVERSE
BEAM SEARCH. See `this paper <https://arxiv.org/pdf/1610.02424.pdf>`__
for more details. Default to 1.
length_penalty (float, optional): The exponential penalty to the
sequence length in the "beam_search" strategy. The larger this
param is, the more that the model would generate shorter
sequences. Default to 0.0, which means no penalty.
early_stopping (bool, optional): Whether to stop searching in the
"beam_search" strategy when at least `num_beams` sentences are
finished per batch or not. Default to False.
bos_token_id (int, optional): The id of the `bos_token`. Default to
None.
eos_token_id (int, optional): The id of the `eos_token`. Default to
None.
pad_token_id (int, optional): The id of the `pad_token`. Default to
None.
decoder_start_token_id (int, optional): The start token id for
encoder-decoder models. Default to None.
forced_bos_token_id (int, optional): The id of the token to force as
the first generated token. Usually use for multilingual models.
Default to None.
forced_eos_token_id (int, optional): The id of the token to force as
the last generated token. Default to None.
num_return_sequences (int, optional): The number of returned
sequences for each sequence in the batch. Default to 1.
diversity_rate (float, optional): If num_beam_groups is 1, this is the
diversity_rate for Diverse Siblings Search. See
`this paper https://arxiv.org/abs/1611.08562`__ for more details.
If not, this is the diversity_rate for DIVERSE BEAM SEARCH.
use_cache: (bool, optional): Whether to use the model cache to
speed up decoding. Default to True.
use_fast: (bool, optional): Whether to use fast entry of model
for FastGeneration. Default to False.
use_fp16_decoding: (bool, optional): Whether to use fp16 for decoding.
Only works when fast entry is avalible. Default to False.
model_kwargs (dict): It can be used to specify additional kwargs
passed to the model.
Returns:
tuple[Tensor]: It is a tuple contains two elements: ids and scores.
Each element is a Tensor.
With the fields:
- ids (Tensor):
The ids of the generated sequences. It is a Tensor with shape
[batch_size * num_return_sequences, sequence_length]. The data
type is same as the input `input_ids`.
- scores (Tensor):
The scores of the generated sequences. It is a Tensor with shape
[batch_size * num_return_sequences, 1]. The data type is float32
or float64, which is the same as the parameters in the model.
Example:
.. code-block::
import paddle
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer
)
paddle.seed(2)
# Initialize the model and tokenizer
model_name_or_path = 'unified_transformer-12L-cn-luge'
model = UnifiedTransformerLMHeadModel.from_pretrained(model_name_or_path)
tokenizer = UnifiedTransformerTokenizer.from_pretrained(model_name_or_path)
# Prepare the model inputs.
history = "ζ©δΈε₯½οΌδ»ε€©η©Ίζ°θ΄¨ιδΈιγ"
inputs = tokenizer.dialogue_encode(history, task_type='chitchat',
add_start_token_as_response=True, return_tensors=True)
.. code-block::
# Generate the sequence by using "greedy_search" strategy
ids, scores = model.generate(
input_ids=inputs['input_ids'],
token_type_ids=inputs['token_type_ids'],
position_ids=inputs['position_ids'],
attention_mask=inputs['attention_mask'],
decode_strategy="greedy_search")
print(ids.shape, scores.shape)
# [1, 3] [1, 1]
sequence_ids = ids.numpy().tolist()[0]
sequence_ids = sequence_ids[:sequence_ids.index(tokenizer.sep_token_id)]
response = tokenizer.convert_ids_to_string(sequence_ids, keep_space=False)
print(response)
# ζ―η
.. code-block::
# Generate 2 sequences by using "sampling" strategy (top_k=5)
ids, scores = model.generate(
input_ids=inputs['input_ids'],
token_type_ids=inputs['token_type_ids'],
position_ids=inputs['position_ids'],
attention_mask=inputs['attention_mask'],
decode_strategy="sampling",
top_k=5,
num_return_sequences=2)
print(ids.shape, scores.shape)
# [2, 7] [2, 1]
response = []
for sequence_ids in ids.numpy().tolist():
sequence_ids = sequence_ids[:sequence_ids.index(tokenizer.sep_token_id)]
text = tokenizer.convert_ids_to_string(sequence_ids, keep_space=False)
response.append(text)
print(response)
# ['倩ζ°ε₯½,εΏζ
δΉε₯½', 'δ½ δΉζ―']
.. code-block::
# Generate 2 sequences by using "beam_search" strategy (num_beams=5)
ids, scores = model.generate(
input_ids=inputs['input_ids'],
token_type_ids=inputs['token_type_ids'],
position_ids=inputs['position_ids'],
attention_mask=inputs['attention_mask'],
decode_strategy="beam_search",
num_beams=5,
num_return_sequences=2)
print(ids.shape, scores.shape)
# [2, 3] [2, 1]
response = []
for sequence_ids in ids.numpy().tolist():
sequence_ids = sequence_ids[:sequence_ids.index(tokenizer.sep_token_id)]
text = tokenizer.convert_ids_to_string(sequence_ids, keep_space=False)
response.append(text)
print(response)
# ['ζ―η', 'ε―ε―']
"""
assert decode_strategy in [
"greedy_search",
"sampling",
"beam_search",
], "`decode_strategy` must be one of 'greedy_search', 'sampling' or 'beam_search' but received {}.".format(
decode_strategy
)
if getattr(self, "deprecated_warnings", None) is None:
self.deprecated_warnings = {}
if "use_faster" in model_kwargs:
use_fast = model_kwargs.pop("use_faster")
if not self.deprecated_warnings.get("use_faster", False):
logger.warning("`use_faster` will be deprecated in near future. Please use `use_fast` instead. ")
self.deprecated_warnings["use_faster"] = True
# TODO: change from model.attribute to model.config.attribute when all models are integrated with PretrainedConfig
bos_token_id = bos_token_id if bos_token_id is not None else getattr(self, "bos_token_id", None)
eos_token_id = eos_token_id if eos_token_id is not None else getattr(self, "eos_token_id", None)
pad_token_id = pad_token_id if pad_token_id is not None else getattr(self, "pad_token_id", None)
forced_bos_token_id = (
forced_bos_token_id if forced_bos_token_id is not None else getattr(self, "forced_bos_token_id", None)
)
forced_eos_token_id = (
forced_eos_token_id if forced_eos_token_id is not None else getattr(self, "forced_eos_token_id", None)
)
decoder_start_token_id = (
decoder_start_token_id
if decoder_start_token_id is not None
else getattr(self, "decoder_start_token_id", None)
)
no_repeat_ngram_size = (
no_repeat_ngram_size if no_repeat_ngram_size is not None else getattr(self, "no_repeat_ngram_size", None)
)
if getattr(self, "_fast_entry", None) is not False and use_fast:
args = locals()
args.pop("self")
args.pop("__class__", None)
model_kwargs = args.pop("model_kwargs")
args.update(model_kwargs)
try:
if getattr(self, "_fast_entry", None) is None:
self._build_fast(args)
if self._fast_entry:
output = self._fast_entry(**args)
if isinstance(output, tuple):
output_ids, dummy_srore = output
else:
output_ids = output
# make result and fast result oneconsistent
dummy_srore = None
if decode_strategy == "beam_search":
output_ids = output_ids.transpose([1, 2, 0])
output_ids = output_ids[:, :num_return_sequences, :].reshape([-1, output_ids.shape[-1]])
if dummy_srore is not None:
dummy_srore = dummy_srore[:, :num_return_sequences].flatten()
else:
output_ids = output_ids.transpose([1, 0])
return output_ids, dummy_srore
except Exception as e:
args["model_kwargs"] = model_kwargs
# TODO
# Prevent self._convert_to_fast to throw Exception
self._convert_to_fast(args)
logger.warning(e)
logger.warning("FastGeneration is not available, " "and the original version would be used instead.")
# params check
if input_ids is None:
# Init `input_ids` with bos_token_id
input_ids = self.prepare_input_ids_for_generation(bos_token_id)
if model_kwargs.get("attention_mask", None) is None:
# TODO
# 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
)
self.is_encoder_decoder = (
getattr(self, "encoder", None) is not None and getattr(self, "decoder", None) is not None
)
if self.is_encoder_decoder:
model_kwargs = self.prepare_encoder_decoder_kwargs_for_generation(input_ids, model_kwargs)
# 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, bos_token_id
)
if pad_token_id is None and eos_token_id is not None:
print("Setting `pad_token_id` to `eos_token_id`:{} for " "open-end generation.".format(eos_token_id))
pad_token_id = eos_token_id
model_kwargs["use_cache"] = use_cache
max_length += input_ids.shape[-1]
generate_min_length = min_length
min_length += input_ids.shape[-1]
logits_processors = self.get_logits_processor(
min_length=min_length if generate_min_length > 0 else None,
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,
num_beams=num_beams,
num_beam_groups=num_beam_groups,
diversity_rate=diversity_rate,
repetition_penalty=repetition_penalty,
no_repeat_ngram_size=no_repeat_ngram_size,
logits_processors=model_kwargs["logits_processors"]
if "logits_processors" in model_kwargs
and isinstance(model_kwargs["logits_processors"], LogitsProcessorList)
else None,
)
if "logits_processors" in model_kwargs:
model_kwargs.pop("logits_processors")
if decode_strategy == "greedy_search":
if num_return_sequences > 1:
raise ValueError(
"`num_return_sequences` has to be 1, but is {} "
"when doing greedy search.".format(num_return_sequences)
)
return self.greedy_search(
input_ids, logits_processors, max_length, pad_token_id, eos_token_id, **model_kwargs
)
elif decode_strategy == "sampling":
if num_return_sequences > 1:
input_ids, model_kwargs = self.expand_inputs_for_generation(
input_ids, expand_size=num_return_sequences, **model_kwargs
)
return self.sample(
input_ids,
logits_processors,
max_length,
pad_token_id,
eos_token_id,
top_k,
top_p,
temperature,
**model_kwargs,
)
elif decode_strategy == "beam_search":
batch_size = input_ids.shape[0]
if num_return_sequences > num_beams:
raise ValueError(
"`num_return_sequences` has to be smaller or equal to "
"`num_beams`. But received `num_return_sequences` is {}, "
"`num_beams` is {}".format(num_return_sequences, num_beams)
)
if num_beams <= 1:
raise ValueError(
"`num_beams` has to be bigger than 1. But received "
"`num_beams` is {}. If `num_beams` is 1, `decode_strategy` "
"should be 'greedy_search'".format(num_beams)
)
if num_beam_groups > 1:
diverse_beam_scorer = BeamSearchScorer(
batch_size=batch_size,
max_length=max_length,
num_beams=num_beams,
length_penalty=length_penalty,
do_early_stopping=early_stopping,
num_beam_hyps_to_keep=num_return_sequences,
num_beam_groups=num_beam_groups,
)
# interleave with `num_beams`
input_ids, model_kwargs = self.expand_inputs_for_generation(
input_ids, expand_size=num_beams, **model_kwargs
)
return self.group_beam_search(
input_ids,
diverse_beam_scorer,
logits_processors,
max_length,
pad_token_id,
eos_token_id,
**model_kwargs,
)
else:
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
max_length=max_length,
num_beams=num_beams,
length_penalty=length_penalty,
do_early_stopping=early_stopping,
num_beam_hyps_to_keep=num_return_sequences,
)
input_ids, model_kwargs = self.expand_inputs_for_generation(
input_ids, expand_size=num_beams, **model_kwargs
)
return self.beam_search(
input_ids,
beam_scorer,
logits_processors,
max_length,
diversity_rate,
pad_token_id,
eos_token_id,
**model_kwargs,
)
def greedy_search(self, input_ids, logits_processors, max_length, pad_token_id, eos_token_id, **model_kwargs):
logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList()
batch_size, cur_len = input_ids.shape
origin_len = cur_len
unfinished_flag = paddle.full([batch_size, 1], True, dtype="bool")
scores = paddle.full([batch_size, 1], 0.0, dtype=paddle.get_default_dtype())
while cur_len < max_length:
# prepare model inputs & get model output
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
outputs = self(**model_inputs)
logits = outputs[0] if isinstance(outputs, tuple) else outputs
# [batch_size, vocab_size]
logits = logits[:, -1, :]
# pre-process distribution
logits = self.adjust_logits_during_generation(logits)
logits = logits_processors(input_ids, logits)
# greedy
probs = F.softmax(logits)
probs = paddle.log(probs)
next_tokens = paddle.argmax(probs, axis=-1).unsqueeze(-1)
next_scores = paddle.index_sample(probs.astype("float32"), next_tokens)
if eos_token_id is not None:
next_tokens = paddle.where(unfinished_flag, next_tokens, paddle.full_like(next_tokens, pad_token_id))
scores = self.update_scores_for_generation(scores, next_scores, cur_len - origin_len, unfinished_flag)
cur_len += 1
input_ids = paddle.concat([input_ids, next_tokens], axis=1)
if eos_token_id is not None:
unfinished_flag = paddle.logical_and(unfinished_flag, next_tokens != eos_token_id)
# Stop when there is a </s> in all sentences
if not paddle.any(unfinished_flag):
break
model_kwargs = self.update_model_kwargs_for_generation(
outputs, model_kwargs, is_encoder_decoder=self.is_encoder_decoder
)
return input_ids[:, origin_len:], scores
def sample(
self,
input_ids,
logits_processors,
max_length,
pad_token_id,
eos_token_id,
top_k=None,
top_p=None,
temperature=None,
min_tokens_to_keep=1,
**model_kwargs
):
logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList()
batch_size, cur_len = input_ids.shape
origin_len = cur_len
unfinished_flag = paddle.full([batch_size, 1], True, dtype="bool")
scores = paddle.full([batch_size, 1], 0.0, dtype=paddle.get_default_dtype())
while cur_len < max_length:
# prepare model inputs & get model output
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
outputs = self(**model_inputs)