File size: 11,412 Bytes
d65fc2e
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
 
 
 
 
 
 
 
 
 
 
 
d65fc2e
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
d65fc2e
 
f9ace88
d65fc2e
f9ace88
d65fc2e
 
f9ace88
d65fc2e
 
f9ace88
d65fc2e
 
 
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
d65fc2e
 
f9ace88
d65fc2e
f9ace88
d65fc2e
f9ace88
d65fc2e
f9ace88
d65fc2e
 
 
 
 
 
 
f9ace88
d65fc2e
f9ace88
d65fc2e
 
f9ace88
d65fc2e
 
 
 
 
f9ace88
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ace88
 
 
 
 
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""Phase-3 analysis (Mac): selection on validation, main table with CIs, peak-depth table, pairwise bootstrap differences,
layer x noise heatmaps and depth profiles.

  python analyze3.py <out_dir> [p3|p4]   # out_dir holds <phase>/*_rows.csv and perimage/<phase>/*.npz

Selection: for each model and task the (block, s) cell with the best validation score (mean over the 3 seeds; depth and
normals: ridge validation MSE, segmentation: validation mIoU, classification: validation top-1 of the mean patch token)
is reported on test.  Pairwise differences: 2000 bootstrap resamples of test images shared by both models, each side
at its own selected cell, seed-averaged; "tie" when the 95% interval contains 0.
"""
from __future__ import annotations

import csv
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
import probes5 as PR  # noqa: E402

TASKS = {  # task: (validation metric, higher is better, test metrics (first = primary), primary higher is better)
    "nyu_depth": ("val_mse", False, ["rmse", "delta1", "absrel"], False),
    "nyu_normals": ("val_mse", False, ["mean_angle", "median_angle", "pct_11.25", "pct_22.5", "pct_30"], False),
    "ade_seg": ("val_miou", True, ["miou"], True),
    "imagenet_cls": ("val_top1", True, ["top1"], True),
}
NAMES = {"sit_b": "SiT-B/2", "jit_b": "JiT-B/16", "mae_b": "MAE-B", "mocov3_b": "MoCo v3-B", "dino_b": "DINO-B",
         "ibot_b": "iBOT-B", "deit3_b": "DeiT III-B", "dinov2_b": "DINOv2-B (ngoài)", "base_latent": "latent VAE có nhiễu",
         "base_pixel": "patch pixel có nhiễu", "base_pixel_clean": "patch pixel sạch",
         "sit_l": "SiT-L/2", "jit_l": "JiT-L/16", "mae_l": "MAE-L", "mocov3_l": "MoCo v3-L (bên thứ ba)",
         "ibot_l": "iBOT-L", "deit3_l": "DeiT III-L"}
PHASE = "p3"


def n_blocks(model):
    return 1 if model.startswith("base_") else (24 if model.endswith("_l") else 12)


def blocks(model):
    n = n_blocks(model)
    return [1] if n == 1 else (list(range(1, 13)) if n == 12 else list(range(2, 25, 2)))
GROUP_ORDER = ["denoise_latent", "denoise_pixel", "masked", "joint_embedding", "supervised", "external_data", "baseline"]


def load_rows(out):
    files = sorted((out / PHASE).glob("*_rows.csv"))
    rows = []
    for p in files:
        with open(p) as f:
            rows += list(csv.DictReader(f))
    for r in rows:
        r["layer"] = int(r["layer"])
        r["mean"] = float(r["mean"])
        r["std"] = float(r["std"]) if r["std"] not in ("", "nan") else float("nan")
        for k in ("ci_lo", "ci_hi"):
            r[k] = float(r[k]) if r[k] not in ("",) else None
    return rows


def select(rows):
    """{(model, task): dict(layer, s, val, group)} chosen on validation."""
    best = {}
    for model in sorted({r["model"] for r in rows}):
        for task, (vm, hi, _, _) in TASKS.items():
            cand = [r for r in rows if r["model"] == model and r["task"] == task and r["metric"] == vm]
            if not cand:
                continue
            r = max(cand, key=lambda r: r["mean"]) if hi else min(cand, key=lambda r: r["mean"])
            best[(model, task)] = dict(layer=r["layer"], s=r["s"], val=r["mean"], group=r["group"])
    return best


def cell(rows, model, task, metric, layer, s):
    for r in rows:
        if (r["model"], r["task"], r["metric"], r["layer"], r["s"]) == (model, task, metric, layer, s):
            return r
    return None


# ----------------------------------------------------------------------------- per-image arrays for pairwise tests
def unit_tag(model, s, task):
    grp = {"nyu_depth": "nyu", "nyu_normals": "nyu", "ade_seg": "seg", "imagenet_cls": "cls"}[task]
    return f"{model}_s{s}_{grp}"


def per_image(out, model, task, layer, s):
    """Seed-resolved per-image quantity at (layer, s): returns (kind, array)."""
    z = np.load(out / "perimage" / PHASE / f"{unit_tag(model, s, task)}.npz")
    li = blocks(model).index(layer)
    if task == "nyu_depth":
        return "mean", z["depth_rmse"][li]                      # [S, N]
    if task == "nyu_normals":
        return "normals", z["normals_stats"][li].astype(np.float64)   # [S, N, 725]
    if task == "ade_seg":
        return "seg", z["ade_counts"][li].astype(np.float64)    # [S, N, 3, C]
    return "mean", z["correct"][li].astype(np.float64)          # [S, N]


def stat(kind, arr, W):
    """W [B, N] resampling counts -> [B] seed-averaged metric (primary)."""
    if kind == "mean":
        return (np.einsum("bn,sn->bs", W, arr) / W.sum(1, keepdims=True)).mean(1)
    if kind == "normals":
        return PR.normals_metrics_from(np.einsum("bn,snk->bsk", W, arr)[:, :, None, :])["mean_angle"].mean(1)
    return PR.miou_from(np.einsum("bn,snkc->bskc", W, arr)).mean(1)


def pairwise(out, best, pairs, tasks, n_boot=2000):
    res = []
    for task in tasks:
        cache = {}
        for a, b in pairs:
            if (a, task) not in best or (b, task) not in best:
                continue
            for m in (a, b):
                if m not in cache:
                    sel = best[(m, task)]
                    cache[m] = per_image(out, m, task, sel["layer"], sel["s"])
            n = cache[a][1].shape[1]
            W = PR.boot_weights(n, n_boot=n_boot, seed=1)
            one = np.ones((1, n))
            da, db = stat(*cache[a], W), stat(*cache[b], W)
            pa, pb = stat(*cache[a], one)[0], stat(*cache[b], one)[0]
            lo, hi = np.percentile(da - db, [2.5, 97.5])
            a_better = (pa > pb) == TASKS[task][3]
            res.append(dict(task=task, a=a, b=b, a_value=pa, b_value=pb, diff=pa - pb, ci_lo=lo, ci_hi=hi,
                            verdict="ngang nhau" if lo <= 0 <= hi else (f"{a} tốt hơn" if a_better else f"{b} tốt hơn")))
    return res


# ----------------------------------------------------------------------------- figures
def figures(rows, best, fig_dir):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig_dir.mkdir(parents=True, exist_ok=True)
    primary = {t: v[2][0] for t, v in TASKS.items()}
    svals = ["0.05", "0.1", "0.3", "0.5", "0.7"]
    for model in [m for m in ("sit_b", "jit_b", "sit_l", "jit_l") if any(r["model"] == m for r in rows)]:
        bl = blocks(model)
        fig, axes = plt.subplots(1, 4, figsize=(18, 3.6))
        for ax, (task, m) in zip(axes, primary.items()):
            H = np.full((len(svals), len(bl)), np.nan)
            for i, s in enumerate(svals):
                for j, l in enumerate(bl):
                    r = cell(rows, model, task, m, l, s)
                    if r:
                        H[i, j] = r["mean"]
            cmap = "viridis_r" if not TASKS[task][3] else "viridis"
            im = ax.imshow(H, aspect="auto", cmap=cmap)
            ax.set_xticks(range(len(bl)), [str(l) for l in bl])
            ax.set_yticks(range(len(svals)), svals)
            ax.set_xlabel("block")
            ax.set_ylabel("s")
            ax.set_title(f"{NAMES[model]} — {task} {m}")
            if (model, task) in best:
                b = best[(model, task)]
                ax.scatter([bl.index(b["layer"])], [svals.index(b["s"])], marker="*", s=160, c="red")
            fig.colorbar(im, ax=ax, fraction=0.046)
        fig.tight_layout()
        fig.savefig(fig_dir / f"heatmap_{model}.png", dpi=130)
        plt.close(fig)
    models = [m for m in NAMES if any(r["model"] == m for r in rows)]
    for task, m in primary.items():
        fig, ax = plt.subplots(figsize=(7.5, 4.6))
        for model in models:
            if (model, task) not in best:
                continue
            s = best[(model, task)]["s"]
            if model.startswith("base_"):
                r = cell(rows, model, task, m, 1, s)
                if r:
                    ax.axhline(r["mean"], ls=":", lw=1, color="gray")
                    ax.text(1.0, r["mean"], f" {NAMES[model]} (s={s})", fontsize=7, va="center", color="gray")
                continue
            xs, ys = [], []
            for l in blocks(model):
                r = cell(rows, model, task, m, l, s)
                if r:
                    xs.append(l / n_blocks(model))
                    ys.append(r["mean"])
            style = "-" if model.startswith(("sit_", "jit_")) else "--"
            ax.plot(xs, ys, style, marker="o", ms=3, label=f"{NAMES[model]}" + (f" (s={s})" if s != "clean" else ""))
        ax.set_xlabel("độ sâu tương đối (block / số block)")
        ax.set_ylabel(f"{m} (test)")
        ax.set_title(f"{task}: hồ sơ theo độ sâu, cỡ {'B' if PHASE == 'p3' else 'L'}")
        ax.legend(fontsize=7, ncol=2)
        fig.tight_layout()
        fig.savefig(fig_dir / f"profile_{task}.png", dpi=130)
        plt.close(fig)


def main():
    global PHASE
    out = Path(sys.argv[1])
    PHASE = sys.argv[2] if len(sys.argv) > 2 else "p3"
    rows = load_rows(out)
    best = select(rows)
    ana = out / PHASE / "analysis"
    ana.mkdir(parents=True, exist_ok=True)
    main_rows = []
    for (model, task), sel in sorted(best.items(), key=lambda kv: (GROUP_ORDER.index(kv[1]["group"])
                                                                    if kv[1]["group"] in GROUP_ORDER else 99, kv[0])):
        rec = dict(model=model, name=NAMES.get(model, model), group=sel["group"], task=task, layer=sel["layer"],
                   s=sel["s"], depth_rel=0.0 if model.startswith("base_") else round(sel["layer"] / n_blocks(model), 3),
                   val=sel["val"])
        for m in TASKS[task][2]:
            r = cell(rows, model, task, m, sel["layer"], sel["s"])
            if r:
                rec[m], rec[f"{m}_std"], rec[f"{m}_ci"] = r["mean"], r["std"], (r["ci_lo"], r["ci_hi"])
        if task == "imagenet_cls":  # CLS reference for encoders: best block by validation of the CLS head
            c = [r for r in rows if r["model"] == model and r["metric"] == "val_top1_cls"]
            if c:
                rc = max(c, key=lambda r: r["mean"])
                t = cell(rows, model, task, "top1_cls", rc["layer"], rc["s"])
                rec["top1_cls"], rec["top1_cls_layer"] = t["mean"], rc["layer"]
        main_rows.append(rec)
    with open(ana / "main_table.json", "w") as f:
        json.dump(main_rows, f, indent=1, default=float)
    present = {r["model"] for r in rows}
    denoisers = [m for m in ("sit_b", "jit_b", "sit_l", "jit_l") if m in present]
    others = [m for m in ("mae_b", "mocov3_b", "dino_b", "ibot_b", "deit3_b", "dinov2_b",
                          "mae_l", "mocov3_l", "ibot_l", "deit3_l") if m in present]
    pairs = [(d, o) for d in denoisers for o in others if d[-1] == o[-1]]
    pairs += [(j, sv) for j, sv in (("jit_b", "sit_b"), ("jit_l", "sit_l")) if j in present and sv in present]
    pw = pairwise(out, best, pairs, list(TASKS))
    with open(ana / "pairwise.json", "w") as f:
        json.dump(pw, f, indent=1, default=float)
    figures(rows, best, ana)
    for r in main_rows:
        print(r["task"], r["name"], f"block {r['layer']} s={r['s']}", {m: round(r[m], 4) for m in TASKS[r["task"]][2] if m in r},
              f"CLS {r['top1_cls']:.4f}@b{r['top1_cls_layer']}" if "top1_cls" in r else "")
    for p in pw:
        print(p["task"], p["a"], "vs", p["b"], f"{p['diff']:+.4f} [{p['ci_lo']:+.4f}, {p['ci_hi']:+.4f}]", p["verdict"])


if __name__ == "__main__":
    main()