trifuse-ad-oasis1 / scripts /make_interpret.py
minhy112's picture
Add scripts
9df13b0 verified
Raw
History Blame Contribute Delete
7.21 kB
"""P11 interpretability: train TriFuse-AD on one representative fold, then run
Grad-CAM on the shared CNN encoder for a few correct + incorrect test cases.
Qualitative only. We do NOT claim the model localizes specific structures; we
report that attended regions overlap with anatomy known to be relevant in AD
(medial temporal lobe, ventricles, cortical atrophy).
Needs the GPU, so run this AFTER the main grid finishes (TriFuse-AD is the last
config in the grid and holds the GPU until then).
"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
RESULTS = ROOT / "results"
FIGURES = RESULTS / "figures"
SUBJECTS_CSV = ROOT / "data/metadata/subjects_clean.csv"
from trifuse.data.datasets import SliceDataset, collate, fit_tab_stats # noqa: E402
from trifuse.data.splits import make_folds, split_for # noqa: E402
from trifuse.models.registry import build_model # noqa: E402
from trifuse.training.config import TrainConfig # noqa: E402
from trifuse.training.trainer import fit # noqa: E402
from trifuse.analysis.gradcam import GradCAM, overlay_heatmap # noqa: E402
from trifuse.eval.metrics import CLASS_NAMES # noqa: E402
from torch.utils.data import DataLoader # noqa: E402
TRI = ("axial", "coronal", "sagittal")
SEED, FOLD = 7, 0
class _SlicesOnly(nn.Module):
"""Adapt TriFuse-AD's (slices, tab) forward to the single-input API Grad-CAM expects."""
def __init__(self, model: nn.Module, tab: torch.Tensor):
super().__init__()
self.model = model
self.tab = tab
def forward(self, slices: torch.Tensor) -> torch.Tensor:
return self.model(slices, self.tab)
def _target_layer(model: nn.Module) -> nn.Module:
"""Last conv stage of the timm ConvNeXt encoder (outputs B,C,H,W)."""
enc = model.encoder
if hasattr(enc, "stages"):
return enc.stages[-1]
# fallback: last Conv2d
convs = [m for m in enc.modules() if isinstance(m, nn.Conv2d)]
return convs[-1]
def _train_fold(device: str) -> tuple[nn.Module, pd.DataFrame, dict, TrainConfig]:
df = pd.read_csv(SUBJECTS_CSV)
folds = make_folds(df)
tr, va, te = split_for(folds, df, SEED, FOLD)
train_df = df[df.subject_id.isin(tr)]
val_df = df[df.subject_id.isin(va)]
test_df = df[df.subject_id.isin(te)]
cfg = TrainConfig(name="trifuse_interp", model="trifuse", modality="multimodal",
n_slices=9, planes=TRI, epochs=70, batch_size=6,
lr=3e-4, backbone_lr=3e-5, freeze_epochs=6, seed=SEED)
tab_stats = fit_tab_stats(train_df, cfg.tab_features)
counts = np.bincount(train_df["class_id"], minlength=3).tolist()
def loader(sub, shuffle, aug):
ds = SliceDataset(sub, cfg.tab_features, tab_stats, planes=TRI,
n_slices=cfg.n_slices, modality="multimodal", augment=aug)
return DataLoader(ds, batch_size=cfg.batch_size, shuffle=shuffle,
num_workers=cfg.num_workers, collate_fn=collate, pin_memory=True)
model = build_model(cfg, n_tab_features=len(cfg.tab_features), pretrained=True)
fit(model, loader(train_df, True, True), loader(val_df, False, False),
cfg, counts, device=device)
return model, test_df, tab_stats, cfg
def _gradcam_for_subject(model, target, batch, device, n_slices, planes):
"""Return {plane: (gray_center, heat_center)} for the argmax class, center slice per plane.
TriFuse-AD flattens the 27 slices into the CNN batch dim, so the target layer's
captured activations/grads are (T, C, H', W') — one per slice. We compute a
per-token Grad-CAM here rather than using GradCAM.__call__'s single-map return.
"""
import torch.nn.functional as F
slices = batch["slices"].to(device) # (1, T, 3, H, W)
tab = batch["tab"].to(device)
wrapper = _SlicesOnly(model, tab)
cam = GradCAM(wrapper, target)
_ = cam(slices, class_idx=None) # triggers fwd+bwd, fills cam._acts/_grads
acts, grads = cam._acts, cam._grads # (T, C, H', W')
cam.remove()
H, W = slices.shape[-2:]
weights = grads.mean(dim=(2, 3), keepdim=True) # (T, C, 1, 1)
heat = F.relu((weights * acts).sum(dim=1)) # (T, H', W')
heat = F.interpolate(heat.unsqueeze(1), size=(H, W), mode="bilinear",
align_corners=False)[:, 0] # (T, H, W)
heat = heat.detach().cpu().numpy()
out = {}
center = n_slices // 2
for p_idx, plane in enumerate(planes):
tok = p_idx * n_slices + center
gray = slices[0, tok, 0].detach().cpu().numpy()
h = heat[tok]
h = (h - h.min()) / (np.ptp(h) + 1e-8) # per-slice normalize
out[plane] = (gray, h)
return out
def main():
device = "cuda" if torch.cuda.is_available() else "cpu"
FIGURES.mkdir(parents=True, exist_ok=True)
print(f"training TriFuse-AD on seed={SEED} fold={FOLD} ({device}) for interpretability...",
flush=True)
model, test_df, tab_stats, cfg = _train_fold(device)
model.eval()
target = _target_layer(model)
ds = SliceDataset(test_df, cfg.tab_features, tab_stats, planes=TRI,
n_slices=cfg.n_slices, modality="multimodal", augment=False)
dl = DataLoader(ds, batch_size=1, shuffle=False, collate_fn=collate)
cases = [] # (subject_id, y_true, y_pred, {plane:(gray,heat)})
for batch in dl:
with torch.no_grad():
logits = model(batch["slices"].to(device), batch["tab"].to(device))
pred = int(logits.argmax(1)[0])
yt = int(batch["y"][0])
maps = _gradcam_for_subject(model, target, batch, device, cfg.n_slices, TRI)
cases.append((batch["subject_id"][0], yt, pred, maps))
correct = [c for c in cases if c[1] == c[2]][:6]
wrong = [c for c in cases if c[1] != c[2]][:3]
picked = correct + wrong
if not picked:
print("no test cases produced; aborting figure")
return
n = len(picked)
fig, axes = plt.subplots(n, 3, figsize=(9, 3 * n))
if n == 1:
axes = axes[None, :]
for r, (sid, yt, yp, maps) in enumerate(picked):
tag = "OK" if yt == yp else "WRONG"
for c, plane in enumerate(TRI):
gray, heat = maps[plane]
axes[r, c].imshow(overlay_heatmap(gray, heat))
axes[r, c].axis("off")
if c == 0:
axes[r, c].set_ylabel(f"{sid}\nT:{CLASS_NAMES[yt]} P:{CLASS_NAMES[yp]} [{tag}]",
fontsize=8, rotation=0, ha="right", va="center")
axes[r, c].set_title(plane if r == 0 else "", fontsize=9)
fig.suptitle("TriFuse-AD Grad-CAM (shared CNN encoder, center slice per plane)")
fig.tight_layout()
out = FIGURES / "fig_gradcam_trifuse.png"
fig.savefig(out, dpi=150)
plt.close(fig)
print(f"wrote {out} ({len(correct)} correct + {len(wrong)} wrong cases)")
if __name__ == "__main__":
main()