pei2333's picture
Add files using upload-large-folder tool
5f0e48f verified
Raw History Blame Contribute Delete
4.86 kB
"""Image-level routing between an old-site model and a new-site adapter with per-site density cards.
Each site keeps a card: per-layer diagonal GMMs over per-image style statistics (channel mean, log-std) of the first k
LoRA-layer inputs, fit on that site's training images along that site's own model, when its data was at hand. At test
time an image goes to the site whose card explains it better (each card scored along its own model); the chosen model
runs with its own BN statistics and LoRA, so there is never a mix of the two. Needs no old-site data during adaptation.
Two thresholds on the log-likelihood ratio: 0, and the q-quantile on the new site's val split (keeps 1-q of it routed
to the adapter; misrouting a new-site image to the old model costs far more than the reverse).
python route_cards.py --weights lt_bncum.pt --src cn.yaml --tgt br.yaml --k 8 --device 0 --out B_eval_cards.csv
"""
import argparse
import torch
from gridkd import * # noqa: F401,F403 (the checkpoint pickles gridkd classes under __main__)
def force(sws, v): # every BN switch closed (0: base model exactly) or open (1: adapter exactly)
for s in sws:
s.forward = lambda x, y, v=v: y.new_full((len(y),), v)
def main():
p = argparse.ArgumentParser()
p.add_argument("--weights", required=True, help="adapter with BN switches (gridkd.py bnsw)")
p.add_argument("--src", required=True, help="old site data.yaml (train split fits its card)")
p.add_argument("--tgt", required=True, help="new site data.yaml (train split fits its card)")
p.add_argument("--k", type=int, default=8, help="first k LoRA layers feed the cards")
p.add_argument("--gmm-k", type=int, default=4)
p.add_argument("--q", type=float, default=0.05)
p.add_argument("--out", required=True)
p.add_argument("--device", default="0")
a = p.parse_args()
def stats(v, data, split): # CPU tensors; no torch.cuda call before ultralytics has pinned the GPU
y = load_plain(a.weights)
force([m for m in y.model.modules() if isinstance(m, BNSwitch)], v)
return layer_stats(y, data, split, a.device)[1][: a.k]
cards = [[DiagGMM.fit(s, a.gmm_k) for s in stats(v, d, "train")] for v, d in ((0.0, a.src), (1.0, a.tgt))]
llr = lambda f0, f1: sum(g.logp(f) for g, f in zip(cards[1], f1)) - sum(g.logp(f) for g, f in zip(cards[0], f0))
val = llr(stats(0.0, a.tgt, "val"), stats(1.0, a.tgt, "val"))
tau = float(val.quantile(a.q))
print(f"new-site val: n={len(val)}, routed to adapter at 0: {float((val > 0).float().mean()):.3f}, tau={tau:.4g}")
y = load_plain(a.weights)
m = y.model
sws = [x for x in m.modules() if isinstance(x, BNSwitch)]
lora = [x for x in m.modules() if isinstance(x, MultiLoRAConv)][: a.k]
feats, tally, live, thr, seen = [None] * a.k, [0.0, 0.0], [False], [0.0], []
for i, x in enumerate(lora): # module order, as the cards were fit
x.register_forward_pre_hook(lambda mod, inp, i=i: feats.__setitem__(i, style_stats(inp[0]).cpu()))
def routed(x, *args, **kw):
outs, ll = [], []
for v, card in zip((0.0, 1.0), cards):
force(sws, v)
o = type(m).forward(m, x, *args, **kw)
outs.append(o[0] if isinstance(o, (list, tuple)) else o)
ll.append(sum(g.logp(f) for g, f in zip(card, feats)))
on = (ll[1] - ll[0] > thr[0]).to(outs[0].device)
if live[0]: # validator batches only, not warmup or the FLOPs probe
tally[0], tally[1] = tally[0] + float(on.sum()), tally[1] + len(on)
seen.append(ll[1] - ll[0])
return torch.where(on.view(-1, *[1] * (outs[0].dim() - 1)), outs[1], outs[0])
n, gf = sum(q.numel() for q in m.parameters()) / 1e6, 2 * get_flops(m, 640) # this evaluation runs both models
m.forward = routed
y.add_callback("on_val_batch_start", lambda _: live.__setitem__(0, True))
y.add_callback("on_val_batch_end", lambda _: live.__setitem__(0, False))
rows, test = [], {}
for t, tag in ((0.0, "cards"), (tau, f"cards_q{round(a.q * 100)}")):
thr[0] = t
for d in (a.src, a.tgt):
tally[:], seen[:] = [0.0, 0.0], []
r = y.val(data=d, split="test", device=a.device, workers=4, plots=False, verbose=False)
test[Path(d).stem] = torch.cat(seen)
rows.append(f"{Path(a.weights).stem.replace('bncum', tag)},{Path(d).stem},{n:.3f},{gf:.2f},{r.box.map50:.4f},{r.box.map:.4f},{tally[0] / max(tally[1], 1):.4f}\n")
print(rows[-1].strip())
(s0, t0) = test.values()
d = t0[None, :] - s0[:, None]
print(f"test AUC (new site above old site) {float((d > 0).float().mean() + 0.5 * (d == 0).float().mean()):.4f}")
Path(a.out).write_text("model,domain,params_M,gflops,map50,map50_95,on_rate\n" + "".join(rows))
if __name__ == "__main__":
main()