File size: 16,905 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
"""Routing lab: every routing rule and density-card setting from one set of forward passes per model.

Sites 0..N-1 arrive in order: model 0 is the old site's model (e.g. S2), model j >= 1 an adapter trained on site j only.
Every model runs once on every site's test split and the per-image detection statistics are kept, so the test mAP of
any per-image routing decision is computed offline (checked: sending every image to one model reproduces that model's
own val mAP). Each pass also records what the routing rules read:
  card    style statistics (channel mean, log-std) of the first 16 LoRA-layer inputs. Per-site diagonal GMMs, fit on
          the site's own training split, along the site's own model (ours) or along the base model only.
  bn-*    per-layer KL / W2 between the BN input's instance statistics and that model's BN running statistics
          (Miyazaki & Yamamoto, DCASE 2026 Task 7; W2 as in BN embeddings, Segu et al. 2023).
  cdtta   base-path instance statistics of the first two LoRA-layer inputs vs per-site prototypes, Bhattacharyya.
  nm-*    pooled base-model backbone features (layer 10) vs a per-site mean or 5 K-means centroids, cosine
          (LDB / S-Prompts style).
  deep    per-site diagonal GMM on those pooled layer-10 features, along the site's own model or the base model.
  fused   card (k=8, K=4) + deep (K=4) log-likelihoods: early-layer style and deep content in one card; fused-z scales
          each by the spread of its log-likelihood ratio on the first new site's val split. Base path only: the deep part
          also from layers 4, 6, 8 (setting .../L<layer>).
Each rule routes by argmax over sites, raw or with per-site offsets set in arrival order on each new site's own val
split so that a share 1-q of it stays on its own model. No site's data is used after that site's own turn.

  python route_lab.py --models s2.pt lt.pt --data cn.yaml br.yaml --device 0 --out ../runs/B_lab.csv
"""
import argparse
import csv

import torch
from ultralytics.utils.metrics import DetMetrics

from gridkd import *  # noqa: F401,F403

NL = 16  # LoRA layers whose input statistics are kept; cards use the first k of them
POOL = (4, 6, 8, 10)  # backbone layers whose pooled output is kept; nm-*, deep and fused read layer 10, the rest is a depth ablation


def lora_names(weights):
    for w in weights:
        n = [k for k, x in load_plain(w).model.named_modules() if isinstance(x, MultiLoRAConv)][:NL]
        if n:
            return n
    raise SystemExit("no LoRA checkpoint among --models: cannot name the card layers")


def bn_params(model):  # every Conv+BN of the unfused model, module order
    return [(n, x.bn.weight.detach().float(), x.bn.bias.detach().float(), x.bn.running_mean.float(), x.bn.running_var.float(), x.bn.eps)
            for n, x in model.named_modules() if isinstance(x, Conv) and hasattr(x, "bn")]


def bn_dist(o, g, b, rm, rv, eps):
    """KL and W2 between the BN input's per-image channel Gaussians (recovered from the fused conv output) and the
    stored running statistics, averaged over channels; channels with |gamma| <= 1e-3 cannot be recovered and are skipped."""
    f = o.float().flatten(2)
    sd, keep = (rv + eps).sqrt(), g.abs() > 1e-3
    mx = (rm + (f.mean(-1) - b) * sd / g)[:, keep]
    sx = (f.std(-1, unbiased=False) * sd / g.abs())[:, keep].clamp_min(1e-6)
    mu, sg = rm[keep], rv[keep].sqrt().clamp_min(1e-6)
    kl = (torch.log(sg / sx) + (sx**2 + (mx - mu) ** 2) / (2 * sg**2) - 0.5).mean(1)
    return kl, ((mx - mu) ** 2 + (sx - sg) ** 2).mean(1)


def collect(weights, names, data, split, device):
    """One val pass of one model over one split."""
    y = load_plain(weights)
    bnp = bn_params(y.model)
    rec = {k: [] for k in ("style", "kl", "w2", "pools", "files", "idx")}
    cur, live, hs = {}, [False], []

    def pre(i):
        def f(m, a):
            if live[0]:
                cur[("s", i)] = style_stats(a[0]).cpu()
        return f

    def post(i, p):
        def f(m, a, o):
            if live[0]:
                cur[("b", i)] = [t.cpu() for t in bn_dist(o, *[t.to(o.device) for t in p[1:5]], p[5])]
        return f

    def pool(L):
        def f(m, a, o):
            if live[0]:
                cur[("p", L)] = o.float().mean((2, 3)).cpu()
        return f

    def on_start(v):  # after AutoBackend fused the model, so the hooks sit on the fused convs
        mods = dict(y.model.named_modules())
        hs.extend(mods[n].register_forward_pre_hook(pre(i)) for i, n in enumerate(names))
        hs.extend(mods[p[0]].conv.register_forward_hook(post(i, p)) for i, p in enumerate(bnp))
        hs.extend(y.model.model[L].register_forward_hook(pool(L)) for L in POOL)
        um = v.update_metrics

        def update(preds, batch):  # the validator skips images with neither predictions nor labels: keep the mapping
            k = len(v.stats["tp"])
            r = um(preds, batch)
            for si, pr in enumerate(preds):
                has = len(pr) > 0 or bool((batch["batch_idx"] == si).any())
                rec["idx"].append(k if has else -1)
                k += has
            assert k == len(v.stats["tp"])
            rec["files"].extend(batch["im_file"])
            return r

        v.update_metrics = update

    def on_batch_end(v):
        live[0] = False
        rec["style"].append([cur[("s", i)] for i in range(len(names))])
        rec["kl"].append(torch.stack([cur[("b", i)][0] for i in range(len(bnp))], 1))
        rec["w2"].append(torch.stack([cur[("b", i)][1] for i in range(len(bnp))], 1))
        rec["pools"].append([cur[("p", L)] for L in POOL])
        cur.clear()

    def on_val_end(v):
        rec["det"] = {k: [t.cpu() for t in x] for k, x in v.stats.items()}
        rec["map"] = (float(v.metrics.box.map50), float(v.metrics.box.map))

    y.add_callback("on_val_start", on_start)
    y.add_callback("on_val_batch_start", lambda v: live.__setitem__(0, True))
    y.add_callback("on_val_batch_end", on_batch_end)
    y.add_callback("on_val_end", on_val_end)
    y.val(data=data, split=split, device=device, workers=4, plots=False, verbose=False)
    for h in hs:
        h.remove()
    out = {k: torch.cat(rec[k]) for k in ("kl", "w2")}
    out["pools"] = {L: torch.cat([b[i] for b in rec["pools"]]) for i, L in enumerate(POOL)}
    out["pool"] = out["pools"][10]
    out["style"] = [torch.cat([b[i] for b in rec["style"]]) for i in range(len(names))]
    out.update(files=rec["files"], idx=rec["idx"], det=rec["det"], map=rec["map"], names=y.model.names)
    w = Path(weights)
    print(f"collected {w.parent.parent.name if w.parent.name == 'weights' else w.stem} on {Path(data).stem}:{split}  n={len(rec['files'])}  map={out['map'][1]:.4f}")
    return out


def mean_ap(passes, choice):
    """mAP50, mAP50-95 when image x takes its detections from passes[choice[x]] (all passes cover one split)."""
    cols = {k: [] for k in ("tp", "conf", "pred_cls", "target_cls")}
    for x, j in enumerate(choice.tolist()):
        k = passes[j]["idx"][x]
        if k >= 0:
            for c in cols:
                cols[c].append(passes[j]["det"][c][k])
    m = DetMetrics(names=passes[0]["names"])
    m.process(*[torch.cat(cols[c]).numpy() for c in ("tp", "conf", "pred_cls", "target_cls")])
    return float(m.box.map50), float(m.box.map)


def kmeans(x, k=5, iters=25, seed=0):  # spherical K-means on unit-norm rows
    c = x[torch.randperm(len(x), generator=torch.Generator().manual_seed(seed))[:k]].clone()
    for _ in range(iters):
        lab = (x @ c.T).argmax(1)
        c = F.normalize(torch.stack([x[lab == j].mean(0) if (lab == j).any() else c[j] for j in range(k)]), dim=1)
    return c


def bhattacharyya(m1, s1, m2, s2):
    v = s1**2 + s2**2
    return (0.25 * (m1 - m2) ** 2 / v + 0.5 * torch.log(v / (2 * s1 * s2))).mean(-1)


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--models", nargs="+", required=True, help="site 0 (old) model, then one adapter per later site")
    p.add_argument("--data", nargs="+", required=True, help="one data.yaml per site, same order")
    p.add_argument("--q", nargs="+", type=float, default=[0.01, 0.05, 0.1])
    p.add_argument("--out", required=True, help="CSV of every rule and setting; per-image scores go next to it (.pt)")
    p.add_argument("--device", default="0")
    a = p.parse_args()
    N = len(a.models)
    assert N == len(a.data) >= 2
    names = lora_names(a.models[1:])
    C = lambda j, d, s: collect(a.models[j], names, a.data[d], s, a.device)  # noqa: E731
    test = {(j, i): C(j, i, "test") for i in range(N) for j in range(N)}  # model j on site i's test split
    own = {j: C(j, j, "train") for j in range(N)}  # site j's training split along its own model
    base = {i: own[0] if i == 0 else C(0, i, "train") for i in range(N)}  # ... and along the base model
    val = {(j, i): C(j, i, "val") for i in range(1, N) for j in range(i + 1)}  # site i's val, models known on its arrival
    for i in range(N):
        assert all(test[(j, i)]["files"] == test[(0, i)]["files"] for j in range(N)), "image order differs between models"
        for j in range(N):  # the offline mAP must reproduce each model's own val result
            got = mean_ap([test[(j, i)]], torch.zeros(len(test[(0, i)]["files"]), dtype=torch.long))
            assert abs(got[1] - test[(j, i)]["map"][1]) < 1e-6, (j, i, got, test[(j, i)]["map"])
    dev = "cuda" if torch.cuda.is_available() else "cpu"  # after ultralytics pinned the GPU

    # every rule maps (model j, pass) -> per-image score of site j; higher = more likely site j
    def pass_of(j, key, path):  # key: ("test", i) | ("val", i)
        jj = j if path == "own" else 0
        return test[(jj, key[1])] if key[0] == "test" else val[(jj, key[1])]

    keys = [("test", i) for i in range(N)] + [("val", i) for i in range(1, N)]
    rules = {}
    ll = {}  # card log-likelihoods per (path, site, K, feat, layer, key)
    for path in ("own", "base"):
        for j in range(N):
            tr = own[j] if path == "own" else base[j]
            for K in (1, 2, 4, 8):
                for feat in ("ms", "m"):
                    for li in range(NL):
                        x = tr["style"][li]
                        x = x[:, : x.shape[1] // 2] if feat == "m" else x
                        g = DiagGMM.fit(x.to(dev), K)
                        for key in keys:
                            if key[0] == "val" and j > key[1]:
                                continue
                            f = pass_of(j, key, path)["style"][li]
                            ll[(path, j, K, feat, li, key)] = g.logp((f[:, : f.shape[1] // 2] if feat == "m" else f).to(dev)).cpu()
    for path in ("own", "base"):
        for K in (1, 2, 4, 8):
            for feat in ("ms", "m"):
                for k in (1, 2, 4, 8, 16):
                    rules[("card", path, k, K, feat)] = lambda j, key, path=path, K=K, feat=feat, k=k: sum(
                        ll[(path, j, K, feat, li, key)] for li in range(k))
    dl = {}  # deep-feature GMM log-likelihoods per (path, site, K, key)
    for path in ("own", "base"):
        for j in range(N):
            tr = own[j] if path == "own" else base[j]
            for K in (1, 4):
                g = DiagGMM.fit(tr["pool"].to(dev), K)
                for key in keys:
                    if key[0] == "val" and j > key[1]:
                        continue
                    dl[(path, j, K, key)] = g.logp(pass_of(j, key, path)["pool"].to(dev)).cpu()
    for path in ("own", "base"):
        for K in (1, 4):
            rules[("deep", path, K)] = lambda j, key, path=path, K=K: dl[(path, j, K, key)]
        card, deep = rules[("card", path, 8, 4, "ms")], rules[("deep", path, 4)]
        rules[("fused", path)] = lambda j, key, card=card, deep=deep: card(j, key) + deep(j, key)
        sc = [float((f(1, ("val", 1)) - f(0, ("val", 1))).std()) for f in (card, deep)]
        rules[("fused-z", path)] = lambda j, key, card=card, deep=deep, sc=sc: card(j, key) / sc[0] + deep(j, key) / sc[1]
    for L in POOL[:-1]:  # depth of the deep part, base path only (its decisions do not depend on the adapters)
        gs = {j: DiagGMM.fit(base[j]["pools"][L].to(dev), 4) for j in range(N)}
        dL = {(j, key): gs[j].logp(pass_of(j, key, "base")["pools"][L].to(dev)).cpu() for j in range(N) for key in keys
              if not (key[0] == "val" and j > key[1])}
        rules[("deep", "base", 4, f"L{L}")] = lambda j, key, dL=dL: dL[(j, key)]
        rules[("fused", "base", f"L{L}")] = lambda j, key, dL=dL, card=rules[("card", "base", 8, 4, "ms")]: card(j, key) + dL[(j, key)]
    L = test[(0, 0)]["kl"].shape[1]
    e, late = range(L // 3), range(L - L // 3, L)
    rules[("bn-kl",)] = lambda j, key: -pass_of(j, key, "own")["kl"].mean(1)
    rules[("bn-w2",)] = lambda j, key: -pass_of(j, key, "own")["w2"].mean(1)
    terms = lambda P: (P["kl"].mean(1), P["kl"][:, e].mean(1), P["w2"][:, late].mean(1))  # noqa: E731
    scale = [torch.cat([terms(val[(j, 1)])[t] for j in range(2)]).mean() for t in range(3)]  # first new site's val only
    rules[("bn-miyazaki",)] = lambda j, key: -sum(t / s for t, s in zip(terms(pass_of(j, key, "own")), scale))
    ms = lambda P: [(P["style"][li][:, : P["style"][li].shape[1] // 2], P["style"][li][:, P["style"][li].shape[1] // 2 :].exp()) for li in (0, 1)]  # noqa: E731
    proto = {j: [(m.mean(0), s.mean(0)) for m, s in ms(base[j])] for j in range(N)}
    rules[("cdtta",)] = lambda j, key: -sum(bhattacharyya(m, s, *proto[j][t]) for t, (m, s) in enumerate(ms(pass_of(j, key, "base"))))
    unit = lambda P: F.normalize(P["pool"], dim=1)  # noqa: E731
    cent = {j: (F.normalize(unit(base[j]).mean(0, keepdim=True), dim=1), kmeans(unit(base[j]))) for j in range(N)}
    rules[("nm-mean",)] = lambda j, key: (unit(pass_of(j, key, "base")) @ cent[j][0].T).max(1).values
    rules[("nm-kmeans5",)] = lambda j, key: (unit(pass_of(j, key, "base")) @ cent[j][1].T).max(1).values

    rows, keep = [], {}
    for rk, fn in rules.items():
        S = {key: torch.stack([fn(j, key) for j in range((key[1] + 1) if key[0] == "val" else N)], 1) for key in keys}
        for q in [None] + a.q:
            b = torch.zeros(N)
            if q is not None:  # offsets in arrival order, each from the newest site's own val split
                for i in range(1, N):
                    s = S[("val", i)]
                    b[i] = float(((s[:, :i] + b[:i]).max(1).values - s[:, i]).quantile(1 - q))
            row = {"rule": rk[0], "setting": "/".join(map(str, rk[1:])), "q": "raw" if q is None else q}
            for i in range(N):
                d = (S[("test", i)] + b).argmax(1)
                row[f"acc{i}"] = round(float((d == i).float().mean()), 4)
                row[f"map50_{i}"], row[f"map_{i}"] = (round(v, 4) for v in mean_ap([test[(j, i)] for j in range(N)], d))
            if N == 2:
                s0, s1 = (S[("test", i)][:, 1] - S[("test", i)][:, 0] for i in range(2))
                dd = s1[None, :] - s0[:, None]
                row["auc"] = round(float((dd > 0).float().mean() + 0.5 * (dd == 0).float().mean()), 4)
            rows.append(row)
        if rk in (("card", "own", 8, 4, "ms"), ("card", "base", 8, 4, "ms"), ("bn-miyazaki",), ("bn-kl",), ("cdtta",), ("nm-mean",),
                  ("deep", "base", 4), ("fused", "own"), ("fused", "base"), ("fused-z", "own"), ("fused-z", "base")):
            keep["/".join(map(str, rk))] = {f"{k[0]}{k[1]}": v for k, v in S.items()}
    ref = []  # references: every image on one model, and the oracle
    for nm in [f"all-{j}" for j in range(N)] + ["oracle"]:
        row = {"rule": nm, "setting": "", "q": ""}
        for i in range(N):
            n = len(test[(0, i)]["files"])
            d = torch.full((n,), i if nm == "oracle" else int(nm.split("-")[1]), dtype=torch.long)
            row[f"acc{i}"] = round(float((d == i).float().mean()), 4)
            row[f"map50_{i}"], row[f"map_{i}"] = (round(v, 4) for v in mean_ap([test[(j, i)] for j in range(N)], d))
        ref.append(row)
    rows = ref + rows
    with open(a.out, "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[-1].keys()))
        w.writeheader()
        w.writerows(rows)
    per_layer = {f"{k[0]}{k[1]}": torch.stack([ll[("own", 1, 4, "ms", li, k)] - ll[("own", 0, 4, "ms", li, k)] for li in range(NL)], 1)
                 for k in keys} if N == 2 else None  # card log-likelihood ratio per layer (figures)
    torch.save({"scores": keep, "per_layer": per_layer, "files": {i: test[(0, i)]["files"] for i in range(N)}, "names": names},
               Path(a.out).with_suffix(".pt"))
    show = [r for r in rows if r["rule"] != "card" or r["setting"] in ("own/8/4/ms", "base/8/4/ms")]  # every non-card rule
    print("\n".join(" | ".join(f"{v}" for v in r.values()) for r in show if r["q"] in ("raw", 0.05, "")))


if __name__ == "__main__":
    main()