File size: 13,418 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
"""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()