Download code/deploy_route.py from pei2333/Grid_CrossDomain_Compress_Delivery_20261105: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/resolve/main/code/deploy_route.py
- Command line
-
hf download hf://datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/code/deploy_route.py
-
curl -L -o deploy_route.py https://huggingface.co/datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/resolve/main/code/deploy_route.py
13.4 kB
| """Deployable density-card routing: one merged model and one density card per site. | |
| The layers the cards read (up to the k-th LoRA conv) run on both site models; each image then finishes on the model | |
| whose card explains it better, so the rest of the network runs once. Cards and threshold as in route_cards.py, fit | |
| here along the merged models themselves. Checks the result equals running both models in full, then reports test mAP | |
| and GFLOPs. Latency: bench_latency.py (single runs on the shared server drift, so it times all paths interleaved). | |
| python deploy_route.py --base s2.pt --site lt_merged.pt --lora lt.pt --src cn.yaml --tgt br.yaml --device 0 --out B_eval_deploy.csv | |
| --mode fused: fused cards (route_lab.py "fused/base": early-layer style + pooled layer-10 features, all along the base | |
| model, threshold 0 with --q 0). The base model's backbone decides; images kept on the old site finish on it, the rest | |
| run the new site's model from the input. | |
| """ | |
| import argparse | |
| import math | |
| import torch | |
| from gridkd import * # noqa: F401,F403 | |
| def stats(y, names, data, split, device, pool=None): | |
| """Per-image style statistics of the named convs' inputs over one split (validator batches only); with pool, the | |
| pooled output of that top-level layer last.""" | |
| mods, out, live = dict(y.model.named_modules()), [[] for _ in range(len(names) + (pool is not None))], [False] | |
| def grab(i): | |
| def f(m, a): | |
| if live[0]: | |
| out[i].append(style_stats(a[0]).cpu()) | |
| return f | |
| hs = [mods[n].register_forward_pre_hook(grab(i)) for i, n in enumerate(names)] | |
| if pool is not None: | |
| hs.append(y.model.model[pool].register_forward_hook(lambda m, a, o: out[-1].append(o.float().mean((2, 3)).cpu()) if live[0] else None)) | |
| start, end = (lambda _: live.__setitem__(0, True)), (lambda _: live.__setitem__(0, False)) | |
| y.add_callback("on_val_batch_start", start) | |
| y.add_callback("on_val_batch_end", end) | |
| y.val(data=data, split=split, device=device, workers=4, plots=False, verbose=False) | |
| for h in hs: | |
| h.remove() | |
| y.callbacks["on_val_batch_start"].remove(start) | |
| y.callbacks["on_val_batch_end"].remove(end) | |
| return [torch.cat(o) for o in out] | |
| def run(m, x, y, lo, hi): | |
| """Ultralytics' forward over layers [lo, hi); y holds the kept outputs of the layers before lo.""" | |
| for layer in m.model[lo:hi]: | |
| if layer.f != -1: | |
| x = y[layer.f] if isinstance(layer.f, int) else [x if j == -1 else y[j] for j in layer.f] | |
| x = layer(x) | |
| y.append(x if layer.i in m.save else None) | |
| return x[0] if isinstance(x, (list, tuple)) else x | |
| def style_fast(x): | |
| """style_stats(x) in fewer kernels: channel mean and log of the (unbiased) std clamped at 1e-6.""" | |
| v, m = torch.var_mean(x.float().flatten(2), dim=-1) | |
| return torch.cat([m, 0.5 * v.clamp_min(1e-12).log()], 1) | |
| class PackedCard: | |
| """One site's GMMs (one per feature part) as one affine map of [z^2, z], z = the parts concatenated: a diagonal | |
| Gaussian's log-density is linear in x^2 and x, so one matmul scores every component of every part.""" | |
| def __init__(self, gmms): | |
| K, dims = gmms[0].mu.shape[0], [g.mu.shape[1] for g in gmms] | |
| assert all(g.mu.shape[0] == K for g in gmms) | |
| D, W, b, o = sum(dims), torch.zeros(2 * sum(dims), len(gmms) * K, dtype=torch.float64), torch.zeros(len(gmms) * K, dtype=torch.float64), 0 | |
| for i, g in enumerate(gmms): | |
| mu, var, d, c = g.mu.double(), g.var.double(), dims[i], slice(i * K, (i + 1) * K) | |
| W[o:o + d, c], W[D + o:D + o + d, c] = (-0.5 / var).T, (mu / var).T | |
| b[c] = g.logw.double() - 0.5 * (var.log().sum(1) + d * math.log(2 * math.pi) + (mu**2 / var).sum(1)) | |
| o += d | |
| self.W, self.b, self.L, self.K = W, b, len(gmms), K | |
| def to(self, device): | |
| self.W, self.b = self.W.to(device), self.b.to(device) | |
| return self | |
| def logp(self, feats): # (n,): sum over parts of that part's GMM log-density | |
| z = torch.cat(feats, 1).double() | |
| return (torch.cat([z * z, z], 1) @ self.W + self.b).view(len(z), self.L, self.K).logsumexp(-1).sum(-1) | |
| class Router: | |
| def __init__(self, models, names, cards, tau): | |
| self.m, self.cards, self.tau, self.dev = models, [PackedCard(c) for c in cards], tau, None | |
| self.split = max(int(n.split(".")[1]) for n in names) + 1 # first layer that runs on one model only | |
| self.f = [[None] * len(names) for _ in models] | |
| for j, m in enumerate(models): | |
| mods = dict(m.named_modules()) | |
| for i, n in enumerate(names): | |
| mods[n].register_forward_pre_hook(self._keep(j, i)) | |
| def _keep(self, j, i): | |
| def f(mod, a): | |
| self.f[j][i] = style_fast(a[0]) # stays on the input's device: no sync per layer | |
| return f | |
| def _decide(self, device): | |
| if self.dev != device: | |
| self.cards, self.dev = [c.to(device) for c in self.cards], device | |
| ll = [c.logp(fs) for c, fs in zip(self.cards, self.f)] | |
| return ll[1] - ll[0] > self.tau | |
| def __call__(self, x): | |
| ys, hs = [[], []], [] | |
| for m, y in zip(self.m, ys): | |
| hs.append(run(m, x, y, 0, self.split)) | |
| on = self._decide(x.device) | |
| if len(x) == 1: # one image: one sync, no masking | |
| j = int(on) | |
| return run(self.m[j], hs[j], ys[j], self.split, len(self.m[j].model)), on | |
| out = None | |
| for m, h, y, keep in zip(self.m, hs, ys, (~on, on)): | |
| if keep.any(): | |
| o = run(m, h[keep], [t[keep] if t is not None else None for t in y], self.split, len(m.model)) | |
| out = o.new_zeros((len(x), *o.shape[1:])) if out is None else out | |
| out[keep] = o | |
| return out, on | |
| def full(self, x): # both models in full, then pick: the reference the split version must equal | |
| o = [run(m, x, [], 0, len(m.model)) for m in self.m] | |
| on = self._decide(x.device) | |
| return torch.where(on.view(-1, 1, 1), o[1], o[0]), on | |
| class BaseRouter: | |
| """Fused cards along the base model: its backbone (up to layer `deep`) decides; images kept on the old site finish | |
| on it, the rest run the new site's model from the input.""" | |
| def __init__(self, models, names, cards, tau, deep=10): | |
| self.m, self.cards, self.tau, self.split, self.dev = models, [PackedCard(c) for c in cards], tau, deep + 1, None | |
| self.f, self.force = [None] * (len(names) + 1), None # force: send every image one way (latency of each path) | |
| mods = dict(models[0].named_modules()) | |
| for i, n in enumerate(names): | |
| mods[n].register_forward_pre_hook(self._keep(i)) | |
| models[0].model[deep].register_forward_hook(lambda mod, a, o: self.f.__setitem__(-1, o.float().mean((2, 3)))) | |
| def _keep(self, i): | |
| def f(mod, a): | |
| self.f[i] = style_fast(a[0]) # stays on the input's device: no sync per layer | |
| return f | |
| def _decide(self, device): | |
| if self.dev != device: | |
| self.cards, self.dev = [c.to(device) for c in self.cards], device | |
| ll = [c.logp(self.f) for c in self.cards] | |
| on = ll[1] - ll[0] > self.tau | |
| return on if self.force is None else torch.full_like(on, self.force) | |
| def __call__(self, x): | |
| y = [] | |
| h = run(self.m[0], x, y, 0, self.split) | |
| on = self._decide(x.device) | |
| if len(x) == 1: # one image: one sync, no masking | |
| return (run(self.m[1], x, [], 0, len(self.m[1].model)) if bool(on) else run(self.m[0], h, y, self.split, len(self.m[0].model))), on | |
| out = None | |
| for keep, go in ((~on, lambda k: run(self.m[0], h[k], [t[k] if t is not None else None for t in y], self.split, len(self.m[0].model))), | |
| (on, lambda k: run(self.m[1], x[k], [], 0, len(self.m[1].model)))): | |
| if keep.any(): | |
| o = go(keep) | |
| out = o.new_zeros((len(x), *o.shape[1:])) if out is None else out | |
| out[keep] = o | |
| return out, on | |
| def full(self, x): # both models in full (base first: its hooks set the features), then pick | |
| o = [run(m, x, [], 0, len(m.model)) for m in self.m] | |
| on = self._decide(x.device) | |
| return torch.where(on.view(-1, 1, 1), o[1], o[0]), on | |
| def fuse_all(m): # DetectionModel.fuse() skips a merged model: it counts < 10 BN layers and calls it fused already | |
| for c in m.modules(): | |
| if isinstance(c, Conv) and hasattr(c, "bn"): | |
| c.conv = fuse_conv_and_bn(c.conv, c.bn) | |
| delattr(c, "bn") | |
| c.forward = c.forward_fuse | |
| return m | |
| def macs_by_layer(m, imgsz=640): | |
| """Conv multiply-accumulates per top-level layer for one image.""" | |
| acc, hs = {}, [] | |
| for layer in m.model: | |
| for c in layer.modules(): | |
| if isinstance(c, nn.Conv2d): | |
| hs.append(c.register_forward_hook(lambda mod, a, o, i=layer.i: acc.__setitem__( | |
| i, acc.get(i, 0) + o.numel() * mod.in_channels // mod.groups * mod.kernel_size[0] * mod.kernel_size[1]))) | |
| p = next(m.parameters()) | |
| with torch.no_grad(): | |
| m.predict(torch.zeros(1, 3, imgsz, imgsz, device=p.device, dtype=p.dtype)) | |
| for h in hs: | |
| h.remove() | |
| return acc | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--base", required=True, help="old site model (e.g. S2)") | |
| p.add_argument("--site", required=True, help="new site model, LoRA merged (gridkd.py merge)") | |
| p.add_argument("--lora", required=True, help="the new site's unmerged LoRA checkpoint: names the card layers") | |
| p.add_argument("--src", required=True) | |
| p.add_argument("--tgt", required=True) | |
| p.add_argument("--k", type=int, default=8) | |
| p.add_argument("--gmm-k", type=int, default=4) | |
| p.add_argument("--q", type=float, default=0.05, help="threshold = this quantile of the new site's val ratio; <= 0: threshold 0") | |
| p.add_argument("--mode", choices=("early", "fused"), default="early") | |
| p.add_argument("--deep", type=int, default=10, help="fused: pooled layer of the deep part") | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--device", default="0") | |
| a = p.parse_args() | |
| names = [n for n, x in load_plain(a.lora).model.named_modules() if isinstance(x, MultiLoRAConv)][: a.k] | |
| fused = a.mode == "fused" | |
| ws, pool = ((a.base, a.base), a.deep) if fused else ((a.base, a.site), None) # fused: every card along the base model | |
| cards = [[DiagGMM.fit(s, a.gmm_k) for s in stats(load_plain(w), names, d, "train", a.device, pool)] for w, d in zip(ws, (a.src, a.tgt))] | |
| tau = 0.0 | |
| if a.q > 0: | |
| val = [stats(load_plain(w), names, a.tgt, "val", a.device, pool) for w in ws] | |
| tau = float((sum(g.logp(f) for g, f in zip(cards[1], val[1])) - sum(g.logp(f) for g, f in zip(cards[0], val[0]))).quantile(a.q)) | |
| y, y1 = load_plain(a.base), load_plain(a.site) | |
| m0, m1 = y.model, fuse_all(y1.model) | |
| g1, macs = get_flops(m1, 640), macs_by_layer(m1) # before val makes the models fp16 (get_flops then returns 0) | |
| r = (BaseRouter((m0, m1), names, cards, tau, a.deep) if fused else Router((m0, m1), names, cards, tau)) | |
| tally, live, err = [0.0, 0.0], [False], [] | |
| def routed(x, *args, **kw): | |
| if next(m1.parameters()).dtype != x.dtype or next(m1.parameters()).device != x.device: | |
| m1.to(device=x.device, dtype=x.dtype) | |
| out, on = r(x) | |
| if live[0]: | |
| tally[0], tally[1] = tally[0] + float(on.sum()), tally[1] + len(on) | |
| if not err: # once: the split forward must equal both models in full | |
| ref, on2 = r.full(x) | |
| err.append(float((out - ref).abs().max() / ref.abs().max())) | |
| assert torch.equal(on, on2) and err[0] < 1e-2, err | |
| return out | |
| m0.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)) | |
| res = [] | |
| for d in (a.src, a.tgt): | |
| tally[:] = [0.0, 0.0] | |
| v = y.val(data=d, split="test", device=a.device, workers=4, plots=False, verbose=False) | |
| res.append((Path(d).stem, v.box.map50, v.box.map, tally[0] / max(tally[1], 1))) | |
| frac = sum(v for i, v in macs.items() if i < r.split) / sum(macs.values()) | |
| # fused: per image the base backbone, then either the rest of the base model or the whole new model; | |
| # early: every image runs the early layers of both models, then one model | |
| gf = (lambda on: g1 * (1 + on * frac)) if fused else (lambda on: g1 * (1 + frac)) | |
| params = sum(q.numel() for q in m0.parameters()) / 1e6 + sum(q.numel() for q in m1.parameters()) / 1e6 | |
| tag = Path(a.site).stem.replace("_merged", "") + ("_deploy_fused" if fused else f"_deploy_q{round(a.q * 100)}") | |
| Path(a.out).write_text("model,domain,params_M,gflops,map50,map50_95,on_rate\n" + "".join( | |
| f"{tag},{d},{params:.3f},{gf(on):.2f},{m50:.4f},{m:.4f},{on:.4f}\n" for d, m50, m, on in res)) | |
| print(f"tau {tau:.4g} | decision after layer {r.split - 1}, share of MACs up to there {frac:.3f} | GFLOPs one model {g1:.2f}, routed " | |
| + " / ".join(f"{gf(on):.2f}" for *_, on in res) + f" | split vs full err {err[0]:.2g}") | |
| for row in res: | |
| print(tag, *[f"{v:.4f}" if isinstance(v, float) else v for v in row]) | |
| if __name__ == "__main__": | |
| main() | |