-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattention_probes.py
More file actions
2825 lines (2403 loc) · 97.2 KB
/
Copy pathattention_probes.py
File metadata and controls
2825 lines (2403 loc) · 97.2 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
import os
import json
import torch
from typing import Any, Dict, List, Optional, Tuple
import matplotlib.pyplot as plt
from utils.constants import DEFAULT_GRAPH_PAD_ID, GRAPH_TOKEN_INDEX
def _get_prompt_step_attentions(generate_outputs) -> Tuple[torch.Tensor, ...]:
"""
Extract step-0 (prompt) attentions from HF generate outputs.
Expected structure:
- tuple over generation steps
- each item is tuple over layers
- each tensor is [B, H, Q, K]
For decoder-only generation with cache, step 0 is prompt attention and Q == K.
"""
attns = getattr(generate_outputs, "attentions", None)
if attns is None:
raise ValueError(
"generate_outputs.attentions is None. Set output_attentions=True and return_dict_in_generate=True."
)
step0 = attns[0]
if not isinstance(step0, (tuple, list)) or len(step0) == 0:
raise ValueError("Unexpected attentions structure from generate().")
t = step0[0]
if t.dim() != 4 or t.shape[-1] != t.shape[-2]:
raise ValueError(
f"Step-0 attentions are not square. Got shape {tuple(t.shape)}. "
"This usually means you are not looking at the prompt step."
)
return tuple(step0)
def get_expanded_graph_key_query_indices(
*,
input_ids_1d: torch.Tensor,
attention_mask_1d: torch.Tensor,
graphs: torch.Tensor,
prompt_len: int,
keep_pad_tokens: bool = True,
mm_use_graph_special_token: bool = False,
use_hop: Optional[int] = None,
sample_neighbor_size: Optional[int] = None,
graph_pad_id: int = DEFAULT_GRAPH_PAD_ID,
) -> Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]:
"""
Compute expanded graph key indices and query indices in the prompt sequence.
Returns:
key_idx: graph key positions to analyze (includes pads if keep_pad_tokens=True)
query_idx: query positions (text tokens after the last graph block)
key_idx_all: all graph key positions in expanded prompt (always includes pads)
key_is_pad: bool mask aligned to key_idx, True where the key token is pad
"""
del sample_neighbor_size # kept for signature parity with existing analysis functions
if input_ids_1d.dim() != 1 or attention_mask_1d.dim() != 1:
raise ValueError("input_ids_1d and attention_mask_1d must be 1D tensors.")
valid = attention_mask_1d.bool()
placeholder_pos = torch.nonzero(
(input_ids_1d == GRAPH_TOKEN_INDEX) & valid, as_tuple=False
).squeeze(-1)
if placeholder_pos.numel() == 0:
return None
if graphs is None:
raise ValueError("graphs must be provided to compute expanded graph indices.")
if graphs.dim() == 1:
graphs = graphs.unsqueeze(0)
placeholder_pos = torch.sort(placeholder_pos).values
num_graph_blocks = graphs.shape[0]
if placeholder_pos.numel() > num_graph_blocks:
raise ValueError(
f"Found {placeholder_pos.numel()} <graph> placeholders but only {num_graph_blocks} graph blocks."
)
selected_key_positions: List[torch.Tensor] = []
selected_key_is_pad: List[torch.Tensor] = []
all_key_positions: List[torch.Tensor] = []
offset = 0
for cur_graph_idx, p in enumerate(placeholder_pos.tolist()):
start = p + offset
g = graphs[cur_graph_idx]
L_base = int(g.numel())
if mm_use_graph_special_token:
if use_hop is None:
raise ValueError(
"use_hop is required when mm_use_graph_special_token=True."
)
L = L_base + (use_hop + 2)
all_pos = torch.arange(start, start + L, device=input_ids_1d.device)
key_pos = all_pos
# No reliable pad mapping once separators are injected.
key_is_pad = torch.zeros_like(key_pos, dtype=torch.bool)
else:
L = L_base
all_pos = torch.arange(start, start + L, device=input_ids_1d.device)
pad_mask = g == graph_pad_id
if keep_pad_tokens:
key_pos = all_pos
key_is_pad = pad_mask
else:
keep = ~pad_mask
key_pos = all_pos[keep]
key_is_pad = torch.zeros_like(key_pos, dtype=torch.bool)
selected_key_positions.append(key_pos)
selected_key_is_pad.append(key_is_pad)
all_key_positions.append(all_pos)
offset += (L - 1)
if len(selected_key_positions) == 0:
return None
key_idx = torch.cat(selected_key_positions, dim=0)
key_is_pad = torch.cat(selected_key_is_pad, dim=0)
key_idx_all = torch.cat(all_key_positions, dim=0)
in_bounds = (key_idx >= 0) & (key_idx < prompt_len)
key_idx = key_idx[in_bounds]
key_is_pad = key_is_pad[in_bounds]
key_idx_all = key_idx_all[(key_idx_all >= 0) & (key_idx_all < prompt_len)]
if key_idx.numel() == 0 or key_idx_all.numel() == 0:
return None
query_start = int(key_idx_all.max().item()) + 1
if query_start >= prompt_len:
return None
query_idx = torch.arange(query_start, prompt_len, device=input_ids_1d.device, dtype=torch.long)
return key_idx, query_idx, key_idx_all, key_is_pad
def _compute_pad_nonpad_stats(
layer_query_to_graph: torch.Tensor,
key_is_pad: torch.Tensor,
) -> Dict[str, Any]:
"""
Compute per-layer pad/non-pad means for one sample.
"""
key_is_pad = key_is_pad.bool()
num_pad = int(key_is_pad.sum().item())
num_nonpad = int((~key_is_pad).sum().item())
if num_pad == 0 or num_nonpad == 0:
return {
"num_pad_keys": num_pad,
"num_nonpad_keys": num_nonpad,
"layer_pad_mean": None,
"layer_nonpad_mean": None,
"layer_pad_nonpad_ratio": None,
}
pad_scores = layer_query_to_graph[:, :, key_is_pad] # [L, Q, K_pad]
nonpad_scores = layer_query_to_graph[:, :, ~key_is_pad] # [L, Q, K_nonpad]
layer_pad_mean = pad_scores.mean(dim=(1, 2))
layer_nonpad_mean = nonpad_scores.mean(dim=(1, 2))
return {
"num_pad_keys": num_pad,
"num_nonpad_keys": num_nonpad,
"layer_pad_mean": layer_pad_mean,
"layer_nonpad_mean": layer_nonpad_mean,
"layer_pad_nonpad_ratio": layer_pad_mean / (layer_nonpad_mean + 1e-12),
}
@torch.no_grad()
def compute_layerwise_query_to_graph_attention(
*,
generate_outputs,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
graphs: torch.Tensor,
keep_pad_tokens: bool = True,
mm_use_graph_special_token: bool = False,
use_hop: Optional[int] = None,
sample_neighbor_size: Optional[int] = None,
) -> Dict[str, Any]:
"""
Per sample, compute per-layer query->graph attention matrices averaged over heads.
Output entries per sample:
- layer_query_to_graph: [num_layers, Q, K]
- key_idx: [K] expanded graph key indices in prompt
- key_idx_all: all expanded graph key indices (with pads)
- key_is_pad: [K] bool, True where key token is pad
- query_idx: [Q] expanded query indices in prompt
- pad_nonpad_stats: per-layer pad vs non-pad means (per sample)
No cross-sample aggregation is performed.
"""
if input_ids.dim() == 1:
input_ids = input_ids.unsqueeze(0)
if attention_mask.dim() == 1:
attention_mask = attention_mask.unsqueeze(0)
attns0 = _get_prompt_step_attentions(generate_outputs)
num_layers = len(attns0)
batch_size = attns0[0].shape[0]
prompt_len = attns0[0].shape[-1]
if graphs is not None and graphs.dim() == 3:
graphs_batched = graphs
else:
graphs_batched = graphs.unsqueeze(0).expand(batch_size, -1, -1)
valid: List[bool] = []
layer_query_to_graph_list: List[Optional[torch.Tensor]] = []
key_idx_list: List[Optional[torch.Tensor]] = []
key_idx_all_list: List[Optional[torch.Tensor]] = []
key_is_pad_list: List[Optional[torch.Tensor]] = []
query_idx_list: List[Optional[torch.Tensor]] = []
pad_nonpad_stats_list: List[Optional[Dict[str, Any]]] = []
for b in range(batch_size):
idxs = get_expanded_graph_key_query_indices(
input_ids_1d=input_ids[b],
attention_mask_1d=attention_mask[b],
graphs=graphs_batched[b],
prompt_len=prompt_len,
keep_pad_tokens=keep_pad_tokens,
mm_use_graph_special_token=mm_use_graph_special_token,
use_hop=use_hop,
sample_neighbor_size=sample_neighbor_size,
)
if idxs is None:
valid.append(False)
layer_query_to_graph_list.append(None)
key_idx_list.append(None)
key_idx_all_list.append(None)
key_is_pad_list.append(None)
query_idx_list.append(None)
pad_nonpad_stats_list.append(None)
continue
key_idx, query_idx, key_idx_all, key_is_pad = idxs # if choosing to remove padded tokens, then key_idx_all will be different than key_idx
layer_mats: List[torch.Tensor] = []
for layer_id in range(num_layers):
# [B, H, T, T] -> [H, T, T] for sample b
layer_attn_b = attns0[layer_id][b].to(torch.float32)
# [H, Q, K]
sub = layer_attn_b.index_select(1, query_idx).index_select(2, key_idx)
# head-average -> [Q, K]
sub_head_avg = sub.mean(dim=0)
layer_mats.append(sub_head_avg)
layer_query_to_graph = torch.stack(layer_mats, dim=0) # [L, Q, K]
pad_nonpad_stats = _compute_pad_nonpad_stats(layer_query_to_graph, key_is_pad)
valid.append(True)
layer_query_to_graph_list.append(layer_query_to_graph)
key_idx_list.append(key_idx)
key_idx_all_list.append(key_idx_all)
key_is_pad_list.append(key_is_pad)
query_idx_list.append(query_idx)
pad_nonpad_stats_list.append(pad_nonpad_stats)
return {
"valid": valid,
"prompt_len": prompt_len,
"layer_query_to_graph": layer_query_to_graph_list,
"key_idx": key_idx_list,
"key_idx_all": key_idx_all_list,
"key_is_pad": key_is_pad_list,
"query_idx": query_idx_list,
"pad_nonpad_stats": pad_nonpad_stats_list,
}
def _choose_ticks(length: int, max_ticks: int) -> List[int]:
if length <= 0:
return []
if length <= max_ticks:
return list(range(length))
step = max(1, length // (max_ticks - 1))
ticks = list(range(0, length, step))
if ticks[-1] != length - 1:
ticks.append(length - 1)
return ticks
def _build_key_tick_labels(
x_ticks: List[int],
k_len: int,
key_idx: Optional[torch.Tensor],
key_is_pad: Optional[torch.Tensor],
sink_prompt_positions: Optional[List[int]] = None,
top2_sink_prompt_positions: Optional[List[int]] = None,
) -> List[str]:
labels: List[str] = []
has_pad_mask = key_is_pad is not None and key_is_pad.numel() == k_len
sink_prompt_position_set = (
{int(pos) for pos in sink_prompt_positions}
if sink_prompt_positions is not None
else set()
)
top2_sink_prompt_position_set = (
{int(pos) for pos in top2_sink_prompt_positions}
if top2_sink_prompt_positions is not None
else set()
)
for t in x_ticks:
if key_idx is not None and key_idx.numel() == k_len:
prompt_pos = int(key_idx[t])
else:
prompt_pos = int(t)
base = str(prompt_pos)
is_pad = has_pad_mask and bool(key_is_pad[t])
if prompt_pos in top2_sink_prompt_position_set:
base += "[T2P]" if is_pad else "[T2]"
elif prompt_pos in sink_prompt_position_set:
base += "[SP]" if is_pad else "[S]"
elif is_pad:
base += "(P)"
labels.append(base)
return labels
def plot_layerwise_query_graph_attention(
*,
layer_query_to_graph: torch.Tensor,
sample_id: str,
save_dir: str,
query_idx: Optional[torch.Tensor] = None,
key_idx: Optional[torch.Tensor] = None,
key_is_pad: Optional[torch.Tensor] = None,
sink_prompt_positions: Optional[List[int]] = None,
top2_sink_prompt_positions: Optional[List[int]] = None,
cmap: str = "viridis",
dpi: int = 180,
max_xticks: int = 16,
max_yticks: int = 16,
) -> List[str]:
"""
Save one heatmap per layer.
y-axis: query tokens
x-axis: graph key tokens
color: head-averaged attention weight
X tick labels can also annotate sink identities:
- "(P)" for padded graph keys
- "[S]" / "[SP]" for sink tokens
- "[T2]" / "[T2P]" for top-2 sink tokens
"""
try:
import matplotlib.pyplot as plt
except ImportError as e:
raise ImportError(
"matplotlib is required for plotting. Install it to save attention heatmaps."
) from e
if layer_query_to_graph.dim() != 3:
raise ValueError("layer_query_to_graph must have shape [num_layers, Q, K].")
os.makedirs(save_dir, exist_ok=True)
layer_query_to_graph = layer_query_to_graph.detach().cpu()
num_layers, q_len, k_len = layer_query_to_graph.shape
if q_len == 0 or k_len == 0:
return []
if query_idx is not None:
query_idx = query_idx.detach().cpu()
if key_idx is not None:
key_idx = key_idx.detach().cpu()
if key_is_pad is not None:
key_is_pad = key_is_pad.detach().cpu().bool()
global_vmin = float(layer_query_to_graph.min().item())
global_vmax = float(layer_query_to_graph.max().item())
saved_paths: List[str] = []
for layer_id in range(num_layers):
mat = layer_query_to_graph[layer_id]
fig_w = max(6.0, 0.14 * k_len)
fig_h = max(4.0, 0.14 * q_len)
fig, ax = plt.subplots(figsize=(fig_w, fig_h), dpi=dpi)
im = ax.imshow(
mat.numpy(),
aspect="auto",
interpolation="nearest",
cmap=cmap,
vmin=global_vmin,
vmax=global_vmax,
)
ax.set_title(f"Sample {sample_id} | Layer {layer_id}")
ax.set_xlabel("Graph key tokens")
ax.set_ylabel("Query tokens")
# Show every graph token index on x-axis.
x_ticks = list(range(k_len))
y_ticks = _choose_ticks(q_len, max_yticks)
ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
x_labels = _build_key_tick_labels(
x_ticks,
k_len,
key_idx,
key_is_pad,
sink_prompt_positions=sink_prompt_positions,
top2_sink_prompt_positions=top2_sink_prompt_positions,
)
ax.set_xticklabels(x_labels, rotation=90, ha="center")
if query_idx is not None and query_idx.numel() == q_len:
ax.set_yticklabels([str(int(query_idx[t])) for t in y_ticks])
else:
ax.set_yticklabels([str(t) for t in y_ticks])
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Attention weight (head-avg)")
fig.tight_layout()
out_path = os.path.join(save_dir, f"sample_{sample_id}_layer_{layer_id:02d}.png")
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
saved_paths.append(out_path)
return saved_paths
def plot_layeravg_query_graph_attention(
*,
layer_query_to_graph: torch.Tensor,
sample_id: str,
save_dir: Optional[str] = None,
save_path: Optional[str] = None,
query_idx: Optional[torch.Tensor] = None,
key_idx: Optional[torch.Tensor] = None,
key_is_pad: Optional[torch.Tensor] = None,
sink_prompt_positions: Optional[List[int]] = None,
top2_sink_prompt_positions: Optional[List[int]] = None,
cmap: str = "viridis",
dpi: int = 180,
max_xticks: int = 16,
max_yticks: int = 16,
) -> Optional[str]:
"""
Save one heatmap after averaging attention across layers.
y-axis: query tokens
x-axis: graph key tokens
color: head-averaged attention weight (then layer-averaged)
X tick labels can also annotate sink identities:
- "(P)" for padded graph keys
- "[S]" / "[SP]" for sink tokens
- "[T2]" / "[T2P]" for top-2 sink tokens
"""
try:
import matplotlib.pyplot as plt
except ImportError as e:
raise ImportError(
"matplotlib is required for plotting. Install it to save attention heatmaps."
) from e
if layer_query_to_graph.dim() != 3:
raise ValueError("layer_query_to_graph must have shape [num_layers, Q, K].")
if save_path is None and save_dir is None:
raise ValueError("Provide save_dir or save_path when saving a layer-averaged attention plot.")
if save_path is not None:
output_dir = os.path.dirname(save_path)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
else:
os.makedirs(save_dir, exist_ok=True)
layer_query_to_graph = layer_query_to_graph.detach().cpu()
avg_mat = layer_query_to_graph.mean(dim=0) # [Q, K]
q_len, k_len = avg_mat.shape
if q_len == 0 or k_len == 0:
return None
if query_idx is not None:
query_idx = query_idx.detach().cpu()
if key_idx is not None:
key_idx = key_idx.detach().cpu()
if key_is_pad is not None:
key_is_pad = key_is_pad.detach().cpu().bool()
fig_w = max(6.0, 0.14 * k_len)
fig_h = max(4.0, 0.14 * q_len)
fig, ax = plt.subplots(figsize=(fig_w, fig_h), dpi=dpi)
im = ax.imshow(
avg_mat.numpy(),
aspect="auto",
interpolation="nearest",
cmap=cmap,
)
ax.set_title(f"Sample {sample_id} | Attention To All Graph Tokens | Layer Avg")
ax.set_xlabel("All graph tokens")
ax.set_ylabel("Query tokens")
# Show every graph token index on x-axis.
x_ticks = list(range(k_len))
y_ticks = _choose_ticks(q_len, max_yticks)
ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
x_labels = _build_key_tick_labels(
x_ticks,
k_len,
key_idx,
key_is_pad,
sink_prompt_positions=sink_prompt_positions,
top2_sink_prompt_positions=top2_sink_prompt_positions,
)
ax.set_xticklabels(x_labels, rotation=90, ha="center")
if query_idx is not None and query_idx.numel() == q_len:
ax.set_yticklabels([str(int(query_idx[t])) for t in y_ticks])
else:
ax.set_yticklabels([str(t) for t in y_ticks])
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Attention weight (head-avg, layer-avg)")
fig.tight_layout()
out_path = save_path
if out_path is None:
out_path = os.path.join(save_dir, f"sample_{sample_id}_layer_avg.png")
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
return out_path
def analyze_and_plot_sample_attention(
*,
generate_outputs,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
graphs: torch.Tensor,
sample_id: str,
save_dir: str,
keep_pad_tokens: bool = True,
mm_use_graph_special_token: bool = False,
use_hop: Optional[int] = None,
sample_neighbor_size: Optional[int] = None,
sink_prompt_positions: Optional[List[int]] = None,
top2_sink_prompt_positions: Optional[List[int]] = None,
) -> Dict[str, Any]:
"""
Convenience wrapper for single-sample usage.
Returns analysis dict plus:
- saved_paths: list of heatmap files for this sample
"""
analysis = compute_layerwise_query_to_graph_attention(
generate_outputs=generate_outputs,
input_ids=input_ids,
attention_mask=attention_mask,
graphs=graphs,
keep_pad_tokens=keep_pad_tokens,
mm_use_graph_special_token=mm_use_graph_special_token,
use_hop=use_hop,
sample_neighbor_size=sample_neighbor_size,
)
saved_paths: List[str] = []
# Primary use case in eval_pretrain is batch size 1, but this handles B>1.
for b, is_valid in enumerate(analysis["valid"]):
if not is_valid:
continue
layer_qk = analysis["layer_query_to_graph"][b]
query_idx = analysis["query_idx"][b]
key_idx = analysis["key_idx"][b]
key_is_pad = analysis["key_is_pad"][b]
suffix = sample_id if len(analysis["valid"]) == 1 else f"{sample_id}_b{b}"
paths = plot_layerwise_query_graph_attention(
layer_query_to_graph=layer_qk,
sample_id=suffix,
save_dir=save_dir,
query_idx=query_idx,
key_idx=key_idx,
key_is_pad=key_is_pad,
sink_prompt_positions=sink_prompt_positions,
top2_sink_prompt_positions=top2_sink_prompt_positions,
)
saved_paths.extend(paths)
analysis["saved_paths"] = saved_paths
return analysis
def analyze_and_plot_sample_attention_layeravg(
*,
generate_outputs,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
graphs: torch.Tensor,
sample_id: str,
save_dir: Optional[str] = None,
save_path: Optional[str] = None,
keep_pad_tokens: bool = True,
mm_use_graph_special_token: bool = False,
use_hop: Optional[int] = None,
sample_neighbor_size: Optional[int] = None,
plotting: bool = False,
sink_prompt_positions: Optional[List[int]] = None,
top2_sink_prompt_positions: Optional[List[int]] = None,
) -> Dict[str, Any]:
"""
Convenience wrapper for single-sample usage with one layer-averaged plot per sample.
Returns analysis dict plus:
- saved_paths_layeravg: list of layer-averaged heatmap files
- optional x-axis markers for sink and top-2 sink prompt positions
"""
analysis = compute_layerwise_query_to_graph_attention(
generate_outputs=generate_outputs,
input_ids=input_ids,
attention_mask=attention_mask,
graphs=graphs,
keep_pad_tokens=keep_pad_tokens,
mm_use_graph_special_token=mm_use_graph_special_token,
use_hop=use_hop,
sample_neighbor_size=sample_neighbor_size,
)
saved_paths_layeravg: List[str] = []
if plotting:
for b, is_valid in enumerate(analysis["valid"]):
if not is_valid:
continue
layer_qk = analysis["layer_query_to_graph"][b]
query_idx = analysis["query_idx"][b]
key_idx = analysis["key_idx"][b]
key_is_pad = analysis["key_is_pad"][b]
suffix = sample_id if len(analysis["valid"]) == 1 else f"{sample_id}_b{b}"
if save_path is not None and len(analysis["valid"]) != 1:
raise ValueError("save_path is only supported when plotting a single sample.")
out_path = plot_layeravg_query_graph_attention(
layer_query_to_graph=layer_qk,
sample_id=suffix,
save_dir=save_dir,
save_path=save_path,
query_idx=query_idx,
key_idx=key_idx,
key_is_pad=key_is_pad,
sink_prompt_positions=sink_prompt_positions,
top2_sink_prompt_positions=top2_sink_prompt_positions,
)
if out_path is not None:
saved_paths_layeravg.append(out_path)
analysis["saved_paths_layeravg"] = saved_paths_layeravg
return analysis
def extract_sink_columns_from_query_graph_attention(
*,
layer_query_to_graph: torch.Tensor,
key_idx: torch.Tensor,
sink_prompt_positions: List[int],
key_is_pad: Optional[torch.Tensor] = None,
) -> Dict[str, Any]:
"""
Select sink-token columns from one sample's [L, Q, K] query->graph attention.
Sink tokens are identified by their expanded prompt positions.
"""
if layer_query_to_graph.dim() != 3:
raise ValueError("layer_query_to_graph must have shape [num_layers, Q, K].")
key_idx = key_idx.reshape(-1)
if key_idx.numel() != layer_query_to_graph.shape[-1]:
raise ValueError("key_idx must align with the last dimension of layer_query_to_graph.")
requested_positions = sorted({int(pos) for pos in sink_prompt_positions})
if len(requested_positions) == 0:
return {
"valid": False,
"reason": "no_sink_prompt_positions",
"layer_query_to_sink": None,
"sink_key_idx": None,
"sink_key_is_pad": None,
"sink_column_indices": None,
"missing_sink_prompt_positions": [],
}
has_pad_mask = key_is_pad is not None and key_is_pad.numel() == key_idx.numel()
if has_pad_mask:
key_is_pad = key_is_pad.reshape(-1).bool()
col_indices: List[int] = []
found_positions: List[int] = []
found_pad_flags: List[bool] = []
for pos in requested_positions:
matches = torch.nonzero(key_idx == int(pos), as_tuple=False).reshape(-1)
if matches.numel() == 0:
continue
col = int(matches[0].item())
col_indices.append(col)
found_positions.append(int(key_idx[col].item()))
if has_pad_mask:
found_pad_flags.append(bool(key_is_pad[col].item()))
missing_positions = [pos for pos in requested_positions if pos not in set(found_positions)]
if len(col_indices) == 0:
return {
"valid": False,
"reason": "sink_prompt_positions_not_found_in_key_idx",
"layer_query_to_sink": None,
"sink_key_idx": None,
"sink_key_is_pad": None,
"sink_column_indices": None,
"missing_sink_prompt_positions": missing_positions,
}
col_idx_attn = torch.tensor(col_indices, dtype=torch.long, device=layer_query_to_graph.device)
layer_query_to_sink = layer_query_to_graph.index_select(2, col_idx_attn)
sink_key_idx = torch.tensor(found_positions, dtype=key_idx.dtype, device=key_idx.device)
sink_key_is_pad = None
if has_pad_mask:
sink_key_is_pad = torch.tensor(found_pad_flags, dtype=torch.bool, device=key_idx.device)
return {
"valid": True,
"reason": None,
"layer_query_to_sink": layer_query_to_sink,
"sink_key_idx": sink_key_idx,
"sink_key_is_pad": sink_key_is_pad,
"sink_column_indices": torch.tensor(col_indices, dtype=torch.long, device=key_idx.device),
"missing_sink_prompt_positions": missing_positions,
}
def plot_layeravg_query_sink_attention(
*,
layer_query_to_sink: torch.Tensor,
sample_id: str,
save_path: str,
query_idx: Optional[torch.Tensor] = None,
sink_key_idx: Optional[torch.Tensor] = None,
sink_key_is_pad: Optional[torch.Tensor] = None,
cmap: str = "viridis",
dpi: int = 180,
max_yticks: int = 16,
) -> Optional[str]:
"""
Save one heatmap after averaging attention across layers for sink-token columns.
y-axis: query tokens after the graph block
x-axis: sink graph tokens
color: head-averaged attention weight (then layer-averaged)
"""
try:
import matplotlib.pyplot as plt
except ImportError as e:
raise ImportError(
"matplotlib is required for plotting. Install it to save attention heatmaps."
) from e
if layer_query_to_sink.dim() != 3:
raise ValueError("layer_query_to_sink must have shape [num_layers, Q, S].")
save_dir = os.path.dirname(save_path)
if save_dir:
os.makedirs(save_dir, exist_ok=True)
layer_query_to_sink = layer_query_to_sink.detach().cpu()
avg_mat = layer_query_to_sink.mean(dim=0) # [Q, S]
q_len, s_len = avg_mat.shape
if q_len == 0 or s_len == 0:
return None
if query_idx is not None:
query_idx = query_idx.detach().cpu()
if sink_key_idx is not None:
sink_key_idx = sink_key_idx.detach().cpu()
if sink_key_is_pad is not None:
sink_key_is_pad = sink_key_is_pad.detach().cpu().bool()
fig_w = max(6.0, 0.7 * s_len)
fig_h = max(4.0, 0.14 * q_len)
fig, ax = plt.subplots(figsize=(fig_w, fig_h), dpi=dpi)
im = ax.imshow(
avg_mat.numpy(),
aspect="auto",
interpolation="nearest",
cmap=cmap,
)
ax.set_title(f"Sample {sample_id} | Attention To Sink Tokens | Layer Avg")
ax.set_xlabel("Sink tokens")
ax.set_ylabel("Query tokens")
x_ticks = list(range(s_len))
y_ticks = _choose_ticks(q_len, max_yticks)
ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
x_labels = _build_key_tick_labels(x_ticks, s_len, sink_key_idx, sink_key_is_pad)
ax.set_xticklabels(x_labels, rotation=90, ha="center")
if query_idx is not None and query_idx.numel() == q_len:
ax.set_yticklabels([str(int(query_idx[t])) for t in y_ticks])
else:
ax.set_yticklabels([str(t) for t in y_ticks])
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Attention weight (head-avg, layer-avg)")
fig.tight_layout()
fig.savefig(save_path, bbox_inches="tight")
plt.close(fig)
return save_path
def analyze_and_plot_sample_attention_to_sink_layeravg(
*,
generate_outputs,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
graphs: torch.Tensor,
sink_prompt_positions: List[int],
sample_id: str,
save_path: Optional[str] = None,
save_dir: Optional[str] = None,
keep_pad_tokens: bool = True,
mm_use_graph_special_token: bool = False,
use_hop: Optional[int] = None,
sample_neighbor_size: Optional[int] = None,
plotting: bool = False,
) -> Dict[str, Any]:
"""
Convenience wrapper for per-sample prompt attention restricted to sink tokens.
Returns analysis dict plus:
- layer_query_to_sink: list of [L, Q, S] tensors or None
- sink_key_idx: sink prompt positions that were found in key_idx
- saved_paths_attention_to_sink: list of saved .jpg heatmaps
"""
if plotting and save_path is None and save_dir is None:
raise ValueError("Provide save_path or save_dir when plotting=True.")
analysis = compute_layerwise_query_to_graph_attention(
generate_outputs=generate_outputs,
input_ids=input_ids,
attention_mask=attention_mask,
graphs=graphs,
keep_pad_tokens=keep_pad_tokens,
mm_use_graph_special_token=mm_use_graph_special_token,
use_hop=use_hop,
sample_neighbor_size=sample_neighbor_size,
)
sink_valid: List[bool] = []
layer_query_to_sink_list: List[Optional[torch.Tensor]] = []
sink_key_idx_list: List[Optional[torch.Tensor]] = []
sink_key_is_pad_list: List[Optional[torch.Tensor]] = []
sink_column_indices_list: List[Optional[torch.Tensor]] = []
missing_sink_prompt_positions_list: List[List[int]] = []
saved_paths_attention_to_sink: List[str] = []
for b, is_valid in enumerate(analysis["valid"]):
if not is_valid:
sink_valid.append(False)
layer_query_to_sink_list.append(None)
sink_key_idx_list.append(None)
sink_key_is_pad_list.append(None)
sink_column_indices_list.append(None)
missing_sink_prompt_positions_list.append([])
continue
selected = extract_sink_columns_from_query_graph_attention(
layer_query_to_graph=analysis["layer_query_to_graph"][b],
key_idx=analysis["key_idx"][b],
sink_prompt_positions=sink_prompt_positions,
key_is_pad=analysis["key_is_pad"][b],
)
sink_valid.append(bool(selected["valid"]))
layer_query_to_sink_list.append(selected["layer_query_to_sink"])
sink_key_idx_list.append(selected["sink_key_idx"])
sink_key_is_pad_list.append(selected["sink_key_is_pad"])
sink_column_indices_list.append(selected["sink_column_indices"])
missing_sink_prompt_positions_list.append(selected["missing_sink_prompt_positions"])
if plotting and selected["valid"]:
suffix = sample_id if len(analysis["valid"]) == 1 else f"{sample_id}_b{b}"
if save_path is not None and len(analysis["valid"]) != 1:
raise ValueError("save_path is only supported when plotting a single sample.")
cur_save_path = save_path
if cur_save_path is None:
cur_save_path = os.path.join(save_dir, f"{suffix}.jpg")
out_path = plot_layeravg_query_sink_attention(
layer_query_to_sink=selected["layer_query_to_sink"],
sample_id=suffix,
save_path=cur_save_path,
query_idx=analysis["query_idx"][b],
sink_key_idx=selected["sink_key_idx"],
sink_key_is_pad=selected["sink_key_is_pad"],
)
if out_path is not None:
saved_paths_attention_to_sink.append(out_path)
analysis["sink_valid"] = sink_valid
analysis["layer_query_to_sink"] = layer_query_to_sink_list
analysis["sink_key_idx"] = sink_key_idx_list
analysis["sink_key_is_pad"] = sink_key_is_pad_list
analysis["sink_column_indices"] = sink_column_indices_list
analysis["missing_sink_prompt_positions"] = missing_sink_prompt_positions_list
analysis["saved_paths_attention_to_sink"] = saved_paths_attention_to_sink
return analysis
def _token_scores_from_layer_query_to_graph(layer_query_to_graph: torch.Tensor) -> torch.Tensor:
"""Return one score per graph token by averaging layers and queries."""
if layer_query_to_graph.dim() == 3:
return layer_query_to_graph.mean(dim=(0, 1))
if layer_query_to_graph.dim() == 2:
return layer_query_to_graph.mean(dim=0)
if layer_query_to_graph.dim() == 1:
return layer_query_to_graph
raise ValueError("layer_query_to_graph must have shape [L,Q,K], [Q,K], or [K].")
def _find_first_nonpad_after_first_pad(key_is_pad: torch.Tensor) -> Optional[int]:
"""
Find the token index j such that:
- key_is_pad contains a first pad run starting at i
- j is the first non-pad index after that first run
"""
key_is_pad = key_is_pad.bool().reshape(-1)
pad_pos = torch.nonzero(key_is_pad, as_tuple=False).reshape(-1)
if pad_pos.numel() == 0:
return None
j = int(pad_pos[0].item())
n = key_is_pad.numel()
while j < n and bool(key_is_pad[j]):
j += 1
if j >= n:
return None
return j
def compute_first_postpad_center_cosine_similarity(
*,
graphs: torch.Tensor,
graph_emb: torch.Tensor,
key_is_pad: Optional[torch.Tensor] = None,
graph_pad_id: int = DEFAULT_GRAPH_PAD_ID,
eps: float = 1e-8,
) -> Dict[str, Any]:
"""
Compute cosine similarity between:
- the first non-pad graph token after the first pad run