File size: 5,219 Bytes
63fba53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
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()