File size: 6,432 Bytes
011a287
 
 
4aa73af
011a287
 
4aa73af
 
011a287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aa73af
011a287
 
 
 
 
 
 
 
 
 
 
4aa73af
011a287
 
 
 
 
 
 
 
4aa73af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
011a287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aa73af
 
 
 
 
 
011a287
 
 
 
 
 
 
4aa73af
 
 
011a287
4aa73af
 
 
011a287
4aa73af
 
 
 
011a287
 
 
 
 
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
"""Export mesmer-ai-image-detector to fp32 ONNX for the browser.

pel/pel.onnx      pixels [N, 3, 336, 336] (already (x/255 - 0.5)/0.5)  -> logit [N]  (LoRA merged in fp32)
peg_a/peg_a.onnx  pixels [1, 3, 448, 448]                              -> x [1, 1024, 1536]   blocks 1-13
peg_b/peg_b.onnx  x                                                    -> x, s25 [1, 3072]    blocks 14-25
peg_c/peg_c.onnx  x                                                    -> x, s38 [1, 3072]    blocks 26-38
peg_d/peg_d.onnx  x                                                    -> s50 [1, 3072], pooled [1, 1280]  blocks 39-50 + pool
peg_head.bin      the linear head, run in JS (no fp16 Cast in ONNX Runtime Web)

s = [mean, population std] over all tokens of a block's output, as Detector.score_peg.
"""
from __future__ import annotations

import sys
import time
from pathlib import Path

import torch
import torch.nn as nn
import torch.nn.functional as F

sys.path.insert(0, str(Path(__file__).parent))
import ref_mesmer as R  # noqa: E402
from safetensors.torch import load_file  # noqa: E402

OUT = Path(R.DET) / "onnx_fp32"
FP16_MAX = 65000.0
torch.set_num_threads(4)


def export(module, args, names, outs, dyn, part):
    path = OUT / part / f"{part}.onnx"
    path.parent.mkdir(parents=True, exist_ok=True)
    t0 = time.time()
    torch.onnx.export(module, args, str(path), dynamo=False, opset_version=18, input_names=names,
                      output_names=outs, dynamic_axes=dyn, do_constant_folding=True)
    print(f"exported {part} in {time.time()-t0:.0f}s", flush=True)


class Pel(nn.Module):
    def __init__(self, m, H):
        super().__init__()
        self.m = m
        for k in ("pel.anchor.mu", "pel.anchor.sd", "pel.head.w", "pel.head.b"):
            self.register_buffer(k.replace(".", "_"), H[k].float().clone())

    def forward(self, x):
        t = self.m.forward_features(x)
        f = torch.cat([t[:, 0], t[:, 1:].mean(1)], 1)
        z = f / f.norm(dim=1, keepdim=True).clamp_min(1e-12)
        z = (z - self.pel_anchor_mu) / self.pel_anchor_sd
        return F.linear(z, self.pel_head_w.view(1, -1), self.pel_head_b).squeeze(1)


def stats(x):
    return torch.cat([x.mean(1), x.std(1, unbiased=False)], 1)


class PegPart(nn.Module):
    def __init__(self, m, lo, hi, rope, first=False, last=False):
        super().__init__()
        self.blocks = nn.ModuleList(m.blocks[lo:hi])
        self.register_buffer("rope", rope.clone())
        self.first, self.last = first, last
        if first:
            self.patch_embed, self.norm_pre = m.patch_embed, m.norm_pre
            self.cls_token, self.pos_embed = m.cls_token, m.pos_embed
        if last:
            self.norm, self.attn_pool, self.fc_norm, self.head = m.norm, m.attn_pool, m.fc_norm, m.head
        self.m = m  # for _pos_embed / pool (not traced as parameters unless used)

    def forward(self, x):
        if self.first:
            x = self.patch_embed(x)
            x, _ = self.m._pos_embed(x)
            x = self.norm_pre(x)
        for blk in self.blocks:
            x = blk(x, rope=self.rope)
        if not self.last:
            return x, stats(x)
        # The linear head (fp16 rounding, per-block L2, standardise, dot) runs in JavaScript:
        # ONNX Runtime Web has no fp16 Cast kernel. See head() below and peg_head.bin.
        return stats(x), self.m.forward_head(self.norm(x))


def head(s25, s38, s50, pooled, H, dims):
    """Detector.score_peg's head on the feature tensors, for checking the JS port."""
    feats = [s25[:, :1536], s25[:, 1536:], s38[:, :1536], s38[:, 1536:], s50[:, :1536], s50[:, 1536:], pooled]
    X = torch.cat([f.clamp(-FP16_MAX, FP16_MAX).half().float() for f in feats], 1)
    X = torch.nan_to_num(X, nan=0.0, posinf=65504.0, neginf=-65504.0)
    a = 0
    for d in dims:
        X[:, a:a + d] /= X[:, a:a + d].norm(dim=1, keepdim=True).clamp_min(1e-12)
        a += d
    X = (X - H["peg.lr.mu"]) / H["peg.lr.sd"]
    return X @ H["peg.lr.w"] + H["peg.lr.b"]


def rope_of(m, S):
    with torch.no_grad():
        _, rope = m._pos_embed(m.patch_embed(torch.zeros(1, 3, S, S)))
    return rope


def main(which):
    import json
    cfg = json.load(open(f"{R.DET}/repo/config.json"))
    W = load_file(f"{R.DET}/repo/model.safetensors")
    H = {k: v.float() for k, v in W.items() if not k.startswith("pel.lora.")}
    if which == "pel":
        m = R.build_pel(cfg)
        m.norm = nn.Identity(); m.attn_pool = None; m.requires_grad_(False)
        m.to(dtype=torch.bfloat16); m.float()
        sc = float(cfg["members"]["pel"]["lora"]["scaling"])
        for i, blk in enumerate(m.blocks):
            for nm in ("qkv", "proj"):
                lin = getattr(blk.attn, nm)
                A = W[f"pel.lora.blocks.{i}.attn.{nm}.lora_A.weight"].double()
                B = W[f"pel.lora.blocks.{i}.attn.{nm}.lora_B.weight"].double()
                lin.weight.data = (lin.weight.data.double() + sc * (B @ A)).float()
        export(Pel(m.eval(), H).eval(), (torch.randn(2, 3, 336, 336),), ["pixels"], ["logit"],
               {"pixels": {0: "n"}, "logit": {0: "n"}}, "pel")
        return
    # PE-G head for JS: float32 little endian, mu | sd | w (10496 each) | b
    dims = cfg["members"]["peg"]["dims"]
    hb = torch.cat([H["peg.lr.mu"].reshape(-1), H["peg.lr.sd"].reshape(-1), H["peg.lr.w"].reshape(-1), H["peg.lr.b"].reshape(-1)])
    assert hb.numel() == 3 * sum(dims) + 1, hb.shape
    OUT.mkdir(parents=True, exist_ok=True)
    hb.float().numpy().astype("<f4").tofile(OUT / "peg_head.bin")
    m = R.build_peg(cfg).requires_grad_(False)
    m.to(dtype=torch.bfloat16); m.float(); m.eval()
    rope = rope_of(m, 448)
    x = torch.randn(1, 3, 448, 448)
    with torch.no_grad():
        a = PegPart(m, 0, 13, rope, first=True).eval()
        xa, _ = a(x)
        if which != "peg_d":
            export(a, (x,), ["pixels"], ["x", "s13"], None, "peg_a")
        b = PegPart(m, 13, 25, rope).eval()
        xb, s25 = b(xa)
        if which != "peg_d":
            export(b, (xa,), ["x"], ["y", "s25"], None, "peg_b")
        c = PegPart(m, 25, 38, rope).eval()
        xc, s38 = c(xb)
        if which != "peg_d":
            export(c, (xb,), ["x"], ["y", "s38"], None, "peg_c")
        d = PegPart(m, 38, 50, rope, last=True).eval()
        export(d, (xc,), ["x"], ["s50", "pooled"], None, "peg_d")


if __name__ == "__main__":
    with torch.no_grad():
        main(sys.argv[1])