Nekochu's picture
LookAnything LA-2B one-pass heads as 8-bit ONNX for WebGPU
6e303cd verified
Raw History Blame Contribute Delete
11.3 kB
"""Export LookAnything LA-2B's one-pass query path to fp32 ONNX parts for the browser.
vis_a patches [N,1536], pos_idx [4,N] i64, pos_w [4,N], cos/sin [N,64] -> x [N,1024], ds0 [N/4,2048], ds1 [N/4,2048] blocks 0-11
vis_b x, cos, sin -> img [N/4,2048], ds2 [N/4,2048] blocks 12-23 + mergers
lm_1..4 hidden [1,S,2048], cos/sin [S,128], mask [S,S] (+ ds [3,S,2048] in lm_1) -> hidden 7 layers each, norm in lm_4
heads gaze [1,9,2048], head [1,9,2048], vis [1,gh,gw,2048] -> point [1,2], box [1,4], heatmap [1,1,64,64], head_mask [1,1,64,64]
LoRA (vision) is merged in fp32 into the weights; the Conv3d patch embedding becomes a Linear.
usage: export_look.py OUT_DIR PART [PART ...] (PART: vis_a vis_b lm_1 lm_2 lm_3 lm_4 heads data)
"""
from __future__ import annotations
import json
import os
import sys
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
SP = os.environ.get("LOOK_DIR", ".") # holds src/ (the code repo), ckpt/LA-2B (the checkpoint), ref/ (reference outputs)
sys.path.insert(0, f"{SP}/src")
from look_anything import inference as li # noqa: E402
from look_anything.heads import build_2d_sincos_pos_embed # noqa: E402
from look_anything.vision_lora import LoRALinear # noqa: E402
torch.set_num_threads(4)
CKPT = f"{SP}/ckpt/LA-2B"
def merge_lora(visual: nn.Module) -> int:
"""Replace every LoRALinear by a plain Linear holding W + scaling * B @ A (fp32)."""
n = 0
for pname, parent in list(visual.named_modules()):
for cname, child in list(parent.named_children()):
if isinstance(child, LoRALinear):
lin = child.linear
w = lin.weight.data.double() + child.scaling * (child.lora_B.data.double() @ child.lora_A.data.double())
new = nn.Linear(lin.in_features, lin.out_features, bias=lin.bias is not None)
new.weight.data = w.float()
if lin.bias is not None:
new.bias.data = lin.bias.data.clone()
setattr(parent, cname, new)
n += 1
return n
def rms(x, w, eps):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
def rot_half(x):
h = x.shape[-1] // 2
return torch.cat((-x[..., h:], x[..., :h]), dim=-1)
class VisPart(nn.Module):
def __init__(self, visual, lo, hi, first, last):
super().__init__()
self.blocks = nn.ModuleList(visual.blocks[lo:hi])
self.first, self.last, self.lo = first, last, lo
self.taps = list(visual.deepstack_visual_indexes)
self.heads, self.hd = visual.config.num_heads, visual.config.hidden_size // visual.config.num_heads
if first:
pe = visual.patch_embed.proj
self.pe = nn.Linear(pe.weight[0].numel(), pe.out_channels, bias=True)
self.pe.weight.data = pe.weight.data.reshape(pe.out_channels, -1).clone()
self.pe.bias.data = pe.bias.data.clone()
self.pos_embed = visual.pos_embed
self.mergers = nn.ModuleList(visual.deepstack_merger_list)
self.merger = visual.merger
def attn(self, blk, x, cos, sin):
n = x.shape[0]
qkv = blk.attn.qkv(x).reshape(n, 3, self.heads, self.hd)
q, k, v = qkv[:, 0], qkv[:, 1], qkv[:, 2]
c, s = cos.unsqueeze(1), sin.unsqueeze(1)
q, k = q * c + rot_half(q) * s, k * c + rot_half(k) * s
q, k, v = q.transpose(0, 1).unsqueeze(0), k.transpose(0, 1).unsqueeze(0), v.transpose(0, 1).unsqueeze(0)
# 4 heads at a time: the full [16, N, N] score map is 199 MB at N = 1764, over the default WebGPU buffer limit
o = torch.cat([F.scaled_dot_product_attention(q[:, g:g + 4], k[:, g:g + 4], v[:, g:g + 4]) for g in range(0, self.heads, 4)], dim=1)
return blk.attn.proj(o.squeeze(0).transpose(0, 1).reshape(n, -1))
def forward(self, *args):
if self.first:
patches, idx, w, cos, sin = args
pos = (self.pos_embed(idx) * w.unsqueeze(-1)).sum(0)
x = self.pe(patches) + pos
else:
x, cos, sin = args
outs = []
for i, blk in enumerate(self.blocks):
x = x + self.attn(blk, blk.norm1(x), cos, sin)
x = x + blk.mlp.linear_fc2(blk.mlp.act_fn(blk.mlp.linear_fc1(blk.norm2(x))))
g = self.lo + i
if g in self.taps:
m = self.mergers[self.taps.index(g)]
outs.append(m.linear_fc2(m.act_fn(m.linear_fc1(m.norm(x.reshape(-1, m.hidden_size))))))
if self.last:
m = self.merger
img = m.linear_fc2(m.act_fn(m.linear_fc1(m.norm(x).reshape(-1, m.hidden_size))))
return (img, *outs)
return (x, *outs)
class LmPart(nn.Module):
def __init__(self, lm, lo, hi, first, last):
super().__init__()
self.layers = nn.ModuleList(lm.layers[lo:hi])
self.first, self.last = first, last
self.norm = lm.norm if last else None
self.eps = lm.config.rms_norm_eps
self.h, self.kv, self.hd = lm.config.num_attention_heads, lm.config.num_key_value_heads, lm.config.head_dim
def layer(self, L, x, cos, sin, mask):
s = x.shape[1]
a = L.self_attn
h = rms(x, L.input_layernorm.weight, self.eps)
q = rms(a.q_proj(h).view(1, s, self.h, self.hd), a.q_norm.weight, self.eps).transpose(1, 2)
k = rms(a.k_proj(h).view(1, s, self.kv, self.hd), a.k_norm.weight, self.eps).transpose(1, 2)
v = a.v_proj(h).view(1, s, self.kv, self.hd).transpose(1, 2)
c, sn = cos.unsqueeze(0).unsqueeze(0), sin.unsqueeze(0).unsqueeze(0)
q, k = q * c + rot_half(q) * sn, k * c + rot_half(k) * sn
rep = self.h // self.kv
k = k.unsqueeze(2).expand(1, self.kv, rep, s, self.hd).reshape(1, self.h, s, self.hd)
v = v.unsqueeze(2).expand(1, self.kv, rep, s, self.hd).reshape(1, self.h, s, self.hd)
o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
x = x + a.o_proj(o.transpose(1, 2).reshape(1, s, -1))
h = rms(x, L.post_attention_layernorm.weight, self.eps)
return x + L.mlp.down_proj(F.silu(L.mlp.gate_proj(h)) * L.mlp.up_proj(h))
def forward(self, x, cos, sin, mask, ds=None):
for i, L in enumerate(self.layers):
x = self.layer(L, x, cos, sin, mask)
if self.first and i < 3:
x = x + ds[i].unsqueeze(0)
if self.last:
x = rms(x, self.norm.weight, self.eps)
return x
class Heads(nn.Module):
def __init__(self, model):
super().__init__()
self.gaze_head, self.head_mask_head, self.point_head, self.box_head = (
model.gaze_head, model.head_mask_head, model.point_head, model.box_head)
self.grid = model.point_head.conv_grid
def forward(self, gaze, head, vis):
b, gh, gw, c = vis.shape
flat = vis.reshape(b, gh * gw, c)
hm = self.gaze_head(gaze, vision_tokens=flat, vision_mask=None, image_grid_thw=None, head_tokens=None)["gaze_heatmap_logits"]
hmask = self.head_mask_head(head)["head_mask_logits"]
p = self.point_head
q = p.q_proj(gaze)
v = p.v_proj(flat).reshape(b, gh, gw, -1).permute(0, 3, 1, 2)
v = F.interpolate(v, size=(self.grid, self.grid), mode="bilinear", align_corners=False)
kv = v.flatten(2).transpose(1, 2)
kv = kv + build_2d_sincos_pos_embed(kv.shape[-1], self.grid).to(kv.dtype).unsqueeze(0)
for blk in p.cross_blocks:
q = blk(q, kv)
point = p.proj(gaze + p.out_proj(q)).sigmoid()
return point, self.box_head(gaze)["box"], hm, hmask
def export(module, args, names, outs, dyn, out_dir, part):
path = Path(out_dir) / part / f"{part}.onnx"
path.parent.mkdir(parents=True, exist_ok=True)
t0 = time.time()
with torch.no_grad():
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 ({path.stat().st_size/1e6:.0f} MB)", flush=True)
def main(out_dir, parts):
model = li.load_model(CKPT, device="cpu", dtype=torch.float32)
model.requires_grad_(False)
visual, lm = model._inner.visual, model._lm
print("LoRA layers merged:", merge_lora(visual), flush=True)
N, S = 1764, 481 + 27
cfg = visual.config
nd = len(visual.deepstack_visual_indexes)
half = cfg.depth // 2
for part in parts:
if part in ("vis_a", "vis_b"):
a = part == "vis_a"
m = VisPart(visual, 0 if a else half, half if a else cfg.depth, first=a, last=not a).eval()
if a:
args = (torch.randn(N, 1536), torch.randint(0, 2304, (4, N)), torch.rand(4, N), torch.randn(N, 64), torch.randn(N, 64))
names, dyn = ["patches", "pos_idx", "pos_w", "cos", "sin"], {"patches": {0: "n"}, "pos_idx": {1: "n"}, "pos_w": {1: "n"}, "cos": {0: "n"}, "sin": {0: "n"}}
outs = ["x", "ds0", "ds1"]
else:
args = (torch.randn(N, 1024), torch.randn(N, 64), torch.randn(N, 64))
names, dyn = ["x", "cos", "sin"], {"x": {0: "n"}, "cos": {0: "n"}, "sin": {0: "n"}}
outs = ["img", "ds2"]
dyn.update({o: {0: "n" if o == "x" else "m"} for o in outs})
export(m, args, names, outs, dyn, out_dir, part)
elif part.startswith("lm_"):
k = int(part[3:])
per = lm.config.num_hidden_layers // 4
m = LmPart(lm, (k - 1) * per, k * per, first=k == 1, last=k == 4).eval()
args = [torch.randn(1, S, 2048), torch.randn(S, 128), torch.randn(S, 128), torch.zeros(S, S)]
names = ["hidden", "cos", "sin", "mask"]
dyn = {"hidden": {1: "s"}, "cos": {0: "s"}, "sin": {0: "s"}, "mask": {0: "s", 1: "s"}, "out": {1: "s"}}
if k == 1:
args.append(torch.randn(3, S, 2048)); names.append("ds"); dyn["ds"] = {1: "s"}
export(m, tuple(args), names, ["out"], dyn, out_dir, part)
elif part == "heads":
m = Heads(model).eval()
args = (torch.randn(1, 9, 2048), torch.randn(1, 9, 2048), torch.randn(1, 21, 21, 2048))
export(m, args, ["gaze", "head", "vis"], ["point", "box", "heatmap", "head_mask"],
{"vis": {1: "gh", 2: "gw"}}, out_dir, "heads")
elif part == "data":
d = Path(out_dir)
d.mkdir(parents=True, exist_ok=True)
model.query_tokens.weight.detach().float().numpy().astype("<f4").tofile(d / "query_tokens.f32")
vp = visual.pos_embed.weight.detach().float().numpy()
print("pos_embed table", vp.shape, flush=True)
json.dump({"queries": list(model.query_tokens.weight.shape), "n_per": model.n_per, "heads": model.head_names,
"deepstack": list(visual.deepstack_visual_indexes), "heatmap_mode": model.config.heatmap_coordinate_mode},
open(d / "meta.json", "w"), indent=1)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])