-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_replace_every_step_pos_permu.py
1498 lines (1316 loc) · 74.2 KB
/
generate_replace_every_step_pos_permu.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 transformers
from typing import Callable, List, Optional, Tuple, Union
import torch
import inspect
import warnings
from torch import nn
import torch.nn.functional as F
import numpy as np
from transformers.generation.utils import (
ModelOutput,
is_hqq_available,
is_quanto_available,
is_torchdynamo_compiling,
)
from transformers.cache_utils import (
DynamicCache,
HQQQuantizedCache,
HybridCache,
QuantizedCacheConfig,
QuantoQuantizedCache,
SlidingWindowCache,
StaticCache,
)
from transformers.generation.configuration_utils import GenerationConfig, GenerationMode
from transformers.generation.logits_process import LogitsProcessorList
from transformers.generation.stopping_criteria import StoppingCriteriaList
from transformers.modeling_utils import PreTrainedModel
from transformers.generation.streamers import BaseStreamer
from transformers.generation.beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
from transformers.generation.utils import _split_model_inputs, stack_model_outputs
from transformers.utils import (
ModelOutput,
is_hqq_available,
is_quanto_available,
is_torchdynamo_compiling,
logging
)
logger = logging.get_logger(__name__)
NEED_SETUP_CACHE_CLASSES_MAPPING = {"static": StaticCache, "sliding_window": SlidingWindowCache, "hybrid": HybridCache}
QUANT_BACKEND_CLASSES_MAPPING = {"quanto": QuantoQuantizedCache, "HQQ": HQQQuantizedCache}
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
import torch.distributed as dist
from transformers.generation.beam_search import BeamSearchScorer, ConstrainedBeamSearchScorer
from transformers.generation.beam_constraints import DisjunctiveConstraint, PhrasalConstraint
def calculate_kl_divergence(probs_with, probs_without):
# 在对概率取对数之前,添加一个小的正常数以避免对零取对数
eps = 1e-9
probs_with_safe = torch.clamp(probs_with, min=eps) # 确保概率值不小于eps
probs_without_safe = torch.clamp(probs_without, min=eps)
kl_div = F.kl_div(probs_with_safe.log(), probs_without_safe, reduction='batchmean')
return kl_div.item()
def calculate_absolute_difference(probs_with, probs_without):
abs_diff = torch.sum(torch.abs(probs_with - probs_without))
return abs_diff.item()
def generate_long_tail_distribution(top_k, size=1000, distribution='powerlaw'):
if distribution == 'powerlaw':
# 使用幂律分布
a = 1.5 # 幂律指数参数
x = np.random.power(a, size)
elif distribution == 'lognormal':
# 使用对数正态分布
mu, sigma = 0, 1 # 均值和标准差
x = np.random.lognormal(mu, sigma, size)
else:
raise ValueError("Unsupported distribution type. Use 'powerlaw' or 'lognormal'.")
# 对分布进行排序并取top_k
x_sorted = np.sort(x)[::-1]
top_k_values = x_sorted[:top_k]
return top_k_values
def weighted_mapping(w_list, x1, x2):
min_w = min(w_list)
max_w = max(w_list)
# 如果最小值和最大值相等,则直接返回范围的中值
if min_w == max_w:
return [0.5 * (x1 + x2)] * len(w_list)
mapped_list = [(x2 - x1) * (w - min_w) / (max_w - min_w) + x1 for w in w_list]
return mapped_list
def generate_long_tail_list(length, imb_type='exp', imb_factor=0.5):
"""
生成一个具有长尾分布的列表
:param length: 列表长度
:param imb_type: 分布类型,可以是'exp', 'step', 'trunk'
:param imb_factor: 分布的陡峭程度因子
:return: 长尾分布的列表
"""
img_max = length
img_num_per_cls = []
if imb_type == 'exp':
for cls_idx in range(length):
num = img_max * (imb_factor**(cls_idx / (length - 1.0)))
img_num_per_cls.append(num)
elif imb_type == 'step':
for cls_idx in range(length // 2):
img_num_per_cls.append(img_max)
for cls_idx in range(length // 2):
img_num_per_cls.append(img_max * imb_factor)
elif imb_type == 'trunk': # imb_factor为截取的比例,如0.8
img_num_per_cls = [img_max for i in range(length)]
for i in range(len(img_num_per_cls)):
img_num_per_cls[i] = imb_factor * img_num_per_cls[i]
else:
img_num_per_cls.extend([img_max] * length)
# 归一化处理,使数据更适合显示
img_num_per_cls = np.array(img_num_per_cls)
img_num_per_cls = img_num_per_cls / np.max(img_num_per_cls)
return img_num_per_cls.tolist()
class GenerateDecoderOnlyOutput(ModelOutput):
sequences: torch.LongTensor = None
scores: Optional[Tuple[torch.FloatTensor]] = None
logits: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
class GenerateEncoderDecoderOutput(ModelOutput):
sequences: torch.LongTensor = None
scores: Optional[Tuple[torch.FloatTensor]] = None
logits: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
class GenerateBeamDecoderOnlyOutput(ModelOutput):
sequences: torch.LongTensor = None
sequences_scores: Optional[torch.FloatTensor] = None
scores: Optional[Tuple[torch.FloatTensor]] = None
logits: Optional[Tuple[torch.FloatTensor]] = None
beam_indices: Optional[torch.LongTensor] = None
attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
class GenerateBeamEncoderDecoderOutput(ModelOutput):
sequences: torch.LongTensor = None
sequences_scores: Optional[torch.FloatTensor] = None
scores: Optional[Tuple[torch.FloatTensor]] = None
logits: Optional[Tuple[torch.FloatTensor]] = None
beam_indices: Optional[torch.LongTensor] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput
ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput
BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]
BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]
BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]
ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]
# Typing shortcuts
GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]
GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]
GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]
# def _sample(
# self,
# input_ids: torch.LongTensor,
# logits_processor: LogitsProcessorList,
# stopping_criteria: StoppingCriteriaList,
# generation_config: GenerationConfig,
# synced_gpus: bool,
# streamer: Optional["BaseStreamer"],
# logits_warper: Optional[LogitsProcessorList] = None,
# **model_kwargs,
# ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
# # init values
# pad_token_id = generation_config.pad_token_id
# output_attentions = generation_config.output_attentions
# output_hidden_states = generation_config.output_hidden_states
# output_scores = generation_config.output_scores
# output_logits = generation_config.output_logits
# return_dict_in_generate = generation_config.return_dict_in_generate
# has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
# do_sample = generation_config.do_sample
# if do_sample is True and not isinstance(logits_warper, LogitsProcessorList):
# raise ValueError(
# "`do_sample` is set to `True`, `logits_warper` must be a `LogitsProcessorList` instance (it is "
# f"{logits_warper})."
# )
# # init attention / hidden states / scores tuples
# scores = () if (return_dict_in_generate and output_scores) else None
# raw_logits = () if (return_dict_in_generate and output_logits) else None
# decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
# cross_attentions = () if (return_dict_in_generate and output_attentions) else None
# decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
# # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
# if return_dict_in_generate and self.config.is_encoder_decoder:
# encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
# encoder_hidden_states = (
# model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
# )
# # keep track of which sequences are already finished
# batch_size = input_ids.shape[0]
# this_peer_finished = False
# unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
# model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
# calibration_enable = True
# prefilling_stage = True
# while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
# if calibration_enable:
# # prepare model
# # if not first_iteration:
# if prefilling_stage:
# if input_ids.shape[1] == 1:
# raise ValueError("input_ids 只有一个元素,无法执行操作。")
# input_ids_next = input_ids[:, -1]
# input_ids = input_ids[:, :-1]
# model_kwargs['attention_mask'] = model_kwargs['attention_mask'][:, :-1]
# model_kwargs['cache_position'] = model_kwargs['cache_position'][:-1]
# model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# # model_inputs['input_ids'] = model_inputs['input_ids'][:, :-1]
# # model_inputs['position_ids'] = model_inputs['position_ids'][:, :-1]
# # model_inputs['cache_position'] = model_inputs['cache_position'][:-1]
# # model_inputs['attention_mask'] = model_inputs['attention_mask'][:, :-1]
# outputs = self(
# **model_inputs,
# return_dict=True,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# )
# input_ids = torch.cat([input_ids, input_ids_next[:, None]], dim=-1)
# model_kwargs = self._update_model_kwargs_for_generation(
# outputs,
# model_kwargs,
# is_encoder_decoder=self.config.is_encoder_decoder,
# )
# prefilling_stage = False
# self.logits_chunks = []
# # permu_num = [1, 10, 100, 1000, 10000, 100000]
# permu_num = [100] * 1
# # 2. 处理每个块
# model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# for num in permu_num:
# # 在position_ids上添加扰动
# # model_inputs['position_ids'] += torch.randint(num, 10 * num, model_inputs['position_ids'].shape, device=model_inputs['position_ids'].device)
# # model_inputs['position_ids'].clamp_(min=0)
# # model_inputs['position_ids'].fill_(1) # 1048576
# if synced_gpus and this_peer_finished:
# continue # don't waste resources running the code we don't need
# with torch.no_grad():
# outputs_chunk = self(
# **model_inputs,
# return_dict=True,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# update_past_key_values=True
# )
# # 裁剪kv cache
# model_inputs['past_key_values'].crop(model_inputs['attention_mask'].shape[1]-1)
# if synced_gpus and this_peer_finished:
# continue # don't waste resources running the code we don't need
# # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# # (the clone itself is always small)
# next_token_logits = outputs_chunk.logits[:, -1, :].clone()
# self.logits_chunks.append(next_token_logits)
# del outputs_chunk
# # 3. formal next token predict
# model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# model_inputs["attention_mask"][0].fill_(1)
# with torch.no_grad():
# outputs = self(
# **model_inputs,
# return_dict=True,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# )
# if synced_gpus and this_peer_finished:
# continue # don't waste resources running the code we don't need
# # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# # (the clone itself is always small)
# next_token_logits_base = outputs.logits[:, -1, :].clone()
# # 计算每个块的KL散度
# # self.w_list = []
# # for i in range(len(self.logits_chunks)):
# # self.w_list.append(calculate_absolute_difference(self.logits_chunks[i].squeeze(0), next_token_logits_base.squeeze(0)))
# # self.w_list = weighted_mapping(self.w_list, 1, 2)
# self.logits_list = []
# for i in range(len(self.logits_chunks)):
# # 只对选出来的topk元素进行计算
# # next_token_logits_base_softmax = nn.functional.softmax(next_token_logits_base, dim=-1)
# # self.logits_chunks[i] = nn.functional.softmax(self.logits_chunks[i], dim=-1)
# calibrated_logits = (1 + 1.5) * next_token_logits_base - 1.5 * self.logits_chunks[i]
# # calibrated_logits = next_token_logits_base - 0.1 * self.logits_chunks[i]
# # calibrated_logits = next_token_logits_base_softmax - self.logits_chunks[i]
# self.logits_list.append(calibrated_logits)
# if len(self.logits_list) == 1:
# next_token_logits = self.logits_list[0]
# else:
# # 使用torch.stack和torch.mean计算self.logits_list的平均值
# logits_tensor = torch.stack(self.logits_list)
# next_token_logits = torch.mean(logits_tensor, dim=0)
# # 截断
# # # 定义 beta
# # beta = 0.99
# # # 获取 next_token_logits 的最大值
# # max_logits, _ = torch.max(next_token_logits_base, dim=-1, keepdim=True)
# # # 计算阈值
# # threshold = beta * max_logits
# # # 创建一个全为 -inf 的掩码
# # mask = torch.full_like(next_token_logits_base, fill_value=-float('inf'))
# # # 获取满足阈值条件的索引
# # valid_indices = next_token_logits >= threshold
# # # 将满足条件的 logits 保留,不满足条件的设为 -inf
# # next_token_logits = torch.where(valid_indices, next_token_logits, mask)
# top_k = 100
# _, topk_indices_ = torch.topk(next_token_logits_base, top_k, dim=-1) # 创建一个全为 -inf 的掩码,形状与 next_token_logits 相同
# mask = torch.full_like(next_token_logits, fill_value=-float('inf'))
# # 使用 scatter 将 next_token_logits 中 top-k 索引对应的位置替换为原始值
# next_token_logits = mask.scatter(dim=-1, index=topk_indices_, src=next_token_logits.gather(dim=-1, index=topk_indices_))
# # # 校准 logits
# # self.logits_list = []
# # chunks_num = len(self.w_list)
# # # chunks_num = 2
# # cali_top_k = chunks_num
# # topk_values, self.topk_indices = torch.topk(torch.tensor(self.w_list), cali_top_k)
# # imb_type = 'exp' # 可选'exp', 'step', 'trunk'
# # imb_factor = 0.01 # 可调整imb_factor值以改变分布的陡峭程度
# # # 生成长尾分布列表
# # self.long_tail_weights = generate_long_tail_list(chunks_num, imb_type, imb_factor)
# # # topk_indices: 降序序号;long_tail_weights:降序权重
# # for i in self.topk_indices:
# # # 只对选出来的topk元素进行计算
# # calibrated_logits = (1 + 1.5) * next_token_logits_base - 1.5 * self.logits_chunks[i]
# # self.logits_list.append(calibrated_logits)
# # # 使用long_tail_weights对logits_list进行加权计算
# # weighted_logits_sum = sum(logit * weight for logit, weight in zip(self.logits_list[0:cali_top_k], self.long_tail_weights[0:cali_top_k]))
# # next_token_logits = weighted_logits_sum / sum(self.long_tail_weights)
# else:
# # prepare model inputs
# model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# with torch.no_grad():
# # forward pass to get next token
# outputs = self(
# **model_inputs,
# return_dict=True,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# )
# if synced_gpus and this_peer_finished:
# continue # don't waste resources running the code we don't need
# # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# # (the clone itself is always small)
# next_token_logits = outputs.logits[:, -1, :].clone()##
# # pre-process distribution
# next_token_scores = logits_processor(input_ids, next_token_logits)
# if do_sample:
# next_token_scores = logits_warper(input_ids, next_token_scores)
# # Store scores, attentions and hidden_states when required
# if return_dict_in_generate:
# if output_scores:
# scores += (next_token_scores,)
# if output_logits:
# raw_logits += (next_token_logits,)
# if output_attentions:
# decoder_attentions += (
# (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
# )
# if self.config.is_encoder_decoder:
# cross_attentions += (outputs.cross_attentions,)
# if output_hidden_states:
# decoder_hidden_states += (
# (outputs.decoder_hidden_states,)
# if self.config.is_encoder_decoder
# else (outputs.hidden_states,)
# )
# # token selection
# if do_sample:
# probs = nn.functional.softmax(next_token_scores, dim=-1)
# next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
# else:
# next_tokens = torch.argmax(next_token_scores, dim=-1)
# # finished sentences should have their next token be a padding token
# if has_eos_stopping_criteria:
# print(next_tokens)
# print(unfinished_sequences)
# print(pad_token_id)
# print(unfinished_sequences)
# next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
# # update generated ids, model inputs, and length for next step
# input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
# if streamer is not None:
# streamer.put(next_tokens.cpu())
# model_kwargs = self._update_model_kwargs_for_generation(
# outputs,
# model_kwargs,
# is_encoder_decoder=self.config.is_encoder_decoder,
# )
# unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
# this_peer_finished = unfinished_sequences.max() == 0
# # This is needed to properly delete outputs.logits which may be very large for first iteration
# # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
# del outputs
# if streamer is not None:
# streamer.end()
# if return_dict_in_generate:
# if self.config.is_encoder_decoder:
# return GenerateEncoderDecoderOutput(
# sequences=input_ids,
# scores=scores,
# logits=raw_logits,
# encoder_attentions=encoder_attentions,
# encoder_hidden_states=encoder_hidden_states,
# decoder_attentions=decoder_attentions,
# cross_attentions=cross_attentions,
# decoder_hidden_states=decoder_hidden_states,
# past_key_values=model_kwargs.get("past_key_values"),
# )
# else:
# return GenerateDecoderOnlyOutput(
# sequences=input_ids,
# scores=scores,
# logits=raw_logits,
# attentions=decoder_attentions,
# hidden_states=decoder_hidden_states,
# past_key_values=model_kwargs.get("past_key_values"),
# )
# else:
# return input_ids
def _sample(
self,
input_ids: torch.LongTensor,
logits_processor: LogitsProcessorList,
stopping_criteria: StoppingCriteriaList,
generation_config: GenerationConfig,
synced_gpus: bool,
streamer: Optional["BaseStreamer"],
logits_warper: Optional[LogitsProcessorList],
**model_kwargs,
) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
# init values
pad_token_id = generation_config._pad_token_tensor
output_attentions = generation_config.output_attentions
output_hidden_states = generation_config.output_hidden_states
output_scores = generation_config.output_scores
output_logits = generation_config.output_logits
return_dict_in_generate = generation_config.return_dict_in_generate
has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
do_sample = generation_config.do_sample
if do_sample is True and not isinstance(logits_warper, LogitsProcessorList):
raise ValueError(
"`do_sample` is set to `True`, `logits_warper` must be a `LogitsProcessorList` instance (it is "
f"{logits_warper})."
)
# init attention / hidden states / scores tuples
scores = () if (return_dict_in_generate and output_scores) else None
raw_logits = () if (return_dict_in_generate and output_logits) else None
decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
# if model is an encoder-decoder, retrieve encoder attention weights and hidden states
if return_dict_in_generate and self.config.is_encoder_decoder:
encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
encoder_hidden_states = (
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
)
# keep track of which sequences are already finished
batch_size = input_ids.shape[0]
this_peer_finished = False
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
calibration_enable = True
prefilling_stage = True
while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
if calibration_enable:
# prepare model
# if not first_iteration:
if prefilling_stage:
if input_ids.shape[1] == 1:
raise ValueError("input_ids 只有一个元素,无法执行操作。")
input_ids_next = input_ids[:, -1]
input_ids = input_ids[:, :-1]
model_kwargs['attention_mask'] = model_kwargs['attention_mask'][:, :-1]
model_kwargs['cache_position'] = model_kwargs['cache_position'][:-1]
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# model_inputs['input_ids'] = model_inputs['input_ids'][:, :-1]
# model_inputs['position_ids'] = model_inputs['position_ids'][:, :-1]
# model_inputs['cache_position'] = model_inputs['cache_position'][:-1]
# model_inputs['attention_mask'] = model_inputs['attention_mask'][:, :-1]
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
input_ids = torch.cat([input_ids, input_ids_next[:, None]], dim=-1)
model_kwargs = self._update_model_kwargs_for_generation(
outputs,
model_kwargs,
is_encoder_decoder=self.config.is_encoder_decoder,
)
prefilling_stage = False
self.logits_chunks = []
# permu_num = [1, 10, 100, 1000, 10000, 100000]
permu_num = [100] * 1
# 2. 处理每个块
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
for num in permu_num:
# 在position_ids上添加扰动
# model_inputs['position_ids'] += torch.randint(num, 10 * num, model_inputs['position_ids'].shape, device=model_inputs['position_ids'].device)
# model_inputs['position_ids'].clamp_(min=0)
# model_inputs['position_ids'].fill_(1) # 1048576
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
with torch.no_grad():
outputs_chunk = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
update_past_key_values=True
)
# 裁剪kv cache
model_inputs['past_key_values'].crop(model_inputs['attention_mask'].shape[1]-1)
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
# Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# (the clone itself is always small)
next_token_logits = outputs_chunk.logits[:, -1, :].clone()
self.logits_chunks.append(next_token_logits)
del outputs_chunk
# 3. formal next token predict
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
model_inputs["attention_mask"][0].fill_(1)
with torch.no_grad():
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
# Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# (the clone itself is always small)
next_token_logits_base = outputs.logits[:, -1, :].clone()
self.logits_list = []
for i in range(len(self.logits_chunks)):
# 只对选出来的topk元素进行计算
# next_token_logits_base_softmax = nn.functional.softmax(next_token_logits_base, dim=-1)
# self.logits_chunks[i] = nn.functional.softmax(self.logits_chunks[i], dim=-1)
calibrated_logits = (1 + 1.5) * next_token_logits_base - 1.5 * self.logits_chunks[i]
# calibrated_logits = next_token_logits_base - 0.1 * self.logits_chunks[i]
# calibrated_logits = next_token_logits_base_softmax - self.logits_chunks[i]
self.logits_list.append(calibrated_logits)
if len(self.logits_list) == 1:
next_token_logits = self.logits_list[0]
else:
# 使用torch.stack和torch.mean计算self.logits_list的平均值
logits_tensor = torch.stack(self.logits_list)
next_token_logits = torch.mean(logits_tensor, dim=0)
top_k = 100
_, topk_indices_ = torch.topk(next_token_logits_base, top_k, dim=-1) # 创建一个全为 -inf 的掩码,形状与 next_token_logits 相同
mask = torch.full_like(next_token_logits, fill_value=-float('inf'))
# 使用 scatter 将 next_token_logits 中 top-k 索引对应的位置替换为原始值
next_token_logits = mask.scatter(dim=-1, index=topk_indices_, src=next_token_logits.gather(dim=-1, index=topk_indices_))
else:
# prepare model inputs
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# prepare variable output controls (note: some models won't accept all output controls)
model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
# forward pass to get next token
outputs = self(**model_inputs, return_dict=True)
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
# Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# (the clone itself is always small)
next_token_logits = outputs.logits[:, -1, :].clone()
##########################################################################################
# pre-process distribution
next_token_scores = logits_processor(input_ids, next_token_logits)
if do_sample:
next_token_scores = logits_warper(input_ids, next_token_scores)
# Store scores, attentions and hidden_states when required
if return_dict_in_generate:
if output_scores:
scores += (next_token_scores,)
if output_logits:
raw_logits += (next_token_logits,)
if output_attentions:
decoder_attentions += (
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
)
if self.config.is_encoder_decoder:
cross_attentions += (outputs.cross_attentions,)
if output_hidden_states:
decoder_hidden_states += (
(outputs.decoder_hidden_states,)
if self.config.is_encoder_decoder
else (outputs.hidden_states,)
)
# token selection
if do_sample:
probs = nn.functional.softmax(next_token_scores, dim=-1)
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
else:
next_tokens = torch.argmax(next_token_scores, dim=-1)
# finished sentences should have their next token be a padding token
if has_eos_stopping_criteria:
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
# update generated ids, model inputs, and length for next step
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
if streamer is not None:
streamer.put(next_tokens.cpu())
model_kwargs = self._update_model_kwargs_for_generation(
outputs,
model_kwargs,
is_encoder_decoder=self.config.is_encoder_decoder,
)
unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
this_peer_finished = unfinished_sequences.max() == 0
# This is needed to properly delete outputs.logits which may be very large for first iteration
# Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
del outputs
if streamer is not None:
streamer.end()
if return_dict_in_generate:
if self.config.is_encoder_decoder:
return GenerateEncoderDecoderOutput(
sequences=input_ids,
scores=scores,
logits=raw_logits,
encoder_attentions=encoder_attentions,
encoder_hidden_states=encoder_hidden_states,
decoder_attentions=decoder_attentions,
cross_attentions=cross_attentions,
decoder_hidden_states=decoder_hidden_states,
past_key_values=model_kwargs.get("past_key_values"),
)
else:
return GenerateDecoderOnlyOutput(
sequences=input_ids,
scores=scores,
logits=raw_logits,
attentions=decoder_attentions,
hidden_states=decoder_hidden_states,
past_key_values=model_kwargs.get("past_key_values"),
)
else:
return input_ids
def _beam_search(
self,
input_ids: torch.LongTensor,
beam_scorer: BeamScorer,
logits_processor: LogitsProcessorList,
stopping_criteria: StoppingCriteriaList,
generation_config: GenerationConfig,
synced_gpus: bool,
logits_warper: Optional[LogitsProcessorList] = None,
**model_kwargs,
) -> Union[GenerateBeamOutput, torch.LongTensor]:
r"""
Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
The sequence used as a prompt for the generation.
beam_scorer (`BeamScorer`):
An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
logits_processor (`LogitsProcessorList`):
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
used to modify the prediction scores of the language modeling head applied at each generation step.
stopping_criteria (`StoppingCriteriaList`:
An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
used to tell if the generation loop should stop.
generation_config ([`~generation.GenerationConfig`]):
The generation configuration to be used as parametrization of the decoding method.
synced_gpus (`bool`):
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
logits_warper (`LogitsProcessorList`, *optional*):
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used
to warp the prediction score distribution of the language modeling head applied before multinomial
sampling at each generation step. Only required with sampling strategies (i.e. `do_sample` is set in
`generation_config`)
model_kwargs:
Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
an encoder-decoder model the kwargs should include `encoder_outputs`.
Return:
[`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
`torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
[`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
`return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
`model.config.is_encoder_decoder=True`.
"""
# init values
pad_token_id = generation_config.pad_token_id
eos_token_id = generation_config.eos_token_id
output_attentions = generation_config.output_attentions
output_hidden_states = generation_config.output_hidden_states
output_scores = generation_config.output_scores
output_logits = generation_config.output_logits
return_dict_in_generate = generation_config.return_dict_in_generate
sequential = generation_config.low_memory
do_sample = generation_config.do_sample
if do_sample is True and not isinstance(logits_warper, LogitsProcessorList):
raise ValueError(
"`do_sample` is set to `True`, `logits_warper` must be a `LogitsProcessorList` instance (it is "
f"{logits_warper})."
)
batch_size = len(beam_scorer._beam_hyps)
num_beams = beam_scorer.num_beams
batch_beam_size, cur_len = input_ids.shape
model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
if num_beams * batch_size != batch_beam_size:
raise ValueError(
f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
)
# init attention / hidden states / scores tuples
scores = () if (return_dict_in_generate and output_scores) else None
raw_logits = () if (return_dict_in_generate and output_logits) else None
beam_indices = (
tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
)
decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
# if model is an encoder-decoder, retrieve encoder attention weights and hidden states
if return_dict_in_generate and self.config.is_encoder_decoder:
encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
encoder_hidden_states = (
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
)
# initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
# of the first beam are considered to avoid sampling the exact same tokens across all beams.
beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
beam_scores[:, 1:] = -1e9
beam_scores = beam_scores.view((batch_size * num_beams,))
this_peer_finished = False
decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# if sequential is True, split the input to batches of batch_size and run sequentially
if sequential:
if any(
model_name in self.__class__.__name__.lower()
for model_name in [
"fsmt",
"reformer",
"bloom",
"ctrl",
"gpt_bigcode",
"transo_xl",
"xlnet",
"cpm",
"jamba",
]
):
raise RuntimeError(
f"Currently generation for {self.__class__.__name__} is not supported "
f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."
)
inputs_per_sub_batches = _split_model_inputs(
model_inputs, split_size=batch_size, full_batch_size=batch_beam_size
)
outputs_per_sub_batch = [
self(
**inputs_per_sub_batch,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
for inputs_per_sub_batch in inputs_per_sub_batches
]
outputs = stack_model_outputs(outputs_per_sub_batch)
else: # Unchanged original behavior
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
if synced_gpus and this_peer_finished:
cur_len = cur_len + 1
continue # don't waste resources running the code we don't need
# Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
# (the clone itself is always small)
next_token_logits = outputs.logits[:, -1, :].clone()
next_token_scores = nn.functional.log_softmax(
next_token_logits, dim=-1
) # (batch_size * num_beams, vocab_size)
next_token_scores_processed = logits_processor(input_ids, next_token_scores)
if do_sample:
next_token_scores_processed = logits_warper(input_ids, next_token_scores_processed)
next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
next_token_scores_processed
)
# Store scores, attentions and hidden_states when required
if return_dict_in_generate:
if output_scores:
scores += (next_token_scores_processed,)
if output_logits:
raw_logits += (next_token_logits,)
if output_attentions:
decoder_attentions += (
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
)
if self.config.is_encoder_decoder:
cross_attentions += (outputs.cross_attentions,)
if output_hidden_states:
decoder_hidden_states += (
(outputs.decoder_hidden_states,)
if self.config.is_encoder_decoder
else (outputs.hidden_states,)
)
# reshape for beam search
vocab_size = next_token_scores.shape[-1]
next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
# Beam token selection: pick 1 + eos_token_id.shape[0] next tokens for each beam so we have at least 1
# non eos token per beam.
n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
n_tokens_to_keep = max(2, 1 + n_eos_tokens) * num_beams
if do_sample:
probs = nn.functional.softmax(next_token_scores, dim=-1)
next_tokens = torch.multinomial(probs, num_samples=n_tokens_to_keep)
next_token_scores = torch.gather(next_token_scores, -1, next_tokens)
next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)
next_tokens = torch.gather(next_tokens, -1, _indices)
else:
next_token_scores, next_tokens = torch.topk(
next_token_scores, n_tokens_to_keep, dim=1, largest=True, sorted=True
)
next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
next_tokens = next_tokens % vocab_size
# stateless
beam_outputs = beam_scorer.process(
input_ids,
next_token_scores,
next_tokens,
next_indices,
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
beam_indices=beam_indices,
decoder_prompt_len=decoder_prompt_len,
)
beam_scores = beam_outputs["next_beam_scores"]
beam_next_tokens = beam_outputs["next_beam_tokens"]
beam_idx = beam_outputs["next_beam_indices"]
input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
model_kwargs = self._update_model_kwargs_for_generation(
outputs,
model_kwargs,
is_encoder_decoder=self.config.is_encoder_decoder,
)
# This is needed to properly delete outputs.logits which may be very large for first iteration
# Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
# IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
# (that way the memory peak does not include outputs.logits)
del outputs
if model_kwargs.get("past_key_values", None) is not None:
model_kwargs["past_key_values"] = self._temporary_reorder_cache(
model_kwargs["past_key_values"], beam_idx
)
if return_dict_in_generate and output_scores:
beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
# increase cur_len
cur_len = cur_len + 1
if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
this_peer_finished = True
sequence_outputs = beam_scorer.finalize(
input_ids,
beam_scores,