File size: 11,226 Bytes
dadc4db 752dc7d dadc4db 752dc7d dadc4db 752dc7d dadc4db 752dc7d dadc4db | 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 | """Export one part of the browser pipeline to fp32 ONNX.
usage: export.py {text,dit_a,dit_b,dit_c,dit_d,vae}
"""
from __future__ import annotations
import math
import sys
import time
from pathlib import Path
import torch
import torch.nn.functional as F
from torch import nn
import dfl
from dflow import modeling as mdl
from dflow.text_encoder import EncoderTaps, LayerKind
def _rms_norm(x, normalized_shape, weight=None, eps=None):
"""Explicit RMSNorm (aten::rms_norm has no ONNX mapping below opset 23)."""
dims = tuple(range(-len(normalized_shape), 0))
eps = torch.finfo(x.dtype).eps if eps is None else eps
y = x * torch.rsqrt(x.pow(2).mean(dims, keepdim=True) + eps)
return y if weight is None else y * weight
F.rms_norm = _rms_norm
torch.rms_norm = _rms_norm
def _sdpa_by_head(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, enable_gqa=False):
"""Attention one head at a time: same math as SDPA, but the largest live score
tensor is [B, 1, S, S] instead of [B, H, S, S] (18x less memory at 1 MP)."""
assert dropout_p == 0.0 and not is_causal and not enable_gqa
heads, dim = int(q.shape[1]), int(q.shape[-1])
sc = scale if scale is not None else 1.0 / math.sqrt(dim)
outs = []
for h in range(heads):
s = torch.matmul(q[:, h:h + 1], k[:, h:h + 1].transpose(-1, -2)) * sc
if attn_mask is not None:
s = s + (attn_mask if attn_mask.shape[1] == 1 else attn_mask[:, h:h + 1])
outs.append(torch.matmul(torch.softmax(s, dim=-1), v[:, h:h + 1]))
return torch.cat(outs, dim=1)
F.scaled_dot_product_attention = _sdpa_by_head
OUT = dfl.SP / "onnx_fp32h"
OUT.mkdir(exist_ok=True)
torch.set_num_threads(4)
def _stream(tact, rsin, rcos, qs):
return mdl._StreamInputs(rope_sin=rsin, rope_cos=rcos, query_scale=qs,
key_bias=None, value_scale=None, time_act=tact)
def _run(x, blocks, adaln, stream):
for blk, proj in zip(blocks, adaln):
x = blk(x, rope_sin=stream.rope_sin, rope_cos=stream.rope_cos,
modulation=proj(stream.time_act).to(torch.float32), query_scale=stream.query_scale,
key_bias=None, value_scale=None)
return x
class TextPart(nn.Module):
"""Scaled token embeddings [1, L, 640] -> refined text tokens [1, L+3, 2304]."""
def __init__(self, enc, adapter, model):
super().__init__()
self.layers = enc.layers
self.adapter = adapter
self.refiner = model.text_refiner_layers
def forward(self, emb, g_cos_s, g_sin_s, g_cos_f, g_sin_f, r_sin, r_cos):
values = emb
taps = []
for index, layer in enumerate(self.layers, start=1):
full = layer.kind == LayerKind.FULL
values = layer._forward_impl(values, cos=g_cos_f if full else g_cos_s,
sin=g_sin_f if full else g_sin_s,
attn_bias=None, value_scale=None)
if index in (2, 6, 12):
taps.append(values)
x = self.adapter.conditioning_tokens(EncoderTaps(*taps))
for blk in self.refiner:
x = blk(x, rope_sin=r_sin, rope_cos=r_cos, modulation=None, query_scale=None,
key_bias=None, value_scale=None)
return x
class DitA(nn.Module):
"""Latent tokens + text -> stream after the 6 prefix blocks, and SiLU(time)."""
def __init__(self, m):
super().__init__()
self.patch_embed, self.time_embed = m.patch_embed, m.time_embed
self.prefix_layers, self.prefix_adaln = m.prefix_layers, m.prefix_adaln
def forward(self, lat, t, text, rope_sin, rope_cos, qscale):
m = self
image = F.linear(lat, m.patch_embed.weight.flatten(1), m.patch_embed.bias)
x = torch.cat([image, text], dim=1)
tact = F.silu(m.time_embed(t))
x = _run(x, m.prefix_layers, m.prefix_adaln, _stream(tact, rope_sin, rope_cos, qscale))
return x, tact
class DitMid(nn.Module):
def __init__(self, m, lo, hi):
super().__init__()
self.blocks = m.middle_layers[lo:hi]
self.adaln = m.middle_adaln[lo:hi]
def forward(self, x, tact, rope_sin, rope_cos, qscale):
return _run(x, self.blocks, self.adaln, _stream(tact, rope_sin, rope_cos, qscale))
class DitD(nn.Module):
"""Tail join + 6 suffix blocks + velocity head on every row: [1, S, 96]."""
def __init__(self, m):
super().__init__()
self.tail_join, self.final_norm = m.tail_join, m.final_norm
self.suffix_layers, self.suffix_adaln = m.suffix_layers, m.suffix_adaln
self.final_modulation, self.velocity_head = m.final_modulation, m.velocity_head
def forward(self, prefix, middle, tact, rope_sin, rope_cos, qscale):
m = self
x = m.tail_join(prefix, middle, None, tact)
x = _run(x, m.suffix_layers, m.suffix_adaln, _stream(tact, rope_sin, rope_cos, qscale))
normed = m.final_norm(x)
shift, scale = m.final_modulation(tact).to(torch.float32).chunk(2, dim=-1)
out = normed * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
return F.linear(out, m.velocity_head.weight, m.velocity_head.bias)
class VaePart(nn.Module):
"""Whitened latents [1, 96, h, w] -> RGB [1, 3, 16h, 16w] in [0, 1]."""
def __init__(self, vae):
super().__init__()
self.dec = vae.decoder
mean, std = vae._latent_stats()
self.register_buffer("mean", mean.clone())
self.register_buffer("std", std.clone())
def forward(self, z, v_sin, v_cos):
z = z * self.std + self.mean
x = self.dec.latent_up(z)
b, c, h, w = x.shape
tokens = x.permute(0, 2, 3, 1).reshape(b, h * w, c)
for block in self.dec.trunk:
tokens = block(tokens, v_sin, v_cos)
feats = tokens.transpose(1, 2).reshape(b, c, h, w)
rgb = self.dec.conv_up_head(feats)
return ((rgb.clamp(-1.0, 1.0) + 1.0) * 0.5)
class VaeTrunk(nn.Module):
"""Whitened latents [1, 96, h, w] -> trunk features [1, 1152, h, w] (global attention)."""
def __init__(self, vae):
super().__init__()
self.dec = vae.decoder
mean, std = vae._latent_stats()
self.register_buffer("mean", mean.clone())
self.register_buffer("std", std.clone())
def forward(self, z, v_sin, v_cos):
x = self.dec.latent_up(z * self.std + self.mean)
b, c, h, w = x.shape
tokens = x.permute(0, 2, 3, 1).reshape(b, h * w, c)
for block in self.dec.trunk:
tokens = block(tokens, v_sin, v_cos)
return tokens.transpose(1, 2).reshape(b, c, h, w)
class VaeHead(nn.Module):
"""Trunk features (any tile) [1, 1152, th, tw] -> RGB [1, 3, 16th, 16tw] in [0, 1].
Purely local (convolutions and per-pixel norms), so it can run tile by tile."""
def __init__(self, vae):
super().__init__()
self.head = vae.decoder.conv_up_head
def forward(self, feats):
return (self.head(feats).clamp(-1.0, 1.0) + 1.0) * 0.5
def export(module, args, names, outs, dyn, path: Path):
t0 = time.time()
path = path.parent / path.stem / path.name
path.parent.mkdir(exist_ok=True)
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 {path.name} in {time.time()-t0:.0f}s", flush=True)
def main(part: str) -> None:
n, lt = 12, 9 # image tokens (3x4 grid), text tokens incl. suffix
s = n + lt
seq = {1: "s"}
if part == "text":
tok, enc = dfl.load_text_encoder()
model, adapter = dfl.load_denoiser(lora=False, prefixes=("text_refiner_layers.",))
L = 6
args = (torch.randn(1, L, 640) * 3, torch.randn(L, 1, 256), torch.randn(L, 1, 256),
torch.randn(L, 1, 256), torch.randn(L, 1, 256),
torch.randn(1, L + 3, 128), torch.randn(1, L + 3, 128))
names = ["emb", "g_cos_s", "g_sin_s", "g_cos_f", "g_sin_f", "r_sin", "r_cos"]
dyn = {"emb": {1: "l"}, "g_cos_s": {0: "l"}, "g_sin_s": {0: "l"}, "g_cos_f": {0: "l"},
"g_sin_f": {0: "l"}, "r_sin": {1: "l3"}, "r_cos": {1: "l3"}, "text": {1: "l3"}}
export(TextPart(enc, adapter, model).eval(), args, names, ["text"], dyn, OUT / "text.onnx")
return
if part == "vae_split":
vae = dfl.load_vae()
export(VaeTrunk(vae).eval(), (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64)),
["z", "v_sin", "v_cos"], ["feats"],
{"z": {2: "h", 3: "w"}, "v_sin": {0: "hw"}, "v_cos": {0: "hw"}, "feats": {2: "h", 3: "w"}},
OUT / "vae_trunk.onnx")
export(VaeHead(vae).eval(), (torch.randn(1, 1152, 3, 4),), ["feats"], ["rgb"],
{"feats": {2: "h", 3: "w"}, "rgb": {2: "H", 3: "W"}}, OUT / "vae_head.onnx")
return
if part == "vae":
vae = dfl.load_vae()
args = (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64))
dyn = {"z": {2: "h", 3: "w"}, "v_sin": {0: "hw"}, "v_cos": {0: "hw"},
"rgb": {2: "H", 3: "W"}}
export(VaePart(vae).eval(), args, ["z", "v_sin", "v_cos"], ["rgb"], dyn, OUT / "vae_dec.onnx")
return
rope = (torch.randn(1, s, 128), torch.randn(1, s, 128), torch.tensor(0.97, dtype=torch.float32))
if part == "dit_a":
model, _ = dfl.load_denoiser(prefixes=("patch_embed.", "time_embed.", "prefix_layers.",
"prefix_adaln."))
args = (torch.randn(1, n, 96), torch.tensor([0.9]), torch.randn(1, lt, 2304), *rope)
dyn = {"lat": {1: "n"}, "text": {1: "lt"}, "rope_sin": seq, "rope_cos": seq, "x": seq}
export(DitA(model).eval(), args, ["lat", "t", "text", "rope_sin", "rope_cos", "qscale"],
["x", "tact"], dyn, OUT / "dit_a.onnx")
elif part in ("dit_b", "dit_c"):
lo, hi = (0, 9) if part == "dit_b" else (9, 18)
pref = tuple(f"middle_{k}.{i}." for k in ("layers", "adaln") for i in range(lo, hi))
model, _ = dfl.load_denoiser(prefixes=pref)
args = (torch.randn(1, s, 2304), torch.randn(1, 256), *rope)
dyn = {"x": seq, "rope_sin": seq, "rope_cos": seq, "y": seq}
export(DitMid(model, lo, hi).eval(), args, ["x", "tact", "rope_sin", "rope_cos", "qscale"],
["y"], dyn, OUT / f"{part}.onnx")
elif part == "dit_d":
model, _ = dfl.load_denoiser(prefixes=("tail_join.", "suffix_layers.", "suffix_adaln.",
"final_norm.", "final_modulation.", "velocity_head."))
args = (torch.randn(1, s, 2304), torch.randn(1, s, 2304), torch.randn(1, 256), *rope)
dyn = {"prefix": seq, "middle": seq, "rope_sin": seq, "rope_cos": seq, "vel": seq}
export(DitD(model).eval(), args, ["prefix", "middle", "tact", "rope_sin", "rope_cos", "qscale"],
["vel"], dyn, OUT / "dit_d.onnx")
else:
raise SystemExit(f"unknown part {part}")
if __name__ == "__main__":
with torch.no_grad():
main(sys.argv[1])
|