-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2690 lines (2486 loc) · 118 KB
/
Copy pathstreamlit_app.py
File metadata and controls
2690 lines (2486 loc) · 118 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 streamlit as st
import pandas as pd
import numpy as np
import html
from typing import Any, List, Dict, Tuple, Optional
import json
import requests
from dataclasses import dataclass
from datetime import datetime
import logging
import io
import os
from pathlib import Path
import plotly.graph_objects as go
from config.model_groups import MODEL_SPECIFIC_GROUPS
from config.model_defaults import MODEL_DEFAULTS
from scipy import interpolate
# Set up logging with a StringIO buffer to capture logs
log_buffer = io.StringIO()
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
stream=log_buffer
)
logger = logging.getLogger(__name__)
# Constants
COLOR_PALETTE = [
"#4ECDC4", # Turquoise
"#FFD166", # Warm yellow
"#7EDC11", # Bright lime
"#FF1493", # Deep pink
"#1A9CE0", # Azure Blue
"#FF8C42", # Bright orange
"#06D6A0", # Bright turquoise
"#FFBB33", # Amber
"#4B0082", # Indigo
"#A7E541", # Lime green
"#FF5C5C", # Coral Red
"#66D7EE", # Sky Blue
"#FFE066", # Yellow Gold
"#233FD2", # Royal Blue
"#74E39A", # Mint Green
"#FF3377", # Hot Pink
"#5BC0EB", # Light blue
"#FFA07A", # Light salmon orange
"#118AB2", # Blue
"#C1FF72", # Lime Green
"#D90368", # Magenta
"#00AA5B", # Emerald Green
"#FF6B35", # Deep orange
"#F8E16C", # Light yellow
"#9F0162", # Deep Magenta
"#1EAE98", # Teal green
"#FF3366", # Coral pink
"#731DD8", # Electric Purple
]
MODEL_INFO = {
"gpt2-small": {"layers": 12, "heads": 12},
"pythia-2.8b": {"layers": 32, "heads": 32},
}
def get_random_color() -> str:
"""Get a random color from the palette."""
return COLOR_PALETTE[np.random.randint(0, len(COLOR_PALETTE))]
@dataclass
class AttentionPattern:
sourceLayer: int
sourceToken: int
destToken: int
weight: float
head: int
headType: Optional[str] = None
@dataclass
class HeadPair:
layer: int
head: int
color: Optional[str] = None # Add color field
@dataclass
class HeadGroup:
id: int
name: str
heads: List[HeadPair]
description: Optional[str] = None
color: Optional[str] = None # Add color field
group_type: str = "custom"
def get_head_color(layer: int, head: int, head_groups: List[HeadGroup]) -> str:
"""Get the color for a head based on its group membership."""
# Check which group this head belongs to
for group in head_groups:
if any(h.layer == layer and h.head == head for h in group.heads):
# Use group's custom color if set, otherwise use default from palette
return group.color or COLOR_PALETTE[group.id % len(COLOR_PALETTE)]
# Default blue for heads not in any group
return '#3B82F6'
def get_active_head_groups(all_groups: List[HeadGroup], active_group_ids: List[int]) -> List[HeadGroup]:
"""Return only groups that are currently active in the graph."""
active_ids = set(active_group_ids)
return [group for group in all_groups if group.id in active_ids]
def iter_attention_patterns(data: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Normalize backend and sample attention payloads into a flat edge list."""
if not data:
return []
if "attentionHeads" in data:
patterns: List[Dict[str, Any]] = []
for head_payload in data.get("attentionHeads", []):
layer = head_payload["layer"]
head = head_payload["head"]
for source_token, dest_token, weight in head_payload.get("edges", []):
patterns.append(
{
"sourceLayer": layer,
"sourceToken": source_token,
"destToken": dest_token,
"weight": weight,
"head": head,
}
)
return patterns
return data.get("attentionPatterns", [])
def get_attention_pattern_count(data: Optional[Dict[str, Any]]) -> int:
"""Return the number of visible serialized edges in either payload format."""
if not data:
return 0
if "numEdges" in data:
return int(data["numEdges"])
return len(data.get("attentionPatterns", []))
class APIService:
def __init__(self, base_url: str = None):
# If no base_url is provided, try to get it from environment variable or use local IP
if base_url is None:
import os
# Try to get URL from environment variable first
env_url = os.getenv('BACKEND_URL')
if env_url:
self.base_url = env_url
else:
import subprocess
try:
# Get IP address using ifconfig (macOS compatible)
result = subprocess.run(['ifconfig'], capture_output=True, text=True)
if result.returncode == 0:
# Parse the output to find the first non-localhost IP
for line in result.stdout.split('\n'):
if 'inet ' in line and '127.0.0.1' not in line:
local_ip = line.strip().split(' ')[1]
self.base_url = f"http://{local_ip}:8000"
break
else:
# Fallback to localhost if no IP found
self.base_url = "http://localhost:8000"
else:
# Fallback to localhost if ifconfig fails
self.base_url = "http://localhost:8000"
except Exception:
# Fallback to localhost if any error occurs
self.base_url = "http://localhost:8000"
else:
self.base_url = base_url
def check_backend_health(self) -> bool:
try:
response = requests.get(f"{self.base_url}/health", timeout=10)
return response.status_code == 200
except requests.exceptions.ConnectionError:
logger.warning(f"Could not connect to backend at {self.base_url}. Make sure the backend server is running.")
return False
except requests.exceptions.Timeout:
logger.warning("Backend request timed out. The server might be overloaded or not responding.")
return False
except Exception as e:
logger.error(f"Unexpected error checking backend health: {str(e)}")
return False
def process_text(
self,
text: str,
model: str,
threshold: float,
top_k: int,
selected_heads: List[Dict[str, int]],
) -> Dict:
response = requests.post(
f"{self.base_url}/process",
json={
"text": text,
"model_name": model,
"threshold": threshold,
"top_k": top_k,
"selected_heads": selected_heads,
},
timeout=30
)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def evaluate_text(
self,
text: str,
model: str,
target_token: Optional[str],
ablated_heads: List[Dict[str, int]]
) -> Dict:
response = requests.post(
f"{self.base_url}/evaluate",
json={
"text": text,
"model_name": model,
"target_token": target_token,
"ablated_heads": ablated_heads,
},
timeout=120
)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def list_datasets(self) -> List[Dict[str, Any]]:
response = requests.get(f"{self.base_url}/datasets", timeout=30)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()["datasets"]
def get_dataset(self, dataset_name: str) -> Dict[str, Any]:
response = requests.get(f"{self.base_url}/datasets/{dataset_name}", timeout=30)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def validate_dataset(self, payload: Dict[str, Any]) -> Dict[str, Any]:
response = requests.post(f"{self.base_url}/datasets/validate", json={"payload": payload}, timeout=30)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def save_dataset(self, payload: Dict[str, Any]) -> Dict[str, Any]:
response = requests.post(f"{self.base_url}/datasets/save", json={"payload": payload}, timeout=30)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def evaluate_dataset(
self,
dataset_name: str,
model: Optional[str],
ablated_heads: List[Dict[str, int]]
) -> Dict:
response = requests.post(
f"{self.base_url}/evaluate-dataset",
json={
"dataset_name": dataset_name,
"model_name": model,
"ablated_heads": ablated_heads,
},
timeout=180
)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def build_max_logit_diff_graph(
self,
text: str,
corrupted_text: str,
model: str,
target_token: Optional[str],
top_k: int,
top_heads_per_layer: int,
selected_heads: List[Dict[str, int]],
) -> Dict:
response = requests.post(
f"{self.base_url}/max-logit-diff-graph",
json={
"text": text,
"corrupted_text": corrupted_text,
"model_name": model,
"target_token": target_token,
"top_k": top_k,
"top_heads_per_layer": top_heads_per_layer,
"selected_heads": selected_heads,
},
timeout=180,
)
if response.status_code != 200:
raise Exception(f"API error: {response.text}")
return response.json()
def get_default_text_for_model(model: str) -> str:
"""Get the default text for a given model from configuration."""
return MODEL_DEFAULTS.get(model, {}).get("default_text", "")
def get_task_presets_for_model(model: str) -> List[Dict[str, str]]:
"""Return task presets for a model."""
return MODEL_DEFAULTS.get(model, {}).get("task_presets", [])
def get_model_dimensions(model: str, attention_data: Optional[Dict] = None) -> Tuple[int, int]:
"""Return source-layer count and heads per layer for a model."""
if attention_data:
num_layers = max(int(attention_data.get("numLayers", 1)) - 1, 1)
num_heads = int(attention_data.get("numHeads", 0))
if num_heads > 0:
return num_layers, num_heads
model_info = MODEL_INFO.get(model)
if model_info:
return model_info["layers"], model_info["heads"]
return 0, 0
def parse_uploaded_dataset(uploaded_file) -> Dict[str, Any]:
"""Parse uploaded JSON or CSV dataset into the canonical payload."""
file_name = uploaded_file.name.lower()
raw_bytes = uploaded_file.getvalue()
if file_name.endswith(".json"):
payload = json.loads(raw_bytes.decode("utf-8"))
if not isinstance(payload, dict):
raise ValueError("JSON dataset must be an object.")
return payload
if file_name.endswith(".csv"):
frame = pd.read_csv(io.BytesIO(raw_bytes))
required_columns = {"id", "text", "target_token"}
missing_columns = required_columns - set(frame.columns)
if missing_columns:
raise ValueError(f"CSV dataset is missing required columns: {', '.join(sorted(missing_columns))}")
examples = []
for row in frame.fillna("").to_dict(orient="records"):
example = {
"id": str(row["id"]),
"text": str(row["text"]),
"target_token": str(row["target_token"]),
}
if str(row.get("corrupted_text", "")).strip():
example["corrupted_text"] = str(row["corrupted_text"])
metadata = {
key: value for key, value in row.items()
if key not in {"id", "text", "target_token", "corrupted_text"} and str(value).strip()
}
if metadata:
example["metadata"] = metadata
examples.append(example)
return {
"name": Path(uploaded_file.name).stem,
"description": "Uploaded from CSV",
"metric": "target_probability",
"examples": examples,
}
raise ValueError("Unsupported file type. Please upload a JSON or CSV dataset.")
def create_attention_graph(
data: Dict,
threshold: float,
selected_heads: List[HeadPair],
head_groups: List[HeadGroup]
) -> None:
"""Create graph visualization using D3.js."""
logger.info(
"Creating graph with data: numLayers=%s, numTokens=%s, numPatterns=%s",
data["numLayers"],
data["numTokens"],
get_attention_pattern_count(data),
)
logger.info(f"Selected heads: {[(h.layer, h.head) for h in selected_heads]}")
logger.info(f"Head groups: {[(g.name, len(g.heads)) for g in head_groups]}")
# Filter attention patterns based on threshold and selected heads
filtered_patterns = get_filtered_attention_patterns(data, threshold, selected_heads, head_groups)
# Prepare data for D3 visualization
viz_data = {
'numLayers': data['numLayers'],
'numTokens': data['numTokens'],
'numHeads': data['numHeads'],
'tokens': data.get('tokens', [f'T{i}' for i in range(data['numTokens'])]),
'attentionPatterns': filtered_patterns,
'headGroups': [
{
'id': group.id,
'name': group.name,
'description': group.description,
'color': group.color,
'heads': [{'layer': h.layer, 'head': h.head} for h in group.heads]
}
for group in head_groups
],
'selectedHeads': [{'layer': h.layer, 'head': h.head} for h in selected_heads]
}
# Create HTML with embedded D3.js visualization
html = f"""
<div id="visualization-container" style="width: 100%; height: 800px;"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.attention-line {{
stroke-opacity: 0.6;
stroke-width: 4;
cursor: pointer;
}}
.attention-line:hover {{
stroke-opacity: 0.9;
stroke-width: 6;
}}
.grid-point {{
fill: #e5e7eb;
cursor: pointer;
}}
.grid-point:hover {{
fill: #d1d5db;
r: 8;
}}
.hover-target {{
fill: transparent;
cursor: pointer;
}}
#graph-tooltip {{
display: none;
position: absolute;
background: white;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
z-index: 1000;
}}
</style>
<script>
// Color palette for individual heads
const colorPalette = [
"#38B2AC", "#9F7AEA", "#F6AD55", "#68D391", "#F687B3",
"#4FD1C5", "#B794F4", "#7F9CF5", "#C6F6D5", "#FBD38D",
"#76E4F7", "#E9D8FD", "#90CDF4", "#FEB2B2", "#81E6D9",
"#D6BCFA", "#FBB6CE", "#B2F5EA", "#667EEA", "#ED64A6"
];
// Graph dimensions
const graphDimensions = {{
width: 1000,
height: 700,
padding: {{ top: 40, right: 180, bottom: 60, left: 60 }}
}};
// Data from Streamlit
const data = {json.dumps(viz_data)};
let headGroups = data.headGroups || [];
let selectedHeads = data.selectedHeads || [];
// Function to get visible heads
function getVisibleHeads() {{
return [...selectedHeads, ...headGroups.flatMap(g => g.heads)];
}}
// Function to get head group
function getHeadGroup(layer, head) {{
for (const group of headGroups) {{
if (group.heads.some(h => h.layer === layer && h.head === head)) {{
return group.id;
}}
}}
return -1;
}}
// Function to get group color
function getGroupColor(groupId) {{
const group = headGroups.find(g => g.id === groupId);
if (group?.color) {{
return group.color;
}}
return colorPalette[groupId % colorPalette.length];
}}
// Function to get head color
function getHeadColor(layer, head) {{
// Check if this is a wildcard head (has grey color)
const headObj = selectedHeads.find(h => h.layer === layer && h.head === head);
if (headObj && headObj.color && headObj.color.startsWith('#')) {{
// Check if it's a grey color (all RGB components are equal)
const r = parseInt(headObj.color.slice(1, 3), 16);
const g = parseInt(headObj.color.slice(3, 5), 16);
const b = parseInt(headObj.color.slice(5, 7), 16);
if (r === g && g === b) {{
return headObj.color;
}}
}}
// For non-wildcard heads, use the original color palette
return individualHeadColorScale(head.toString());
}}
// Main drawing function
function drawGraph() {{
const svg = d3.select("#visualization-container")
.append("svg")
.attr("width", graphDimensions.width)
.attr("height", graphDimensions.height);
const width = graphDimensions.width;
const height = graphDimensions.height;
const padding = graphDimensions.padding;
const legendWidth = padding.right;
const graphWidth = width - padding.left - padding.right;
const graphHeight = height - padding.top - padding.bottom;
const tokenWidth = graphWidth / data.numTokens;
const layerHeight = graphHeight / (data.numLayers - 1);
// Create nodes
const nodes = [];
for (let l = 0; l < data.numLayers; l++) {{
for (let t = 0; t < data.numTokens; t++) {{
nodes.push({{
id: `${{l}}-${{t}}`,
layer: l,
token: t,
x: padding.left + t * tokenWidth + tokenWidth / 2,
y: height - (padding.bottom + l * layerHeight)
}});
}}
}}
// Create color scales
const individualHeadColorScale = d3.scaleOrdinal(colorPalette)
.domain(Array.from({{ length: data.numHeads }}, (_, i) => i.toString()));
// Filter edges
const visibleHeadPairs = getVisibleHeads();
const links = data.attentionPatterns
.filter(edge => {{
const isVisible = visibleHeadPairs.some(h =>
h.layer === edge.sourceLayer && h.head === edge.head
);
return edge.weight >= {threshold} && isVisible;
}})
.map(edge => ({{
source: `${{edge.sourceLayer}}-${{edge.sourceToken}}`,
target: `${{edge.sourceLayer + 1}}-${{edge.destToken}}`,
weight: edge.weight,
head: edge.head,
groupId: getHeadGroup(edge.sourceLayer, edge.head) ?? -1
}}));
// Draw layers and tokens labels
const g = svg.append("g");
// Layer labels
for (let l = 0; l < data.numLayers; l++) {{
g.append("text")
.attr("x", padding.left / 2 + 25)
.attr("y", height - (padding.bottom + l * layerHeight))
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(l.toString());
}}
// Y-axis label
g.append("text")
.attr("x", padding.left / 2)
.attr("y", height / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("font-size", "14px")
.attr("font-weight", "medium")
.text("Layer");
// Token labels
for (let t = 0; t < data.numTokens; t++) {{
g.append("text")
.attr("x", padding.left + t * tokenWidth + tokenWidth / 2)
.attr("y", height - padding.bottom / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(data.tokens?.[t] || `T${{t}}`);
}}
// X-axis label
g.append("text")
.attr("x", width / 2)
.attr("y", height - padding.bottom / 4)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("font-size", "14px")
.attr("font-weight", "medium")
.text("Token");
// Draw edges with curved paths
const linkElements = g.selectAll("path")
.data(links)
.enter()
.append("path")
.attr("d", d => {{
const source = nodes.find(n => n.id === d.source);
const target = nodes.find(n => n.id === d.target);
const dx = target.x - source.x;
const controlPoint1x = source.x + dx * 0.5;
const controlPoint1y = source.y;
const controlPoint2x = target.x - dx * 0.5;
const controlPoint2y = target.y;
return `M ${{source.x}} ${{source.y}} C ${{controlPoint1x}} ${{controlPoint1y}}, ${{controlPoint2x}} ${{controlPoint2y}}, ${{target.x}} ${{target.y}}`;
}})
.attr("fill", "none")
.attr("stroke", d => {{
if (d.groupId >= 0) {{
return getGroupColor(d.groupId);
}}
return getHeadColor(d.sourceLayer, d.head);
}})
.attr("stroke-width", 4)
.attr("opacity", 0.6)
.attr("class", "attention-line")
.on("mouseover", function(event, d) {{
d3.select(this)
.attr("opacity", 1)
.attr("stroke-width", 6);
const tooltip = d3.select("#graph-tooltip");
const group = headGroups.find(g => g.id === d.groupId);
const headObj = selectedHeads.find(h => h.layer === d.sourceLayer && h.head === d.head);
const isWildcard = headObj && headObj.color && headObj.color.startsWith('#') &&
parseInt(headObj.color.slice(1, 3), 16) === parseInt(headObj.color.slice(3, 5), 16) &&
parseInt(headObj.color.slice(3, 5), 16) === parseInt(headObj.color.slice(5, 7), 16);
tooltip.style("display", "block")
.html(`Head: Layer ${{d.source.split("-")[0]}}, Head ${{d.head}}${{isWildcard ? ' (Wildcard)' : ''}}<br>
Weight: ${{d.weight.toFixed(4)}}${{group ?
`<br>Group: ${{group.name}}${{group.description ?
`<br><span style="font-style: italic; font-size: 11px;">${{group.description}}</span>` : ''}}` :
'<br>Individual Head'}}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
}})
.on("mouseout", function() {{
d3.select(this)
.attr("opacity", 0.6)
.attr("stroke-width", 4);
d3.select("#graph-tooltip").style("display", "none");
}});
// Draw nodes
const nodeElements = g.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("class", "grid-point")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", 6)
.attr("fill", "#e5e7eb")
.on("mouseover", function(event, d) {{
d3.select(this)
.attr("r", 8)
.attr("fill", "#d1d5db");
const tooltip = d3.select("#graph-tooltip");
tooltip.style("display", "block")
.html(`Layer ${{d.layer}}, Token ${{d.token}}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
}})
.on("mouseout", function() {{
d3.select(this)
.attr("r", 6)
.attr("fill", "#e5e7eb");
d3.select("#graph-tooltip").style("display", "none");
}});
// Add invisible hover targets for easier interaction
g.selectAll("circle.hover-target")
.data(nodes)
.enter()
.append("circle")
.attr("class", "hover-target")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", 12)
.attr("fill", "transparent")
.on("mouseover", function(event, d) {{
const tooltip = d3.select("#graph-tooltip");
tooltip.style("display", "block")
.html(`Layer ${{d.layer}}, Token ${{d.token}}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
d3.select(this.parentNode)
.select(`circle:not(.hover-target)[data-node-id="${{d.id}}"]`)
.attr("r", 8)
.attr("fill", "#d1d5db");
}})
.on("mouseout", function(event, d) {{
d3.select("#graph-tooltip").style("display", "none");
d3.select(this.parentNode)
.select(`circle:not(.hover-target)[data-node-id="${{d.id}}"]`)
.attr("r", 6)
.attr("fill", "#e5e7eb");
}});
// Draw legend
const legend = g.append("g")
.attr("transform", `translate(${{width - legendWidth + 20}}, ${{padding.top}})`);
// Add legend title
legend.append("text")
.attr("x", 0)
.attr("y", 0)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.text("Legend");
// Add group colors to legend
headGroups.forEach((group, i) => {{
const y = 30 + i * 25;
legend.append("rect")
.attr("x", 0)
.attr("y", y)
.attr("width", 15)
.attr("height", 15)
.attr("fill", getGroupColor(group.id));
const groupText = legend.append("text")
.attr("x", 25)
.attr("y", y + 12)
.attr("font-size", "12px")
.text(group.name);
if (group.description) {{
groupText
.on("mouseenter", function(event) {{
const tooltip = d3.select("#graph-tooltip");
tooltip.style("display", "block")
.html(`<strong>${{group.name}}</strong><br>${{group.description}}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
}})
.on("mouseleave", function() {{
d3.select("#graph-tooltip").style("display", "none");
}});
}}
}});
// Add separator
const separatorY = 30 + headGroups.length * 25 + 10;
legend.append("line")
.attr("x1", 0)
.attr("x2", legendWidth - padding.left)
.attr("y1", separatorY)
.attr("y2", separatorY)
.attr("stroke", "#e5e7eb")
.attr("stroke-width", 2);
// Add individual heads section
legend.append("text")
.attr("x", 0)
.attr("y", separatorY + 25)
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text("Individual Heads");
// Add individual head colors to legend
const visibleIndividualHeads = selectedHeads.filter(h =>
!headGroups.some(g => g.heads.some(gh => gh.layer === h.layer && gh.head === h.head))
);
visibleIndividualHeads.forEach((head, i) => {{
const y = separatorY + 40 + i * 25;
legend.append("rect")
.attr("x", 0)
.attr("y", y)
.attr("width", 15)
.attr("height", 15)
.attr("fill", getHeadColor(head.layer, head.head));
legend.append("text")
.attr("x", 25)
.attr("y", y + 12)
.attr("font-size", "12px")
.text(`Layer ${{head.layer}}, Head ${{head.head}}${{head.color && head.color.startsWith('#') &&
parseInt(head.color.slice(1, 3), 16) === parseInt(head.color.slice(3, 5), 16) &&
parseInt(head.color.slice(3, 5), 16) === parseInt(head.color.slice(5, 7), 16) ? ' (Wildcard)' : ''}}`);
}});
}}
// Add tooltip div
const tooltip = document.createElement("div");
tooltip.id = "graph-tooltip";
document.body.appendChild(tooltip);
// Draw the graph
drawGraph();
</script>
"""
# Display the visualization
st.components.v1.html(html, height=800)
def create_max_logit_diff_graph(data: Dict) -> None:
"""Create a graph for the best clean-corrupted logit-diff head in each layer at the final position."""
html = f"""
<div id="max-logit-diff-container" style="width: 100%; height: 800px;"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.causal-line {{
fill: none;
stroke-linecap: round;
cursor: pointer;
}}
.causal-node {{
cursor: pointer;
}}
#causal-graph-tooltip {{
display: none;
position: absolute;
background: rgba(255, 255, 255, 0.98);
padding: 8px 10px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 12px;
pointer-events: none;
z-index: 1000;
box-shadow: 0 10px 25px rgba(15, 23, 42, 0.12);
}}
</style>
<script>
const data = {json.dumps(data)};
const dims = {{
width: 1000,
height: 700,
padding: {{ top: 40, right: 40, bottom: 60, left: 60 }}
}};
const svg = d3.select("#max-logit-diff-container")
.append("svg")
.attr("width", dims.width)
.attr("height", dims.height);
const width = dims.width;
const height = dims.height;
const padding = dims.padding;
const graphWidth = width - padding.left - padding.right;
const graphHeight = height - padding.top - padding.bottom;
const tokenWidth = graphWidth / data.numTokens;
const layerHeight = graphHeight / (data.numLayers - 1);
const selectedNodes = data.importantNodes || [];
const selectedNodeLookup = new Map();
selectedNodes.forEach(node => {{
const key = `${{node.layer}}-${{node.token}}`;
if (!selectedNodeLookup.has(key)) {{
selectedNodeLookup.set(key, []);
}}
selectedNodeLookup.get(key).push(node);
}});
const edgeScores = data.attentionPatterns.map(edge => Math.abs(edge.combined_score));
const maxEdgeScore = d3.max(edgeScores) || 1;
const colorScale = d3.scaleLinear()
.domain([-1, 0, 1])
.range(["#b91c1c", "#a8a29e", "#166534"]);
const nodes = [];
for (let layer = 0; layer < data.numLayers; layer++) {{
for (let token = 0; token < data.numTokens; token++) {{
nodes.push({{
id: `${{layer}}-${{token}}`,
layer,
token,
x: padding.left + token * tokenWidth + tokenWidth / 2,
y: height - (padding.bottom + layer * layerHeight)
}});
}}
}}
const g = svg.append("g");
const tooltip = document.createElement("div");
tooltip.id = "causal-graph-tooltip";
document.body.appendChild(tooltip);
for (let layer = 0; layer < data.numLayers; layer++) {{
g.append("text")
.attr("x", padding.left / 2 + 25)
.attr("y", height - (padding.bottom + layer * layerHeight))
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(layer.toString());
}}
for (let token = 0; token < data.numTokens; token++) {{
g.append("text")
.attr("x", padding.left + token * tokenWidth + tokenWidth / 2)
.attr("y", height - padding.bottom / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(data.tokens?.[token] || `T${{token}}`);
}}
g.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("class", "causal-node")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", d => selectedNodeLookup.has(`${{d.layer}}-${{d.token}}`) ? 9 : 5)
.attr("fill", d => {{
const nodeList = selectedNodeLookup.get(`${{d.layer}}-${{d.token}}`);
const topNode = nodeList?.[0];
return topNode
? colorScale(Math.max(-1, Math.min(1, topNode.logit_diff_delta / (Math.abs(topNode.logit_diff_delta) || 1))))
: "#d6d3d1";
}})
.attr("stroke", d => selectedNodeLookup.has(`${{d.layer}}-${{d.token}}`) ? "#1f2937" : "none")
.attr("stroke-width", d => selectedNodeLookup.has(`${{d.layer}}-${{d.token}}`) ? 1.5 : 0)
.on("mouseover", function(event, d) {{
const tooltipDiv = d3.select("#causal-graph-tooltip");
const nodeList = selectedNodeLookup.get(`${{d.layer}}-${{d.token}}`);
if (nodeList?.length) {{
const headLines = nodeList.map(node =>
`L${{node.sourceLayer}}H${{node.head}} (#${{(node.rankInLayer || 0) + 1}}): ${{node.logit_diff_delta.toFixed(4)}}`
).join("<br>");
tooltipDiv.style("display", "block")
.html(
`Layer ${{d.layer}}, Token ${{d.token}}<br>` +
`Important heads:<br>${{headLines}}`
)
.style("left", (event.pageX + 12) + "px")
.style("top", (event.pageY - 12) + "px");
}} else {{
tooltipDiv.style("display", "block")
.html(`Layer ${{d.layer}}, Token ${{d.token}}`)
.style("left", (event.pageX + 12) + "px")
.style("top", (event.pageY - 12) + "px");
}}
}})
.on("mouseout", function() {{
d3.select("#causal-graph-tooltip").style("display", "none");
}});
g.selectAll("path")
.data(data.attentionPatterns)
.enter()
.append("path")
.attr("class", "causal-line")
.attr("d", edge => {{
const source = nodes.find(node => node.id === `${{edge.sourceLayer}}-${{edge.sourceToken}}`);
const target = nodes.find(node => node.id === `${{edge.sourceLayer + 1}}-${{edge.destToken}}`);
const dx = target.x - source.x;
const controlPoint1x = source.x + dx * 0.5;
const controlPoint1y = source.y;
const controlPoint2x = target.x - dx * 0.5;
const controlPoint2y = target.y;
return `M ${{source.x}} ${{source.y}} C ${{controlPoint1x}} ${{controlPoint1y}}, ${{controlPoint2x}} ${{controlPoint2y}}, ${{target.x}} ${{target.y}}`;
}})
.attr("stroke", edge => colorScale(Math.max(-1, Math.min(1, edge.logit_diff_delta / (Math.abs(edge.logit_diff_delta) || 1)))))
.attr("stroke-width", edge => 2 + 8 * (Math.abs(edge.combined_score) / maxEdgeScore))
.attr("stroke-opacity", edge => 0.28 + 0.72 * (Math.abs(edge.combined_score) / maxEdgeScore))
.on("mouseover", function(event, edge) {{
d3.select(this).attr("stroke-opacity", 1);
d3.select("#causal-graph-tooltip")
.style("display", "block")
.html(
`L${{edge.sourceLayer}}H${{edge.head}}<br>` +
`source: ${{data.tokens?.[edge.sourceToken] || edge.sourceToken}} -> target: ${{data.tokens?.[edge.destToken] || edge.destToken}}<br>` +
`attention: ${{edge.weight.toFixed(4)}}<br>` +
`clean - corrupted: ${{edge.logit_diff_delta.toFixed(4)}}`
)
.style("left", (event.pageX + 12) + "px")
.style("top", (event.pageY - 12) + "px");
}})
.on("mouseout", function(event, edge) {{
d3.select(this)
.attr("stroke-opacity", 0.28 + 0.72 * (Math.abs(edge.combined_score) / maxEdgeScore));
d3.select("#causal-graph-tooltip").style("display", "none");
}});
const labelGroup = g.append("g");
const highlightedNodes = selectedNodes.map(node => {{
const graphNode = nodes.find(candidate => candidate.id === `${{node.layer}}-${{node.token}}`);
return {{
...node,
x: graphNode?.x ?? 0,
y: graphNode?.y ?? 0
}};
}});
const labelSelection = labelGroup.selectAll("g")
.data(highlightedNodes)
.enter()
.append("g")
.attr("transform", node => `translate(${{node.x + 12 + (node.rankInLayer || 0) * 52}}, ${{node.y - 10}})`);
labelSelection.append("rect")
.attr("class", "causal-head-halo")
.attr("rx", 6)
.attr("ry", 6)