-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrace_circuit.py
2761 lines (2494 loc) · 139 KB
/
trace_circuit.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
from random import seed, randrange, shuffle
import numpy as np
import torch
from torch import nn, LongTensor, FloatTensor
from train import generate_example, lookahead_depth, generate_eval_data
from gpt2 import TokenEmbedding
import math
def normalize_conditions(conditions):
# normalize the list of conditions
for i in range(len(conditions)):
(row1,col1,sign1,row2,col2,sign2) = conditions[i]
if row1 < row2:
continue
elif row1 == row2 and col1 < col2:
continue
elif row1 == row2 and col1 == col2 and sign1 < sign2:
continue
conditions[i] = (row2,col2,sign2,row1,col1,sign1)
conditions.sort()
def compute_attention(layer_index: int, attn_layer, x: torch.Tensor, mask: torch.Tensor):
n, d = x.shape[-2], x.shape[-1]
k_params = {k:v for k,v in attn_layer.proj_k.named_parameters()}
q_params = {k:v for k,v in attn_layer.proj_q.named_parameters()}
P_k = k_params['weight']
P_q = q_params['weight']
U_k = torch.cat((P_k,k_params['bias'].unsqueeze(1)),1)
U_q = torch.cat((P_q,q_params['bias'].unsqueeze(1)),1)
A = torch.matmul(U_q.transpose(-2,-1),U_k)
x_prime = torch.cat((x, torch.ones(x.shape[:-1] + (1,), device=device)), -1)
QK = torch.matmul(torch.matmul(x_prime, A), x_prime.transpose(-2,-1)) / math.sqrt(d)
attn_pre_softmax = QK + mask.type_as(QK) * QK.new_tensor(-1e9)
attn = attn_layer.attn.dropout(attn_pre_softmax.softmax(-1))
if attn_layer.proj_v:
v = attn_layer.proj_v(x)
else:
v = x
new_x = torch.matmul(attn, v)
if attn_layer.linear:
out = attn_layer.linear(new_x)
else:
out = new_x
return out, attn_pre_softmax, attn, v, new_x, A
def forward(model, x: torch.Tensor, mask: torch.Tensor, start_layer: int, start_at_ff: bool, end_layer: int, perturbations, frozen_ops):
# Apply transformer layers sequentially.
layer_inputs = [None] * start_layer
attn_inputs = [None] * start_layer
attn_matrices = [None] * start_layer
v_outputs = [None] * start_layer
attn_linear_inputs = [None] * start_layer
attn_outputs = [None] * start_layer
attn_pre_softmax = [None] * start_layer
A_matrices = [None] * start_layer
ff_inputs = [None] * start_layer
ff_parameters = [None] * start_layer
current_layer = start_layer
for layer_idx in range(start_layer,end_layer+1):
transformer = model.transformers[layer_idx]
# Layer normalizations are performed before the layers respectively.
if perturbations != None:
for (perturb_layer, perturb_index, perturb_vec) in perturbations:
if current_layer == perturb_layer:
if perturb_index == -1:
x[0:,:] = perturb_vec[0:,:]
else:
x[perturb_index,:] = perturb_vec
if start_at_ff:
layer_inputs.append(None)
attn_inputs.append(None)
v_outputs.append(None)
attn_matrices.append(None)
attn_linear_inputs.append(None)
A_matrices.append(None)
start_at_ff = False
else:
layer_inputs.append(x)
a = transformer.ln_attn(x)
attn_inputs.append(a)
if frozen_ops != None and layer_idx < len(frozen_ops):
attn_matrix = frozen_ops[layer_idx][0]
if transformer.attn.proj_v:
v = transformer.attn.proj_v(a)
else:
v = x
attn_linear_input = torch.matmul(attn_matrix, v)
if transformer.attn.linear:
a = transformer.attn.linear(attn_linear_input)
else:
a = attn_linear_input
pre_softmax, A = None, None
elif transformer.attn.proj_v:
a, pre_softmax, attn_matrix, v, attn_linear_input, A = compute_attention(current_layer, transformer.attn, a, mask)
else:
a, pre_softmax, attn_matrix, v, attn_linear_input, A = compute_attention(current_layer, transformer.attn, x, mask)
v_outputs.append(v)
attn_matrices.append(attn_matrix)
attn_pre_softmax.append(pre_softmax)
attn_linear_inputs.append(attn_linear_input)
attn_outputs.append(a)
A_matrices.append(A)
x = x + a
ff_inputs.append(x)
if transformer.ff:
if False and frozen_ops != None and layer_idx < len(frozen_ops):
ff_mask = frozen_ops[layer_idx][1]
x = x + transformer.ff[3](transformer.ff[2](ff_mask * transformer.ff[0](transformer.ln_ff(x))))
else:
x = x + transformer.ff(transformer.ln_ff(x))
ff_params = {k:v for k,v in transformer.ff.named_parameters()}
ff_parameters.append((ff_params['0.weight'].T, ff_params['3.weight'].T, ff_params['0.bias'], ff_params['3.bias']))
else:
ff_parameters.append((None, None, None, None))
#print(x[-1,:])
current_layer += 1
layer_inputs.append(x)
token_dim = model.token_embedding.shape[0]
if model.ln_head:
x = model.ln_head(x)
if model.positional_embedding is not None:
x = x[...,:-model.positional_embedding.shape[0]]
if type(model.token_embedding) == TokenEmbedding:
x = model.token_embedding(x, transposed=True)
else:
x = torch.matmul(x, model.token_embedding.transpose(0, 1))
prediction = torch.argmax(x[...,-1,:token_dim], dim=-1).tolist()
return layer_inputs, attn_inputs, attn_pre_softmax, attn_matrices, v_outputs, attn_linear_inputs, attn_outputs, A_matrices, ff_inputs, ff_parameters, prediction
@torch.no_grad()
def activation_patch_output_logit(model, j, layer_input, mask, prediction, attn_matrices):
n = layer_input.size(0)
frozen_ops = []
for k in range(j):
frozen_ops.append((attn_matrices[k], None))
frozen_ops.append(None)
attn_matrix = attn_matrices[j]
zero_output_logits = torch.empty(n*n, device=layer_input.device)
max_output_logits = torch.empty(n*n, device=layer_input.device)
# try zeroing attn_matrix[a,b] for all a,b
new_attn_matrices = attn_matrix.repeat(n*n,1,1).detach()
diag_indices = torch.cat((torch.arange(0,n*n).unsqueeze(1),torch.cartesian_prod(torch.arange(0,n),torch.arange(0,n))),dim=1)
new_attn_matrices[tuple(diag_indices.T)] = 0.0
# perform forward pass on other_inputs
BATCH_SIZE = 1024
for start in range(0, n*n, BATCH_SIZE):
end = min(start + BATCH_SIZE, n*n)
frozen_ops[j] = (new_attn_matrices[start:end,], None)
perturb_layer_inputs, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, layer_input.repeat(end-start,1,1).detach(), mask, j, False, len(model.transformers)-1, None, frozen_ops)
# try computing the attention dot product but with perturbed dst embeddings
zero_output_logits[start:end] = perturb_layer_inputs[-1][:,-1,prediction]
del perturb_attn_inputs
del perturb_layer_inputs
zero_output_logits = zero_output_logits.reshape((n,n))
# try maxing attn_matrix[a,b] for all a,b
new_attn_matrices = attn_matrix.repeat(n*n,1,1).detach()
new_attn_matrices[tuple(diag_indices.T)] = torch.max(attn_matrix,dim=0).values.repeat((1,n)).T.flatten()
#new_attn_matrices /= torch.sum(new_attn_matrices,dim=0).unsqueeze(-1).repeat((1,1,n))
# perform forward pass on other_inputs
BATCH_SIZE = 1024
for start in range(0, n*n, BATCH_SIZE):
end = min(start + BATCH_SIZE, n*n)
frozen_ops[j] = (new_attn_matrices[start:end,], None)
perturb_layer_inputs, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, layer_input.repeat(end-start,1,1).detach(), mask, j, False, len(model.transformers)-1, None, frozen_ops)
# try computing the attention dot product but with perturbed dst embeddings
max_output_logits[start:end] = perturb_layer_inputs[-1][:,-1,prediction]
del perturb_attn_inputs
del perturb_layer_inputs
max_output_logits = max_output_logits.reshape((n,n))
return zero_output_logits, max_output_logits
@torch.no_grad()
def perturb_attn_ops(model, i, j, dst, src, layer_input, mask, A_matrices, attn_matrices, attn_inputs):
A = A_matrices[i][:-1,:-1]
n = attn_inputs[i].size(0)
frozen_ops = []
for k in range(j):
frozen_ops.append((attn_matrices[k], None))
frozen_ops.append(None)
attn_matrix = attn_matrices[j]
zero_src_products = torch.empty(n*n, device=layer_input.device)
zero_dst_products = torch.empty(n*n, device=layer_input.device)
max_src_products = torch.empty(n*n, device=layer_input.device)
max_dst_products = torch.empty(n*n, device=layer_input.device)
# try zeroing attn_matrix[a,b] for all a,b
new_attn_matrices = attn_matrix.repeat(n*n,1,1).detach()
diag_indices = torch.cat((torch.arange(0,n*n).unsqueeze(1),torch.cartesian_prod(torch.arange(0,n),torch.arange(0,n))),dim=1)
new_attn_matrices[tuple(diag_indices.T)] = 0.0
# perform forward pass on other_inputs
BATCH_SIZE = 1024
for start in range(0, n*n, BATCH_SIZE):
end = min(start + BATCH_SIZE, n*n)
frozen_ops[j] = (new_attn_matrices[start:end,], None)
#_, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, layer_input.repeat(end-start,1,1).detach(), mask, j, False, i, None, frozen_ops)
perturb_layer_inputs, perturb_attn_inputs, perturb_attn_pre_softmax, perturb_attn_matrices, perturb_v_outputs, perturb_attn_linear_inputs, perturb_attn_outputs, perturb_A_matrices, perturb_ff_inputs, perturb_ff_parameters, perturb_prediction = forward(model, layer_input.repeat(end-start,1,1).detach(), mask, j, False, i, None, frozen_ops)
# try computing the attention dot product but with perturbed dst embeddings
zero_src_products[start:end] = torch.matmul(torch.matmul(attn_inputs[i], A), perturb_attn_inputs[i].transpose(-2,-1))[:,dst,src]
zero_dst_products[start:end] = torch.matmul(torch.matmul(perturb_attn_inputs[i], A), attn_inputs[i].transpose(-2,-1))[:,dst,src]
del perturb_attn_inputs
zero_src_products = zero_src_products.reshape((n,n))
zero_dst_products = zero_dst_products.reshape((n,n))
# try maxing attn_matrix[a,b] for all a,b
new_attn_matrices = attn_matrix.repeat(n*n,1,1).detach()
new_attn_matrices[tuple(diag_indices.T)] = torch.max(attn_matrix,dim=0).values.repeat((1,n)).T.flatten()
#new_attn_matrices /= torch.sum(new_attn_matrices,dim=0).unsqueeze(-1).repeat((1,1,n))
# perform forward pass on other_inputs
BATCH_SIZE = 1024
for start in range(0, n*n, BATCH_SIZE):
end = min(start + BATCH_SIZE, n*n)
frozen_ops[j] = (new_attn_matrices[start:end,], None)
_, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, layer_input.repeat(end-start,1,1).detach(), mask, j, False, i, None, frozen_ops)
# try computing the attention dot product but with perturbed dst embeddings
max_src_products[start:end] = torch.matmul(torch.matmul(attn_inputs[i], A), perturb_attn_inputs[i].transpose(-2,-1))[:,dst,src]
max_dst_products[start:end] = torch.matmul(torch.matmul(perturb_attn_inputs[i], A), attn_inputs[i].transpose(-2,-1))[:,dst,src]
del perturb_attn_inputs
max_src_products = max_src_products.reshape((n,n))
max_dst_products = max_dst_products.reshape((n,n))
return zero_src_products, zero_dst_products, max_src_products, max_dst_products
@torch.no_grad()
def perturb_residuals(model, i, j, dst, src, mask, A_matrices, attn_inputs, attn_outputs, ff_inputs):
A = A_matrices[i][:-1,:-1]
n = attn_inputs[i].size(0)
d = attn_inputs[i].size(1)
res_src_products = torch.empty(n, device=attn_inputs[i].device)
res_dst_products = torch.empty(n, device=attn_inputs[i].device)
# try zeroing the residual of token k, for all k
new_ff_input = ff_inputs[j].repeat(n,1,1).detach()
diag_indices = torch.cartesian_prod(torch.arange(0,n),torch.arange(0,d))
diag_indices = torch.cat((diag_indices[:,0].unsqueeze(1),diag_indices),dim=-1)
new_ff_input[tuple(diag_indices.T)] = attn_outputs[j].reshape(n*d)
# perform forward pass on other_inputs
_, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, new_ff_input.detach(), mask, j, True, i, None, None)
res_src_products = torch.matmul(torch.matmul(attn_inputs[i], A), perturb_attn_inputs[i].transpose(-2,-1))[:,dst,src]
res_dst_products = torch.matmul(torch.matmul(perturb_attn_inputs[i], A), attn_inputs[i].transpose(-2,-1))[:,dst,src]
del perturb_attn_inputs
return res_src_products, res_dst_products
class NoUnusedVertexIDs(Exception):
pass
@torch.no_grad()
def explain_attn_op(model, input, mask, A_matrices, attn_matrices, attn_inputs, ff_inputs, i, dst, src, sign):
n, d = attn_inputs[0].size(0), attn_inputs[0].size(1)
EDGE_PREFIX_TOKEN = (n - 5) // 3 + 2
edge_indices = [i + 1 for i in range(len(input)) if input[i] == EDGE_PREFIX_TOKEN]
# create perturbed inputs where each input replaces every occurrence of a token value with an unused token value
max_vertex_id = (n - 5) // 3
try:
unused_id = next(t for t in range(1, max_vertex_id + 5) if t not in input)
except StopIteration:
raise NoUnusedVertexIDs()
other_inputs = input.repeat(max_vertex_id + 5 + n, 1)
for j in range(max_vertex_id + 5):
other_inputs[j,input == j] = unused_id
# perform forward pass on other_inputs
other_inputs = model.token_embedding[other_inputs]
if len(other_inputs.shape) == 2:
pos = model.positional_embedding
else:
pos = model.positional_embedding.unsqueeze(0).expand(other_inputs.shape[0:-2] + (-1,-1))
other_inputs = torch.cat((other_inputs, pos), -1)
other_inputs = model.dropout_embedding(other_inputs)
# for the last n rows of `other_inputs`, perturb the position embeddings
for j in range(n):
#if j < edge_indices[-1] or j > edge_indices[-1] + 2:
# src_edge_index = edge_indices[-1]
#else:
# src_edge_index = edge_indices[-2]
#offset = (src_edge_index % 3) - (j % 3)
#if offset > 1:
# offset -= 3
other_inputs[max_vertex_id+5+j,j,d-n:] = 0 #other_inputs[max_vertex_id+5+j,src_edge_index-offset,d-n:].clone().detach()
frozen_ops = []
for j in range(i):
frozen_ops.append((attn_matrices[j], model.transformers[j].ff[0](model.transformers[j].ln_ff(ff_inputs[j])) > 0.0))
_, perturb_attn_inputs, _, _, _, _, _, _, _, _, _ = forward(model, other_inputs, mask, 0, False, i, None, frozen_ops)
# try computing the attention dot product but with perturbed dst embeddings
A = A_matrices[i][:-1,:-1]
old_products = torch.matmul(torch.matmul(attn_inputs[i], A), attn_inputs[i].T)
old_product = old_products[dst, src]
new_src_products = torch.matmul(torch.matmul(attn_inputs[i], A), perturb_attn_inputs[i].transpose(-2,-1))
new_dst_products = torch.matmul(torch.matmul(perturb_attn_inputs[i], A), attn_inputs[i].transpose(-2,-1))
new_src_products = new_src_products[:,dst,src]
new_dst_products = new_dst_products[:,dst,src]
if sign == 0:
print('WARNING: Found an attention operation that is both positive and negative.')
is_negative_copy = (sign == -1) #(attn_matrices[i][dst,src] < torch.median(attn_matrices[i][dst,edge_indices]))
if is_negative_copy:
src_dependencies = torch.nonzero(new_src_products > old_product + math.sqrt(d) / 10)
dst_dependencies = torch.nonzero(new_dst_products > old_product + math.sqrt(d) / 10)
src_dependencies = src_dependencies[torch.sort(new_src_products[src_dependencies],dim=0,descending=True).indices]
dst_dependencies = dst_dependencies[torch.sort(new_dst_products[dst_dependencies],dim=0,descending=True).indices]
else:
src_dependencies = torch.nonzero(new_src_products < old_product - math.sqrt(d) / 10)
dst_dependencies = torch.nonzero(new_dst_products < old_product - math.sqrt(d) / 10)
src_dependencies = src_dependencies[torch.sort(new_src_products[src_dependencies],dim=0,descending=False).indices]
dst_dependencies = dst_dependencies[torch.sort(new_dst_products[dst_dependencies],dim=0,descending=False).indices]
return src_dependencies, dst_dependencies
class TransformerProber(nn.Module):
def __init__(self, tfm_model, probe_layer):
super().__init__()
d = tfm_model.ln_head.normalized_shape[0]
self.model = tfm_model
for param in tfm_model.parameters():
param.requires_grad = False
self.probe_layer = probe_layer
n = tfm_model.positional_embedding.size(0)
self.A_ops = [nn.parameter.Parameter(torch.empty((d,d)))]
if probe_layer > len(tfm_model.transformers):
raise Exception('probe_layer must be <= number of layers')
def reset_parameters(self) -> None:
for A_op in self.A_ops:
nn.init.kaiming_uniform_(A_op, a=math.sqrt(5))
def to(self, device):
super().to(device)
for A_op in self.A_ops:
A_op.to(device)
def forward(self, x: torch.Tensor):
d = self.model.ln_head.normalized_shape[0]
n = self.model.positional_embedding.size(0)
QUERY_PREFIX_TOKEN = (n - 5) // 3 + 4
PADDING_TOKEN = (n - 5) // 3 + 3
EDGE_PREFIX_TOKEN = (n - 5) // 3 + 2
PATH_PREFIX_TOKEN = (n - 5) // 3 + 1
other_inputs = x.repeat((3*n+1,1))
# create perturbed inputs where each input replaces every occurrence of a token value with an unused token value
max_vertex_id = (n - 5) // 3
unused_id = next(t for t in range(1, max_vertex_id + 1) if t not in x)
for j in range(max_vertex_id + 1):
other_inputs[j,x == j] = unused_id
# create perturbed inputs where each input swaps the position of one token
other_inputs = self.model.token_embedding[other_inputs]
if len(other_inputs.shape) == 2:
pos = self.model.positional_embedding
else:
pos = self.model.positional_embedding.unsqueeze(0).expand(other_inputs.shape[0], -1, -1)
other_inputs = torch.cat((other_inputs, pos), -1)
other_inputs = self.model.dropout_embedding(other_inputs)
# perturb the position embeddings
edge_indices = [i + 1 for i in range(len(x)) if x[i] == EDGE_PREFIX_TOKEN]
for j in range(n):
if x[j] in (PADDING_TOKEN, QUERY_PREFIX_TOKEN, PATH_PREFIX_TOKEN):
continue
if j < edge_indices[-1] or j > edge_indices[-1] + 2:
src_edge_index = edge_indices[-1]
else:
src_edge_index = edge_indices[-2]
offset = (src_edge_index % 3) - (j % 3)
if offset > 1:
offset -= 3
other_inputs[n+j,j,:d-n] = 0
other_inputs[n+j,j,unused_id] = 1
other_inputs[2*n+j,j,d-n:] = other_inputs[n+j,src_edge_index-offset,d-n:].clone().detach()
# Create masking tensor.
mask = self.model.pad_masking(x, 0)
if not self.model.bidirectional:
mask = mask + self.model.future_masking(x, 0)
# perform forward pass on original input
x = self.model.token_embedding[x]
if len(x.shape) == 2:
pos = self.model.positional_embedding
else:
pos = self.model.positional_embedding.unsqueeze(0).expand(x.shape[0], -1, -1)
x = torch.cat((x, pos), -1)
x = self.model.dropout_embedding(x)
_,attn_inputs,_,_,_,_,_,A_matrices,_,_,_ = forward(self.model, x, mask, 0, False, self.probe_layer, None, None)
# perform forward pass on other_inputs
_,perturb_attn_inputs,_,_,_,_,_,_,_,_,_ = forward(self.model, other_inputs, mask, 0, False, self.probe_layer, None, None)
y = x.clone().detach()
perturb_y = other_inputs.clone().detach()
mixed_A_predictions = []
mixed_A_labels = []
for i in range(self.probe_layer + 1):
left_mixed_a = torch.matmul(torch.matmul(perturb_y, self.A_ops[i]), y.transpose(-2,-1))
right_mixed_a = torch.matmul(torch.matmul(y, self.A_ops[i]), perturb_y.transpose(-2,-1))
mixed_A_predictions.append((left_mixed_a,right_mixed_a))
A = A_matrices[i][:-1,:-1]
left_mixed_a_label = torch.matmul(torch.matmul(perturb_attn_inputs[i], A), attn_inputs[i].T)
right_mixed_a_label = torch.matmul(torch.matmul(attn_inputs[i], A), torch.permute(perturb_attn_inputs[i],(0,2,1)))
mixed_A_labels.append((left_mixed_a_label,right_mixed_a_label))
break
a = torch.matmul(torch.matmul(y, self.A_ops[i]), y.transpose(-2,-1))
if mask is not None:
a += mask.type_as(a) * a.new_tensor(-1e9)
a = a.softmax(-1)
y += torch.matmul(a, y)
perturb_a = torch.matmul(torch.matmul(perturb_y, self.A_ops[i]), perturb_y.transpose(-2,-1))
if mask is not None:
perturb_a += mask.type_as(perturb_a) * perturb_a.new_tensor(-1e9)
perturb_a = perturb_a.softmax(-1)
perturb_y += torch.matmul(perturb_a, perturb_y)
return mixed_A_predictions, mixed_A_labels
class AlgorithmCase:
def __init__(self, conditions, then, inputs):
# `conditions` is a list of tuples (x_i,y_i,z_i,u_i,v_i,w_i), representing a conjunction of conditions checking if x_i[y_i] is large if `z_i == True`, or x_i[y_i] is small if `z_i == False`, and u_i[v_i] is large if `w_i == True`, or u_i[v_i] is small if `w_i == False`
self.conditions = conditions
# `then` is a list of tuples (s_i,d_i) representing a sequence of copy operations, where row s_i from the input is copied into row d_i of the output
self.then = then
self.inputs = inputs
# normalize the list of conditions and then
normalize_conditions(self.conditions)
def __str__(self):
s = 'if'
first = True
for (x,y,z,u,v,w) in self.conditions:
if not first:
s += ' and'
first = False
if z == True:
s += ' (x[{},{}] is large'.format(x,y)
else:
s += ' (x[{},{}] is small'.format(x,y)
if w == True:
s += ' and x[{},{}] is large)'.format(u,v)
else:
s += ' and x[{},{}] is small)'.format(u,v)
s += ':'
for (src,dst) in self.then:
s += '\n copy x[{},:] into x[{},:]'.format(src,dst)
return s
class AlgorithmStep:
def __init__(self):
self.cases = []
self.residual_copies = []
self.token_operations = {}
self.position_operations = {}
self.token_operation_inputs = {}
self.position_operation_inputs = {}
def add_case(self, conditions, then_instruction, input):
normalize_conditions(conditions)
for case in self.cases:
if conditions == case.conditions:
if then_instruction not in case.then:
case.then.append(then_instruction)
case.inputs.append(input)
return
self.cases.append(AlgorithmCase(conditions, [then_instruction], [input]))
def add_residual_copy(self, row):
if row not in self.residual_copies:
self.residual_copies.append(row)
def identify_operations(self, embedding_dim, token_dim, position_dim):
self.token_operations = {}
self.position_operations = {}
self.token_operation_inputs = {}
self.position_operation_inputs = {}
for case in self.cases:
for (x,y,z,u,v,w) in case.conditions:
diff = y - v
if y < token_dim and v < token_dim:
if diff not in self.token_operations:
self.token_operations[diff] = []
self.token_operation_inputs[diff] = []
if y not in self.token_operations[diff]:
self.token_operations[diff].append(y)
self.token_operation_inputs[diff].extend(case.inputs)
elif y >= embedding_dim - position_dim and v >= embedding_dim - position_dim:
if diff not in self.position_operations:
self.position_operations[diff] = []
self.position_operation_inputs[diff] = []
if y not in self.position_operations[diff]:
self.position_operations[diff].append(y)
self.position_operation_inputs[diff].extend(case.inputs)
def list_to_tuple(l):
if isinstance(l, list):
return tuple(list_to_tuple(element) for element in l)
return l
class ComputationNode:
def __init__(self, layer, row_id):
self.layer = layer
self.row_id = row_id
self.predecessors = []
self.successors = []
self.reachable = []
self.op_explanations = []
self.copy_directions = []
self.weights = []
def add_predecessor(self, predecessor, weight):
self.predecessors.append(predecessor)
predecessor.successors.append(self)
predecessor.op_explanations.append(None)
predecessor.copy_directions.append(None)
predecessor.weights.append(weight.item() if isinstance(weight, torch.Tensor) else weight)
def __str__(self):
return '{{layer:{},id:{}}}'.format(self.layer, self.row_id)
def __repr__(self):
return '{{layer:{},id:{}}}'.format(self.layer, self.row_id)
def all_reachable_nodes(self):
visited = []
queue = [self]
while len(queue) != 0:
node = queue.pop()
if node in visited:
continue
visited.append(node)
queue.extend([s for s in node.successors if s not in queue and s not in visited])
queue.extend([s for s in node.predecessors if s not in queue and s not in visited])
return visited
def to_map(self, node_list):
return {
'layer' : self.layer,
'row_id' : self.row_id,
'predecessors' : [node_list.index(n) for n in self.predecessors],
'successors' : [node_list.index(n) for n in self.successors],
'reachable' : self.reachable,
'op_explanations' : self.op_explanations,
'copy_directions' : self.copy_directions,
'weights' : self.weights
}
def from_map(self, m, node_list):
self.layer = m['layer']
self.row_id = m['row_id']
self.predecessors = [node_list[i] for i in m['predecessors']]
self.successors = [node_list[i] for i in m['successors']]
self.reachable = m['reachable']
self.op_explanations = [list_to_tuple(e) for e in m['op_explanations']]
self.copy_directions = m['copy_directions']
self.weights = m['weights']
class TransformerTracer:
def __init__(self, tfm_model):
self.model = tfm_model
self.model.eval()
self.algorithm = [AlgorithmStep() for i in range(len(self.model.transformers))]
'''def input_derivatives(self, x: torch.Tensor, mask: torch.Tensor, dx: float, start_layer: int, start_at_ff: bool, old_prediction: int, last_layer_output: torch.Tensor):
dfdx = torch.empty(x.shape)
for i in range(x.size(0)):
for j in range(x.size(1)):
new_x = x.clone().detach()
new_x[i,j] += dx
layer_inputs, _, _, _, _, _, _, _, _, _, _ = forward(self.model, new_x, mask, start_layer, start_at_ff)
dfdx[i,j] = (layer_inputs[-1][-1,old_prediction] - last_layer_output[-1,old_prediction]) / dx
return dfdx'''
def input_derivative(self, start_layer: int, input_row_id: int, input_col_id: int, output_row_id: int, output_col_id: int, start_at_ff: bool, layer_inputs: torch.Tensor, attn_inputs: torch.Tensor, attn_pre_softmax: torch.Tensor, attn_matrices: torch.Tensor, ff_inputs: torch.Tensor):
dydx = torch.zeros(layer_inputs[start_layer].shape)
dydx[input_row_id,input_col_id] = 1.0
for i in range(start_layer, len(self.model.transformers)):
if not (i == start_layer and start_at_ff):
mu = torch.mean(layer_inputs[i], dim=1).unsqueeze(1)
dmudx = torch.mean(dydx, dim=1).unsqueeze(1)
var = (self.model.transformers[i].ln_attn.eps + torch.var(layer_inputs[i], dim=1, correction=0)).unsqueeze(1)
dybardx = (mu - layer_inputs[i])*torch.mean((layer_inputs[i] - mu)*(dydx - dmudx), dim=1).unsqueeze(1)/var + dydx - dmudx
dybardx /= torch.sqrt(var)
dybardx *= self.model.transformers[i].ln_attn.weight
left = torch.matmul(self.model.transformers[i].attn.proj_q(attn_inputs[i]), torch.matmul(dybardx, self.model.transformers[i].attn.proj_k.weight.T).T)
right = torch.matmul(torch.matmul(dybardx, self.model.transformers[i].attn.proj_q.weight.T), self.model.transformers[i].attn.proj_k(attn_inputs[i]).T)
dadx = (left + right) / math.sqrt(attn_inputs[i].size(-1))
shift = -torch.max(attn_pre_softmax[i], dim=1).values.unsqueeze(1)
numerator = torch.sum(dadx * torch.exp(attn_pre_softmax[i] + shift), dim=1)
denominator = torch.sum(torch.exp(attn_pre_softmax[i] + shift), dim=1)
dsdx = attn_matrices[i] * (dadx - numerator / denominator)
left = torch.matmul(attn_matrices[i], torch.matmul(dybardx, self.model.transformers[i].attn.proj_v.weight.T))
right = torch.matmul(dsdx, self.model.transformers[i].attn.proj_v(attn_inputs[i]))
dfdx = dydx + torch.matmul(left + right, self.model.transformers[i].attn.linear.weight.T)
dydx = dfdx
if self.model.transformers[i].ff:
mu = torch.mean(layer_inputs[i], dim=1).unsqueeze(1)
dmudx = torch.mean(dydx, dim=1).unsqueeze(1)
var = (self.model.transformers[i].ln_ff.eps + torch.var(layer_inputs[i], dim=1, correction=0)).unsqueeze(1)
dybardx = (mu - layer_inputs[i])*torch.mean((layer_inputs[i] - mu)*(dydx - dmudx), dim=1).unsqueeze(1)/var + dydx - dmudx
dybardx /= torch.sqrt(var)
dybardx *= self.model.transformers[i].ln_ff.weight
mask = self.model.transformers[i].ff[0](self.model.transformers[i].ln_ff(ff_inputs[i])) > 0.0
dfdx = dydx + torch.matmul(mask * torch.matmul(dybardx, self.model.transformers[i].ff[0].weight.T), self.model.transformers[i].ff[3].weight.T)
dydx = dfdx
return dydx[output_row_id, output_col_id]
def input_derivatives(self, start_layer: int, input_row_id: int, output_row_id: int, output_col_id: int, start_at_ff: bool, layer_inputs: torch.Tensor, attn_inputs: torch.Tensor, attn_pre_softmax: torch.Tensor, attn_matrices: torch.Tensor, ff_inputs: torch.Tensor):
out = torch.empty(layer_inputs[start_layer].size(1))
for i in range(layer_inputs[start_layer].size(1)):
out[i] = self.input_derivative(start_layer, input_row_id, i, output_row_id, output_col_id, start_at_ff, layer_inputs, attn_inputs, attn_pre_softmax, attn_matrices, ff_inputs)
return out
def trace2(self, x: torch.Tensor, quiet: bool = True):
n = x.shape[0]
max_vertex_id = (n - 5) // 3
# first check if the input has any unused vertex IDs
if all([t in x for t in range(1, max_vertex_id + 5)]):
raise NoUnusedVertexIDs()
QUERY_PREFIX_TOKEN = (n - 5) // 3 + 4
PADDING_TOKEN = (n - 5) // 3 + 3
EDGE_PREFIX_TOKEN = (n - 5) // 3 + 2
PATH_PREFIX_TOKEN = (n - 5) // 3 + 1
# Create masking tensor.
mask = self.model.pad_masking(x, 0)
if not self.model.bidirectional:
mask = mask + self.model.future_masking(x, 0)
# Use token embedding and positional embedding layers.
input = x # store the input for keeping track the code paths executed by each input
x = self.model.token_embedding[x]
if len(x.shape) == 2:
pos = self.model.positional_embedding
else:
pos = self.model.positional_embedding.unsqueeze(0).expand(x.shape[0], -1, -1)
x = torch.cat((x, pos), -1)
x = self.model.dropout_embedding(x)
d = x.shape[1]
layer_inputs, attn_inputs, attn_pre_softmax, attn_matrices, v_outputs, attn_linear_inputs, attn_outputs, A_matrices, ff_inputs, ff_parameters, prediction = forward(self.model, x, mask, 0, False, len(self.model.transformers)-1, None, None)
zero_output_logit_list = []
max_output_logit_list = []
for j in range(len(self.model.transformers)):
print('[PROFILE] Calling `activation_patch_output_logit` for layer', j, flush=True)
zero_output_logits, max_output_logits = activation_patch_output_logit(self.model, j, layer_inputs[j], mask, prediction, attn_matrices)
zero_output_logit_list.append(zero_output_logits)
max_output_logit_list.append(max_output_logits)
#major_copy_threshold = torch.min(zero_output_logit_list[len(self.model.transformers)-1]) * (1 - 1/6) + layer_inputs[-1][-1,prediction] * 1/6
#major_last_copies = torch.nonzero(zero_output_logit_list[len(self.model.transformers)-1] < major_copy_threshold)
major_last_copies = torch.nonzero(zero_output_logit_list[len(self.model.transformers)-1] < layer_inputs[-1][-1,prediction] - 0.4)
if len(major_last_copies) == 0:
print('[PROFILE] `major_last_copies` is empty, using fallback to compute major copies.', flush=True)
major_last_copies = torch.nonzero(zero_output_logit_list[len(self.model.transformers)-1] < torch.min(zero_output_logit_list[len(self.model.transformers)-1]) + 1e-6)
# only consider attention operations that copy into the last token
major_last_copies = major_last_copies[major_last_copies[:,0] == n-1,:]
last_copy_srcs = major_last_copies[:,1]
print('[PROFILE] Size of `major_last_copies`:', major_last_copies.size(0), flush=True)
zero_src_product_list = []
zero_dst_product_list = []
max_src_product_list = []
max_dst_product_list = []
res_src_product_list = []
res_dst_product_list = []
for k in range(len(last_copy_srcs)):
zero_src_product_list.append([])
zero_dst_product_list.append([])
max_src_product_list.append([])
max_dst_product_list.append([])
res_src_product_list.append([])
res_dst_product_list.append([])
for j in range(len(self.model.transformers)):
print('[PROFILE] Calling `perturb_attn_ops` for layer {}, copy index {}'.format(j, k), flush=True)
zero_src_products, zero_dst_products, max_src_products, max_dst_products = perturb_attn_ops(self.model, len(self.model.transformers)-1, j, n-1, last_copy_srcs[k], layer_inputs[j], mask, A_matrices, attn_matrices, attn_inputs)
zero_src_product_list[k].append(zero_src_products)
zero_dst_product_list[k].append(zero_dst_products)
max_src_product_list[k].append(max_src_products)
max_dst_product_list[k].append(max_dst_products)
#if j < len(self.model.transformers) - 1:
# res_src_products, res_dst_products = perturb_residuals(self.model, len(self.model.transformers)-1, j, n-1, last_copy_srcs[k], mask, A_matrices, attn_inputs, attn_outputs, ff_inputs)
# res_src_product_list[k].append(res_src_products)
# res_dst_product_list[k].append(res_dst_products)
A = A_matrices[len(self.model.transformers)-1][:-1,:-1]
old_products = torch.matmul(torch.matmul(attn_inputs[len(self.model.transformers)-1], A), attn_inputs[len(self.model.transformers)-1].T)
old_products = old_products[n-1,last_copy_srcs]
important_positive_ops = []
important_negative_ops = []
for j in range(len(self.model.transformers)):
print('[PROFILE] Identifying important attention operations in layer', j, flush=True)
new_important_positive_ops = []
new_important_negative_ops = []
positive_copies = torch.nonzero(zero_output_logit_list[j] < layer_inputs[-1][-1,prediction] - 0.4)
negative_copies = torch.nonzero(max_output_logit_list[j] < layer_inputs[-1][-1,prediction] - 0.4)
if not quiet:
print("Layer {}:".format(j))
print(" Positive copies from output logit perturbations: {}".format(positive_copies.tolist()))
print(" Negative copies from output logit perturbations: {}".format(negative_copies.tolist()))
if positive_copies.size(0) > negative_copies.size(0) or positive_copies.size(0) == 0:
new_important_negative_ops += [op.tolist() for op in negative_copies]
if positive_copies.size(0) <= negative_copies.size(0) or negative_copies.size(0) == 0:
new_important_positive_ops += [op.tolist() for op in positive_copies]
for k in range(len(zero_dst_product_list)):
positive_copies = torch.nonzero(zero_src_product_list[k][j] < old_products[k] - math.sqrt(d) / 20)
negative_copies = torch.nonzero(max_src_product_list[k][j] < old_products[k] - math.sqrt(d) / 20)
if not quiet:
print(" Positive copies from src dot product perturbations[{}]: {}".format(k, positive_copies.tolist()))
print(" Negative copies from src dot product perturbations[{}]: {}".format(k, negative_copies.tolist()))
if positive_copies.size(0) > negative_copies.size(0):
new_important_negative_ops += [c.tolist() for c in negative_copies if c.tolist() not in new_important_negative_ops]
else:
new_important_positive_ops += [c.tolist() for c in positive_copies if c.tolist() not in new_important_positive_ops]
positive_copies = torch.nonzero(zero_dst_product_list[k][j] < old_products[k] - math.sqrt(d) / 20)
negative_copies = torch.nonzero(max_dst_product_list[k][j] < old_products[k] - math.sqrt(d) / 20)
if not quiet:
print(" Positive copies from dst dot product perturbations[{}]: {}".format(k, positive_copies.tolist()))
print(" Negative copies from dst dot product perturbations[{}]: {}".format(k, negative_copies.tolist()))
if positive_copies.size(0) > negative_copies.size(0):
new_important_negative_ops += [c.tolist() for c in negative_copies if c.tolist() not in new_important_negative_ops]
else:
new_important_positive_ops += [c.tolist() for c in positive_copies if c.tolist() not in new_important_positive_ops]
#if j < len(self.model.transformers) - 1:
# residual_copies = torch.nonzero(res_src_product_list[k][j] < old_products[k] - math.sqrt(d) / 2)
# residual_copies = torch.cat((residual_copies,residual_copies),dim=-1)
# new_important_ops += [c.tolist() for c in residual_copies if c.tolist() not in new_important_ops]
# residual_copies = torch.nonzero(res_dst_product_list[k][j] < old_products[k] - math.sqrt(d) / 2)
# residual_copies = torch.cat((residual_copies,residual_copies),dim=-1)
# new_important_ops += [c.tolist() for c in residual_copies if c.tolist() not in new_important_ops]
important_positive_ops.append(new_important_positive_ops)
important_negative_ops.append(new_important_negative_ops)
important_ops = []
for j in range(len(self.model.transformers)):
new_important_ops = [(op,1) for op in important_positive_ops[j] if op not in important_negative_ops[j]]
new_important_ops += [(op,-1) for op in important_negative_ops[j] if op not in important_positive_ops[j]]
new_important_ops += [(op,0) for op in important_positive_ops[j] if op in important_negative_ops[j]]
important_ops.append(new_important_ops)
for last_copy_src in last_copy_srcs:
if ([n-1, last_copy_src], 1) not in important_ops[-1]:
important_ops[-1].append(([n-1, last_copy_src.item()], 1))
forward_edges = []
start_index = torch.sum(input == PADDING_TOKEN)
for i in range((n - 5) // 3 + 1):
forward_edges.append([])
for i in range((n + 2) % 3, n-5, 3):
if i >= start_index:
forward_edges[input[i].item()].append(input[i+1].item())
def path_length(start, end):
if input[start] > (n - 5) // 3 or input[end] > (n - 5) // 3:
return -1
queue = [(input[start],0)]
best_distance = -1
while len(queue) != 0:
current, distance = queue.pop()
if current == input[end]:
if best_distance == -1 or distance < best_distance:
best_distance = distance
continue
for child in forward_edges[current]:
queue.append((child,distance+1))
return best_distance
# reconstruct the circuit pathway for this input
print('[PROFILE] Reconstructing circuit.', flush=True)
root = ComputationNode(len(self.model.transformers), n-1)
nodes = [root]
all_nodes = [root]
for j in reversed(range(len(self.model.transformers))):
# identify the operations whose destination is in relevant_indices
new_nodes = []
for node in nodes:
new_node = ComputationNode(j, node.row_id)
node.add_predecessor(new_node, None)
new_nodes.append(new_node)
for op,sign in important_ops[j]:
for node in nodes:
if node.row_id == op[0]:
try:
predecessor = next(n for n in new_nodes if n.row_id == op[1])
except StopIteration:
predecessor = ComputationNode(j, int(op[1]))
new_nodes.append(predecessor)
if sign == 1:
weight = layer_inputs[-1][-1,prediction] - zero_output_logit_list[j][op[0],op[1]]
for k in range(len(zero_dst_product_list)):
weight = max(weight, (old_products[k] - zero_src_product_list[k][j][op[0],op[1]]) / math.sqrt(d))
weight = max(weight, (old_products[k] - zero_dst_product_list[k][j][op[0],op[1]]) / math.sqrt(d))
else:
weight = layer_inputs[-1][-1,prediction] - max_output_logit_list[j][op[0],op[1]]
for k in range(len(zero_dst_product_list)):
weight = max(weight, -(old_products[k] - max_src_product_list[k][j][op[0],op[1]]) / math.sqrt(d))
weight = max(weight, -(old_products[k] - max_dst_product_list[k][j][op[0],op[1]]) / math.sqrt(d))
node.add_predecessor(predecessor, weight)
# explain the copy from `predecessor` to `node`
src_dependencies, dst_dependencies = explain_attn_op(self.model, input, mask, A_matrices, attn_matrices, attn_inputs, ff_inputs, predecessor.layer, node.row_id, predecessor.row_id, sign)
op_causes = []
for src_dep in src_dependencies:
if src_dep >= max_vertex_id+5 and src_dep+1 in dst_dependencies:
# this is a position-based backward step
if (int(src_dep)+1,int(src_dep)) not in op_causes:
op_causes.append((int(src_dep)+1,int(src_dep)))
elif src_dep >= max_vertex_id+5 and src_dep-1 in dst_dependencies:
# this is a position-based forward step
if (int(src_dep)-1,int(src_dep)) not in op_causes:
op_causes.append((int(src_dep)-1,int(src_dep)))
elif src_dep <= max_vertex_id and src_dep in dst_dependencies:
# this is a token matching step
if int(src_dep) not in op_causes:
op_causes.append(int(src_dep))
if max_vertex_id+5+n-4 in src_dependencies and max_vertex_id+5+n-3 in src_dependencies and max_vertex_id+5+n-1 in dst_dependencies:
# this is a hard-coded copy from tokens that are reachable from both the start and goal vertices into the last token
if (max_vertex_id+5+n-1, (max_vertex_id+5+n-3,max_vertex_id+5+n-4)) not in op_causes:
op_causes.append((max_vertex_id+5+n-1, (max_vertex_id+5+n-3,max_vertex_id+5+n-4)))
if max_vertex_id+5+n-3 in src_dependencies:
# this is a hard-coded copy from tokens that are reachable from the goal vertex
if (None, max_vertex_id+5+n-3) not in op_causes:
op_causes.append((None, max_vertex_id+5+n-3))
forward_dist = path_length(predecessor.row_id, node.row_id)
backward_dist = path_length(node.row_id, predecessor.row_id)
if node.row_id == predecessor.row_id:
copy_direction = None
elif forward_dist != -1:
if backward_dist != -1:
# this could be an effective forwards or backwards copy
copy_direction = '*'
else:
# this is an effective backward step
copy_direction = 'b'
else:
if backward_dist != -1:
# this is an effective forward step
copy_direction = 'f'
else:
copy_direction = None
index = predecessor.successors.index(node)
predecessor.op_explanations[index] = op_causes
predecessor.copy_directions[index] = copy_direction
nodes = new_nodes
all_nodes += new_nodes
for node in all_nodes:
node.reachable = [int(input[node.row_id]),max_vertex_id+5+node.row_id]
# identify the paths in the graph that can be explained by the path-merging algorithm
path_merge_explainable = []
for node in reversed(all_nodes):
if node.layer == 0 and node.row_id != n-1:
path_merge_explainable.append(node)
elif node not in path_merge_explainable:
continue
# check if this is a path merge operation
for k in range(len(node.successors)):
successor = node.successors[k]
if successor in path_merge_explainable:
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
continue
if node.op_explanations[k] == None:
if node.row_id == successor.row_id:
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
continue
if node.copy_directions[k] == 'f' and any(e[0]+1 == e[1] and e[0] in successor.reachable and e[1] in node.reachable for e in node.op_explanations[k] if type(e) == tuple and type(e[0]) == int):
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
continue
if node.copy_directions[k] == 'b' and any(e[0]-1 == e[1] and e[0] in successor.reachable and e[1] in node.reachable for e in node.op_explanations[k] if type(e) == tuple and type(e[0]) == int):
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
continue
for explanation in node.op_explanations[k]:
if any(explanation == input[r-(max_vertex_id+5)] for r in node.reachable if r >= max_vertex_id+5):
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
break
if (max_vertex_id+5+n-1,(max_vertex_id+5+n-3,max_vertex_id+5+n-4)) in node.op_explanations[k] and successor.row_id == n-1 and max_vertex_id+5+n-3 in node.reachable and max_vertex_id+5+n-4 in node.reachable:
if successor not in path_merge_explainable:
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
if (None,max_vertex_id+5+n-3) in node.op_explanations[k] and successor.row_id == n-1 and max_vertex_id+5+n-3 in node.reachable:
if successor not in path_merge_explainable:
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
if (None,max_vertex_id+5+n-3) in node.op_explanations[k] and max_vertex_id+5+n-3 in node.reachable:
# this is a hard copy into a token for the purpose of temporary storage
if successor not in path_merge_explainable:
path_merge_explainable.append(successor)
successor.reachable += [n for n in node.reachable if n not in successor.reachable]
return root, forward_edges, important_ops, path_merge_explainable, prediction
def trace(self, x: torch.Tensor, other_x: torch.Tensor, quiet: bool = True):
n = x.shape[0]
QUERY_PREFIX_TOKEN = (n - 5) // 3 + 4
PADDING_TOKEN = (n - 5) // 3 + 3
EDGE_PREFIX_TOKEN = (n - 5) // 3 + 2
PATH_PREFIX_TOKEN = (n - 5) // 3 + 1
# Create masking tensor.
mask = self.model.pad_masking(x, 0)
if not self.model.bidirectional:
mask = mask + self.model.future_masking(x, 0)
# Use token embedding and positional embedding layers.
input = x # store the input for keeping track the code paths executed by each input
x = self.model.token_embedding[x]
if len(x.shape) == 2:
pos = self.model.positional_embedding
else:
pos = self.model.positional_embedding.unsqueeze(0).expand(x.shape[0], -1, -1)
x = torch.cat((x, pos), -1)
x = self.model.dropout_embedding(x)
d = x.shape[1]
# Use token embedding and positional embedding layers.
other_input = other_x # store the input for keeping track the code paths executed by each input
other_x = self.model.token_embedding[other_x]
if len(other_x.shape) == 2:
pos = self.model.positional_embedding
else:
pos = self.model.positional_embedding.unsqueeze(0).expand(other_x.shape[0], -1, -1)
other_x = torch.cat((other_x, pos), -1)
other_x = self.model.dropout_embedding(other_x)
other_layer_inputs, other_attn_inputs, other_attn_pre_softmax, other_attn_matrices, other_v_outputs, other_attn_linear_inputs, other_attn_outputs, other_A_matrices, other_ff_inputs, other_ff_parameters, other_prediction = forward(self.model, other_x, mask, 0, False, len(self.model.transformers)-1, None, None)
layer_inputs, attn_inputs, attn_pre_softmax, attn_matrices, v_outputs, attn_linear_inputs, attn_outputs, A_matrices, ff_inputs, ff_parameters, prediction = forward(self.model, x, mask, 0, False, len(self.model.transformers)-1, None, None)
#[(3,65,other_layer_inputs[3][65,:]),(3,68,other_layer_inputs[3][68,:])]
#[(4,23,other_layer_inputs[4][23,:]),(4,20,other_layer_inputs[4][20,:])]
#[(5,89,other_layer_inputs[5][89,:])]
#[(5,35,other_layer_inputs[5][35,:]),(5,38,other_layer_inputs[5][38,:])]
#[(3,14,other_layer_inputs[3][14,:]),(3,71,other_layer_inputs[3][71,:])]
#[(4,14,other_layer_inputs[4][14,:]),(4,41,other_layer_inputs[4][41,:]),(4,71,other_layer_inputs[4][71,:])]
#[(3,29,other_layer_inputs[3][29,:]),(3,32,other_layer_inputs[3][32,:])]
if not quiet:
print("Model prediction: {}".format(prediction))
print("Model prediction for other input: {}".format(other_prediction))
def check_copy(i, dst, src, attn_inputs, attn_matrices):
attn_input = attn_inputs[i]
if not quiet:
print('Attention layer {} is copying row {} into row {} with weight {} because:'.format(i,src,dst,attn_matrices[i][dst,src]))
# determine why row `src` is being copied from
attn_input_prime = torch.cat((attn_input, torch.ones((n,1))), 1)
right_products = torch.matmul(attn_input_prime[dst,:], A_matrices[i]) * attn_input_prime[src,:]
for right_index in torch.nonzero(right_products[:-1] > torch.max(right_products[:-1]) - 5.0).tolist():
right_index = right_index[0]