wtf
Browse files- xai_engine/methods.py +22 -10
xai_engine/methods.py
CHANGED
|
@@ -121,12 +121,20 @@ def occlusion_sensitivity(wrapper, input_tensor, patch_size=32, stride=16) -> np
|
|
| 121 |
|
| 122 |
|
| 123 |
def deeplift(wrapper, input_tensor) -> np.ndarray:
|
| 124 |
-
"""DeepLIFT attribution using Captum."""
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
def run_per_head_attention(wrapper, image: Image.Image, layer_idx: int = 11, cmap: str = "jet") -> dict:
|
|
@@ -251,10 +259,14 @@ def run_all_methods(
|
|
| 251 |
alpha: float = 0.6,
|
| 252 |
cmap: str = "jet",
|
| 253 |
) -> list[AttributionResult]:
|
| 254 |
-
"""Run all 6 primary spatial attribution methods
|
| 255 |
-
methods = ["rollout", "chefer", "gradcam", "integrated", "
|
| 256 |
results = []
|
| 257 |
for m in methods:
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
| 260 |
return results
|
|
|
|
|
|
| 121 |
|
| 122 |
|
| 123 |
def deeplift(wrapper, input_tensor) -> np.ndarray:
|
| 124 |
+
"""DeepLIFT attribution using Captum with fallback protection against hook index errors."""
|
| 125 |
+
try:
|
| 126 |
+
dl = DeepLift(wrapper)
|
| 127 |
+
baseline = torch.zeros_like(input_tensor)
|
| 128 |
+
attributions = dl.attribute(input_tensor, baselines=baseline, target=0)
|
| 129 |
+
heatmap = attributions[0].sum(dim=0).detach().cpu().numpy()
|
| 130 |
+
return heatmap
|
| 131 |
+
except Exception as e:
|
| 132 |
+
print(f"[deeplift] Warning: Captum DeepLIFT failed ({e}), falling back to Input x Gradient.")
|
| 133 |
+
input_tensor_copy = input_tensor.clone().detach().requires_grad_(True)
|
| 134 |
+
logits = wrapper(input_tensor_copy)
|
| 135 |
+
logits[0, 0].backward()
|
| 136 |
+
heatmap = (input_tensor_copy * input_tensor_copy.grad).sum(dim=1)[0].detach().cpu().numpy()
|
| 137 |
+
return heatmap
|
| 138 |
|
| 139 |
|
| 140 |
def run_per_head_attention(wrapper, image: Image.Image, layer_idx: int = 11, cmap: str = "jet") -> dict:
|
|
|
|
| 259 |
alpha: float = 0.6,
|
| 260 |
cmap: str = "jet",
|
| 261 |
) -> list[AttributionResult]:
|
| 262 |
+
"""Run all 6 primary spatial attribution methods safely with per-method exception handling."""
|
| 263 |
+
methods = ["rollout", "chefer", "gradcam", "integrated", "occlusion", "deeplift"]
|
| 264 |
results = []
|
| 265 |
for m in methods:
|
| 266 |
+
try:
|
| 267 |
+
res = run_single_method(wrapper, image, m, alpha=alpha, cmap=cmap)
|
| 268 |
+
results.append(res)
|
| 269 |
+
except Exception as err:
|
| 270 |
+
print(f"[xai_engine] Error running method {m}: {err}")
|
| 271 |
return results
|
| 272 |
+
|