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/analyzer.py ADDED
@@ -0,0 +1,802 @@
1
+ """Architecture-agnostic Spectral Harmonic Routing (SHR) analyzer."""
2
+
3
+ from collections import Counter
4
+ from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ try:
12
+ from tqdm import tqdm
13
+ except ImportError: # pragma: no cover
14
+ def tqdm(iterable, **_kwargs):
15
+ return iterable
16
+
17
+
18
+ class UniversalSHRAnalyzer:
19
+ """
20
+ Universal Spectral Harmonic Routing (SHR) Analyzer.
21
+
22
+ Works with arbitrary Transformer architectures (timm ViT, DINOv2, DINOv3,
23
+ EVA-02, Focal, CaiT, DeiT, Swin, LingBot-Vision, HuggingFace ViT/AST, and
24
+ custom PyTorch nn.Module transformers).
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ model: nn.Module,
30
+ device: Optional[Union[str, torch.device]] = None,
31
+ layers: Optional[Sequence[nn.Module]] = None,
32
+ num_prefix_tokens: Optional[int] = None,
33
+ grid_size: Optional[Tuple[int, int]] = None,
34
+ flatten_stages: bool = True,
35
+ ):
36
+ self.model = model
37
+ if device is None:
38
+ try:
39
+ device = next(model.parameters()).device
40
+ except StopIteration:
41
+ device = torch.device("cpu")
42
+ self.device = torch.device(device)
43
+
44
+ if isinstance(model, (nn.DataParallel, nn.parallel.DistributedDataParallel)):
45
+ self.base_model = model.module
46
+ else:
47
+ self.base_model = model
48
+
49
+ self.num_prefix_tokens = num_prefix_tokens
50
+ self.grid_size = grid_size
51
+ self.flatten_stages = flatten_stages
52
+
53
+ if layers is not None:
54
+ self.layers = list(layers)
55
+ else:
56
+ self.layers = list(self._find_layers(self.base_model))
57
+
58
+ self.num_layers = len(self.layers)
59
+ if self.num_layers == 0:
60
+ raise ValueError("No transformer layers found. Pass `layers=...` explicitly.")
61
+
62
+ self._warned_ambiguous_cls = False
63
+ self._layer_weights_cache: Optional[Dict[int, float]] = None
64
+
65
+ def _maybe_flatten_stages(self, modules: Sequence[nn.Module]) -> List[nn.Module]:
66
+ if not self.flatten_stages:
67
+ return list(modules)
68
+ flattened: List[nn.Module] = []
69
+ for mod in modules:
70
+ if hasattr(mod, "blocks") and isinstance(mod.blocks, (nn.ModuleList, list)):
71
+ flattened.extend(list(mod.blocks))
72
+ elif hasattr(mod, "layers") and isinstance(mod.layers, (nn.ModuleList, list)):
73
+ flattened.extend(list(mod.layers))
74
+ else:
75
+ flattened.append(mod)
76
+ return flattened
77
+
78
+ def _find_layers(self, model: nn.Module) -> List[nn.Module]:
79
+ roots = [model]
80
+ for attr in ("backbone", "model", "vit", "ast", "dinov2", "swin", "transformer", "encoder"):
81
+ sub = getattr(model, attr, None)
82
+ if isinstance(sub, nn.Module):
83
+ roots.append(sub)
84
+ enc = getattr(sub, "encoder", None)
85
+ if isinstance(enc, nn.Module):
86
+ roots.append(enc)
87
+
88
+ for root in roots:
89
+ for attr in ("blocks", "layers", "layer", "stages"):
90
+ cand = getattr(root, attr, None)
91
+ if isinstance(cand, (nn.ModuleList, nn.ModuleDict)) and len(cand) >= 1:
92
+ items = list(cand.values()) if isinstance(cand, nn.ModuleDict) else list(cand)
93
+ flattened = self._maybe_flatten_stages(items)
94
+ if len(flattened) >= 2:
95
+ return flattened
96
+
97
+ # Fallback: deep search for ModuleList/ModuleDict containing transformer blocks
98
+ best_match: List[nn.Module] = []
99
+ for _, module in model.named_modules():
100
+ if isinstance(module, (nn.ModuleList, nn.ModuleDict)) and len(module) >= 2:
101
+ children = list(module.values()) if isinstance(module, nn.ModuleDict) else list(module)
102
+ first = children[0]
103
+ if any(hasattr(first, a) for a in ("attn", "attention", "self_attn", "mlp", "ffn", "blocks")):
104
+ cand = self._maybe_flatten_stages(children)
105
+ if len(cand) > len(best_match):
106
+ best_match = cand
107
+
108
+ if best_match:
109
+ return best_match
110
+
111
+ raise ValueError(
112
+ "Could not automatically locate transformer layers. "
113
+ "Pass `layers=[...]` explicitly to UniversalSHRAnalyzer."
114
+ )
115
+
116
+ @staticmethod
117
+ def extract_tensor(output) -> Optional[torch.Tensor]:
118
+ """Extracts the primary tensor from Tensor, list, tuple, or dict/ModelOutput."""
119
+ if isinstance(output, torch.Tensor):
120
+ return output
121
+ if isinstance(output, (list, tuple)):
122
+ for item in output:
123
+ if isinstance(item, torch.Tensor):
124
+ return item
125
+ return None
126
+ if isinstance(output, dict):
127
+ for key in ("logits", "last_hidden_state", "hidden_states"):
128
+ val = output.get(key)
129
+ if isinstance(val, torch.Tensor):
130
+ return val
131
+ for val in output.values():
132
+ if isinstance(val, torch.Tensor):
133
+ return val
134
+ return None
135
+ # HuggingFace ModelOutput / dataclass-like objects
136
+ for attr in ("logits", "last_hidden_state"):
137
+ val = getattr(output, attr, None)
138
+ if isinstance(val, torch.Tensor):
139
+ return val
140
+ return None
141
+
142
+ @staticmethod
143
+ def _to_batch_tokens_channel(t: Optional[torch.Tensor]) -> Tuple[Optional[torch.Tensor], bool]:
144
+ """Normalizes activation/gradient tensors to (B, N, C) token format."""
145
+ if t is None or not torch.is_tensor(t) or not t.is_floating_point():
146
+ return None, False
147
+ if t.dim() == 2:
148
+ return None, False
149
+ if t.dim() == 3:
150
+ return t, True
151
+ if t.dim() == 4:
152
+ b, d1, d2, d3 = t.shape
153
+ # Detect (B, C, H, W) vs (B, H, W, C)
154
+ if d2 == d3 and d1 != d2:
155
+ t = t.permute(0, 2, 3, 1).contiguous()
156
+ b, d1, d2, d3 = t.shape
157
+ return t.reshape(b, d1 * d2, d3), True
158
+ if t.dim() > 4:
159
+ b, c = t.shape[0], t.shape[-1]
160
+ return t.reshape(b, -1, c), True
161
+ return None, False
162
+
163
+ def _infer_cls_offset(self, num_tokens: int) -> int:
164
+ """Infers prefix token count (CLS / distillation / register tokens)."""
165
+ if self.num_prefix_tokens is not None:
166
+ return min(self.num_prefix_tokens, max(0, num_tokens - 1))
167
+
168
+ if self.grid_size is not None:
169
+ expected_spatial = self.grid_size[0] * self.grid_size[1]
170
+ if num_tokens >= expected_spatial:
171
+ return num_tokens - expected_spatial
172
+
173
+ # Common prefix counts: 0 (no CLS), 1 (CLS), 2 (DeiT dist), 5 (CLS + 4 registers)
174
+ for prefix in (0, 1, 2, 5):
175
+ rem = num_tokens - prefix
176
+ if rem > 0:
177
+ root = int(round(rem ** 0.5))
178
+ if root * root == rem:
179
+ return prefix
180
+
181
+ if not self._warned_ambiguous_cls:
182
+ self._warned_ambiguous_cls = True
183
+ return 0
184
+
185
+ def _infer_grid_shape(self, num_spatial_tokens: int) -> Optional[Tuple[int, int]]:
186
+ if self.grid_size is not None and self.grid_size[0] * self.grid_size[1] == num_spatial_tokens:
187
+ return self.grid_size
188
+ root = int(round(num_spatial_tokens ** 0.5))
189
+ if root * root == num_spatial_tokens:
190
+ return (root, root)
191
+ return None
192
+
193
+ @staticmethod
194
+ def _mad_clip(arr: np.ndarray, z_thresh: float = 3.5) -> np.ndarray:
195
+ """Robust MAD clip to dampen ViT sink/register outlier tokens."""
196
+ median = np.median(arr)
197
+ mad = np.median(np.abs(arr - median))
198
+ if mad <= 1e-12:
199
+ return arr
200
+ mod_z = 0.6745 * (arr - median) / mad
201
+ clip_val = median + (z_thresh * mad / 0.6745)
202
+ return np.where(mod_z > z_thresh, clip_val, arr)
203
+
204
+ @staticmethod
205
+ def _gaussian_blur_2d(arr: np.ndarray, sigma: float = 1.0) -> np.ndarray:
206
+ if sigma is None or sigma <= 0:
207
+ return arr
208
+ try:
209
+ from scipy.ndimage import gaussian_filter
210
+ return gaussian_filter(arr, sigma=sigma)
211
+ except ImportError:
212
+ radius = max(1, int(3 * sigma))
213
+ x = np.arange(-radius, radius + 1)
214
+ kernel = np.exp(-(x ** 2) / (2 * sigma ** 2))
215
+ kernel /= kernel.sum()
216
+ out = np.apply_along_axis(lambda m: np.convolve(m, kernel, mode="same"), 0, arr)
217
+ out = np.apply_along_axis(lambda m: np.convolve(m, kernel, mode="same"), 1, out)
218
+ return out
219
+
220
+ @staticmethod
221
+ def _contrastive_logit(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
222
+ target_logits = logits.gather(1, labels.unsqueeze(1)).squeeze(1)
223
+ if logits.shape[1] > 1:
224
+ mean_other = (logits.sum(dim=1) - target_logits) / (logits.shape[1] - 1)
225
+ return target_logits - mean_other
226
+ return target_logits
227
+
228
+ def _register_layer_hooks(
229
+ self,
230
+ layer_indices: Iterable[int],
231
+ acts: Dict[int, torch.Tensor],
232
+ grads: Dict[int, torch.Tensor],
233
+ routing_mode: str = "residual",
234
+ modules: Optional[Sequence[nn.Module]] = None,
235
+ ) -> List[torch.utils.hooks.RemovableHandle]:
236
+ target_modules = self.layers if modules is None else modules
237
+ hooks = []
238
+ for i in layer_indices:
239
+ if i < 0 or i >= len(target_modules) or target_modules[i] is None:
240
+ continue
241
+
242
+ def make_hook(idx: int):
243
+ def hook(_mod, inp, out):
244
+ t_out = self.extract_tensor(out)
245
+ if t_out is None:
246
+ return
247
+ if routing_mode == "marginal":
248
+ raw_in = inp[0] if isinstance(inp, (tuple, list)) and len(inp) > 0 else inp
249
+ t_in = self.extract_tensor(raw_in)
250
+ if t_in is not None and t_in.shape == t_out.shape:
251
+ acts[idx] = (t_out - t_in).detach()
252
+ else:
253
+ acts[idx] = t_out.detach()
254
+ else:
255
+ acts[idx] = t_out.detach()
256
+ if t_out.is_floating_point():
257
+ if not t_out.requires_grad:
258
+ t_out.requires_grad_(True)
259
+ t_out.retain_grad()
260
+ t_out.register_hook(lambda g, inner_idx=idx: grads.update({inner_idx: g.detach()}))
261
+
262
+ return hook
263
+
264
+ hooks.append(target_modules[i].register_forward_hook(make_hook(i)))
265
+ return hooks
266
+
267
+ @staticmethod
268
+ def _find_submodules(layer: nn.Module) -> Tuple[Optional[nn.Module], Optional[nn.Module]]:
269
+ attn_mod = None
270
+ mlp_mod = None
271
+ for attr in ("attn", "attention", "self_attn"):
272
+ cand = getattr(layer, attr, None)
273
+ if isinstance(cand, nn.Module):
274
+ attn_mod = cand
275
+ break
276
+ for attr in ("mlp", "ffn", "feed_forward"):
277
+ cand = getattr(layer, attr, None)
278
+ if isinstance(cand, nn.Module):
279
+ mlp_mod = cand
280
+ break
281
+ return attn_mod, mlp_mod
282
+
283
+ def compute_patch_routing_scores(
284
+ self,
285
+ dataloader,
286
+ num_samples: Optional[int] = 50,
287
+ target_class: Optional[int] = None,
288
+ use_positive_clamp: bool = True,
289
+ routing_mode: str = "residual",
290
+ show_progress: bool = True,
291
+ ) -> Tuple[Dict[int, float], np.ndarray, np.ndarray]:
292
+ """
293
+ Computes dataset-wide (or class-conditional if `target_class` is set)
294
+ layer routing scores and patch-level routing / activation energy matrices.
295
+ Set `routing_mode="marginal"` to isolate each layer's added delta (out - in).
296
+ """
297
+ count = 0
298
+ patch_scores_sum = None
299
+ patch_energy_sum = None
300
+ canonical_n = None
301
+ layer_scores = {i: 0.0 for i in range(self.num_layers)}
302
+
303
+ self.model.eval()
304
+ iterator = tqdm(dataloader, desc="Patch SHR") if show_progress else dataloader
305
+
306
+ for batch in iterator:
307
+ if num_samples is not None and count >= num_samples:
308
+ break
309
+
310
+ images, labels = batch[0], batch[1]
311
+ labels = labels.view(-1).to(self.device)
312
+
313
+ if target_class is not None:
314
+ mask = labels == int(target_class)
315
+ if not mask.any():
316
+ continue
317
+ images = images[mask]
318
+ labels = labels[mask]
319
+
320
+ self.model.zero_grad()
321
+ acts: Dict[int, torch.Tensor] = {}
322
+ grads: Dict[int, torch.Tensor] = {}
323
+ hooks = self._register_layer_hooks(
324
+ range(self.num_layers), acts, grads, routing_mode=routing_mode
325
+ )
326
+
327
+ try:
328
+ images = images.to(self.device).detach().requires_grad_(True)
329
+ outs = self.model(images)
330
+ logits = self.extract_tensor(outs)
331
+ if logits is None:
332
+ continue
333
+ if logits.dim() == 1:
334
+ logits = logits.unsqueeze(0)
335
+
336
+ signal = self._contrastive_logit(logits, labels).sum()
337
+ signal.backward()
338
+ finally:
339
+ for h in hooks:
340
+ h.remove()
341
+
342
+ normalized = {}
343
+ per_layer_n = []
344
+
345
+ for i in range(self.num_layers):
346
+ if i not in acts or i not in grads:
347
+ continue
348
+
349
+ prod = (acts[i] * grads[i]).sum(dim=-1)
350
+ causal_prod = prod.clamp(min=0) if use_positive_clamp else prod.abs()
351
+ layer_scores[i] += causal_prod.reshape(causal_prod.shape[0], -1).sum(dim=-1).mean().item()
352
+
353
+ a_norm, has_spatial = self._to_batch_tokens_channel(acts[i])
354
+ g_norm, _ = self._to_batch_tokens_channel(grads[i])
355
+ if not has_spatial or a_norm is None or g_norm is None:
356
+ continue
357
+
358
+ cls_offset = self._infer_cls_offset(a_norm.shape[1])
359
+ a_norm = a_norm[:, cls_offset:, :]
360
+ g_norm = g_norm[:, cls_offset:, :]
361
+
362
+ normalized[i] = (a_norm, g_norm)
363
+ per_layer_n.append(a_norm.shape[1])
364
+
365
+ if not normalized:
366
+ count += images.size(0)
367
+ continue
368
+
369
+ if canonical_n is None and per_layer_n:
370
+ canonical_n = Counter(per_layer_n).most_common(1)[0][0]
371
+
372
+ for i, (a_norm, g_norm) in normalized.items():
373
+ p_prod = (a_norm * g_norm).sum(dim=2)
374
+ patch_contrib = p_prod.clamp(min=0) if use_positive_clamp else p_prod.abs()
375
+ patch_energy = a_norm.abs().sum(dim=2)
376
+
377
+ if patch_contrib.shape[1] != canonical_n:
378
+ patch_contrib = F.adaptive_avg_pool1d(patch_contrib.unsqueeze(1), canonical_n).squeeze(1)
379
+ patch_energy = F.adaptive_avg_pool1d(patch_energy.unsqueeze(1), canonical_n).squeeze(1)
380
+
381
+ if patch_scores_sum is None:
382
+ patch_scores_sum = np.zeros((canonical_n, self.num_layers), dtype=np.float64)
383
+ patch_energy_sum = np.zeros((canonical_n, self.num_layers), dtype=np.float64)
384
+
385
+ patch_scores_sum[:, i] += patch_contrib.mean(dim=0).detach().cpu().numpy()
386
+ patch_energy_sum[:, i] += patch_energy.mean(dim=0).detach().cpu().numpy()
387
+
388
+ count += images.size(0)
389
+
390
+ total_layer = sum(layer_scores.values()) + 1e-8
391
+ layer_scores = {k: v / total_layer for k, v in layer_scores.items()}
392
+ self._layer_weights_cache = dict(layer_scores)
393
+
394
+ if patch_scores_sum is not None:
395
+ patch_scores_norm = patch_scores_sum / (patch_scores_sum.sum() + 1e-8)
396
+ patch_energy_norm = patch_energy_sum / (patch_energy_sum.sum() + 1e-8)
397
+ else:
398
+ patch_scores_norm = np.zeros((1, self.num_layers), dtype=np.float64)
399
+ patch_energy_norm = np.zeros((1, self.num_layers), dtype=np.float64)
400
+
401
+ return layer_scores, patch_scores_norm, patch_energy_norm
402
+
403
+ def compute_signed_routing_scores(
404
+ self,
405
+ dataloader,
406
+ num_samples: Optional[int] = 50,
407
+ target_class: Optional[int] = None,
408
+ routing_mode: str = "residual",
409
+ show_progress: bool = True,
410
+ ) -> Dict[str, object]:
411
+ """
412
+ Separates excitatory (+) and inhibitory (-) causal routing across layers and patches.
413
+ """
414
+ count = 0
415
+ exc_layer = {i: 0.0 for i in range(self.num_layers)}
416
+ inh_layer = {i: 0.0 for i in range(self.num_layers)}
417
+ exc_patch_sum = None
418
+ inh_patch_sum = None
419
+ canonical_n = None
420
+
421
+ self.model.eval()
422
+ iterator = tqdm(dataloader, desc="Signed SHR") if show_progress else dataloader
423
+
424
+ for batch in iterator:
425
+ if num_samples is not None and count >= num_samples:
426
+ break
427
+ images, labels = batch[0], batch[1].view(-1).to(self.device)
428
+ if target_class is not None:
429
+ mask = labels == int(target_class)
430
+ if not mask.any():
431
+ continue
432
+ images, labels = images[mask], labels[mask]
433
+
434
+ self.model.zero_grad()
435
+ acts: Dict[int, torch.Tensor] = {}
436
+ grads: Dict[int, torch.Tensor] = {}
437
+ hooks = self._register_layer_hooks(
438
+ range(self.num_layers), acts, grads, routing_mode=routing_mode
439
+ )
440
+ try:
441
+ images = images.to(self.device).detach().requires_grad_(True)
442
+ logits = self.extract_tensor(self.model(images))
443
+ if logits is None:
444
+ continue
445
+ if logits.dim() == 1:
446
+ logits = logits.unsqueeze(0)
447
+ self._contrastive_logit(logits, labels).sum().backward()
448
+ finally:
449
+ for h in hooks:
450
+ h.remove()
451
+
452
+ normalized = {}
453
+ per_layer_n = []
454
+ for i in range(self.num_layers):
455
+ if i not in acts or i not in grads:
456
+ continue
457
+ prod = (acts[i] * grads[i]).sum(dim=-1)
458
+ exc_layer[i] += prod.clamp(min=0).reshape(prod.shape[0], -1).sum(dim=-1).mean().item()
459
+ inh_layer[i] += (-prod).clamp(min=0).reshape(prod.shape[0], -1).sum(dim=-1).mean().item()
460
+
461
+ a_norm, has_spatial = self._to_batch_tokens_channel(acts[i])
462
+ g_norm, _ = self._to_batch_tokens_channel(grads[i])
463
+ if not has_spatial or a_norm is None or g_norm is None:
464
+ continue
465
+ cls_offset = self._infer_cls_offset(a_norm.shape[1])
466
+ normalized[i] = (a_norm[:, cls_offset:, :], g_norm[:, cls_offset:, :])
467
+ per_layer_n.append(normalized[i][0].shape[1])
468
+
469
+ if normalized:
470
+ if canonical_n is None:
471
+ canonical_n = Counter(per_layer_n).most_common(1)[0][0]
472
+ for i, (a_norm, g_norm) in normalized.items():
473
+ p_prod = (a_norm * g_norm).sum(dim=2)
474
+ p_exc = p_prod.clamp(min=0)
475
+ p_inh = (-p_prod).clamp(min=0)
476
+ if p_exc.shape[1] != canonical_n:
477
+ p_exc = F.adaptive_avg_pool1d(p_exc.unsqueeze(1), canonical_n).squeeze(1)
478
+ p_inh = F.adaptive_avg_pool1d(p_inh.unsqueeze(1), canonical_n).squeeze(1)
479
+ if exc_patch_sum is None:
480
+ exc_patch_sum = np.zeros((canonical_n, self.num_layers), dtype=np.float64)
481
+ inh_patch_sum = np.zeros((canonical_n, self.num_layers), dtype=np.float64)
482
+ exc_patch_sum[:, i] += p_exc.mean(dim=0).detach().cpu().numpy()
483
+ inh_patch_sum[:, i] += p_inh.mean(dim=0).detach().cpu().numpy()
484
+ count += images.size(0)
485
+
486
+ exc_tot = sum(exc_layer.values()) + 1e-8
487
+ inh_tot = sum(inh_layer.values()) + 1e-8
488
+ return {
489
+ "excitatory_layer_scores": {k: v / exc_tot for k, v in exc_layer.items()},
490
+ "inhibitory_layer_scores": {k: v / inh_tot for k, v in inh_layer.items()},
491
+ "excitatory_patch_scores": (
492
+ exc_patch_sum / (exc_patch_sum.sum() + 1e-8)
493
+ if exc_patch_sum is not None
494
+ else np.zeros((1, self.num_layers), dtype=np.float64)
495
+ ),
496
+ "inhibitory_patch_scores": (
497
+ inh_patch_sum / (inh_patch_sum.sum() + 1e-8)
498
+ if inh_patch_sum is not None
499
+ else np.zeros((1, self.num_layers), dtype=np.float64)
500
+ ),
501
+ }
502
+
503
+ def compute_component_routing_scores(
504
+ self,
505
+ dataloader,
506
+ num_samples: Optional[int] = 50,
507
+ target_class: Optional[int] = None,
508
+ num_heads: Optional[int] = None,
509
+ top_k_mlp_channels: int = 10,
510
+ show_progress: bool = True,
511
+ ) -> Dict[str, object]:
512
+ """
513
+ Decomposes each transformer block into Attention (with per-head breakdown
514
+ when `num_heads` is inferable or provided) and MLP routing scores.
515
+ """
516
+ attn_mods, mlp_mods, inferred_heads = [], [], []
517
+ for layer in self.layers:
518
+ a_mod, m_mod = self._find_submodules(layer)
519
+ attn_mods.append(a_mod)
520
+ mlp_mods.append(m_mod)
521
+ h = num_heads
522
+ if h is None and a_mod is not None:
523
+ h = getattr(a_mod, "num_heads", getattr(a_mod, "num_attention_heads", None))
524
+ inferred_heads.append(h)
525
+
526
+ attn_scores = {i: 0.0 for i in range(self.num_layers)}
527
+ mlp_scores = {i: 0.0 for i in range(self.num_layers)}
528
+ head_scores_acc: Dict[int, np.ndarray] = {}
529
+ mlp_chan_acc: Dict[int, np.ndarray] = {}
530
+
531
+ count = 0
532
+ self.model.eval()
533
+ iterator = tqdm(dataloader, desc="Component SHR") if show_progress else dataloader
534
+
535
+ for batch in iterator:
536
+ if num_samples is not None and count >= num_samples:
537
+ break
538
+ images, labels = batch[0], batch[1].view(-1).to(self.device)
539
+ if target_class is not None:
540
+ mask = labels == int(target_class)
541
+ if not mask.any():
542
+ continue
543
+ images, labels = images[mask], labels[mask]
544
+
545
+ self.model.zero_grad()
546
+ a_acts, a_grads = {}, {}
547
+ m_acts, m_grads = {}, {}
548
+ hooks = self._register_layer_hooks(
549
+ range(self.num_layers), a_acts, a_grads, modules=attn_mods
550
+ ) + self._register_layer_hooks(
551
+ range(self.num_layers), m_acts, m_grads, modules=mlp_mods
552
+ )
553
+ try:
554
+ images = images.to(self.device).detach().requires_grad_(True)
555
+ logits = self.extract_tensor(self.model(images))
556
+ if logits is None:
557
+ continue
558
+ if logits.dim() == 1:
559
+ logits = logits.unsqueeze(0)
560
+ self._contrastive_logit(logits, labels).sum().backward()
561
+ finally:
562
+ for h in hooks:
563
+ h.remove()
564
+
565
+ for i in range(self.num_layers):
566
+ if i in a_acts and i in a_grads:
567
+ prod = (a_acts[i] * a_grads[i]).clamp(min=0)
568
+ attn_scores[i] += prod.reshape(prod.shape[0], -1).sum(dim=-1).mean().item()
569
+ a_tok, ok = self._to_batch_tokens_channel(a_acts[i])
570
+ g_tok, _ = self._to_batch_tokens_channel(a_grads[i])
571
+ h_cnt = inferred_heads[i]
572
+ if ok and a_tok is not None and h_cnt and a_tok.shape[-1] % h_cnt == 0:
573
+ head_dim = a_tok.shape[-1] // h_cnt
574
+ b, n, _ = a_tok.shape
575
+ ah = a_tok.view(b, n, h_cnt, head_dim)
576
+ gh = g_tok.view(b, n, h_cnt, head_dim)
577
+ h_val = (ah * gh).sum(dim=-1).clamp(min=0).sum(dim=1).mean(dim=0).detach().cpu().numpy()
578
+ head_scores_acc[i] = head_scores_acc[i] + h_val if i in head_scores_acc else h_val
579
+
580
+ if i in m_acts and i in m_grads:
581
+ prod = (m_acts[i] * m_grads[i]).clamp(min=0)
582
+ mlp_scores[i] += prod.reshape(prod.shape[0], -1).sum(dim=-1).mean().item()
583
+ m_tok, ok = self._to_batch_tokens_channel(m_acts[i])
584
+ mg_tok, _ = self._to_batch_tokens_channel(m_grads[i])
585
+ if ok and m_tok is not None:
586
+ c_val = (m_tok * mg_tok).clamp(min=0).sum(dim=1).mean(dim=0).detach().cpu().numpy()
587
+ mlp_chan_acc[i] = mlp_chan_acc[i] + c_val if i in mlp_chan_acc else c_val
588
+
589
+ count += images.size(0)
590
+
591
+ tot_a = sum(attn_scores.values()) + 1e-8
592
+ tot_m = sum(mlp_scores.values()) + 1e-8
593
+ head_norm = {
594
+ i: (v / (v.sum() + 1e-8)).tolist() for i, v in head_scores_acc.items()
595
+ }
596
+ top_mlp = {
597
+ i: np.argsort(v)[::-1][:top_k_mlp_channels].tolist() for i, v in mlp_chan_acc.items()
598
+ }
599
+ return {
600
+ "attn_layer_scores": {k: v / tot_a for k, v in attn_scores.items()},
601
+ "mlp_layer_scores": {k: v / tot_m for k, v in mlp_scores.items()},
602
+ "head_scores": head_norm,
603
+ "top_mlp_channels": top_mlp,
604
+ }
605
+
606
+ def get_instance_saliency_map(
607
+ self,
608
+ image: torch.Tensor,
609
+ label: int,
610
+ target_layers: Optional[Sequence[int]] = None,
611
+ layer_weights: Union[str, Dict[int, float], None] = "auto",
612
+ top_k_layers: Optional[int] = None,
613
+ aggregation: str = "weighted_sum",
614
+ routing_mode: str = "residual",
615
+ method: str = "grad_act",
616
+ ig_steps: int = 10,
617
+ baseline: Optional[torch.Tensor] = None,
618
+ num_samples: int = 1,
619
+ noise_std: float = 0.10,
620
+ sink_z_thresh: Optional[float] = 3.5,
621
+ gaussian_sigma: float = 0.0,
622
+ normalize: Optional[str] = "minmax",
623
+ output_size: Optional[Tuple[int, int]] = None,
624
+ ) -> np.ndarray:
625
+ """Generates a 2D spatial saliency map (`method='grad_act'` or `'integrated'`)."""
626
+ self.model.eval()
627
+
628
+ if target_layers is None:
629
+ target_layers = list(range(self.num_layers))
630
+ else:
631
+ target_layers = list(target_layers)
632
+
633
+ if layer_weights == "auto":
634
+ weights = (
635
+ dict(self._layer_weights_cache)
636
+ if self._layer_weights_cache
637
+ else {i: 1.0 for i in target_layers}
638
+ )
639
+ elif layer_weights is None:
640
+ weights = {i: 1.0 for i in target_layers}
641
+ else:
642
+ weights = dict(layer_weights)
643
+
644
+ if top_k_layers is not None:
645
+ ranked = sorted(target_layers, key=lambda idx: weights.get(idx, 0.0), reverse=True)
646
+ target_layers = ranked[:top_k_layers]
647
+
648
+ base_image = image.clone().to(self.device)
649
+ if base_image.dim() == 3:
650
+ base_image = base_image.unsqueeze(0)
651
+
652
+ if output_size is None:
653
+ output_size = (int(base_image.shape[-2]), int(base_image.shape[-1]))
654
+
655
+ total_shr_map = None
656
+ n_runs = max(1, num_samples)
657
+
658
+ for _ in range(n_runs):
659
+ self.model.zero_grad()
660
+ img = base_image
661
+ if n_runs > 1:
662
+ img = img + torch.randn_like(img) * noise_std
663
+ img = img.clone().detach().requires_grad_(True)
664
+
665
+ acts: Dict[int, torch.Tensor] = {}
666
+ grads: Dict[int, torch.Tensor] = {}
667
+
668
+ if method == "integrated":
669
+ base_ref = (
670
+ torch.zeros_like(img)
671
+ if baseline is None
672
+ else baseline.clone().to(self.device).view_as(img)
673
+ )
674
+ base_acts: Dict[int, torch.Tensor] = {}
675
+ base_grads: Dict[int, torch.Tensor] = {}
676
+ b_hooks = self._register_layer_hooks(
677
+ target_layers, base_acts, base_grads, routing_mode=routing_mode
678
+ )
679
+ try:
680
+ with torch.no_grad():
681
+ self.model(base_ref)
682
+ finally:
683
+ for h in b_hooks:
684
+ h.remove()
685
+
686
+ # Capture actual activations at target image
687
+ t_hooks = self._register_layer_hooks(
688
+ target_layers, acts, {}, routing_mode=routing_mode
689
+ )
690
+ try:
691
+ with torch.no_grad():
692
+ self.model(img)
693
+ finally:
694
+ for h in t_hooks:
695
+ h.remove()
696
+
697
+ steps = max(2, int(ig_steps))
698
+ label_tensor = torch.tensor([int(label)], device=self.device, dtype=torch.long)
699
+ grad_sums: Dict[int, torch.Tensor] = {}
700
+ for alpha in np.linspace(1.0 / steps, 1.0, steps):
701
+ self.model.zero_grad()
702
+ interp = (base_ref + float(alpha) * (img - base_ref)).detach().requires_grad_(True)
703
+ step_acts: Dict[int, torch.Tensor] = {}
704
+ step_grads: Dict[int, torch.Tensor] = {}
705
+ s_hooks = self._register_layer_hooks(
706
+ target_layers, step_acts, step_grads, routing_mode=routing_mode
707
+ )
708
+ try:
709
+ logits = self.extract_tensor(self.model(interp))
710
+ if logits.dim() == 1:
711
+ logits = logits.unsqueeze(0)
712
+ self._contrastive_logit(logits, label_tensor).sum().backward()
713
+ finally:
714
+ for h in s_hooks:
715
+ h.remove()
716
+ for k, g in step_grads.items():
717
+ grad_sums[k] = grad_sums[k] + g if k in grad_sums else g.clone()
718
+
719
+ for k in list(acts.keys()):
720
+ if k in grad_sums:
721
+ grads[k] = grad_sums[k] / steps
722
+ if k in base_acts and base_acts[k].shape == acts[k].shape:
723
+ acts[k] = acts[k] - base_acts[k]
724
+ else:
725
+ hooks = self._register_layer_hooks(
726
+ target_layers, acts, grads, routing_mode=routing_mode
727
+ )
728
+ try:
729
+ outs = self.model(img)
730
+ logits = self.extract_tensor(outs)
731
+ if logits.dim() == 1:
732
+ logits = logits.unsqueeze(0)
733
+
734
+ label_tensor = torch.tensor([int(label)], device=self.device, dtype=torch.long)
735
+ contrastive_signal = self._contrastive_logit(logits, label_tensor).sum()
736
+ contrastive_signal.backward()
737
+ finally:
738
+ for h in hooks:
739
+ h.remove()
740
+
741
+ sample_map = None
742
+ for i in target_layers:
743
+ if i not in acts or i not in grads:
744
+ continue
745
+ w = weights.get(i, 1.0)
746
+ if w <= 0:
747
+ continue
748
+
749
+ a_norm, has_spatial = self._to_batch_tokens_channel(acts[i])
750
+ g_norm, _ = self._to_batch_tokens_channel(grads[i])
751
+ if not has_spatial or a_norm is None or g_norm is None:
752
+ continue
753
+
754
+ cls_offset = self._infer_cls_offset(a_norm.shape[1])
755
+ a_sp = a_norm[:, cls_offset:, :]
756
+ g_sp = g_norm[:, cls_offset:, :]
757
+ flat = (a_sp * g_sp).sum(dim=-1).clamp(min=0)[0]
758
+
759
+ grid_hw = self._infer_grid_shape(flat.shape[0])
760
+ if grid_hw is None:
761
+ continue
762
+
763
+ flat_np = flat.detach().cpu().numpy()
764
+ if sink_z_thresh:
765
+ flat_np = self._mad_clip(flat_np, z_thresh=sink_z_thresh)
766
+
767
+ mn, mx = flat_np.min(), flat_np.max()
768
+ if mx > mn:
769
+ flat_np = (flat_np - mn) / (mx - mn)
770
+ else:
771
+ flat_np = np.zeros_like(flat_np)
772
+
773
+ causal_map = (
774
+ torch.from_numpy(flat_np)
775
+ .to(self.device)
776
+ .view(1, 1, grid_hw[0], grid_hw[1])
777
+ .float()
778
+ )
779
+ upsampled = F.interpolate(causal_map, size=output_size, mode="bilinear", align_corners=False)
780
+
781
+ if aggregation == "max":
782
+ weighted = upsampled * w if w != 1.0 else upsampled
783
+ sample_map = weighted if sample_map is None else torch.maximum(sample_map, weighted)
784
+ else:
785
+ sample_map = upsampled * w if sample_map is None else sample_map + upsampled * w
786
+
787
+ if sample_map is None:
788
+ sample_map = torch.zeros(1, 1, output_size[0], output_size[1], device=self.device)
789
+
790
+ total_shr_map = sample_map if total_shr_map is None else total_shr_map + sample_map
791
+
792
+ out_map = (total_shr_map / n_runs).squeeze().cpu().detach().numpy()
793
+
794
+ if gaussian_sigma:
795
+ out_map = self._gaussian_blur_2d(out_map, sigma=gaussian_sigma)
796
+
797
+ if normalize == "minmax":
798
+ mn, mx = out_map.min(), out_map.max()
799
+ if mx > mn:
800
+ out_map = (out_map - mn) / (mx - mn)
801
+
802
+ return out_map