Download MedEvalKit/visualize_attention.py from Master-Shi/ExplainableVQA: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/datasets/Master-Shi/ExplainableVQA/resolve/main/MedEvalKit/visualize_attention.py
- Command line
-
hf download hf://datasets/Master-Shi/ExplainableVQA/MedEvalKit/visualize_attention.py
-
curl -L -o visualize_attention.py https://huggingface.co/datasets/Master-Shi/ExplainableVQA/resolve/main/MedEvalKit/visualize_attention.py
5.22 kB
| """ | |
| visualize_attention.py | |
| Visualize layer-wise attention results for all models, comparing COCO vs VGMED. | |
| Usage: | |
| python visualize_attention.py | |
| python visualize_attention.py --metric js | |
| python visualize_attention.py --output_dir my_plots | |
| """ | |
| import argparse | |
| import os | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| ATTENTION_ROOT = "attention_results" | |
| MODELS = { | |
| "HuatuoGPT-V-7B": "HuatuoGPT-V-7B/HuatuoGPT-Vision-7B", | |
| "LLaVA-7B": "LLaVA-7B/llava-1.5-7b-hf", | |
| "LLaVA-13B": "LLaVA-13B/llava-1.5-13b-hf", | |
| "LLaVA-Med-7B": "LLaVA-Med-7B/llava-med-v1.5-mistral-7b", | |
| "MedGemma-4B-IT": "MedGemma-4B-IT/medgemma-4b-it", | |
| "Qwen2.5VL-3B": "Qwen2.5VL-3B/Qwen2.5-VL-3B-Instruct", | |
| "Qwen2.5VL-7B": "Qwen2.5VL-7B/Qwen2.5-VL-7B-Instruct", | |
| "Qwen3VL-2B": "Qwen3VL-2B/Qwen3-VL-2B-Instruct", | |
| "Qwen3VL-4B": "Qwen3VL-4B/Qwen3-VL-4B-Instruct", | |
| "Qwen3VL-8B": "Qwen3VL-8B/Qwen3-VL-8B-Instruct", | |
| } | |
| METRICS = { | |
| "js": "JS Divergence", | |
| "kl": "KL Divergence", | |
| "ratios": "Attention Ratios", | |
| } | |
| DATASETS = ["COCO", "VGMED"] | |
| # ββ shared style constants (kept in sync with visualize_grounding.py) βββββββββ | |
| # Each model is saved as its own standalone PNG, so every figure must be readable | |
| # on its own at a small size: large fonts, thick lines, high DPI. | |
| COLORS = {"COCO": "#2196F3", "VGMED": "#F44336"} | |
| DIFF_POS = "#F44336" | |
| DIFF_NEG = "#2196F3" | |
| FIG_WIDTH = 8.0 | |
| ROW_HEIGHT = 5.0 | |
| TITLE_FS = 22 | |
| AXIS_FS = 18 | |
| TICK_FS = 16 | |
| LEGEND_FS = 16 | |
| MARKER = "o" | |
| MARKER_SIZE = 9 | |
| LINE_WIDTH = 3.5 | |
| GRID_ALPHA = 0.3 | |
| DPI = 600 | |
| plt.rcParams["font.weight"] = "bold" | |
| plt.rcParams["axes.labelweight"] = "bold" | |
| plt.rcParams["axes.titleweight"] = "bold" | |
| plt.rcParams["axes.linewidth"] = 1.5 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_pt(path): | |
| data = torch.load(path, map_location="cpu", weights_only=False) | |
| arr = np.stack(data, axis=0) # [N, num_layers] | |
| return arr.mean(axis=0) # [num_layers] | |
| def plot_metric(metric_key, metric_label, output_dir): | |
| """One standalone PNG per model: top = metric curves, bottom = VGMED-COCO diff bars.""" | |
| for model_name, model_dir in MODELS.items(): | |
| fig, (ax_top, ax_bot) = plt.subplots( | |
| 2, 1, figsize=(FIG_WIDTH, ROW_HEIGHT * 2), | |
| ) | |
| fig.suptitle( | |
| f"{model_name} β {metric_label} (COCO vs VGMED)", | |
| fontsize=TITLE_FS, fontweight="bold", | |
| ) | |
| loaded = {} | |
| for ds in DATASETS: | |
| fname = f"{ds}_localization_attention_{metric_key}_normalized.pt" | |
| fpath = os.path.join(ATTENTION_ROOT, model_dir, fname) | |
| if not os.path.exists(fpath): | |
| print(f"[skip] {fpath}") | |
| continue | |
| loaded[ds] = load_pt(fpath) | |
| # top: curves | |
| for ds, vals in loaded.items(): | |
| layers = np.arange(len(vals)) | |
| ax_top.plot(layers, vals, label=ds, color=COLORS[ds], | |
| linewidth=LINE_WIDTH, marker=MARKER, markersize=MARKER_SIZE) | |
| ax_top.set_ylabel(metric_label, fontsize=AXIS_FS) | |
| ax_top.tick_params(labelsize=TICK_FS) | |
| ax_top.grid(True, alpha=GRID_ALPHA) | |
| if loaded: | |
| ax_top.legend(fontsize=LEGEND_FS) | |
| # bottom: VGMED β COCO diff bars | |
| if "VGMED" in loaded and "COCO" in loaded: | |
| vgmed = loaded["VGMED"] | |
| coco = loaded["COCO"] | |
| n = min(len(vgmed), len(coco)) | |
| diff = vgmed[:n] - coco[:n] | |
| layers = np.arange(n) | |
| ax_bot.bar(layers, diff, | |
| color=[DIFF_POS if d >= 0 else DIFF_NEG for d in diff], | |
| alpha=0.7, width=0.8) | |
| ax_bot.axhline(0, color="black", linewidth=0.8, linestyle="--") | |
| ax_bot.set_xlabel("Layer", fontsize=AXIS_FS) | |
| ax_bot.set_ylabel("VGMED β COCO", fontsize=AXIS_FS) | |
| ax_bot.tick_params(labelsize=TICK_FS) | |
| ax_bot.grid(True, alpha=GRID_ALPHA, axis="y") | |
| else: | |
| ax_bot.set_visible(False) | |
| plt.tight_layout() | |
| model_dir_out = os.path.join(output_dir, metric_key) | |
| os.makedirs(model_dir_out, exist_ok=True) | |
| out_path = os.path.join(model_dir_out, f"{model_name}_{metric_key}.png") | |
| plt.savefig(out_path, dpi=DPI, bbox_inches="tight") | |
| plt.close() | |
| print(f"Saved: {out_path}") | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--metric", choices=list(METRICS.keys()), default=None, | |
| help="Plot only one metric (default: all)") | |
| parser.add_argument("--output_dir", default="attention_plots") | |
| args = parser.parse_args() | |
| targets = {args.metric: METRICS[args.metric]} if args.metric else METRICS | |
| for metric_key, metric_label in targets.items(): | |
| plot_metric(metric_key, metric_label, args.output_dir) | |
| if __name__ == "__main__": | |
| main() | |