File size: 17,370 Bytes
5f0e48f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""Paper figures from saved run outputs; each figure is skipped while its inputs are missing.

  python make_figs.py stats --device cpu        # style statistics of the test images through S2 (t-SNE input), once
  python make_figs.py figs                      # writes ../figs/*.pdf from whatever exists in ../runs
  python make_figs.py export --device cuda:0    # runs/fig_examples.pt for paper/figs.py (journal-style figures)
"""
import argparse
import csv
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import torch  # noqa: E402

from gridkd import *  # noqa: F401,F403,E402

R, F = Path("../runs"), Path("../figs")
BENCH = {"A": ("../datasets/A_weather", ("clear", "fog")), "B": ("../datasets/B_region", ("cn", "br"))}
plt.rcParams.update({"font.size": 8, "axes.titlesize": 8, "figure.dpi": 200, "savefig.bbox": "tight"})


def auc(neg, pos):  # P(pos > neg), ties count half
    d = pos[None, :] - neg[:, None]
    return float((d > 0).float().mean() + 0.5 * (d == 0).float().mean())


def card_names(b, k=8):
    return [n for n, x in load_plain(R / f"{b}_Lt/weights/best.pt").model.named_modules() if isinstance(x, MultiLoRAConv)][:k]


def cmd_stats(a):
    from deploy_route import stats
    for b, (d, doms) in BENCH.items():
        out = R / f"{b}_style_test.pt"
        if out.exists():
            continue
        names = card_names(b)
        torch.save({dom: torch.cat(stats(load_plain(R / f"{b}_S2/weights/best.pt"), names, f"{d}/{dom}.yaml", "test", a.device), 1)
                    for dom in doms}, out)
        print("wrote", out)


def fig_layer_auc():
    """Per-layer and first-k domain separability: BN statistics (all 81 layers) and density cards (first 16 LoRA inputs)."""
    have = [b for b in BENCH if (R / f"{b}_bnllr_on.pt").exists()]
    if not have:
        return
    fig, axs = plt.subplots(1, len(have), figsize=(3.4 * len(have), 2.4), squeeze=False)
    for ax, b in zip(axs[0], have):
        on, off = torch.load(R / f"{b}_bnllr_on.pt"), torch.load(R / f"{b}_bnllr_off.pt")
        (s1, t1, _), (s0, t0, _) = on.values(), off.values()
        S, T = s1[..., 0] - s0[..., 1], t1[..., 0] - t0[..., 1]  # each model on its own path: target-BN vs source-BN fit
        L = range(1, S.shape[1] + 1)
        ax.plot(L, [auc(S[:, i], T[:, i]) for i in range(S.shape[1])], lw=0.8, c="C0", alpha=0.6, label="BN, single layer")
        ax.plot(L, [auc(S[:, :k].sum(1), T[:, :k].sum(1)) for k in L], lw=1.2, c="C0", label="BN, first k layers")
        lab = R / f"{b}_lab_s0.pt"
        if lab.exists():
            p = torch.load(lab)["per_layer"]
            P0, P1 = p["test0"], p["test1"]
            K = range(1, P0.shape[1] + 1)
            ax.plot(K, [auc(P0[:, i], P1[:, i]) for i in range(P0.shape[1])], lw=0.8, c="C3", alpha=0.6, label="card, single layer")
            ax.plot(K, [auc(P0[:, :k].sum(1), P1[:, :k].sum(1)) for k in K], lw=1.2, c="C3", label="card, first k layers")
        for rule, se, c, lab in (("deep", "base/4", "C2", "deep part (layer-10 features)"), ("fused", "base", "k", "fused card")):
            v = [float(x["auc"]) for x in lab_rows(b) if x["rule"] == rule and x["setting"] == se and x["q"] == "raw"]
            if v:
                ax.axhline(v[0], c=c, lw=0.8, ls="--", label=lab)
        doms = BENCH[b][1]
        ax.set(title=f"{b}: {doms[0]} vs {doms[1]} (test)", xlabel="layer (network order)", ylabel="AUC", xscale="log", ylim=(0, 1.02))
        ax.axhline(0.5, c="k", lw=0.5, ls=":")
        ax.grid(alpha=0.3)
    axs[0][0].legend(loc="lower right", fontsize=6)
    fig.savefig(F / "layer_auc.pdf")
    print("wrote layer_auc.pdf")


def fig_tsne():
    from sklearn.manifold import TSNE
    have = [b for b in BENCH if (R / f"{b}_style_test.pt").exists()]
    if not have:
        return
    fig, axs = plt.subplots(1, len(have), figsize=(3.0 * len(have), 2.8), squeeze=False)
    g = torch.Generator().manual_seed(0)
    for ax, b in zip(axs[0], have):
        st = torch.load(R / f"{b}_style_test.pt")
        xs = [v[torch.randperm(len(v), generator=g)[:800]] for v in st.values()]  # ponytail: 800 per domain keeps t-SNE fast
        x = torch.cat(xs)
        x = ((x - x.mean(0)) / (x.std(0) + 1e-6)).numpy()
        e = TSNE(2, init="pca", perplexity=30, random_state=0).fit_transform(x)
        i = 0
        for c, (dom, v) in zip(("C0", "C3"), zip(st, xs)):
            ax.scatter(*e[i:i + len(v)].T, s=2, c=c, alpha=0.5, lw=0, label=dom)
            i += len(v)
        ax.set(title=f"{b}: style statistics, first 8 LoRA inputs (S2)", xticks=[], yticks=[])
        ax.legend(markerscale=4, fontsize=6)
    fig.savefig(F / "tsne_style.pdf")
    print("wrote tsne_style.pdf")


def lab_rows(b, seed="s0"):
    p = R / f"{b}_lab_{seed}.csv"
    return list(csv.DictReader(open(p))) if p.exists() else []


def fig_llr_hist():
    """Image-level log-likelihood ratio on both test sets: early-layer card (own path, 5% threshold) and fused card
    (base path, threshold 0)."""
    have = [b for b in BENCH if (R / f"{b}_lab_s0.pt").exists() and "fused/base" in torch.load(R / f"{b}_lab_s0.pt")["scores"]]
    if not have:
        return
    fig, axs = plt.subplots(2, len(have), figsize=(3.2 * len(have), 4.2), squeeze=False)
    for j, b in enumerate(have):
        sc = torch.load(R / f"{b}_lab_s0.pt")["scores"]
        for i, (key, title, q) in enumerate((("card/own/8/4/ms", "early-layer card", 0.05), ("fused/base", "fused card", None))):
            ax, s = axs[i][j], sc[key]
            r = {k: v[:, 1] - v[:, 0] for k, v in s.items()}
            tau = float(r["val1"].quantile(q)) if q else 0.0
            sl = lambda t: torch.sign(t) * torch.log10(1 + t.abs())  # noqa: E731  signed log: the ratios span 1e0-1e4
            r, tau = {k: sl(v) for k, v in r.items()}, float(sl(torch.tensor(tau)))
            for c, k, dom in zip(("C0", "C3"), ("test0", "test1"), BENCH[b][1]):
                ax.hist(r[k].numpy(), bins=80, color=c, alpha=0.55, density=True, label=dom)
            ax.axvline(tau, c="k", lw=0.8, label=r"$\tau$" + (" (5% of new-site val)" if q else " = 0"))
            ax.set(title=f"{b}: {title} (test)", yticks=[], xlabel="signed log10(1 + |LLR|), LLR = log p(new) - log p(old)" if i else None)
            ax.legend(fontsize=6)
    fig.tight_layout()
    fig.savefig(F / "llr_hist.pdf")
    print("wrote llr_hist.pdf")


def fig_depth():
    """Fused card with the deep part read at layer 4 / 6 / 8 / 10 of the base model: AUC against the share of the base
    model's MACs spent before the decision."""
    have = {b: r for b in BENCH for st_ in ("s2", "s1", "s0") if (r := [x for x in lab_rows(b, st_) if x["rule"] in ("deep", "fused") and x["q"] == "raw"])
            and any("/L" in x["setting"] for x in r)}
    if not have:
        return
    from deploy_route import macs_by_layer
    macs = macs_by_layer(load_plain(R / "A_S2/weights/best.pt").model.float(), 640)
    share = {L: sum(v for i, v in macs.items() if i <= L) / sum(macs.values()) for L in (4, 6, 8, 10)}
    fig, ax = plt.subplots(figsize=(3.4, 2.4))
    for b, rows in have.items():
        get = lambda rule, se: next(float(x["auc"]) for x in rows if x["rule"] == rule and x["setting"] == se)  # noqa: E731
        for rule, ls, lab in (("fused", "-", "fused card"), ("deep", ":", "deep part only")):
            ys = [get(rule, ("base" if rule == "fused" else "base/4") + ("" if L == 10 else f"/L{L}")) for L in (4, 6, 8, 10)]
            ax.plot([share[L] for L in (4, 6, 8, 10)], ys, ls=ls, marker="o", ms=3, c="C0" if b == "A" else "C3", label=f"{b}: {lab}")
    for L in (4, 6, 8, 10):
        ax.annotate(f"L{L}", (share[L], 0.5), fontsize=6, ha="center")
    ax.set(xlabel="share of base-model MACs before the decision", ylabel="AUC (test)", ylim=(0.45, 1.01))
    ax.grid(alpha=0.3)
    ax.legend(fontsize=6)
    fig.savefig(F / "depth.pdf")
    print("wrote depth.pdf")


def fig_card_grid():
    """Early part of the fused card (base path, threshold 0): mean test mAP50-95 over both sites against layers read (k)
    and GMM components (K)."""
    have = [b for b in BENCH if lab_rows(b)]
    if not have:
        return
    fig, axs = plt.subplots(1, 2 * len(have), figsize=(2.3 * 2 * len(have), 2.0), squeeze=False)
    for j, b in enumerate(have):
        rows = [r for r in lab_rows(b) if r["rule"] == "card" and r["q"] == "raw"]
        for ax, feat in zip(axs[0][2 * j:2 * j + 2], ("ms", "m")):
            ks = sorted({int(r["setting"].split("/")[1]) for r in rows})
            Ks = sorted({int(r["setting"].split("/")[2]) for r in rows})
            M = torch.full((len(Ks), len(ks)), float("nan"))
            for r in rows:
                path, k, K, f = r["setting"].split("/")
                if path == "base" and f == feat:
                    M[Ks.index(int(K)), ks.index(int(k))] = (float(r["map_0"]) + float(r["map_1"])) / 2
            im = ax.imshow(M.numpy(), cmap="viridis", origin="lower")
            for (yy, xx), v in zip(((yy, xx) for yy in range(len(Ks)) for xx in range(len(ks))), M.flatten()):
                ax.text(xx, yy, f"{v:.3f}", ha="center", va="center", fontsize=5, c="w")
            ax.set(xticks=range(len(ks)), xticklabels=ks, yticks=range(len(Ks)), yticklabels=Ks, xlabel="k (layers)",
                   ylabel="K (components)" if feat == "ms" else None, title=f"{b}: {'mean + log-std' if feat == 'ms' else 'mean only'}")
    fig.tight_layout()
    fig.savefig(F / "card_grid.pdf")
    print("wrote card_grid.pdf")


def gt_boxes(img, w, h):
    p = Path(str(img).replace("/images/", "/labels/")).with_suffix(".txt")
    t = torch.tensor([[float(v) for v in ln.split()[1:5]] for ln in p.read_text().splitlines() if ln.strip()]).view(-1, 4)
    return torch.stack([(t[:, 0] - t[:, 2] / 2) * w, (t[:, 1] - t[:, 3] / 2) * h, (t[:, 0] + t[:, 2] / 2) * w, (t[:, 1] + t[:, 3] / 2) * h], 1)


def fig_examples():
    """One random test image per site (seed 0, >= 2 insulators): ground truth, old-site model, new-site model; the
    panel of the model the fused card picks (threshold 0) is framed."""
    from PIL import Image
    have = [b for b in BENCH if (R / f"{b}_lab_s0.pt").exists()]
    if not have:
        return
    rows = [(b, i) for b in have for i in range(2)]
    fig, axs = plt.subplots(len(rows), 3, figsize=(6.6, 1.9 * len(rows)), squeeze=False)
    g = torch.Generator().manual_seed(0)
    for b in have:
        lab = torch.load(R / f"{b}_lab_s0.pt")
        s, tau = lab["scores"]["fused/base"], 0.0
        ms = [load_plain(R / f"{b}_{w}/weights/best.pt") for w in ("S2", "Lt")]
        for i in range(2):
            files = lab["files"][i]
            for j in torch.randperm(len(files), generator=g).tolist():
                im = Image.open(files[j]).convert("RGB")
                gt = gt_boxes(files[j], *im.size)
                if len(gt) >= 2:
                    break
            llr = float(s[f"test{i}"][j, 1] - s[f"test{i}"][j, 0])
            pick = int(llr > tau)
            ax = axs[rows.index((b, i))]
            pr = [m.predict(files[j], conf=0.25, device="cpu", verbose=False)[0].boxes for m in ms]
            for c, (bx, title) in enumerate(zip([gt] + [p.xyxy for p in pr],
                                                ["ground truth", "old-site model (S2)", "new-site model (LoRA)"])):
                ax[c].imshow(im)
                for x0, y0, x1, y1 in bx.tolist():
                    ax[c].add_patch(plt.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, lw=0.8, ec="lime" if c == 0 else "yellow"))
                ax[c].set(xticks=[], yticks=[], title=title if c == 0 else f"{title}: {len(bx)} box" + ("" if len(bx) == 1 else "es"))
                if c == pick + 1:  # the router's choice
                    for sp in ax[c].spines.values():
                        sp.set(ec="red", lw=2.5)
            ax[0].set_ylabel(f"{b} {BENCH[b][1][i]}\nfused-card LLR {llr:.0f}", fontsize=7)
    fig.savefig(F / "examples.pdf")
    print("wrote examples.pdf")


SHOW = {"T": "teacher (YOLO11l)", "S0": "student (YOLO11n)", "S2": "KD + projection (old site)", "FT": "full fine-tune", "J": "joint training (both sites)",
        "S3nt": "multi-LoRA + router", "Lt": "LoRA, source-free", "Lt_deploy_q5": "LoRA + density cards (deployed)",
        "S2p2": "pruned 30%", "S3p2": "pruned + multi-LoRA", "S3ntp": "pruned + multi-LoRA + router", "Ltp_deploy_q5": "pruned + LoRA + cards (deployed)",
        "Lt_deploy_fused": "LoRA + fused cards (deployed)", "Ltp_deploy_fused": "pruned + LoRA + fused cards (deployed)"}


def fig_tradeoff():
    """Mean test mAP50-95 over both sites against GFLOPs per image (mean over both test sets)."""
    pts = {b: {} for b in BENCH}
    for p in sorted(R.glob("*_eval*.csv")):
        if any(t in p.stem for t in ("_v1", "_nanbug", "_seed", "_cards_s")):
            continue
        for r in csv.DictReader(open(p)):
            b, m = r["model"].split("_", 1)
            if b in pts and m in SHOW:
                pts[b].setdefault(m, [{}, {}])  # per domain: GFLOPs (routed models vary with the routed share), mAP; later files win
                pts[b][m][0][r["domain"]], pts[b][m][1][r["domain"]] = float(r["gflops"]), float(r["map50_95"])
    have = [b for b in BENCH if pts[b]]
    fig, axs = plt.subplots(1, len(have), figsize=(3.0 * len(have), 2.6), squeeze=False)
    style = {m: (f"C{i % 10}", "osD^v<>p"[i % 8]) for i, m in enumerate(SHOW)}
    for ax, b in zip(axs[0], have):
        for m in SHOW:
            if m in pts[b] and len(pts[b][m][1]) == 2:
                gf, v = sum(pts[b][m][0].values()) / 2, list(pts[b][m][1].values())
                ax.scatter(gf, sum(v) / 2, s=16, c=style[m][0], marker=style[m][1], label=SHOW[m], ec="k", lw=0.3)
        ax.set(xscale="log", xlabel="GFLOPs per image", title=b)
        ax.grid(alpha=0.3)
    axs[0][0].set_ylabel("mean test mAP50-95 (both sites)")
    fig.subplots_adjust(wspace=0.25)
    h = {l: x for ax in axs[0] for x, l in zip(*ax.get_legend_handles_labels())}
    fig.legend(h.values(), h.keys(), loc="upper center", bbox_to_anchor=(0.5, -0.02), ncol=3, fontsize=6, frameon=False)
    fig.savefig(F / "tradeoff.pdf")
    print("wrote tradeoff.pdf")


def fig_confusion():
    """Three-site sequence (cn -> cnfog -> br): where each site's test images are routed, per rule (threshold 0)."""
    p = R / "B_lab3.pt"
    if not p.exists():
        return
    sc, names = torch.load(p)["scores"], ("cn", "cnfog", "br")
    rules = [(k, t) for k, t in (("fused/base", "fused card"), ("card/base/8/4/ms", "early-layer style only"), ("deep/base/4", "deep part only"),
                                 ("bn-miyazaki", "BN statistics (Miyazaki)"), ("nm-mean", "nearest mean")) if k in sc]
    fig, axs = plt.subplots(1, len(rules), figsize=(2.0 * len(rules), 2.2), squeeze=False)
    for ax, (k, title) in zip(axs[0], rules):
        M = torch.stack([torch.bincount(sc[k][f"test{i}"].argmax(1), minlength=3).float() / len(sc[k][f"test{i}"]) for i in range(3)])
        ax.imshow(M.numpy(), cmap="Blues", vmin=0, vmax=1)
        for i in range(3):
            for j in range(3):
                ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=6, c="w" if M[i, j] > 0.6 else "k")
        ax.set(title=title, xticks=range(3), xticklabels=names, yticks=range(3), yticklabels=names if ax is axs[0][0] else [], xlabel="routed to")
        if ax is axs[0][0]:
            ax.set_ylabel("test images of")
    fig.tight_layout()
    fig.savefig(F / "confusion3.pdf")
    print("wrote confusion3.pdf")


def cmd_export(a):
    """The example images of fig_examples (same seed and order), downscaled, with ground-truth and predicted boxes, so
    paper/figs.py can draw them off the server: runs/fig_examples.pt."""
    import numpy as np
    from PIL import Image
    out, g = [], torch.Generator().manual_seed(0)
    for b in BENCH:
        lab = torch.load(R / f"{b}_lab_s0.pt")
        s = lab["scores"]["fused/base"]
        ms = [load_plain(R / f"{b}_{w}/weights/best.pt") for w in ("S2", "Lt")]
        for i in range(2):
            files = lab["files"][i]
            for j in torch.randperm(len(files), generator=g).tolist():
                im = Image.open(files[j]).convert("RGB")
                gt = gt_boxes(files[j], *im.size)
                if len(gt) >= 2:
                    break
            pr = [m.predict(files[j], conf=0.25, device=a.device, verbose=False)[0].boxes.xyxy.cpu() for m in ms]
            sc = 640 / max(im.size)
            small = im.resize((round(im.width * sc), round(im.height * sc)))
            out.append({"b": b, "i": i, "file": str(files[j]), "img": torch.from_numpy(np.asarray(small).copy()),
                        "boxes": [x * sc for x in [gt] + pr], "llr": float(s[f"test{i}"][j, 1] - s[f"test{i}"][j, 0])})
    torch.save(out, R / "fig_examples.pt")
    print("wrote", R / "fig_examples.pt")


def cmd_figs(a):
    F.mkdir(exist_ok=True)
    for f in (fig_layer_auc, fig_tsne, fig_llr_hist, fig_depth, fig_card_grid, fig_examples, fig_tradeoff, fig_confusion):
        f()


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("cmd", choices=("stats", "figs", "export"))
    p.add_argument("--device", default="cpu")
    a = p.parse_args()
    {"stats": cmd_stats, "figs": cmd_figs, "export": cmd_export}[a.cmd](a)