"""Cross-domain compression transfer for power-grid detection (Task 2). Student YOLO = detection loss + logit KD from a big teacher (binary KL on class scores, KL on DFL box distributions) + projection-alignment branch: student backbone features -> teacher class-logit space (training only) + optional multi-down / shared-up LoRA with a style router (multi-domain adaptation, mergeable per site) python gridkd.py train --data D.yaml --model yolo11n.pt --teacher T.pt -- epochs=100 device=0 name=s2 python gridkd.py eval --weights a.pt b.pt --data A.yaml B.yaml python gridkd.py merge --weights lora.pt --gates 1,0,0,0 --out site.pt (or --gates fog.yaml: mean gates of that domain) python gridkd.py prune --weights s2.pt --ratio 0.3 --out s2_p30.pt (then train --model s2_p30.pt to recover) python gridkd.py lsl --weights lt.pt --pos br.yaml --neg ref_1c.yaml --out lt_lsl.pt (LoRA on only where inputs look like br) python gridkd.py bnsw --weights lt.pt --base s2.pt --out lt_bnsw.pt (same, decided by the two models' BN statistics) python gridkd.py selftest """ import argparse from copy import deepcopy import math import sys from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from ultralytics.models.yolo.detect import DetectionTrainer from ultralytics.nn.modules import C2f, Conv from ultralytics.nn.tasks import DetectionModel, attempt_load_one_weight from ultralytics.utils.loss import v8DetectionLoss from ultralytics.utils.torch_utils import de_parallel, fuse_conv_and_bn, get_flops LAYER_ATTRS = ("f", "i", "type", "np") # ultralytics routes layers by these def _copy_layer_attrs(dst, src): for a in LAYER_ATTRS: if hasattr(src, a): setattr(dst, a, getattr(src, a)) # ----------------------------------------------------------------------------- LoRA + style router class StyleRouter(nn.Module): """Style code = channel mean/std of stem features (AdaIN statistics) -> softmax gates over K experts.""" def __init__(self, c, k, tau=1.0): super().__init__() self.fc, self.tau = nn.Linear(2 * c, k), tau self.logits = self.gates = None self.fixed = None # (k,) tensor pins the gates: one site / one style, or before merging def forward(self, f): s = torch.cat([f.mean((2, 3)), f.flatten(2).std(-1)], 1) self.logits = self.fc(s) g = (self.logits.float() / self.tau).softmax(-1) self.gates = g if self.fixed is None else self.fixed.to(g).expand_as(g) return f def __getstate__(self): # per-forward tensors are not state (non-leaf ones also break EMA deepcopy) return {**self.__dict__, "logits": None, "gates": None} class RoutedStem(nn.Module): """Layer 0 + router, so gates exist before any LoRA layer runs.""" def __init__(self, stem, router): super().__init__() self.stem, self.router = stem, router _copy_layer_attrs(self, stem) def forward(self, x): return self.router(self.stem(x)) class MultiLoRAConv(nn.Module): """y = act(BN(Wx) + s * B(sum_k g_k A_k x)): K style-specific down-projections A_k, one shared up-projection B.""" def __init__(self, m: Conv, router: StyleRouter, r=4, alpha=8): super().__init__() c, k = m.conv, router.fc.out_features self.m, self.k, self.r, self.s = m, k, r, alpha / r self.A = nn.Conv2d(c.in_channels, k * r, c.kernel_size, c.stride, c.padding, c.dilation, bias=False) self.B = nn.Conv2d(r, c.out_channels, 1, bias=False) nn.init.kaiming_uniform_(self.A.weight, a=math.sqrt(5)) nn.init.zeros_(self.B.weight) # starts exactly at the base model self._router = [router] # shared reference, deliberately not a submodule _copy_layer_attrs(self, m) def forward(self, x): m = self.m y = m.bn(m.conv(x)) if hasattr(m, "bn") else m.conv(x) # survives ultralytics fuse() a = self.A(x) n, _, h, w = a.shape g = self._router[0].gates.to(a.dtype).view(n, self.k, 1, 1, 1) d = self.s * self.B((a.view(n, self.k, self.r, h, w) * g).sum(1)) sw = getattr(self, "switch", None) # local-support switch: adapter only on inputs from its own domain if sw is None: return m.act(y + d) on = sw(x, y).to(d).view(n, 1, 1, 1) return m.act(on * (y + d) + (1 - on) * sw.off(y)) @torch.no_grad() def merged(self, g): """Fold LoRA for fixed gates g (k,) into a plain fused Conv -> zero deployment overhead.""" m = self.m if hasattr(m, "bn"): m.conv = fuse_conv_and_bn(m.conv, m.bn) delattr(m, "bn") m.forward = m.forward_fuse A = (self.A.weight.view(self.k, self.r, *self.A.weight.shape[1:]) * g.view(-1, 1, 1, 1, 1).to(self.A.weight)).sum(0) m.conv.weight += self.s * torch.einsum("or,rihw->oihw", self.B.weight[:, :, 0, 0], A).to(m.conv.weight) return m def inject_lora(model: DetectionModel, r=4, k=4, alpha=8, tau=1.0): seq = model.model stem = seq[0] router = StyleRouter(stem.conv.out_channels, k, tau) seq[0] = RoutedStem(stem, router) for mod in list(model.modules()): for name, child in list(mod.named_children()): if type(child) is Conv and child.conv.groups == 1 and child is not stem: # skips DWConv / stem setattr(mod, name, MultiLoRAConv(child, router, r, alpha)) return router def find_router(model): return next((m.router for m in model.modules() if isinstance(m, RoutedStem)), None) @torch.no_grad() def merge_lora(model, gates): """Replace every LoRA wrapper by its merged Conv and drop the router (in place).""" g = torch.as_tensor(gates, dtype=torch.float32) g = g / g.sum() for mod in list(model.modules()): for name, child in list(mod.named_children()): if isinstance(child, MultiLoRAConv): setattr(mod, name, child.merged(g)) elif isinstance(child, RoutedStem): setattr(mod, name, child.stem) return model def lora_params(model): return [p for m in model.modules() if isinstance(m, (MultiLoRAConv, StyleRouter)) for n, p in m.named_parameters() if not n.startswith("m.")] # ----------------------------------------------------------------------------- local-support switch (after LSL, arXiv 2610.02126) def style_stats(x): """Per-image channel mean and log-std (AdaIN statistics) of a feature map -> (n, 2c).""" x = x.float().flatten(2) return torch.cat([x.mean(-1), x.std(-1).clamp_min(1e-6).log()], 1) class DiagGMM(nn.Module): """Diagonal Gaussian mixture, fit by EM.""" def __init__(self, mu, var, logw): super().__init__() self.register_buffer("mu", mu) self.register_buffer("var", var) self.register_buffer("logw", logw) def _ll(self, x): # (n, d) -> (n, k): log w_k + log N(x | mu_k, var_k) return self.logw - 0.5 * ((x[:, None] - self.mu) ** 2 / self.var + self.var.log() + math.log(2 * math.pi)).sum(-1) def logp(self, x): return self._ll(x.to(self.mu)).logsumexp(-1) @classmethod @torch.no_grad() def fit(cls, x, k=4, iters=100, seed=0): x = x.double() n, d = x.shape k = min(k, n) floor = 1e-3 * x.var(0).mean() + 1e-8 # ponytail: one variance floor for all dims; per-dim floors if a dim is near-constant idx = torch.randperm(n, generator=torch.Generator().manual_seed(seed))[:k].to(x.device) g = cls(x[idx].clone(), x.var(0).expand(k, d).clone() + floor, torch.full((k,), -math.log(k), dtype=x.dtype, device=x.device)) for _ in range(iters): r = g._ll(x).softmax(-1) # responsibilities nk = r.sum(0) + 1e-12 mu = r.T @ x / nk[:, None] g = cls(mu, (r.T @ x**2 / nk[:, None] - mu**2).clamp_min(0) + floor, (nk / n).log()) return cls(g.mu.float(), g.var.float(), g.logw.float()) class DensitySwitch(nn.Module): """Adapter on for an image iff its style statistics at this layer are likelier under the adapter's own training data (pos) than under a small set of generic images (neg). Needs no data from earlier domains.""" def __init__(self, pos, neg): super().__init__() self.pos, self.neg = pos, neg self.hits = self.seen = 0.0 # on-rate bookkeeping for eval def forward(self, x, y=None): f = style_stats(x) on = (self.pos.logp(f) > self.neg.logp(f)).float() self.hits, self.seen = self.hits + float(on.sum()), self.seen + len(on) return on def off(self, y): return y class ConstSwitch(nn.Module): # adapter forced on (1) or off (0) def __init__(self, v): super().__init__() self.v = v def forward(self, x, y=None): return x.new_full((x.shape[0],), self.v) def off(self, y): return y class BNSwitch(nn.Module): """Adapter on for an image iff this layer's base output is likelier under the adapted model's BN statistics (target) than under the base model's (source); off also restores the source normalisation, so a closed switch is exactly the base layer. Both densities are read from the two checkpoints: no data needed. With a shared `acc`, each layer decides on the log-likelihood ratio summed over all layers run so far (one consistent decision per image).""" def __init__(self, bn_t, bn_s, acc=None, first=False): super().__init__() g, b = bn_t.weight.detach(), bn_t.bias.detach() # BN affine parameters were frozen with the base: same in both st, ss = (bn_t.running_var + bn_t.eps).sqrt(), (bn_s.running_var + bn_s.eps).sqrt() # base output o = g (z - m_t) / s_t + b; each model's BN statistics give a diagonal Gaussian over o self.register_buffer("mu", torch.stack([b, b + g * (bn_s.running_mean - bn_t.running_mean) / st])) self.register_buffer("var", torch.stack([bn_t.running_var, bn_s.running_var]) * (g / st) ** 2 + 1e-6) self.register_buffer("a", st / ss) # o -> source-normalised output: a * o + c self.register_buffer("c", b * (1 - st / ss) + g * (bn_t.running_mean - bn_s.running_mean) / ss) self.acc, self.first = acc, first self.hits = self.seen = 0.0 def forward(self, x, y): f = y.float().flatten(2) m, v = f.mean(-1)[:, None], f.var(-1, unbiased=False)[:, None] # (n, 1, c) ll = -0.5 * (((m - self.mu) ** 2 + v) / self.var + self.var.log()).sum(-1) # (n, 2): mean per-pixel log-density r = ll[:, 0] - ll[:, 1] if self.acc is not None: r = self.acc["r"] = r if self.first else self.acc["r"] + r on = (r > 0).float() self.hits, self.seen = self.hits + float(on.sum()), self.seen + len(on) return on def off(self, y): return y * self.a.view(1, -1, 1, 1).to(y) + self.c.view(1, -1, 1, 1).to(y) class SwitchedConv(nn.Module): """A conv without adapter whose BN statistics follow the same switch (on: adapted model's, off: base model's).""" def __init__(self, m, switch): super().__init__() self.m, self.switch = m, switch def forward(self, x): m = self.m y = m.bn(m.conv(x)) if hasattr(m, "bn") else m.conv(x) on = self.switch(x, y).to(y).view(-1, 1, 1, 1) return m.act(on * y + (1 - on) * self.switch.off(y)) def attach_bn_switches(model, base, cumulative=True): """BN switches on every BN layer of an adapted model, against its base model (same architecture, unfused).""" ref, mods = dict(base.named_modules()), dict(model.named_modules()) acc = {} if cumulative else None inner = {id(x.m) for x in mods.values() if isinstance(x, MultiLoRAConv)} for n, x in mods.items(): if isinstance(x, MultiLoRAConv): x.switch = BNSwitch(x.m.bn, ref[n].bn, acc) elif isinstance(x, Conv) and id(x) not in inner: parent, _, leaf = n.rpartition(".") stem = leaf == "stem" # RoutedStem holds layer 0's conv as .stem (the base has it at model.0); it runs first setattr(mods[parent], leaf, SwitchedConv(x, BNSwitch(x.bn, ref[parent if stem else n].bn, acc, first=stem))) sws = [x for x in model.modules() if isinstance(x, BNSwitch)] assert acc is None or sum(x.first for x in sws) == 1, "cumulative mode needs the routed stem to reset the sum" return len(sws) # ----------------------------------------------------------------------------- KD criterion def _bkl(s_logit, t_logit, T): """Binary KL(sigmoid(t/T) || sigmoid(s/T)) per element.""" q = (t_logit / T).sigmoid() return F.binary_cross_entropy_with_logits(s_logit / T, q, reduction="none") - F.binary_cross_entropy_with_logits( t_logit / T, q, reduction="none" ) class KDLoss(v8DetectionLoss): """v8 detection loss + [logit KD, projection alignment, router CE]. Items: box cls dfl kd pa rt. teacher: one model, or one expert per domain (aligned with `domains`, path substrings of im_file).""" def __init__(self, model, teacher=None, proj=None, feats=None, layers=(), T=2.0, w_kd=1.0, w_pa=1.0, router=None, w_rt=0.1, domains=(), route_ce=True): super().__init__(model) self.teachers = [teacher] if isinstance(teacher, nn.Module) else list(teacher or ()) self.pa_proj, self.feats, self.layers, self.T = proj, feats, tuple(layers), T # self.proj is v8's DFL self.w_kd, self.w_pa, self.router, self.w_rt, self.domains, self.route_ce = w_kd, w_pa, router, w_rt, domains, route_ce def _ids(self, batch): # domain index per image, -1 if none matches return torch.tensor([next((j for j, d in enumerate(self.domains) if d in f), -1) for f in batch["im_file"]], device=self.device) @torch.no_grad() def _teach(self, img, ids): if len(self.teachers) == 1: return self._flat(self.teachers[0](img)[1]) k, out = ids.clamp(min=0), None # unmatched images go to the first expert for j, te in enumerate(self.teachers): m = k == j if m.any(): d, c = self._flat(te(img[m])[1]) out = out or (d.new_zeros(len(img), *d.shape[1:]), c.new_zeros(len(img), *c.shape[1:])) out[0][m], out[1][m] = d, c return out def _flat(self, maps): b = maps[0].shape[0] d, c = torch.cat([x.view(b, self.no, -1) for x in maps], 2).split((self.reg_max * 4, self.nc), 1) return d.permute(0, 2, 1).float(), c.permute(0, 2, 1).float() # (B,A,4R) (B,A,nc) def __call__(self, preds, batch): loss, items = super().__call__(preds, batch) bs, T = batch["img"].shape[0], self.T extra = torch.zeros(3, device=self.device) # kd, pa, rt ids = self._ids(batch) if self.domains else None if self.teachers: t_dist, t_cls = self._teach(batch["img"], ids) s_dist, s_cls = self._flat(preds[1] if isinstance(preds, tuple) else preds) # anchors where either model sees an object; keeps background false positives in the loss w = torch.maximum(t_cls.sigmoid(), s_cls.detach().sigmoid()).amax(-1) wt = t_cls.sigmoid().amax(-1) kd_cls = (_bkl(s_cls, t_cls, T).sum(-1) * w).sum() / w.sum().clamp(min=1) sd, td = s_dist.view(bs, -1, 4, self.reg_max), t_dist.view(bs, -1, 4, self.reg_max) kd_box = F.kl_div((sd / T).log_softmax(-1), (td / T).log_softmax(-1), reduction="none", log_target=True) kd_box = (kd_box.sum(-1).mean(-1) * wt).sum() / wt.sum().clamp(min=1) extra[0] = (kd_cls + kd_box) * T * T if self.pa_proj is not None: p = torch.cat([pj(self.feats[i]).flatten(2) for i, pj in zip(self.layers, self.pa_proj)], 2) extra[1] = (_bkl(p.permute(0, 2, 1).float(), t_cls, T).sum(-1) * w).sum() / w.sum().clamp(min=1) * T * T if self.router is not None and self.route_ce and self.domains: if (ids >= 0).any(): extra[2] = F.cross_entropy(self.router.logits.float()[ids >= 0], ids[ids >= 0]) wvec = torch.tensor([self.w_kd, self.w_pa, self.w_rt], device=self.device) return torch.cat([loss, extra * wvec * bs]), torch.cat([items, extra.detach()]) # ----------------------------------------------------------------------------- trainer class KDTrainer(DetectionTrainer): def __init__(self, kd=None, **kw): self.kd = kd or {} super().__init__(**kw) self.add_callback("on_pretrain_routine_end", KDTrainer._attach) def get_model(self, cfg=None, weights=None, verbose=True): # a pruned net no longer matches its yaml, so train the loaded module itself model = weights if getattr(weights, "pruned", False) else super().get_model(cfg, weights, verbose) kd = self.kd if kd.get("lora_r"): inject_lora(model, kd["lora_r"], kd["lora_k"], kd["lora_alpha"]) if kd.get("teacher") and kd.get("w_pa"): layers, ch = kd["pa_layers"], {} hs = [model.model[i].register_forward_hook(lambda m, a, o, i=i: ch.__setitem__(i, o.shape[1])) for i in layers] model.eval()(torch.zeros(1, 3, 64, 64)) # probe channel counts model.train() [h.remove() for h in hs] nc = model.model[-1].nc model.kd_proj = nn.ModuleList(nn.Sequential(Conv(ch[i], ch[i], 1), nn.Conv2d(ch[i], nc, 1)) for i in layers) return model def get_validator(self): v = super().get_validator() self.loss_names = "box_loss", "cls_loss", "dfl_loss", "kd_loss", "pa_loss", "rt_loss" return v @staticmethod def _attach(trainer): """After EMA/optimizer exist: hooks + KD criterion on the live model only (keeps checkpoints clean).""" kd, model = trainer.kd, de_parallel(trainer.model) teachers, feats = [], None for w in filter(None, (kd.get("teacher") or "").split(",")): # one teacher, or one expert per domain t, _ = attempt_load_one_weight(w, device=trainer.device, fuse=True) assert t.model[-1].nc == model.model[-1].nc, "teacher/student class sets differ" teachers.append(t.requires_grad_(False).eval()) if hasattr(model, "kd_proj"): feats = {} for i in kd["pa_layers"]: model.model[i].register_forward_hook(lambda m, a, o, i=i: feats.__setitem__(i, o)) router = find_router(model) if router is not None: # LoRA stage: freeze the compressed student, train adapters + router (+ projector) keep = {id(p) for p in lora_params(model)} | {id(p) for p in getattr(model, "kd_proj", nn.Module()).parameters()} for p in model.parameters(): p.requires_grad_(id(p) in keep) doms = tuple(kd.get("domains", ())) assert len(teachers) <= 1 or len(teachers) == len(doms), "per-domain experts need one teacher per domain" model.criterion = KDLoss( model, teachers, getattr(model, "kd_proj", None), feats, kd.get("pa_layers", ()), kd.get("T", 2.0), kd.get("w_kd", 1.0), kd.get("w_pa", 1.0), router, kd.get("w_rt", 0.1), doms, route_ce=router is not None and router.fc.out_features >= len(doms), # K=1: plain LoRA, no router CE ) trainer.ema.ema.criterion = KDLoss(trainer.ema.ema) # val loss needs the same 6 items; stripped in save_model def save_model(self): ema = self.ema.ema c = ema.__dict__.pop("criterion", None) # keep checkpoints loadable without gridkd.KDLoss try: super().save_model() finally: ema.criterion = c # ----------------------------------------------------------------------------- CLI def _overrides(pairs): out = {} for s in pairs: k, v = s.split("=", 1) try: v = eval(v, {}, {}) # numbers / bools / lists except Exception: pass out[k] = v return out def load_plain(weights): from ultralytics import YOLO y = YOLO(weights) if hasattr(y.model, "kd_proj"): del y.model.kd_proj # training-only branch return y def cmd_train(a): kd = dict(teacher=a.teacher, T=a.T, w_kd=a.w_kd, w_pa=a.w_pa, pa_layers=[int(i) for i in a.pa_layers.split(",")], lora_r=a.lora_r, lora_k=a.lora_k, lora_alpha=a.lora_alpha, w_rt=a.w_rt, domains=[d for d in a.domains.split(",") if d]) ov = {**dict(model=a.model, data=a.data, workers=4, exist_ok=True), **_overrides(a.rest)} # CLI overrides win KDTrainer(kd=kd, overrides=ov).train() def cmd_eval(a): rows = [] for w in a.weights: y = load_plain(w) router = find_router(y.model) if router is not None and a.gates: router.fixed = torch.tensor([float(x) for x in a.gates.split(",")]) n, gf = sum(p.numel() for p in y.model.parameters()) / 1e6, get_flops(y.model, a.imgsz) tag = Path(w).parent.parent.name if Path(w).parent.name == "weights" else Path(w).stem sws = [s for s in y.model.modules() if isinstance(s, (DensitySwitch, BNSwitch))] for d in a.data: for s in sws: s.hits = s.seen = 0.0 m = y.val(data=d, split=a.split, imgsz=a.imgsz, batch=a.batch, device=a.device, workers=4, plots=False, verbose=False) on = sum(s.hits for s in sws) / max(sum(s.seen for s in sws), 1) if sws else None # share of (image, layer) switches on rows.append((tag, Path(d).stem, n, gf, m.box.map50, m.box.map, on)) print(f"\n{'model':24s} {'domain':10s} {'params(M)':>9s} {'GFLOPs':>7s} {'mAP50':>7s} {'mAP50-95':>8s} {'on-rate':>7s}") for r in rows: print(f"{r[0]:24s} {r[1]:10s} {r[2]:9.2f} {r[3]:7.1f} {r[4]:7.3f} {r[5]:8.3f} {'' if r[6] is None else f'{r[6]:7.3f}'}") if a.out: Path(a.out).write_text("model,domain,params_M,gflops,map50,map50_95,on_rate\n" + "".join( f"{r[0]},{r[1]},{r[2]:.3f},{r[3]:.2f},{r[4]:.4f},{r[5]:.4f},{'' if r[6] is None else f'{r[6]:.4f}'}\n" for r in rows)) class C2fSplit(nn.Module): """C2f/C3k2 with cv1 cut into two convs (exact): chunk+cat of one tensor breaks DepGraph's channel indexing.""" def __init__(self, m): super().__init__() self.cv0, self.cv1 = (_conv_slice(m.cv1, sl) for sl in (slice(0, m.c), slice(m.c, 2 * m.c))) self.m, self.cv2 = m.m, m.cv2 _copy_layer_attrs(self, m) def forward(self, x): y = [self.cv0(x), self.cv1(x)] y.extend(m(y[-1]) for m in self.m) return self.cv2(torch.cat(y, 1)) def _conv_slice(conv, sl): # Conv keeping output channels sl c = deepcopy(conv) c.conv.weight = nn.Parameter(conv.conv.weight[sl].clone()) c.conv.out_channels = c.conv.weight.shape[0] for k in ("weight", "bias"): setattr(c.bn, k, nn.Parameter(getattr(conv.bn, k)[sl].clone())) c.bn.running_mean, c.bn.running_var = conv.bn.running_mean[sl].clone(), conv.bn.running_var[sl].clone() c.bn.num_features = c.conv.out_channels return c def cmd_prune(a): """DepGraph structured channel pruning (L2 group magnitude). C2PSA attention and the head's output convs are kept.""" import torch_pruning as tp y = load_plain(a.weights) model, det = y.model.float(), y.model.model[-1] keep = [det.dfl, *(b[-1] for b in (*det.cv2, *det.cv3)), *(m for m in model.model if type(m).__name__ == "C2PSA")] model.requires_grad_(True).eval() x = torch.randn(1, 3, a.imgsz, a.imgsz) with torch.no_grad(): ref = torch.cat([t.flatten() for t in model(x)[1]]) for mod in list(model.modules()): for name, child in list(mod.named_children()): if isinstance(child, C2f): # C3k2 included setattr(mod, name, C2fSplit(child)) with torch.no_grad(): err = (torch.cat([t.flatten() for t in model(x)[1]]) - ref).abs().max().item() assert err < 1e-4, f"C2f split changed outputs by {err}" det.training = True # BN frozen, Detect returns raw maps for tracing n0, f0 = sum(p.numel() for p in model.parameters()), get_flops(model, a.imgsz) tp.pruner.MetaPruner(model, x, tp.importance.GroupMagnitudeImportance(p=2), pruning_ratio=a.ratio, ignored_layers=keep, round_to=8).step() model.eval() with torch.no_grad(): model(x) # still runs end to end model.pruned = True n1, f1 = sum(p.numel() for p in model.parameters()), get_flops(model, a.imgsz) torch.save({**y.ckpt, "model": model, "ema": None}, a.out) print(f"pruned {a.ratio:.0%} channels: params {n0 / 1e6:.2f}M -> {n1 / 1e6:.2f}M, GFLOPs {f0:.1f} -> {f1:.1f}, saved {a.out}") @torch.no_grad() def domain_gates(y, data, device): """Mean router gates over one domain's val images = the fixed gates of that site's merged model.""" stem, g = next(m for m in y.model.modules() if isinstance(m, RoutedStem)), [] def hook(m, a, o): if a[0].any(): # skip the validator's all-zero warmup image g.append(m.router.gates.float().cpu()) h = stem.register_forward_hook(hook) y.val(data=data, split="val", device=device, workers=4, plots=False, verbose=False) h.remove() return torch.cat(g).mean(0) def cmd_merge(a): y = load_plain(a.weights) if a.gates.endswith(".yaml"): g = domain_gates(y, a.gates, a.device) y = load_plain(a.weights) # val left inference-mode (fused) tensors behind; merge a fresh copy else: g = [float(x) for x in a.gates.split(",")] print("gates", [round(float(v), 3) for v in g]) merge_lora(y.model, g) torch.save({**y.ckpt, "model": y.model.float(), "ema": None}, a.out) # fp32: BN-fused weights overflow fp16 (YOLO.save halves) print("saved", a.out, sum(p.numel() for p in y.model.parameters()) / 1e6, "M params") @torch.no_grad() def layer_stats(y, data, split, device): """Style statistics of every LoRA conv's input over one split, through the validator's own preprocessing.""" mods = [m for m in y.model.modules() if isinstance(m, MultiLoRAConv)] out, live = [[] for _ in mods], [False] # only inside the validator's batch loop: skips warmup and the 32x32 FLOPs probe def grab(i): def f(m, a): if live[0]: out[i].append(style_stats(a[0]).cpu()) return f def start(_): live[0] = True def end(_): live[0] = False y.add_callback("on_val_batch_start", start) y.add_callback("on_val_batch_end", end) hs = [m.register_forward_pre_hook(grab(i)) for i, m in enumerate(mods)] try: y.val(data=data, split=split, device=device, workers=4, plots=False, verbose=False) finally: for h in hs: h.remove() y.callbacks["on_val_batch_start"].remove(start) y.callbacks["on_val_batch_end"].remove(end) out = [torch.cat(o) for o in out] assert all(o.isfinite().all() for o in out), "non-finite style statistics" return mods, out def cmd_lsl(a): """Fit local-support switches for one domain adapter: pos = its own training split (adapter on, as in training), neg = generic images through the base model (adapter off). No data from earlier domains is used.""" y = load_plain(a.weights) mods, pos = layer_stats(y, a.pos, "train", a.device) for m in mods: m.switch = ConstSwitch(0.0) _, neg = layer_stats(y, a.neg, "val", a.device) dev = "cuda" if torch.cuda.is_available() else "cpu" y = load_plain(a.weights) # val left inference-mode (fused) tensors behind; attach switches to a fresh copy mods = [m for m in y.model.modules() if isinstance(m, MultiLoRAConv)] tpr, tnr = [], [] for m, p, q in zip(mods, pos, neg): p, q = p.to(dev), q.to(dev) s = DensitySwitch(DiagGMM.fit(p, a.k), DiagGMM.fit(q, a.k_neg)).to(dev) tpr.append(float((s.pos.logp(p) > s.neg.logp(p)).float().mean())) tnr.append(float((s.pos.logp(q) <= s.neg.logp(q)).float().mean())) m.switch = s.cpu() print(f"{len(mods)} switches | {len(pos[0])} own images, {len(neg[0])} generic | fit-set on-rate {sum(tpr) / len(tpr):.3f}, off-rate on generic {sum(tnr) / len(tnr):.3f}") torch.save({**y.ckpt, "model": y.model.float(), "ema": None}, a.out) print("saved", a.out) def cmd_bnsw(a): """BN switches for an adapter trained on the new domain only, against its base model: no data needed. adabn / srcbn are attribution controls: adapted BN statistics without LoRA / LoRA with the base model's statistics.""" y = load_plain(a.weights) base = load_plain(a.base).model.float() if a.mode == "adabn": for m in y.model.modules(): if isinstance(m, MultiLoRAConv): m.switch = ConstSwitch(0.0) n = "LoRA removed, adapted BN statistics kept" elif a.mode == "srcbn": ref = dict(base.named_modules()) bns = [(x, ref[k.replace(".stem.bn", ".bn").replace(".m.bn", ".bn")]) for k, x in y.model.named_modules() if isinstance(x, nn.BatchNorm2d)] for x, r in bns: x.running_mean.copy_(r.running_mean), x.running_var.copy_(r.running_var) n = f"LoRA kept, base BN statistics on all {len(bns)} BN layers" else: n = f"{attach_bn_switches(y.model, base, a.mode == 'cum')} BN switches ({a.mode})" torch.save({**y.ckpt, "model": y.model.float(), "ema": None}, a.out) print(f"{n} | saved {a.out}") def selftest(): """LoRA merge must be exact; KD loss must run forward/backward. No downloads needed.""" torch.manual_seed(0) s = DetectionModel("yolo11n.yaml", nc=2, verbose=False) router = inject_lora(s, r=4, k=3) s.eval() x = torch.rand(2, 3, 128, 128) neck = [] # compare head inputs: a random model's head output is just its bias s.model[-1].register_forward_pre_hook(lambda m, a: neck.append(torch.cat([t.flatten(1) for t in a[0]], 1))) router.fixed = torch.tensor([0.2, 0.5, 0.3]) s(x) # B = 0 -> base model for m in s.modules(): if isinstance(m, MultiLoRAConv): nn.init.normal_(m.B.weight, std=0.1) s(x) merge_lora(s, router.fixed)(x) base, y0, y1 = neck assert not any(isinstance(m, (MultiLoRAConv, RoutedStem)) for m in s.modules()) change, err = (y0 - base).abs().max(), (y0 - y1).abs().max() assert change > 0.05 * base.abs().max() and err < 1e-3 * change, (change, err) from types import SimpleNamespace st = DetectionModel("yolo11n.yaml", nc=2, verbose=False) st.args = SimpleNamespace(box=7.5, cls=0.5, dfl=1.5) te = DetectionModel("yolo11s.yaml", nc=2, verbose=False).eval() feats = {} for i in (4, 6, 10): st.model[i].register_forward_hook(lambda m, a, o, i=i: feats.__setitem__(i, o)) proj = nn.ModuleList(nn.Sequential(Conv(c, c, 1), nn.Conv2d(c, 2, 1)) for c in (128, 128, 256)) crit = KDLoss(st, te, proj, feats, (4, 6, 10)) batch = dict(img=torch.rand(2, 3, 128, 128), batch_idx=torch.tensor([0.0, 1.0]), cls=torch.tensor([[0.0], [1.0]]), bboxes=torch.tensor([[0.5, 0.5, 0.2, 0.3], [0.3, 0.6, 0.1, 0.2]]), im_file=["a", "b"]) st.train() loss, items = crit(st(batch["img"]), batch) loss.sum().backward() assert items.shape == (6,) and torch.isfinite(items).all() and items[3] > 0 and items[4] > 0, items assert all(p.grad is not None for p in proj.parameters()) # per-domain experts: two copies of one teacher must reproduce single-teacher KD exactly two = KDLoss(st, [te, te], proj, feats, (4, 6, 10), domains=("a", "b")) with torch.no_grad(): preds = st(batch["img"]) kd1, kd2 = crit(preds, batch)[1][3:5], two(preds, batch)[1][3:5] assert torch.allclose(kd1, kd2, atol=1e-5), (kd1, kd2) # local-support switch: the likelihood ratio separates two domains; a closed switch gives exactly the base model ga, gb = DiagGMM.fit(torch.randn(500, 6), 2), DiagGMM.fit(torch.randn(500, 6) + 3, 2) za, zb = torch.randn(200, 6), torch.randn(200, 6) + 3 acc = float(((ga.logp(za) > gb.logp(za)).float().mean() + (gb.logp(zb) > ga.logp(zb)).float().mean()) / 2) assert acc > 0.97, acc s3 = DetectionModel("yolo11n.yaml", nc=2, verbose=False) inject_lora(s3, r=4, k=1) s3.eval() lo, hs = [m for m in s3.modules() if isinstance(m, MultiLoRAConv)], [] s3.model[-1].register_forward_pre_hook(lambda m, a: hs.append(torch.cat([t.flatten(1) for t in a[0]], 1))) with torch.no_grad(): s3(x) for m in lo: nn.init.normal_(m.B.weight, std=0.1) m.switch = ConstSwitch(0.0) s3(x) for m in lo: m.switch = ConstSwitch(1.0) s3(x) b0, off, on = hs assert torch.equal(b0, off) and (on - b0).abs().max() > 0.05 * b0.abs().max() def neck(model): h = [] k = model.model[-1].register_forward_pre_hook(lambda m, a: h.append(torch.cat([t.flatten(1) for t in a[0]], 1))) with torch.no_grad(): model(x) k.remove() return h[0] # BN switch: closed it must be exactly the base model (source BN restored everywhere), open the adapted one base = DetectionModel("yolo11n.yaml", nc=2, verbose=False).eval() for v in base.modules(): if isinstance(v, nn.BatchNorm2d): v.running_mean.normal_(0, 0.5), v.running_var.uniform_(0.5, 2) ad = deepcopy(base) inject_lora(ad, r=4, k=1) ad.eval() for v in ad.modules(): if isinstance(v, nn.BatchNorm2d): v.running_mean.add_(torch.randn_like(v.running_mean)), v.running_var.mul_(2) if isinstance(v, MultiLoRAConv): nn.init.normal_(v.B.weight, std=0.1) want_on, want_off = neck(ad), neck(base) nsw = attach_bn_switches(ad, base) bsw = [v for v in ad.modules() if isinstance(v, BNSwitch)] for v in bsw: v.forward = lambda x, y: y.new_zeros(len(y)) got_off = neck(ad) for v in bsw: v.forward = lambda x, y: y.new_ones(len(y)) got_on = neck(ad) e_off, e_on = ((g - w).abs().max() / w.abs().max() for g, w in ((got_off, want_off), (got_on, want_on))) assert e_off < 1e-4 and e_on < 1e-5 and (want_on - want_off).abs().max() > 0.05 * want_off.abs().max(), (e_off, e_on) print(f"selftest ok | LoRA change {float(change):.3g}, merge err {float(err):.3g} | switch acc {acc:.3f} | " f"{nsw} BN switches, closed err {float(e_off):.2g}, open err {float(e_on):.2g} | loss items", [round(float(v), 4) for v in items]) def main(): p = argparse.ArgumentParser() sp = p.add_subparsers(dest="cmd", required=True) t = sp.add_parser("train") t.add_argument("--data", required=True) t.add_argument("--model", default="yolo11n.pt") t.add_argument("--teacher", default="", help="weights, or comma list = one expert per --domains entry") t.add_argument("--T", type=float, default=2.0) t.add_argument("--w-kd", type=float, default=1.0) t.add_argument("--w-pa", type=float, default=1.0) t.add_argument("--pa-layers", default="4,6,10") # YOLO11 backbone P3/P4/P5 t.add_argument("--lora-r", type=int, default=0) t.add_argument("--lora-k", type=int, default=4) t.add_argument("--lora-alpha", type=float, default=8) t.add_argument("--w-rt", type=float, default=0.1) t.add_argument("--domains", default="") # path substrings -> router labels t.add_argument("rest", nargs="*", help="ultralytics overrides key=value") e = sp.add_parser("eval") e.add_argument("--weights", nargs="+", required=True) e.add_argument("--data", nargs="+", required=True) e.add_argument("--split", default="test") e.add_argument("--gates", default="") e.add_argument("--imgsz", type=int, default=640) e.add_argument("--batch", type=int, default=32) e.add_argument("--device", default="0") e.add_argument("--out", default="", help="also write the table as CSV") m = sp.add_parser("merge") m.add_argument("--weights", required=True) m.add_argument("--gates", required=True, help="comma list, or a domain data.yaml -> mean gates on its val split") m.add_argument("--out", required=True) m.add_argument("--device", default="0") r = sp.add_parser("prune") r.add_argument("--weights", required=True) r.add_argument("--ratio", type=float, default=0.3, help="fraction of channels removed per layer group") r.add_argument("--out", required=True) r.add_argument("--imgsz", type=int, default=640) s = sp.add_parser("lsl") s.add_argument("--weights", required=True, help="LoRA run trained on one domain only") s.add_argument("--pos", required=True, help="that domain's data.yaml; its train split fits the on-density") s.add_argument("--neg", required=True, help="generic images data.yaml (val split), e.g. ref_coco128/ref_1c.yaml") s.add_argument("--k", type=int, default=4, help="GMM components, own domain") s.add_argument("--k-neg", type=int, default=1, help="GMM components, generic images") s.add_argument("--out", required=True) s.add_argument("--device", default="0") s = sp.add_parser("bnsw") s.add_argument("--weights", required=True, help="LoRA run trained on one domain only") s.add_argument("--base", required=True, help="the model it was adapted from (its BN statistics describe the old domain)") s.add_argument("--mode", choices=("cum", "local", "adabn", "srcbn"), default="cum", help="decide on the ratio summed over layers so far, or per layer; adabn/srcbn: attribution controls") s.add_argument("--out", required=True) sp.add_parser("selftest") a = p.parse_args() {"train": cmd_train, "eval": cmd_eval, "merge": cmd_merge, "prune": cmd_prune, "lsl": cmd_lsl, "bnsw": cmd_bnsw, "selftest": lambda _: selftest()}[a.cmd](a) if __name__ == "__main__": sys.path.insert(0, str(Path(__file__).parent)) __import__("gridkd").main() # classes pickle as gridkd.*, not __main__.*