SpectralHarmonicRouting 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shr/__init__.py +51 -0
- shr/ablation.py +284 -0
- shr/acfg.py +349 -0
- shr/analyzer.py +802 -0
- shr/clustering.py +162 -0
- shr/faithfulness.py +347 -0
- shr/flow.py +285 -0
- shr/py.typed +0 -0
- spectralharmonicrouting-0.1.0.dist-info/METADATA +101 -0
- spectralharmonicrouting-0.1.0.dist-info/RECORD +12 -0
- spectralharmonicrouting-0.1.0.dist-info/WHEEL +4 -0
- spectralharmonicrouting-0.1.0.dist-info/licenses/LICENSE +21 -0
shr/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Spectral Head Routing (SHR) mechanistic interpretability package."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .ablation import (
|
|
6
|
+
LayerAblator,
|
|
7
|
+
evaluate_causal_ablation,
|
|
8
|
+
patch_activation_mediation,
|
|
9
|
+
sweep_activation_patching,
|
|
10
|
+
sweep_layer_bypass,
|
|
11
|
+
)
|
|
12
|
+
from .acfg import draw_data_driven_acfg
|
|
13
|
+
from .analyzer import UniversalSHRAnalyzer
|
|
14
|
+
from .clustering import (
|
|
15
|
+
discover_acoustic_clusters,
|
|
16
|
+
select_optimal_k,
|
|
17
|
+
separate_outlier_patches,
|
|
18
|
+
)
|
|
19
|
+
from .flow import compute_signal_flow, draw_signal_flow_acfg
|
|
20
|
+
from .faithfulness import (
|
|
21
|
+
attention_rollout,
|
|
22
|
+
deletion_insertion_auc,
|
|
23
|
+
integrated_gradients_saliency,
|
|
24
|
+
run_faithfulness_comparison,
|
|
25
|
+
vanilla_gradient_saliency,
|
|
26
|
+
vit_gradcam,
|
|
27
|
+
vit_gradcam_plusplus,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"__version__",
|
|
32
|
+
"UniversalSHRAnalyzer",
|
|
33
|
+
"LayerAblator",
|
|
34
|
+
"evaluate_causal_ablation",
|
|
35
|
+
"patch_activation_mediation",
|
|
36
|
+
"sweep_activation_patching",
|
|
37
|
+
"sweep_layer_bypass",
|
|
38
|
+
"separate_outlier_patches",
|
|
39
|
+
"select_optimal_k",
|
|
40
|
+
"discover_acoustic_clusters",
|
|
41
|
+
"draw_data_driven_acfg",
|
|
42
|
+
"deletion_insertion_auc",
|
|
43
|
+
"vanilla_gradient_saliency",
|
|
44
|
+
"integrated_gradients_saliency",
|
|
45
|
+
"vit_gradcam",
|
|
46
|
+
"vit_gradcam_plusplus",
|
|
47
|
+
"attention_rollout",
|
|
48
|
+
"run_faithfulness_comparison",
|
|
49
|
+
"compute_signal_flow",
|
|
50
|
+
"draw_signal_flow_acfg",
|
|
51
|
+
]
|
shr/ablation.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Causal layer ablation utilities for any Transformer analyzed by UniversalSHRAnalyzer."""
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
from typing import Dict, Iterable, List, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
import torch.nn as nn
|
|
8
|
+
|
|
9
|
+
from .analyzer import UniversalSHRAnalyzer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _zero_like_output(out):
|
|
13
|
+
if isinstance(out, torch.Tensor):
|
|
14
|
+
return torch.zeros_like(out)
|
|
15
|
+
if isinstance(out, tuple):
|
|
16
|
+
return tuple(_zero_like_output(x) if i == 0 else x for i, x in enumerate(out))
|
|
17
|
+
if isinstance(out, list):
|
|
18
|
+
return [_zero_like_output(x) if i == 0 else x for i, x in enumerate(out)]
|
|
19
|
+
if isinstance(out, dict):
|
|
20
|
+
new_out = dict(out)
|
|
21
|
+
for key in ("last_hidden_state", "logits", "hidden_states"):
|
|
22
|
+
if key in new_out and isinstance(new_out[key], torch.Tensor):
|
|
23
|
+
new_out[key] = torch.zeros_like(new_out[key])
|
|
24
|
+
break
|
|
25
|
+
return new_out
|
|
26
|
+
return out
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LayerAblator:
|
|
30
|
+
"""Context manager that bypasses (residual-delta ablation) or zeros selected transformer layers."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, layers: Sequence[nn.Module], layer_indices: Iterable[int], mode: str = "bypass"):
|
|
33
|
+
self.layers = list(layers)
|
|
34
|
+
self.layer_indices = [int(i) for i in layer_indices if 0 <= int(i) < len(self.layers)]
|
|
35
|
+
self.mode = mode
|
|
36
|
+
self._hooks: List[torch.utils.hooks.RemovableHandle] = []
|
|
37
|
+
|
|
38
|
+
def __enter__(self):
|
|
39
|
+
for idx in self.layer_indices:
|
|
40
|
+
def hook(_mod, inp, out):
|
|
41
|
+
if self.mode == "bypass":
|
|
42
|
+
x_in = inp[0] if isinstance(inp, (tuple, list)) and len(inp) > 0 else inp
|
|
43
|
+
if isinstance(x_in, torch.Tensor):
|
|
44
|
+
if isinstance(out, torch.Tensor) and x_in.shape == out.shape:
|
|
45
|
+
return x_in
|
|
46
|
+
if isinstance(out, tuple) and len(out) > 0 and isinstance(out[0], torch.Tensor) and x_in.shape == out[0].shape:
|
|
47
|
+
return (x_in,) + out[1:]
|
|
48
|
+
return _zero_like_output(out)
|
|
49
|
+
|
|
50
|
+
self._hooks.append(self.layers[idx].register_forward_hook(hook))
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
54
|
+
for h in self._hooks:
|
|
55
|
+
h.remove()
|
|
56
|
+
self._hooks.clear()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _eval_accuracy(
|
|
60
|
+
model: nn.Module,
|
|
61
|
+
dataloader,
|
|
62
|
+
device: torch.device,
|
|
63
|
+
max_samples: Optional[int] = None,
|
|
64
|
+
) -> float:
|
|
65
|
+
model.eval()
|
|
66
|
+
correct = 0
|
|
67
|
+
total = 0
|
|
68
|
+
with torch.no_grad():
|
|
69
|
+
for batch in dataloader:
|
|
70
|
+
images, labels = batch[0].to(device), batch[1].view(-1).to(device)
|
|
71
|
+
outs = model(images)
|
|
72
|
+
logits = UniversalSHRAnalyzer.extract_tensor(outs)
|
|
73
|
+
if logits.dim() == 1:
|
|
74
|
+
logits = logits.unsqueeze(0)
|
|
75
|
+
preds = logits.argmax(dim=-1)
|
|
76
|
+
correct += int((preds == labels).sum().item())
|
|
77
|
+
total += int(labels.numel())
|
|
78
|
+
if max_samples is not None and total >= max_samples:
|
|
79
|
+
break
|
|
80
|
+
return correct / max(total, 1)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def evaluate_causal_ablation(
|
|
84
|
+
analyzer: UniversalSHRAnalyzer,
|
|
85
|
+
dataloader,
|
|
86
|
+
ablate_indices: Sequence[int],
|
|
87
|
+
include_random_control: bool = True,
|
|
88
|
+
seed: int = 42,
|
|
89
|
+
max_samples: Optional[int] = None,
|
|
90
|
+
mode: str = "bypass",
|
|
91
|
+
random_trials: int = 5,
|
|
92
|
+
) -> Dict[str, object]:
|
|
93
|
+
"""
|
|
94
|
+
Measures baseline accuracy, accuracy after ablating `ablate_indices`,
|
|
95
|
+
and (optionally) a multi-seed random-layer control ablation of the same cardinality.
|
|
96
|
+
"""
|
|
97
|
+
baseline_acc = _eval_accuracy(analyzer.model, dataloader, analyzer.device, max_samples=max_samples)
|
|
98
|
+
|
|
99
|
+
with LayerAblator(analyzer.layers, ablate_indices, mode=mode):
|
|
100
|
+
ablated_acc = _eval_accuracy(analyzer.model, dataloader, analyzer.device, max_samples=max_samples)
|
|
101
|
+
|
|
102
|
+
result: Dict[str, object] = {
|
|
103
|
+
"baseline_accuracy": baseline_acc,
|
|
104
|
+
"ablated_layers": list(ablate_indices),
|
|
105
|
+
"ablated_accuracy": ablated_acc,
|
|
106
|
+
"accuracy_drop": baseline_acc - ablated_acc,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if include_random_control:
|
|
110
|
+
remaining = [i for i in range(analyzer.num_layers) if i not in set(ablate_indices)]
|
|
111
|
+
k = min(len(ablate_indices), len(remaining))
|
|
112
|
+
if k > 0:
|
|
113
|
+
rand_accs = []
|
|
114
|
+
last_rand_layers = []
|
|
115
|
+
for t in range(max(1, random_trials)):
|
|
116
|
+
rng = random.Random(seed + t)
|
|
117
|
+
last_rand_layers = sorted(rng.sample(remaining, k))
|
|
118
|
+
with LayerAblator(analyzer.layers, last_rand_layers, mode=mode):
|
|
119
|
+
rand_accs.append(_eval_accuracy(analyzer.model, dataloader, analyzer.device, max_samples=max_samples))
|
|
120
|
+
mean_rand_acc = sum(rand_accs) / len(rand_accs)
|
|
121
|
+
result["random_control_layers"] = last_rand_layers
|
|
122
|
+
result["random_control_accuracy"] = mean_rand_acc
|
|
123
|
+
result["random_control_drop"] = baseline_acc - mean_rand_acc
|
|
124
|
+
|
|
125
|
+
return result
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _replace_tokens_in_output(out, ref_tensor: torch.Tensor, token_indices: Sequence[int], analyzer: UniversalSHRAnalyzer, include_prefix_offset: bool):
|
|
129
|
+
"""Replaces selected spatial token indices in `out` with values from `ref_tensor`."""
|
|
130
|
+
t_out = UniversalSHRAnalyzer.extract_tensor(out)
|
|
131
|
+
if t_out is None or t_out.shape != ref_tensor.shape:
|
|
132
|
+
return out
|
|
133
|
+
|
|
134
|
+
patched = t_out.clone()
|
|
135
|
+
idx_list = [int(i) for i in token_indices]
|
|
136
|
+
|
|
137
|
+
if patched.dim() == 3:
|
|
138
|
+
offset = analyzer._infer_cls_offset(patched.shape[1]) if include_prefix_offset else 0
|
|
139
|
+
valid = [offset + i for i in idx_list if 0 <= offset + i < patched.shape[1]]
|
|
140
|
+
if valid:
|
|
141
|
+
patched[:, valid, :] = ref_tensor[:, valid, :]
|
|
142
|
+
elif patched.dim() == 4:
|
|
143
|
+
b, d1, d2, d3 = patched.shape
|
|
144
|
+
if d2 == d3 and d1 != d2:
|
|
145
|
+
# (B, C, H, W)
|
|
146
|
+
flat_p = patched.view(b, d1, d2 * d3)
|
|
147
|
+
flat_r = ref_tensor.view(b, d1, d2 * d3)
|
|
148
|
+
valid = [i for i in idx_list if 0 <= i < d2 * d3]
|
|
149
|
+
if valid:
|
|
150
|
+
flat_p[:, :, valid] = flat_r[:, :, valid]
|
|
151
|
+
patched = flat_p.view(b, d1, d2, d3)
|
|
152
|
+
else:
|
|
153
|
+
# (B, H, W, C)
|
|
154
|
+
flat_p = patched.view(b, d1 * d2, d3)
|
|
155
|
+
flat_r = ref_tensor.view(b, d1 * d2, d3)
|
|
156
|
+
valid = [i for i in idx_list if 0 <= i < d1 * d2]
|
|
157
|
+
if valid:
|
|
158
|
+
flat_p[:, valid, :] = flat_r[:, valid, :]
|
|
159
|
+
patched = flat_p.view(b, d1, d2, d3)
|
|
160
|
+
|
|
161
|
+
if isinstance(out, torch.Tensor):
|
|
162
|
+
return patched
|
|
163
|
+
if isinstance(out, tuple):
|
|
164
|
+
return tuple(patched if i == 0 else x for i, x in enumerate(out))
|
|
165
|
+
if isinstance(out, list):
|
|
166
|
+
return [patched if i == 0 else x for i, x in enumerate(out)]
|
|
167
|
+
if isinstance(out, dict):
|
|
168
|
+
new_out = dict(out)
|
|
169
|
+
for key in ("logits", "last_hidden_state", "hidden_states"):
|
|
170
|
+
if key in new_out and isinstance(new_out[key], torch.Tensor):
|
|
171
|
+
new_out[key] = patched
|
|
172
|
+
break
|
|
173
|
+
return new_out
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def patch_activation_mediation(
|
|
178
|
+
analyzer: UniversalSHRAnalyzer,
|
|
179
|
+
target_image: torch.Tensor,
|
|
180
|
+
reference_image: torch.Tensor,
|
|
181
|
+
target_class: int,
|
|
182
|
+
layer_idx: int,
|
|
183
|
+
token_indices: Sequence[int],
|
|
184
|
+
include_prefix_offset: bool = True,
|
|
185
|
+
) -> Dict[str, float]:
|
|
186
|
+
"""
|
|
187
|
+
Causal mediation via token-level activation patching: replaces `token_indices`
|
|
188
|
+
at `layer_idx` in `target_image` with activations from `reference_image` and
|
|
189
|
+
measures the shift in target class logit.
|
|
190
|
+
"""
|
|
191
|
+
analyzer.model.eval()
|
|
192
|
+
tgt = target_image.clone().to(analyzer.device)
|
|
193
|
+
ref = reference_image.clone().to(analyzer.device)
|
|
194
|
+
if tgt.dim() in (2, 3):
|
|
195
|
+
tgt = tgt.unsqueeze(0)
|
|
196
|
+
if ref.dim() in (2, 3):
|
|
197
|
+
ref = ref.unsqueeze(0)
|
|
198
|
+
|
|
199
|
+
ref_cache = {}
|
|
200
|
+
|
|
201
|
+
def capture_hook(_mod, _inp, out):
|
|
202
|
+
t = UniversalSHRAnalyzer.extract_tensor(out)
|
|
203
|
+
if t is not None:
|
|
204
|
+
ref_cache["act"] = t.detach()
|
|
205
|
+
|
|
206
|
+
h_cap = analyzer.layers[layer_idx].register_forward_hook(capture_hook)
|
|
207
|
+
try:
|
|
208
|
+
with torch.no_grad():
|
|
209
|
+
analyzer.model(ref)
|
|
210
|
+
finally:
|
|
211
|
+
h_cap.remove()
|
|
212
|
+
|
|
213
|
+
with torch.no_grad():
|
|
214
|
+
base_logits = UniversalSHRAnalyzer.extract_tensor(analyzer.model(tgt))
|
|
215
|
+
if base_logits.dim() == 1:
|
|
216
|
+
base_logits = base_logits.unsqueeze(0)
|
|
217
|
+
base_logit = float(base_logits[0, int(target_class)].item())
|
|
218
|
+
|
|
219
|
+
if "act" not in ref_cache:
|
|
220
|
+
return {"base_logit": base_logit, "patched_logit": base_logit, "causal_effect": 0.0}
|
|
221
|
+
|
|
222
|
+
def patch_hook(_mod, _inp, out):
|
|
223
|
+
return _replace_tokens_in_output(out, ref_cache["act"], token_indices, analyzer, include_prefix_offset)
|
|
224
|
+
|
|
225
|
+
h_patch = analyzer.layers[layer_idx].register_forward_hook(patch_hook)
|
|
226
|
+
try:
|
|
227
|
+
with torch.no_grad():
|
|
228
|
+
patched_logits = UniversalSHRAnalyzer.extract_tensor(analyzer.model(tgt))
|
|
229
|
+
if patched_logits.dim() == 1:
|
|
230
|
+
patched_logits = patched_logits.unsqueeze(0)
|
|
231
|
+
patched_logit = float(patched_logits[0, int(target_class)].item())
|
|
232
|
+
finally:
|
|
233
|
+
h_patch.remove()
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
"layer_idx": int(layer_idx),
|
|
237
|
+
"base_logit": base_logit,
|
|
238
|
+
"patched_logit": patched_logit,
|
|
239
|
+
"causal_effect": base_logit - patched_logit,
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def sweep_activation_patching(
|
|
244
|
+
analyzer: UniversalSHRAnalyzer,
|
|
245
|
+
target_image: torch.Tensor,
|
|
246
|
+
reference_image: torch.Tensor,
|
|
247
|
+
target_class: int,
|
|
248
|
+
token_indices: Sequence[int],
|
|
249
|
+
include_prefix_offset: bool = True,
|
|
250
|
+
) -> List[Dict[str, float]]:
|
|
251
|
+
"""Sweeps token-level activation patching across all layers to locate the critical layer."""
|
|
252
|
+
return [
|
|
253
|
+
patch_activation_mediation(
|
|
254
|
+
analyzer,
|
|
255
|
+
target_image,
|
|
256
|
+
reference_image,
|
|
257
|
+
target_class,
|
|
258
|
+
layer_idx=i,
|
|
259
|
+
token_indices=token_indices,
|
|
260
|
+
include_prefix_offset=include_prefix_offset,
|
|
261
|
+
)
|
|
262
|
+
for i in range(analyzer.num_layers)
|
|
263
|
+
]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def sweep_layer_bypass(
|
|
267
|
+
analyzer: UniversalSHRAnalyzer,
|
|
268
|
+
dataloader,
|
|
269
|
+
mode: str = "bypass",
|
|
270
|
+
max_samples: Optional[int] = None,
|
|
271
|
+
) -> List[Dict[str, float]]:
|
|
272
|
+
"""Evaluates single-layer bypass ablation drop across every layer."""
|
|
273
|
+
baseline_acc = _eval_accuracy(analyzer.model, dataloader, analyzer.device, max_samples=max_samples)
|
|
274
|
+
rows: List[Dict[str, float]] = []
|
|
275
|
+
for i in range(analyzer.num_layers):
|
|
276
|
+
with LayerAblator(analyzer.layers, [i], mode=mode):
|
|
277
|
+
acc_i = _eval_accuracy(analyzer.model, dataloader, analyzer.device, max_samples=max_samples)
|
|
278
|
+
rows.append({
|
|
279
|
+
"layer_idx": int(i),
|
|
280
|
+
"baseline_accuracy": float(baseline_acc),
|
|
281
|
+
"ablated_accuracy": float(acc_i),
|
|
282
|
+
"accuracy_drop": float(baseline_acc - acc_i),
|
|
283
|
+
})
|
|
284
|
+
return rows
|
shr/acfg.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Publication-grade Activation-based Computational Flow Graph (ACFG) visualization."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import Any, Dict, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
import matplotlib.pyplot as plt
|
|
7
|
+
import numpy as np
|
|
8
|
+
from matplotlib.patches import Circle, FancyArrowPatch, FancyBboxPatch, Rectangle
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# Colorblind-safe, muted academic palette (Okabe-Ito / Nature inspired)
|
|
12
|
+
_CLUSTER_PALETTE = [
|
|
13
|
+
"#0f766e", # deep teal
|
|
14
|
+
"#1d4ed8", # cobalt blue
|
|
15
|
+
"#b45309", # amber-ochre
|
|
16
|
+
"#6d28d9", # muted violet
|
|
17
|
+
"#0369a1", # steel cyan
|
|
18
|
+
"#be185d", # muted plum
|
|
19
|
+
]
|
|
20
|
+
_OUTLIER_COLOR = "#64748b"
|
|
21
|
+
_BOTTLENECK_COLOR = "#b91c1c"
|
|
22
|
+
_SLATE_DARK = "#0f172a"
|
|
23
|
+
_SLATE_MID = "#334155"
|
|
24
|
+
_SLATE_MUTED = "#64748b"
|
|
25
|
+
_BORDER_LIGHT = "#cbd5e1"
|
|
26
|
+
_CARD_BG = "#f8fafc"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def draw_data_driven_acfg(
|
|
30
|
+
layer_scores: Dict[int, float],
|
|
31
|
+
cluster_info: Dict[str, Dict[str, Any]],
|
|
32
|
+
output_classes: Sequence[str],
|
|
33
|
+
save_dir: str = "evaluation_results",
|
|
34
|
+
filename: str = "acfg_data_driven_empirical.png",
|
|
35
|
+
class_layer_scores: Optional[Dict[str, Dict[int, float]]] = None,
|
|
36
|
+
bottleneck_top_k: int = 2,
|
|
37
|
+
show: bool = True,
|
|
38
|
+
) -> str:
|
|
39
|
+
"""
|
|
40
|
+
Renders a publication-grade two-panel Acoustic Causal Flow Graph (ACFG):
|
|
41
|
+
(a) Directed causal flow: Spectral Clusters -> Transformer Layers -> Classes
|
|
42
|
+
(b) Aligned layerwise SHR attribution profile with data-driven bottleneck.
|
|
43
|
+
"""
|
|
44
|
+
os.makedirs(save_dir, exist_ok=True)
|
|
45
|
+
|
|
46
|
+
plt.rcParams.update({
|
|
47
|
+
"font.family": "sans-serif",
|
|
48
|
+
"font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"],
|
|
49
|
+
"axes.edgecolor": _BORDER_LIGHT,
|
|
50
|
+
"axes.linewidth": 0.8,
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
n_layers = len(layer_scores)
|
|
54
|
+
n_clusters = len(cluster_info)
|
|
55
|
+
n_out = len(output_classes)
|
|
56
|
+
|
|
57
|
+
# Identify data-driven dominant layers (top-k by SHR score)
|
|
58
|
+
ranked_layers = sorted(layer_scores.keys(), key=lambda k: layer_scores[k], reverse=True)
|
|
59
|
+
bottleneck_set = set(ranked_layers[: min(bottleneck_top_k, n_layers)])
|
|
60
|
+
bottleneck_mass = sum(layer_scores[k] for k in bottleneck_set)
|
|
61
|
+
|
|
62
|
+
# Scale figure height and y-coordinates together to preserve circle aspect ratio
|
|
63
|
+
scale = 1.0 if n_layers <= 12 else min(1.75, n_layers / 16.0)
|
|
64
|
+
fig_h = 8.6 * scale
|
|
65
|
+
y_max = 10.2 * scale
|
|
66
|
+
y_top = 8.40 * scale + (0.65 * (scale - 1.0) if scale > 1.0 else 0.0)
|
|
67
|
+
y_bottom = 0.65
|
|
68
|
+
|
|
69
|
+
fig = plt.figure(figsize=(15.5, fig_h), dpi=300)
|
|
70
|
+
fig.patch.set_facecolor("#ffffff")
|
|
71
|
+
|
|
72
|
+
gs = fig.add_gridspec(1, 2, width_ratios=[3.1, 1.15], wspace=0.06, left=0.03, right=0.97, top=0.88 if scale > 1.0 else 0.86, bottom=0.05)
|
|
73
|
+
ax = fig.add_subplot(gs[0, 0])
|
|
74
|
+
ax_bar = fig.add_subplot(gs[0, 1])
|
|
75
|
+
|
|
76
|
+
ax.set_facecolor("#ffffff")
|
|
77
|
+
ax.set_xlim(0.0, 12.2)
|
|
78
|
+
ax.set_ylim(0.0, y_max)
|
|
79
|
+
ax.axis("off")
|
|
80
|
+
|
|
81
|
+
# Column coordinates
|
|
82
|
+
x_in, x_layer, x_out = 1.65, 6.1, 10.55
|
|
83
|
+
|
|
84
|
+
y_layers = np.linspace(y_top, y_bottom, n_layers) if n_layers > 1 else np.array([(y_top + y_bottom) / 2])
|
|
85
|
+
pos: Dict[str, tuple] = {f"L{i}": (x_layer, float(y_layers[i])) for i in range(n_layers)}
|
|
86
|
+
|
|
87
|
+
card_w = 2.85
|
|
88
|
+
card_h = max(0.85, min(1.45, (y_top - y_bottom) / max(n_clusters, 1) - 0.45))
|
|
89
|
+
y_inputs = (
|
|
90
|
+
np.linspace(y_top - 0.35 * scale, y_bottom + 0.35 * scale, n_clusters)
|
|
91
|
+
if n_clusters > 1
|
|
92
|
+
else np.array([(y_top + y_bottom) / 2])
|
|
93
|
+
)
|
|
94
|
+
for i, name in enumerate(cluster_info.keys()):
|
|
95
|
+
pos[name] = (x_in, float(y_inputs[i]))
|
|
96
|
+
|
|
97
|
+
y_outputs = np.linspace(y_top - 0.40 * scale, y_bottom + 0.40 * scale, n_out) if n_out > 1 else np.array([(y_top + y_bottom) / 2])
|
|
98
|
+
for i, cls in enumerate(output_classes):
|
|
99
|
+
pos[cls] = (x_out, float(y_outputs[i]))
|
|
100
|
+
|
|
101
|
+
# Subtle column headers with generous spacing above the graph
|
|
102
|
+
header_y = y_max - 0.40 * scale
|
|
103
|
+
underline_y = y_max - 0.68 * scale
|
|
104
|
+
col_headers = [
|
|
105
|
+
(x_in, "Acoustic Patch Clusters"),
|
|
106
|
+
(x_layer, "Transformer Layers"),
|
|
107
|
+
(x_out, "Diagnostic Classes"),
|
|
108
|
+
]
|
|
109
|
+
for cx, title in col_headers:
|
|
110
|
+
ax.text(cx, header_y, title, ha="center", va="center", fontsize=10.5, fontweight="bold", color=_SLATE_DARK)
|
|
111
|
+
ax.plot([cx - 1.15, cx + 1.15], [underline_y, underline_y], color=_BORDER_LIGHT, lw=1.0)
|
|
112
|
+
|
|
113
|
+
# Data-driven bottleneck highlight band(s) — group contiguous layers so split bottlenecks don't wrap unrelated layers
|
|
114
|
+
if bottleneck_set:
|
|
115
|
+
sorted_bn = sorted(bottleneck_set)
|
|
116
|
+
bn_groups = [[sorted_bn[0]]]
|
|
117
|
+
for idx in sorted_bn[1:]:
|
|
118
|
+
if idx == bn_groups[-1][-1] + 1:
|
|
119
|
+
bn_groups[-1].append(idx)
|
|
120
|
+
else:
|
|
121
|
+
bn_groups.append([idx])
|
|
122
|
+
|
|
123
|
+
band_pad = 0.32 if n_layers <= 12 else 0.26
|
|
124
|
+
top_band_y_max = -1.0
|
|
125
|
+
for g_idx, grp in enumerate(bn_groups):
|
|
126
|
+
b_ys = [pos[f"L{i}"][1] for i in grp]
|
|
127
|
+
band_y_min = min(b_ys) - band_pad
|
|
128
|
+
band_y_max = max(b_ys) + band_pad
|
|
129
|
+
if g_idx == 0:
|
|
130
|
+
top_band_y_max = band_y_max
|
|
131
|
+
band = FancyBboxPatch(
|
|
132
|
+
(x_layer - 0.56, band_y_min),
|
|
133
|
+
1.12,
|
|
134
|
+
band_y_max - band_y_min,
|
|
135
|
+
boxstyle="round,pad=0.02,rounding_size=0.12",
|
|
136
|
+
facecolor="#fef2f2",
|
|
137
|
+
edgecolor="#fca5a5",
|
|
138
|
+
linewidth=1.0,
|
|
139
|
+
zorder=1,
|
|
140
|
+
)
|
|
141
|
+
ax.add_patch(band)
|
|
142
|
+
|
|
143
|
+
b_label = ", ".join(f"L{i}" for i in sorted_bn)
|
|
144
|
+
ax.text(
|
|
145
|
+
x_layer,
|
|
146
|
+
top_band_y_max + 0.12,
|
|
147
|
+
f"Bottleneck ({b_label}: {bottleneck_mass * 100:.1f}%)",
|
|
148
|
+
ha="center",
|
|
149
|
+
va="bottom",
|
|
150
|
+
fontsize=8.2,
|
|
151
|
+
fontweight="bold",
|
|
152
|
+
color=_BOTTLENECK_COLOR,
|
|
153
|
+
zorder=4,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# Edges: Clusters -> Layers (pruned cleanly by relative strength)
|
|
157
|
+
max_c_score = max(
|
|
158
|
+
(float(info["scores"].max()) if len(info["scores"]) > 0 else 1e-8)
|
|
159
|
+
for info in cluster_info.values()
|
|
160
|
+
) + 1e-8
|
|
161
|
+
|
|
162
|
+
cluster_colors: Dict[str, str] = {}
|
|
163
|
+
c_idx = 0
|
|
164
|
+
for cname, info in cluster_info.items():
|
|
165
|
+
if info.get("is_outlier_group", False):
|
|
166
|
+
cluster_colors[cname] = _OUTLIER_COLOR
|
|
167
|
+
else:
|
|
168
|
+
cluster_colors[cname] = _CLUSTER_PALETTE[c_idx % len(_CLUSTER_PALETTE)]
|
|
169
|
+
c_idx += 1
|
|
170
|
+
|
|
171
|
+
c_thresh = 0.10 if n_layers <= 12 else 0.16
|
|
172
|
+
head_len = 4.5 if n_layers <= 12 else 3.8
|
|
173
|
+
head_wid = 2.5 if n_layers <= 12 else 2.1
|
|
174
|
+
|
|
175
|
+
for cname, info in cluster_info.items():
|
|
176
|
+
x1, y1 = pos[cname]
|
|
177
|
+
c_scores = info["scores"]
|
|
178
|
+
col = cluster_colors[cname]
|
|
179
|
+
for l_idx in range(n_layers):
|
|
180
|
+
strength = float(c_scores[l_idx] / max_c_score)
|
|
181
|
+
if strength < c_thresh:
|
|
182
|
+
continue
|
|
183
|
+
x2, y2 = pos[f"L{l_idx}"]
|
|
184
|
+
rad = 0.05 * np.sign(y2 - y1) if abs(y2 - y1) > 0.25 else 0.0
|
|
185
|
+
arrow = FancyArrowPatch(
|
|
186
|
+
(x1 + card_w / 2 + 0.04, y1),
|
|
187
|
+
(x2 - 0.28, y2),
|
|
188
|
+
connectionstyle=f"arc3,rad={rad}",
|
|
189
|
+
arrowstyle=f"-|>,head_length={head_len},head_width={head_wid}",
|
|
190
|
+
linewidth=0.55 + strength * (2.6 if n_layers <= 12 else 2.2),
|
|
191
|
+
color=col,
|
|
192
|
+
alpha=(0.18 if n_layers <= 12 else 0.14) + strength * 0.58,
|
|
193
|
+
zorder=2,
|
|
194
|
+
)
|
|
195
|
+
ax.add_patch(arrow)
|
|
196
|
+
|
|
197
|
+
# Edges: Layers -> Output Classes (class-conditional if provided, else top layers)
|
|
198
|
+
max_l_score = max(layer_scores.values()) + 1e-8
|
|
199
|
+
l_thresh = 0.18 if n_layers <= 12 else 0.24
|
|
200
|
+
for cls in output_classes:
|
|
201
|
+
x2, y2 = pos[cls]
|
|
202
|
+
cls_scores = class_layer_scores.get(cls, layer_scores) if class_layer_scores else layer_scores
|
|
203
|
+
cls_max = max(cls_scores.values()) + 1e-8 if cls_scores else max_l_score
|
|
204
|
+
for l_idx in range(n_layers):
|
|
205
|
+
l_strength = float(cls_scores.get(l_idx, 0.0)) / cls_max
|
|
206
|
+
if l_strength < l_thresh:
|
|
207
|
+
continue
|
|
208
|
+
x1, y1 = pos[f"L{l_idx}"]
|
|
209
|
+
is_bn = l_idx in bottleneck_set
|
|
210
|
+
rad = 0.05 * np.sign(y1 - y2) if abs(y1 - y2) > 0.25 else 0.0
|
|
211
|
+
arrow = FancyArrowPatch(
|
|
212
|
+
(x1 + 0.28, y1),
|
|
213
|
+
(x2 - 1.12, y2),
|
|
214
|
+
connectionstyle=f"arc3,rad={rad}",
|
|
215
|
+
arrowstyle=f"-|>,head_length={head_len},head_width={head_wid}",
|
|
216
|
+
linewidth=0.45 + l_strength * (2.4 if is_bn or n_layers <= 12 else 1.8),
|
|
217
|
+
color=_BOTTLENECK_COLOR if is_bn else _SLATE_MUTED,
|
|
218
|
+
alpha=(0.30 + l_strength * 0.55) if is_bn else ((0.18 if n_layers <= 12 else 0.12) + l_strength * 0.38),
|
|
219
|
+
zorder=3 if is_bn else 2,
|
|
220
|
+
)
|
|
221
|
+
ax.add_patch(arrow)
|
|
222
|
+
|
|
223
|
+
# Cluster cards (clean white/slate cards with left accent bar)
|
|
224
|
+
for cname, info in cluster_info.items():
|
|
225
|
+
x, y = pos[cname]
|
|
226
|
+
col = cluster_colors[cname]
|
|
227
|
+
is_outlier = info.get("is_outlier_group", False)
|
|
228
|
+
is_low_support = info.get("low_support", False)
|
|
229
|
+
|
|
230
|
+
card = FancyBboxPatch(
|
|
231
|
+
(x - card_w / 2, y - card_h / 2),
|
|
232
|
+
card_w,
|
|
233
|
+
card_h,
|
|
234
|
+
boxstyle="round,pad=0.02,rounding_size=0.08",
|
|
235
|
+
facecolor=_CARD_BG,
|
|
236
|
+
edgecolor=_BOTTLENECK_COLOR if (is_low_support and not is_outlier) else _BORDER_LIGHT,
|
|
237
|
+
linewidth=1.0,
|
|
238
|
+
zorder=5,
|
|
239
|
+
)
|
|
240
|
+
ax.add_patch(card)
|
|
241
|
+
accent = Rectangle((x - card_w / 2, y - card_h / 2), 0.10, card_h, facecolor=col, edgecolor="none", zorder=6)
|
|
242
|
+
ax.add_patch(accent)
|
|
243
|
+
|
|
244
|
+
hz_str = f" · ~{info['centroid_hz']:.0f} Hz" if "centroid_hz" in info else ""
|
|
245
|
+
tag = " (Outlier)" if is_outlier else (" (Low N)" if is_low_support else "")
|
|
246
|
+
title_str = f"{cname}{tag}"
|
|
247
|
+
meta_str = (
|
|
248
|
+
f"Peak: L{info['dominant_layer']}{hz_str}\n"
|
|
249
|
+
f"Energy: {info['activation_energy']:.3f} | H: {info['routing_entropy']:.2f} | n={info['patch_count']}"
|
|
250
|
+
)
|
|
251
|
+
ax.text(x - card_w / 2 + 0.22, y + card_h * 0.20, title_str, ha="left", va="center", fontsize=8.8, fontweight="bold", color=_SLATE_DARK, zorder=7)
|
|
252
|
+
ax.text(x - card_w / 2 + 0.22, y - card_h * 0.18, meta_str, ha="left", va="center", fontsize=7.6, color=_SLATE_MID, linespacing=1.45, zorder=7)
|
|
253
|
+
|
|
254
|
+
# Layer nodes (clean circles, no overlapping score text)
|
|
255
|
+
score_min, score_max = min(layer_scores.values()), max(layer_scores.values())
|
|
256
|
+
gap = abs(y_layers[0] - y_layers[1]) if n_layers > 1 else 1.0
|
|
257
|
+
r_min = min(0.18, gap * 0.28)
|
|
258
|
+
r_max = max(r_min + 0.02, min(0.29, gap * 0.42))
|
|
259
|
+
node_fs = 8.2 if n_layers <= 12 else 7.4
|
|
260
|
+
|
|
261
|
+
for i in range(n_layers):
|
|
262
|
+
x, y = pos[f"L{i}"]
|
|
263
|
+
t = (layer_scores[i] - score_min) / (score_max - score_min) if score_max > score_min else 0.5
|
|
264
|
+
r = r_min + t * (r_max - r_min)
|
|
265
|
+
is_bn = i in bottleneck_set
|
|
266
|
+
face = _BOTTLENECK_COLOR if is_bn else "#334155"
|
|
267
|
+
circle = Circle((x, y), r, facecolor=face, edgecolor="#ffffff", linewidth=1.2, zorder=5)
|
|
268
|
+
ax.add_patch(circle)
|
|
269
|
+
ax.text(x, y, f"L{i}", ha="center", va="center", fontsize=node_fs, fontweight="bold", color="#ffffff", zorder=6)
|
|
270
|
+
|
|
271
|
+
# Output class pills (uniform clean academic style)
|
|
272
|
+
out_w, out_h = 2.15, 0.62
|
|
273
|
+
for cls in output_classes:
|
|
274
|
+
x, y = pos[cls]
|
|
275
|
+
is_normal = cls.lower() in ("healthy", "normal")
|
|
276
|
+
accent_col = "#0f766e" if is_normal else _SLATE_DARK
|
|
277
|
+
box = FancyBboxPatch(
|
|
278
|
+
(x - out_w / 2, y - out_h / 2),
|
|
279
|
+
out_w,
|
|
280
|
+
out_h,
|
|
281
|
+
boxstyle="round,pad=0.02,rounding_size=0.08",
|
|
282
|
+
facecolor=_CARD_BG,
|
|
283
|
+
edgecolor=_BORDER_LIGHT,
|
|
284
|
+
linewidth=1.0,
|
|
285
|
+
zorder=5,
|
|
286
|
+
)
|
|
287
|
+
ax.add_patch(box)
|
|
288
|
+
bar = Rectangle((x - out_w / 2, y - out_h / 2), 0.09, out_h, facecolor=accent_col, edgecolor="none", zorder=6)
|
|
289
|
+
ax.add_patch(bar)
|
|
290
|
+
ax.text(x + 0.04, y, cls, ha="center", va="center", fontsize=9.2, fontweight="bold", color=_SLATE_DARK, zorder=7)
|
|
291
|
+
|
|
292
|
+
# Layerwise SHR Attribution Profile
|
|
293
|
+
ax_bar.set_facecolor("#ffffff")
|
|
294
|
+
scores_ordered = [layer_scores[i] for i in range(n_layers)]
|
|
295
|
+
bar_colors = [_BOTTLENECK_COLOR if i in bottleneck_set else "#94a3b8" for i in range(n_layers)]
|
|
296
|
+
bar_h = min(0.42, gap * 0.52)
|
|
297
|
+
|
|
298
|
+
ax_bar.barh(y_layers, scores_ordered, height=bar_h, color=bar_colors, edgecolor="none", zorder=3)
|
|
299
|
+
ax_bar.set_ylim(0.0, y_max)
|
|
300
|
+
max_bar = max(scores_ordered) if scores_ordered else 1.0
|
|
301
|
+
ax_bar.set_xlim(0.0, max_bar * 1.32)
|
|
302
|
+
ax_bar.set_yticks(y_layers)
|
|
303
|
+
ax_bar.set_yticklabels([f"L{i}" for i in range(n_layers)], fontsize=8.0 if n_layers <= 12 else 7.6, color=_SLATE_MID)
|
|
304
|
+
ax_bar.tick_params(axis="x", labelsize=8.0, colors=_SLATE_MUTED)
|
|
305
|
+
ax_bar.tick_params(axis="y", length=0)
|
|
306
|
+
ax_bar.grid(axis="x", linestyle=":", linewidth=0.6, color=_BORDER_LIGHT, zorder=0)
|
|
307
|
+
for spine in ("top", "right"):
|
|
308
|
+
ax_bar.spines[spine].set_visible(False)
|
|
309
|
+
|
|
310
|
+
for y_val, val, i in zip(y_layers, scores_ordered, range(n_layers)):
|
|
311
|
+
ax_bar.text(
|
|
312
|
+
val + max_bar * 0.03,
|
|
313
|
+
y_val,
|
|
314
|
+
f"{val:.3f}",
|
|
315
|
+
va="center",
|
|
316
|
+
ha="left",
|
|
317
|
+
fontsize=7.8,
|
|
318
|
+
fontweight="bold" if i in bottleneck_set else "normal",
|
|
319
|
+
color=_BOTTLENECK_COLOR if i in bottleneck_set else _SLATE_MID,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
ax_bar.text(max_bar * 0.66, header_y, "Layerwise SHR Score", ha="center", va="center", fontsize=10.5, fontweight="bold", color=_SLATE_DARK)
|
|
323
|
+
ax_bar.plot([0.0, max_bar * 1.25], [underline_y, underline_y], color=_BORDER_LIGHT, lw=1.0)
|
|
324
|
+
|
|
325
|
+
# Figure suptitle
|
|
326
|
+
routing_note = "Class-Conditional Routing" if class_layer_scores else "Aggregate Causal Routing"
|
|
327
|
+
fig.suptitle(
|
|
328
|
+
"Acoustic Causal Flow Graph (ACFG) & Layerwise SHR Attribution",
|
|
329
|
+
fontsize=13.5,
|
|
330
|
+
fontweight="bold",
|
|
331
|
+
color=_SLATE_DARK,
|
|
332
|
+
y=0.955,
|
|
333
|
+
)
|
|
334
|
+
fig.text(
|
|
335
|
+
0.5,
|
|
336
|
+
0.915,
|
|
337
|
+
f"{routing_note} | Top-{min(bottleneck_top_k, n_layers)} Bottleneck Mass: {bottleneck_mass * 100:.1f}%",
|
|
338
|
+
ha="center",
|
|
339
|
+
fontsize=9.5,
|
|
340
|
+
color=_SLATE_MUTED,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
save_path = os.path.join(save_dir, filename)
|
|
344
|
+
plt.savefig(save_path, dpi=300, bbox_inches="tight", facecolor="#ffffff")
|
|
345
|
+
if show:
|
|
346
|
+
plt.show()
|
|
347
|
+
else:
|
|
348
|
+
plt.close(fig)
|
|
349
|
+
return save_path
|