File size: 11,285 Bytes
6e303cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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:])