Nekochu's picture
PE-G head out of the graph (ONNX Runtime Web has no fp16 Cast): peg_d returns s50 + pooled, head in peg_head.bin
4aa73af verified
Raw History Blame Contribute Delete
6.43 kB
"""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])