-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchscopes_utils.py
More file actions
2446 lines (2133 loc) · 81.8 KB
/
patchscopes_utils.py
File metadata and controls
2446 lines (2133 loc) · 81.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2024 The Google Research Authors.
#
# 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 numpy as np
import torch
import tqdm
from general_utils import decode_tokens
from general_utils import make_inputs
import os
# ##############
#
# Hooks
#
# ##############
def set_hs_patch_hooks_neox(
model,
hs_patch_config,
module="hs", # mlp, attn
patch_input=False,
skip_final_ln=False,
generation_mode=False,
):
"""Neox patch hooks."""
# when using mode.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need to
# handle these cases in this call because this hook wraps the generation call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation if
# we are handling the initial input or a future step and thus don't know if
# a patching is needed or not.
# if generation_mode:
# for i in hs_patch_config:
# for position_, _ in hs_patch_config[i]:
# assert position_ > 0
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, input):
# (batch, sequence, hidden_state)
input_len = len(input[0][0])
if generation_mode and input_len == 1:
return
for position_, hs_ in position_hs:
input[0][0, position_] = hs_
def post_hook(module, input, output):
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[0])
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][0])
if generation_mode and output_len == 1:
return
for position_, hs_ in position_hs:
if "skip_ln" in name:
output[0][position_] = hs_
else:
output[0][0, position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for i in hs_patch_config:
if patch_input:
hooks.append(
model.gpt_neox.layers[i].register_forward_pre_hook(
patch_hs(
f"patch_hs_{i}",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
else:
# when patching a last-layer representation to the last layer of the
# same model, the final layer norm is not needed because it was already
# applied (assuming that the representation for patching was obtained by
# setting output_hidden_representations to True).
if skip_final_ln and i == len(model.gpt_neox.layers) - 1:
hooks.append(
model.gpt_neox.final_layer_norm.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
else:
hooks.append(
model.gpt_neox.layers[i].register_forward_hook(
patch_hs(
f"patch_hs_{i}",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
return hooks
def set_hs_patch_hooks_llama(
model,
hs_patch_config,
module="hs", # mlp, attn
patch_input=False,
skip_final_ln=False,
generation_mode=False,
):
"""Llama patch hooks."""
# when using model.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need to
# handle these cases in this call because this hook wraps the generation call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation if
# we are handling the initial input or a future step and thus don't know if
# a patching is needed or not.
# if generation_mode:
# for i in hs_patch_config:
# for position_, _ in hs_patch_config[i]:
# assert position_ > 0
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, input):
# (batch, sequence, hidden_state)
input_len = len(input[0][0])
if generation_mode and input_len == 1:
return
for position_, hs_ in position_hs:
input[0][0, position_] = hs_
def post_hook(module, input, output):
if "skip_ln" in name or "mlp" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[0])
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][0])
if generation_mode and output_len == 1:
return
for position_, hs_ in position_hs:
if "skip_ln" in name or "mlp" in name:
output[0][position_] = hs_
else:
output[0][0, position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for i in hs_patch_config:
# patch_hook = patch_hs(
# f"patch_{module}_{i}",
# position_hs=hs_patch_config[i],
# patch_input=patch_input,
# generation_mode=generation_mode,
# )
patch_hook = patch_hs(
f"patch_{module}_{i}",
position_hs=hs_patch_config[i],
patch_input=patch_input,
generation_mode=generation_mode,
)
print(hs_patch_config[i])
if patch_input:
if module == "hs":
hooks.append(
model.model.layers[i].register_forward_pre_hook(patch_hook)
)
elif module == "mlp":
hooks.append(
model.model.layers[i].mlp.register_forward_pre_hook(patch_hook)
)
elif module == "attn":
hooks.append(
model.model.layers[i].self_attn.register_forward_pre_hook(
patch_hook
)
)
else:
raise ValueError("Module %s not supported", module)
else:
# when patching a last-layer representation to the last layer of the same
# model, the final layer norm is not needed because it was already applied
# (assuming that the representation for patching was obtained by
# setting output_hidden_representations to True).
if skip_final_ln and i == len(model.model.layers) - 1 and module == "hs":
hooks.append(
model.model.norm.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
else:
if module == "hs":
hooks.append(model.model.layers[i].register_forward_hook(patch_hook))
elif module == "mlp":
hooks.append(
model.model.layers[i].mlp.register_forward_hook(patch_hook)
)
elif module == "attn":
hooks.append(
model.model.layers[i].self_attn.register_forward_hook(patch_hook)
)
else:
raise ValueError("Module %s not supported", module)
return hooks
def set_hs_patch_hooks_gptj(
model,
hs_patch_config,
module="hs", # mlp, attn
patch_input=False,
skip_final_ln=False,
generation_mode=False,
):
"""GPTJ patch hooks."""
# when using mode.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need
# to handle these cases in this call because this hook wraps the generation
# call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation
# if we are handling the initial input or a future step and thus don't know
# if a patching is needed or not.
# if generation_mode:
# for i in hs_patch_config:
# for position_, _ in hs_patch_config[i]:
# assert position_ > 0
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, input):
# (batch, sequence, hidden_state)
input_len = len(input[0][0])
if generation_mode and input_len == 1:
return
for position_, hs_ in position_hs:
input[0][0, position_] = hs_
def post_hook(module, input, output):
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[0])
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][0])
if generation_mode and output_len == 1:
return
for position_, hs_ in position_hs:
if "skip_ln" in name:
output[0][position_] = hs_
else:
output[0][0, position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for i in hs_patch_config:
if patch_input:
hooks.append(
model.transformer.h[i].register_forward_pre_hook(
patch_hs(
f"patch_hs_{i}",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
else:
# when patching a last-layer representation to the last layer of the same
# model, the final layer norm is not needed because it was already applied
# (assuming that the representation for patching was obtained by
# setting output_hidden_representations to True).
if skip_final_ln and i == len(model.transformer.h) - 1:
hooks.append(
model.transformer.ln_f.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
else:
# print(f"hs_patch_config[i] is {hs_patch_config[i]}")
# target_later = hs_patch_config[i]['layer_target']
hooks.append(
model.transformer.h[i].register_forward_hook(
patch_hs(
f"patch_hs_{i}",
hs_patch_config[i],
patch_input,
generation_mode,
)
)
)
return hooks
def remove_hooks(hooks):
for hook in hooks:
hook.remove()
# ##############
#
# Inspection
#
# ##############
def inspect(
mt,
prompt_source,
prompt_target,
layer_source,
layer_target,
position_source,
position_target,
module="hs",
generation_mode=False,
max_gen_len=20,
verbose=False,
temperature=None,
):
"""Inspection via patching."""
# adjust position_target to be absolute rather than relative
inp_target = make_inputs(mt.tokenizer, [prompt_target], mt.device)
if position_target < 0:
position_target = len(inp_target["input_ids"][0]) + position_target
# first run the the model on prompt_patch and get all hidden states.
inp_source = make_inputs(mt.tokenizer, [prompt_source], mt.device)
if verbose:
print(
"prompt_patch:",
[mt.tokenizer.decode(x) for x in inp_source["input_ids"][0]],
)
hs_cache_ = []
# We manually store intermediate states that the model API does not expose
store_hooks = []
if module == "mlp":
def store_mlp_hook(module, input, output):
hs_cache_.append(output[0])
for layer in mt.model.model.layers:
store_hooks.append(layer.mlp.register_forward_hook(store_mlp_hook))
elif module == "attn":
def store_attn_hook(module, input, output):
hs_cache_.append(output[0].squeeze())
for layer in mt.model.model.layers:
store_hooks.append(layer.self_attn.register_forward_hook(store_attn_hook))
output = mt.model(**inp_source, output_hidden_states=True)
if module == "hs":
hs_cache_ = [
output["hidden_states"][layer + 1][0] for layer in range(mt.num_layers)
]
remove_hooks(store_hooks)
# now do a second run on prompt, while patching
# a specific hidden state from the first run.
hs_patch_config = {
layer_target: [(
position_target,
hs_cache_[layer_source][position_source],
)]
}
if layer_source == layer_target == mt.num_layers - 1:
skip_final_ln = True
else:
skip_final_ln = False
patch_hooks = mt.set_hs_patch_hooks(
mt.model,
hs_patch_config,
module=module,
patch_input=False,
skip_final_ln=skip_final_ln,
generation_mode=True,
)
# Single prediction / generation
if verbose:
print(
"prompt:", [mt.tokenizer.decode(x) for x in inp_source["input_ids"][0]]
)
print(
f"patching position {position_target} with the hidden state from layer"
f" {layer_source} at position {position_source}."
)
if generation_mode:
# Checking if should perform temperature sampling, to allow smoother
# non-repeating long outputs.
if temperature:
output_toks = mt.model.generate(
inp_target["input_ids"],
max_length=len(inp_target["input_ids"][0]) + max_gen_len,
pad_token_id=mt.model.generation_config.eos_token_id,
temperature=temperature,
do_sample=True,
top_k=0,
)[0][len(inp_target["input_ids"][0]) :]
else:
output_toks = mt.model.generate(
inp_target["input_ids"],
max_length=len(inp_target["input_ids"][0]) + max_gen_len,
pad_token_id=mt.model.generation_config.eos_token_id,
)[0][len(inp_target["input_ids"][0]) :]
output = mt.tokenizer.decode(output_toks)
if verbose:
print(
"generation with patching: ",
[mt.tokenizer.decode(x) for x in output_toks],
)
else:
output = mt.model(**inp_target)
answer_prob, answer_t = torch.max(
torch.softmax(output.logits[0, -1, :], dim=0), dim=0
)
output = decode_tokens(mt.tokenizer, [answer_t])[0], round(
answer_prob.cpu().item(), 4
)
if verbose:
print("prediction with patching: ", output)
# remove patching hooks
remove_hooks(patch_hooks)
return output
def evaluate_patch_next_token_prediction(
mt,
prompt_source,
prompt_target,
layer_source,
layer_target,
position_source,
position_target,
module="hs",
position_prediction=-1,
transform=None,
):
"""Evaluate next token prediction."""
if module != "hs":
raise ValueError("Module %s not yet supported", module)
# adjust position_target to be absolute rather than relative
inp_target = make_inputs(mt.tokenizer, [prompt_target], mt.device)
if position_target < 0:
position_target = len(inp_target["input_ids"][0]) + position_target
# first run the the model on without patching and get the results.
inp_source = make_inputs(mt.tokenizer, [prompt_source], mt.device)
output_orig = mt.model(**inp_source, output_hidden_states=True)
dist_orig = torch.softmax(output_orig.logits[0, position_source, :], dim=0)
_, answer_t_orig = torch.max(dist_orig, dim=0)
hidden_rep = output_orig["hidden_states"][layer_source + 1][0][
position_source
]
if transform is not None:
hidden_rep = transform(hidden_rep)
# now do a second run on prompt, while patching the input hidden state.
hs_patch_config = {layer_target: [(position_target, hidden_rep)]}
if layer_source == layer_target == mt.num_layers - 1:
skip_final_ln = True
else:
skip_final_ln = False
patch_hooks = mt.set_hs_patch_hooks(
mt.model,
hs_patch_config,
module=module,
patch_input=False,
skip_final_ln=skip_final_ln,
generation_mode=True,
)
output = mt.model(**inp_target)
dist = torch.softmax(output.logits[0, position_prediction, :], dim=0)
_, answer_t = torch.max(dist, dim=0)
# remove patching hooks
remove_hooks(patch_hooks)
prec_1 = (answer_t == answer_t_orig).detach().cpu().item()
surprisal = -torch.log(dist_orig[answer_t]).detach().cpu().numpy()
return prec_1, surprisal
def evaluate_patch_next_token_prediction_x_model(
mt_1,
mt_2,
prompt_source,
prompt_target,
layer_source,
layer_target,
position_source,
position_target,
module="hs",
position_prediction=-1,
transform=None,
):
"""evaluate next token prediction across models."""
if module != "hs":
raise ValueError("Module %s not yet supported", module)
# adjust position_target to be absolute rather than relative
inp_target = make_inputs(mt_2.tokenizer, [prompt_target], device=mt_2.device)
if position_target < 0:
position_target = len(inp_target["input_ids"][0]) + position_target
# first run the the model on without patching and get the results.
inp_source = make_inputs(mt_1.tokenizer, [prompt_source], device=mt_1.device)
output_orig = mt_1.model(**inp_source, output_hidden_states=True)
dist_orig = torch.softmax(output_orig.logits[0, position_source, :], dim=0)
_, answer_t_orig = torch.max(dist_orig, dim=0)
hidden_rep = output_orig["hidden_states"][layer_source + 1][0][
position_source
]
if transform is not None:
hidden_rep = transform(hidden_rep)
# now do a second run on prompt, while patching the input hidden state.
hs_patch_config = {layer_target: [(position_target, hidden_rep)]}
skip_final_ln = False
patch_hooks = mt_2.set_hs_patch_hooks(
mt_2.model,
hs_patch_config,
module=module,
patch_input=False,
skip_final_ln=skip_final_ln,
generation_mode=True,
)
output = mt_2.model(**inp_target)
dist = torch.softmax(output.logits[0, position_prediction, :], dim=0)
_, answer_t = torch.max(dist, dim=0)
# remove patching hooks
remove_hooks(patch_hooks)
prec_1 = answer_t.detach().cpu().item() == answer_t_orig.detach().cpu().item()
surprisal = -torch.log(dist_orig[answer_t]).detach().cpu().numpy()
return prec_1, surprisal
# Adding support for batched patching. More than 10x speedup
# Currently only supporting GPT-J
def set_hs_patch_hooks_gptj_batch(
model,
hs_patch_config,
module="hs",
patch_input=False,
generation_mode=False,
):
"""GPTJ patch hooks - supporting batch."""
# when using mode.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need to
# handle these cases in this call because this hook wraps the generation call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation if
# we are handling the initial input or a future step and thus don't know if
# a patching is needed or not.
# if generation_mode:
# for i in hs_patch_config:
# for position_, _ in hs_patch_config[i]:
# assert position_ > 0
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, inp):
# (batch, sequence, hidden_state)
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
input_len = len(inp[0][idx_])
if generation_mode and input_len == 1:
return
inp[0][idx_][position_] = hs_
def post_hook(module, inp, output):
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[idx_])
if generation_mode and output_len == 1:
return
output[idx_][position_] = hs_
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][idx_])
if generation_mode and output_len == 1:
return
output[0][idx_][position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for item in hs_patch_config:
i = item["layer_target"]
skip_final_ln = item["skip_final_ln"]
if patch_input:
hooks.append(
model.transformer.h[i].register_forward_pre_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
else:
# when patching a last-layer representation to the last layer of the same
# model, the final layer norm is not needed because it was already
# applied (assuming that the representation for patching was obtained by
# setting output_hidden_representations to True).
if skip_final_ln and i == len(model.transformer.h) - 1:
hooks.append(
model.transformer.ln_f.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln",
item,
patch_input,
generation_mode,
)
)
)
else:
hooks.append(
model.transformer.h[i].register_forward_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
return hooks
def set_hs_patch_hooks_llama_batch(
model,
hs_patch_config,
module="hs",
patch_input=False,
generation_mode=False,
):
"""LLAMA patch hooks - supporting batch."""
# when using mode.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need to
# handle these cases in this call because this hook wraps the generation call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation if
# we are handling the initial input or a future step and thus don't know if
# a patching is needed or not.
# if generation_mode:
# for i in hs_patch_config:
# for position_, _ in hs_patch_config[i]:
# assert position_ > 0
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, inp):
# inp[0]: (batch, sequence, hidden_state)
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
input_len = len(inp[0][idx_])
if generation_mode and input_len == 1:
return
inp[0][idx_][position_] = hs_
def post_hook(module, inp, output):
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[idx_])
if generation_mode and output_len == 1:
return
output[idx_][position_] = hs_
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][idx_])
if generation_mode and output_len == 1:
return
output[0][idx_][position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for item in hs_patch_config:
i = item["layer_target"]
skip_final_ln = item["skip_final_ln"]
if patch_input:
hooks.append(
model.model.layers[i].register_forward_pre_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
else:
# when patching a last-layer representation to the last layer of the same
# model, the final layer norm is not needed because it was already applied
# (assuming that the representation for patching was obtained by setting
# output_hidden_representations to True).
if skip_final_ln and i == len(model.model.layers) - 1:
hooks.append(
model.model.norm.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln", item, patch_input, generation_mode
)
)
)
else:
hooks.append(
model.model.layers[i].register_forward_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
return hooks
def set_hs_patch_hooks_neox_batch(
model,
hs_patch_config,
module="hs", # mlp, attn
patch_input=False,
skip_final_ln=False,
generation_mode=False,
):
"""Neox patch hooks - supporting batch."""
# when using mode.generate() the hidden states in the input are cached after
# the first inference pass, and in the next steps the input/output are of
# size 1. In these cases we don't need to patch anymore the previous hidden
# states from the initial input, because they are cached, but we do need
# to handle these cases in this call because this hook wraps the generation
# call.
#
# NOTE: To use generation mode, we must patch a position that is not the
# first one. This is because in this case we don't know during generation if
# we are handling the initial input or a future step and thus don't know
# if a patching is needed or not.
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, inp):
# (batch, sequence, hidden_state)
idx_, position_, hs_ = position_hs["batch_idx"], position_hs["position_target"], position_hs["hidden_rep"]
input_len = len(inp[0][idx_])
if generation_mode and input_len == 1:
return
inp[0][idx_][position_] = hs_
def post_hook(module, inp, output):
idx_, position_, hs_ = position_hs["batch_idx"], position_hs["position_target"], position_hs["hidden_rep"]
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = len(output[idx_])
if generation_mode and output_len == 1:
return
output[idx_][position_] = hs_
else:
# output[0]: (batch, sequence, hidden_state)
output_len = len(output[0][idx_])
if generation_mode and output_len == 1:
return
output[0][idx_][position_] = hs_
if patch_input:
return pre_hook
else:
return post_hook
hooks = []
for item in hs_patch_config:
i = item["layer_target"]
skip_final_ln = item["skip_final_ln"]
if patch_input:
hooks.append(
model.gpt_neox.layers[i].register_forward_pre_hook(
patch_hs(
f"patch_hs_{i}",
item,
patch_input,
generation_mode,
)
)
)
else:
# when patching a last-layer representation to the last layer of the
# same model, the final layer norm is not needed because it was already
# applied (assuming that the representation for patching was obtained by
# setting output_hidden_representations to True).
if skip_final_ln and i == len(model.gpt_neox.layers) - 1:
hooks.append(
model.gpt_neox.final_layer_norm.register_forward_hook(
patch_hs(
f"patch_hs_{i}_skip_ln",
item,
patch_input,
generation_mode,
)
)
)
else:
hooks.append(
model.gpt_neox.layers[i].register_forward_hook(
patch_hs(
f"patch_hs_{i}",
item,
patch_input,
generation_mode,
)
)
)
return hooks
def set_hs_patch_hooks_mistral_batch(
model,
hs_patch_config,
module="hs",
patch_input=False,
generation_mode=False,
):
"""MISTRAL patch hooks - supporting batch."""
if module != "hs":
raise ValueError("Module %s not yet supported", module)
def patch_hs(name, position_hs, patch_input, generation_mode):
def pre_hook(module, inp):
# inp[0]: (batch, sequence, hidden_state)
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
input_len = inp[0][idx_].size(0) # 使用PyTorch Tensor的size获取长度
if generation_mode and input_len == 1:
return
inp[0][idx_][position_] = hs_
def post_hook(module, inp, output):
idx_, position_, hs_ = (
position_hs["batch_idx"],
position_hs["position_target"],
position_hs["hidden_rep"],
)
if "skip_ln" in name:
# output: (batch, sequence, hidden_state)
output_len = output[idx_].size(0)
if generation_mode and output_len == 1:
return
output[idx_][position_] = hs_
else:
# output[0]: (batch, sequence, hidden_state)
output_len = output[0][idx_].size(0)
if generation_mode and output_len == 1:
return
output[0][idx_][position_] = hs_
return pre_hook if patch_input else post_hook
hooks = []
for item in hs_patch_config:
i = item["layer_target"]
skip_final_ln = item["skip_final_ln"]
target_layer = model.model.layers[i]
target_norm = model.model.norm
if patch_input:
hooks.append(
target_layer.register_forward_pre_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
else:
if skip_final_ln and i == len(model.model.layers) - 1:
hooks.append(
target_norm.register_forward_hook(
patch_hs(f"patch_hs_{i}_skip_ln", item, patch_input, generation_mode)
)
)
else:
hooks.append(
target_layer.register_forward_hook(
patch_hs(f"patch_hs_{i}", item, patch_input, generation_mode)
)
)
return hooks
def set_hs_patch_T5_batch(
model,
hs_patch_config,
module="hs",
patch_input=False,
generation_mode=False,
):
"""T5 patch hooks - supporting batch."""
if module != "hs":
raise ValueError("Module %s not yet supported", module)