LookAnything LA-2B one-pass heads as 8-bit ONNX for WebGPU
Browse filesFiles changed (23)
- .gitattributes+2
- LICENSEAdded+203
- README.mdAdded+89
- heads.onnxAdded+3
- ids.jsonAdded+1
- lm_1.onnxAdded+3
- lm_2.onnxAdded+3
- lm_3.onnxAdded+3
- lm_4.onnxAdded+3
- manifest.jsonAdded+68
- prompt.jsonAdded+1
- prompt_rows.bf16Added+3
- query_tokens.f32Added+3
- scripts/export_look.pyAdded+229
- scripts/make_data.pyAdded+61
- scripts/pack.pyAdded+17
- scripts/quant_mixed.pyAdded+23
- scripts/quantize.pyAdded+77
- scripts/ref_look.pyAdded+90
- scripts/tables.pyAdded+72
- scripts/verify_look.pyAdded+66
- vis_a.onnxAdded+3
- vis_b.onnxAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textprompt_rows.bf16 filter=lfs diff=lfs merge=lfs -textquery_tokens.f32 filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203Copyright 2018- The Hugging Face team. All rights reserved.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889---license: apache-2.0base_model: JYT4chenxiyuxi/LookAnythingbase_model_relation: quantizedlibrary_name: onnxtags: - onnx - onnxruntime-web - webgpu - gaze-following - quantized---
# LookAnything, ONNX for WebGPU
[JYT4chenxiyuxi/LookAnything](https://huggingface.co/JYT4chenxiyuxi/LookAnything) (LA-2B, gaze following, Apache-2.0)converted to ONNX so it runs in a browser with ONNX Runtime Web on WebGPU: photos, video files and the webcam.Demo: [WeReCooking/LookAnything-WebGPU](https://huggingface.co/spaces/WeReCooking/LookAnything-WebGPU).
LA-2B is Qwen3-VL-2B with LoRA on the vision tower and learned gaze queries. This conversion covers the **one-passquery path** only: a single forward pass over `[prompt, image tokens, 27 gaze-query tokens]` gives the gaze point, thegaze box, a heatmap and the head mask through the small decoder heads. Text generation (the describe / reasoningtasks) is not included.
## Files (2.26 GB)
| file | what | size ||---|---|---|| `vis_a.onnx`, `vis_b.onnx` | vision tower in two halves, LoRA merged, 8-bit weights; outputs the image tokens and the 3 DeepStack features | 245 + 234 MB || `lm_1.onnx` … `lm_4.onnx` | the 28 language layers, 7 per file, 8-bit weights, final norm in `lm_4` | 408 MB each || `heads.onnx` | gaze point / box / heatmap / head-mask decoders, fp32 | 148 MB || `prompt.json`, `prompt_rows.bf16`, `ids.json` | the prompt token ids and just their embedding rows (55 rows), so no tokenizer or 600 MB embedding table is needed | 0.2 MB || `query_tokens.f32` | the 27 learned query embeddings | 0.2 MB || `manifest.json` | sizes, SHA-256 | |
Everything the model needs around the graphs (image resize and patch layout, vision position tables, M-RoPE ids andtables, the query-group attention mask, prompt assembly) is in the Space's `app.js` and was checked againsttransformers: `prep.js` / `infer.js` there, `scripts/tables.py` here.
## How to run it
1. Pixels: Qwen smart-resize to multiples of 32 within 12,544 to 451,584 pixels (the repo's `inference_config.json`), Pillow bicubic, `(x/255 - 0.5)/0.5`, patches of 16 px, merged 2×2, each patch `C × 2 × 16 × 16` (image repeated twice).2. `vis_a(patches, pos_idx, pos_w, cos, sin)` → `x, ds0, ds1`; `vis_b(x, cos, sin)` → `img, ds2`.3. Sequence: prompt tokens with the image placeholders replaced by `img`, then the 27 queries; `ds0..2` are added at the image positions after language layers 1 to 3 (`lm_1` takes them zero-padded as `ds [3, S, 2048]`).4. `lm_1 … lm_4` with M-RoPE `cos/sin [S, 128]` and the additive mask `[S, S]` (causal; the depth, head and gaze query groups cannot see each other).5. `heads(gaze = hidden[P+18 : P+27], head = hidden[P+9 : P+18], vis = image-token hidden states [1, gh, gw, 2048])` → `point [1,2]`, `box [1,4]`, `heatmap [1,1,64,64]` logits, `head_mask [1,1,64,64]` logits (all in 0..1 picture coordinates; `P` = prompt length).
Prompts are the repo's `GTL_POINT` template ("the person") or `GTL_B2P` with a head box in 0..999.
## Accuracy against the original
Original `look_anything` code in fp32 on CPU against these files, 6 Unsplash photos (people from the front and the back):
| set | size | largest point change | largest box change | heatmap peak moved ||---|---|---|---|---|| fp32 export | 8 GB | < 0.001 | < 0.001 | no || **vision + language 8-bit (this repo)** | **2.26 GB** | **0.008** | **0.025** | no (one by 1 cell) || language MLP 4-bit, rest 8-bit | 1.6 GB | 0.102 | 0.312 | yes || everything 4-bit | 1.4 GB | 0.182 | 0.386 | yes |
Coordinates are fractions of the picture, so 0.008 is under 1% of its width. 4-bit was dropped. The page's ownJavaScript (resize, tables, prompt assembly) run end to end on these files with ONNX Runtime CPU agrees with the PyTorchreference to within 0.005 on 5 runs, including a head-box prompt. About 10 s per picture on 4 CPU cores.
Pixel budget: the page uses 451,584 pixels for stills and about 200,000 for live video. In PyTorch the 200,000pixel setting moved the point by 0.02 to 0.06 of the picture against the full setting, 100,000 by up to 0.10.
Note: with transformers 5.4.0 the code repo's `load_processor` silently skips its `min_pixels` / `max_pixels` (theQwen2VL image processor has no such attribute there), so stock inference uses far more image tokens than`inference_config.json` asks for. These files follow `inference_config.json`.
## Rebuild
`scripts/ref_look.py` (reference), `export_look.py` (fp32 ONNX, LoRA merged in fp64; `LOOK_DIR` points at a folder holding`src/` = the code repo, `ckpt/LA-2B`), `quantize.py` (ONNX Runtime `MatMulNBits`, block 32), `make_data.py`,`pack.py`, `verify_look.py`. Made with torch 2.15, transformers 5.4.0, onnx 1.23 and onnxruntime 1.32.Code repo used: github.com/Look-Anything/LookAnything at commit 689501f. Checkpoint revision 60790cf.
## License
Apache-2.0, as the original. Changes: format conversion, vision LoRA merged into the weights, weight quantization,vision and language stacks split into several graphs, heads kept as fp32.Reference: Tang, Zhou et al., *LookAnything: A Foundation Model for Holistic Gaze Following*, arXiv:2611.32351.Do not use gaze estimates as the only evidence for decisions about people.123version https://git-lfs.github.com/spec/v1oid sha256:15d8457274732242d30c31b28355ed8cee0bd9a2a99720fb28d5762ce340d2aasize 1482922681{"image_pad": 151655, "ids": {"vision_start": 151652, "vision_end": 151653}}123version https://git-lfs.github.com/spec/v1oid sha256:8885deaaaadb76ff01925e1882ada783b1525fe3645ca93e50275b4b35f2bbdasize 407633913123version https://git-lfs.github.com/spec/v1oid sha256:dd4f0d64afce3ef7924e7e51b3be3bd7c9d15c9471b8215aa6ec3a379dbd7750size 407632629123version https://git-lfs.github.com/spec/v1oid sha256:ea7bb12bdef67d5a12d00d53448616dc27baece0ed12d7eabecd1595adc4f662size 407632629123version https://git-lfs.github.com/spec/v1oid sha256:fdeec7cc59cb1ad129698a11f6b32aeb1daec6f04c27ddb7f577560619ad8856size 4076416891234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768{ "format": 1, "files": { "vis_a": { "path": "vis_a.onnx", "bytes": 245064414, "sha256": "6f9208513962fdff828c20d414a191a9fd118b5e9af7d5ec82341c729eec08be" }, "vis_b": { "path": "vis_b.onnx", "bytes": 233778779, "sha256": "03a35f279b183a2c8574b3a0f8bcd054cdb363a14c8ac3df4d275eff14a74328" }, "lm_1": { "path": "lm_1.onnx", "bytes": 407633913, "sha256": "8885deaaaadb76ff01925e1882ada783b1525fe3645ca93e50275b4b35f2bbda" }, "lm_2": { "path": "lm_2.onnx", "bytes": 407632629, "sha256": "dd4f0d64afce3ef7924e7e51b3be3bd7c9d15c9471b8215aa6ec3a379dbd7750" }, "lm_3": { "path": "lm_3.onnx", "bytes": 407632629, "sha256": "ea7bb12bdef67d5a12d00d53448616dc27baece0ed12d7eabecd1595adc4f662" }, "lm_4": { "path": "lm_4.onnx", "bytes": 407641689, "sha256": "fdeec7cc59cb1ad129698a11f6b32aeb1daec6f04c27ddb7f577560619ad8856" }, "heads": { "path": "heads.onnx", "bytes": 148292268, "sha256": "15d8457274732242d30c31b28355ed8cee0bd9a2a99720fb28d5762ce340d2aa" } }, "data": { "prompt.json": { "path": "prompt.json", "bytes": 1125 }, "prompt_rows.bf16": { "path": "prompt_rows.bf16", "bytes": 225280 }, "ids.json": { "path": "ids.json", "bytes": 76 }, "query_tokens.f32": { "path": "query_tokens.f32", "bytes": 221184 } }, "order": [ "vis_a", "vis_b", "lm_1", "lm_2", "lm_3", "lm_4", "heads" ], "total_bytes": 2257676321}1{"head": [151644, 872, 198, 151652], "point": [151653, 9064, 374, 279, 1697, 3330, 518, 30, 9258, 1172, 1181, 29410, 1459, 438, 320, 87, 7358, 701, 1667, 7546, 13934, 504, 220, 15, 311, 220, 16, 15, 15, 15, 13, 151645, 198, 151644, 77091, 198], "box": [151653, 9064, 374, 279, 1697, 3330, 518, 30, 9258, 1172, 1181, 29410, 30618, 3745, 438, 508, 87, 16, 7358, 16, 12803, 17, 7358, 17, 1125, 1667, 7546, 13934, 504, 220, 15, 311, 220, 16, 15, 15, 15, 13, 151645, 198, 151644, 77091, 198], "b2p": {"mid": [151653, 9152, 349, 279, 35396, 2169, 315, 279, 1697, 448, 1968, 3745, 508], "tail": [936, 9258, 1172, 1181, 29410, 1459, 438, 320, 87, 7358, 701, 1667, 7546, 13934, 504, 220, 15, 311, 220, 16, 15, 15, 15, 13, 151645, 198, 151644, 77091, 198]}, "digits": [15, 16, 17, 18, 19, 20, 21, 22, 23, 24], "comma": 11, "row_ids": [11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30, 87, 198, 220, 279, 311, 315, 320, 349, 374, 438, 448, 504, 508, 518, 701, 872, 936, 1125, 1172, 1181, 1459, 1667, 1697, 1968, 2169, 3330, 3745, 7358, 7546, 9064, 9152, 9258, 12803, 13934, 29410, 30618, 35396, 77091, 151644, 151645, 151652, 151653]}123version https://git-lfs.github.com/spec/v1oid sha256:9fd68cd40a7fc38da0f78ebd10fe9e0f07f0ad1103a64c30eace4ed9b46d37c0size 225280123version https://git-lfs.github.com/spec/v1oid sha256:83024008714b06b46028ff628068d9dacfd1f22d9fc5f1de9e21d9c4027e0c11size 221184123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""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-11vis_b x, cos, sin -> img [N/4,2048], ds2 [N/4,2048] blocks 12-23 + mergerslm_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_4heads 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 jsonimport osimport sysimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn as nnimport 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: E402from look_anything.heads import build_2d_sincos_pos_embed # noqa: E402from 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:])12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Prompt token pieces + their embedding rows (bf16, exact from the checkpoint) so the page needs no tokenizerand no 600 MB embedding table. Checked against the HF tokenizer for random head boxes.usage: make_data.py OUT_DIR"""import jsonimport os, random, sysfrom pathlib import Pathimport numpy as npfrom safetensors import safe_openfrom transformers import AutoProcessorSP = 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"); sys.path.insert(0, f"{SP}/work")from look_anything.processing_attend_thing import build_chat_textimport ref_look as Rout = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)p = AutoProcessor.from_pretrained(f"{SP}/ckpt/LA-2B"); tok = p.tokenizerIMG = tok.convert_tokens_to_ids("<|image_pad|>")
def ids_of(prompt, n_img=1): return tok(build_chat_text(p, prompt).replace("<|image_pad|>", "<|image_pad|>" * n_img))["input_ids"]
def split(ids): a = ids.index(IMG); b = len(ids) - ids[::-1].index(IMG) return ids[:a], ids[b:]
head, mid_point = split(ids_of(R.prompt_for("point")))head_b, mid_box = split(ids_of(R.prompt_for("box")))ref = ids_of(R.prompt_for("b2p:1,2,3,4")); head_c, post = split(ref)digit = {str(d): tok.convert_tokens_to_ids(str(d)) for d in range(10)}; comma = tok.convert_tokens_to_ids(",")k = post.index(digit["1"]) # the box starts right after ' ['mid_b2p, tail_b2p = post[:k], post[post.index(tok.convert_tokens_to_ids("]."))] if False else post[post.index(tok.convert_tokens_to_ids("].")):]assert head == head_b == head_cpieces = {"head": head, "point": mid_point, "box": mid_box, "b2p": {"mid": mid_b2p, "tail": tail_b2p}, "digits": [digit[str(d)] for d in range(10)], "comma": comma}
def build(kind, box=None, n_img=7): if kind == "b2p": mid = pieces["b2p"]["mid"] for ch in ",".join(str(v) for v in box): mid = mid + [pieces["comma"] if ch == "," else pieces["digits"][int(ch)]] tail = pieces["b2p"]["tail"] return head + [IMG] * n_img + mid + tail return head + [IMG] * n_img + pieces[kind]
assert build("point") == ids_of(R.prompt_for("point"), 7) and build("box") == ids_of(R.prompt_for("box"), 7)rng = random.Random(0)for _ in range(500): x1, y1 = rng.randint(0, 900), rng.randint(0, 900); box = [x1, y1, rng.randint(x1, 1000), rng.randint(y1, 1000)] assert build("b2p", box) == ids_of(R.prompt_for("b2p:" + ",".join(map(str, box))), 7), boxprint("pieces verified: point, box, 500 random head boxes")
used = sorted(set(head + mid_point + mid_box + mid_b2p + tail_b2p + pieces["digits"] + [comma]))w = Nonewith safe_open(f"{SP}/ckpt/LA-2B/backbone/model.safetensors", "pt") as f: key = next(k for k in f.keys() if k.endswith("embed_tokens.weight")); print("embedding key", key) emb = f.get_tensor(key) # bf16 [V, 2048]rows = emb[used].view(__import__("torch").int16).numpy().astype("<i2") # raw bf16 bitsrows.tofile(out / "prompt_rows.bf16")pieces["row_ids"] = usedjson.dump(pieces, open(out / "prompt.json", "w"))print(len(used), "rows,", rows.nbytes, "bytes;", "image_pad", IMG, "vision tokens in pieces", head[-1], mid_point[0])json.dump({"image_pad": IMG, "ids": {"vision_start": tok.convert_tokens_to_ids("<|vision_start|>"), "vision_end": tok.convert_tokens_to_ids("<|vision_end|>")}}, open(out / "ids.json", "w"))1234567891011121314151617"""Re-save the quantized parts as single .onnx files (no external data) and write manifest.json.usage: pack.py Q8_DIR FP32_DIR DATA_DIR OUT_DIR Q8_DIR quantize.py output (vis_a vis_b lm_1..4); FP32_DIR export_look.py output (heads, query_tokens.f32) DATA_DIR make_data.py output (prompt.json, ids.json, prompt_rows.bf16)"""import hashlib, json, os, shutil, sysimport onnxq8, fp32, data, out = sys.argv[1:5]os.makedirs(out, exist_ok=True)files = {}for p in ("vis_a", "vis_b", "lm_1", "lm_2", "lm_3", "lm_4", "heads"): src = f"{q8}/{p}/{p}.onnx" if p != "heads" else f"{fp32}/heads/heads.onnx" onnx.save_model(onnx.load(src), f"{out}/{p}.onnx") files[p] = {"path": f"{p}.onnx", "bytes": os.path.getsize(f"{out}/{p}.onnx"), "sha256": hashlib.sha256(open(f"{out}/{p}.onnx", "rb").read()).hexdigest()}extra = {}for name, d in (("prompt.json", data), ("ids.json", data), ("prompt_rows.bf16", data), ("query_tokens.f32", fp32)): shutil.copy(f"{d}/{name}", f"{out}/{name}"); extra[name] = {"path": name, "bytes": os.path.getsize(f"{out}/{name}")}json.dump({"format": 1, "files": files, "data": extra, "order": list(files), "total_bytes": sum(f["bytes"] for f in files.values())}, open(f"{out}/manifest.json", "w"), indent=1)1234567891011121314151617181920212223"""Two-pass MatMulNBits: nodes whose name matches --lo get LO bits, all other constant-weight MatMuls HI bits.usage: quant_mixed.py PART SRC OUT HI_BITS LO_BITS LO_REGEX [--block 32]"""import sys, re, logging, timefrom pathlib import Pathimport onnxfrom onnxruntime.quantization.matmul_nbits_quantizer import DefaultWeightOnlyQuantConfig, MatMulNBitsQuantizerlogging.basicConfig(level=logging.WARNING)part, src, out, hi, lo, rx = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), re.compile(sys.argv[6])t0 = time.time()m = onnx.load(str(src / part / f"{part}.onnx"))const = {i.name: i for i in m.graph.initializer}mm = [n for n in m.graph.node if n.op_type == "MatMul" and n.input[1] in const and len(const[n.input[1]].dims) == 2]lo_nodes = {n.name for n in mm if rx.search(n.name)}; hi_nodes = {n.name for n in mm} - lo_nodesdef run(model, bits, include): ex = [n.name for n in model.graph.node if n.op_type == "MatMul" and n.name not in include] q = MatMulNBitsQuantizer(model, bits=bits, block_size=32, is_symmetric=False, nodes_to_exclude=ex, algo_config=DefaultWeightOnlyQuantConfig(block_size=32, is_symmetric=False, bits=bits)) q.process(); return q.model.modelm = run(m, hi, hi_nodes); m = run(m, lo, lo_nodes)d = out / part; d.mkdir(parents=True, exist_ok=True)for f in d.glob("*"): f.unlink()onnx.save_model(m, str(d / f"{part}.onnx"), save_as_external_data=True, all_tensors_to_one_file=True, location=f"{part}.onnx.data", size_threshold=1024)print(f"{part}: hi={len(hi_nodes)}@q{hi} lo={len(lo_nodes)}@q{lo} {sum(f.stat().st_size for f in d.glob('*'))/1e6:.0f} MB in {time.time()-t0:.0f}s", flush=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Weight-only MatMulNBits quantization of one exported detector part.
usage: quant_det.py PART SRC_DIR OUT_DIR BITS BLOCK [--sym] [--skip REGEX]Constant-weight Gemm nodes become MatMul + Add first (the quantizer only handles MatMul).MatMul nodes whose name matches --skip stay fp32. Writes OUT_DIR/PART/PART.onnx(+.data)."""from __future__ import annotations
import argparseimport loggingimport reimport timefrom pathlib import Path
import numpy as npimport onnxfrom onnx import helper, numpy_helperfrom onnxruntime.quantization.matmul_nbits_quantizer import DefaultWeightOnlyQuantConfig, MatMulNBitsQuantizer
logging.basicConfig(level=logging.WARNING)ap = argparse.ArgumentParser()ap.add_argument("part")ap.add_argument("src", type=Path)ap.add_argument("out", type=Path)ap.add_argument("bits", type=int)ap.add_argument("block", type=int)ap.add_argument("--sym", action="store_true")ap.add_argument("--skip", default=None)a = ap.parse_args()
t0 = time.time()src, dst = a.src / a.part / f"{a.part}.onnx", a.out / a.part / f"{a.part}.onnx"dst.parent.mkdir(parents=True, exist_ok=True)model = onnx.load(str(src))g = model.graphinits = {i.name: i for i in g.initializer}nodes = []for n in g.node: if n.op_type != "Gemm" or n.input[1] not in inits: nodes.append(n) continue at = {x.name: helper.get_attribute_value(x) for x in n.attribute} assert at.get("alpha", 1.0) == 1.0 and at.get("beta", 1.0) == 1.0 and not at.get("transA", 0) w = numpy_helper.to_array(inits[n.input[1]]) w = w.T if at.get("transB", 0) else w wn = f"gemm_w_{len(nodes)}" g.initializer.append(numpy_helper.from_array(np.ascontiguousarray(w), wn)) mo = n.output[0] + "_mm" if len(n.input) > 2 else n.output[0] nodes.append(helper.make_node("MatMul", [n.input[0], wn], [mo], name=f"{n.name}_mm")) if len(n.input) > 2: nodes.append(helper.make_node("Add", [mo, n.input[2]], [n.output[0]], name=f"{n.name}_add"))del g.node[:]g.node.extend(nodes)used = {i for n in g.node for i in n.input}keep = [i for i in g.initializer if i.name in used]del g.initializer[:]g.initializer.extend(keep)
const = {i.name: i for i in g.initializer}skip = re.compile(a.skip) if a.skip else None# only 2-D constant weights with K divisible by the block are worth quantizingexclude = [n.name for n in g.node if n.op_type == "MatMul" and ( n.input[1] not in const or len(const[n.input[1]].dims) != 2 or (skip and skip.search(n.name)))]cfg = DefaultWeightOnlyQuantConfig(block_size=a.block, is_symmetric=a.sym, bits=a.bits)q = MatMulNBitsQuantizer(model, bits=a.bits, block_size=a.block, is_symmetric=a.sym, nodes_to_exclude=exclude, algo_config=cfg)q.process()model = q.model.modelfor f in dst.parent.glob("*"): f.unlink()onnx.save_model(model, str(dst), save_as_external_data=True, all_tensors_to_one_file=True, location=f"{a.part}.onnx.data", size_threshold=1024)ops: dict[str, int] = {}for n in model.graph.node: ops[n.op_type] = ops.get(n.op_type, 0) + 1size = sum(f.stat().st_size for f in dst.parent.glob("*")) / 1e6print(f"{a.part} q{a.bits} b{a.block}{' sym' if a.sym else ''}: {size:.0f} MB, MatMulNBits={ops.get('MatMulNBits', 0)} " f"MatMul left={ops.get('MatMul', 0)} Gemm left={ops.get('Gemm', 0)} in {time.time()-t0:.0f}s", flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Reference outputs of LookAnything LA-2B (fp32 on CPU, the repo's own code) for the one-passquery path (point, box, heatmap), plus the intermediate tensors the ONNX parts must reproduce.
usage: ref_look.py OUT_DIR PROMPT_KEY IMAGE [IMAGE ...] PROMPT_KEY: point | box | b2p:x1,y1,x2,y2 (head box in 0..1000)"""from __future__ import annotations
import jsonimport osimport sysimport time
import numpy as npimport torch
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 PIL import Image # noqa: E402
from look_anything import inference as li # noqa: E402
torch.set_num_threads(4)CKPT = f"{SP}/ckpt/LA-2B"MIN_PIXELS, MAX_PIXELS = 28 * 28 * 16, int(os.environ.get("LOOK_MAXPX", 28 * 28 * 576)) # Predictor defaults (what serve.py uses)TEMPLATES = { "point": "Where is the person looking at? Output only its normalized point as (x,y), using integer coordinates from 0 to 1000.", "box": "Where is the person looking at? Output only its normalized bounding box as [x1,y1,x2,y2], using integer coordinates from 0 to 1000.",}
def prompt_for(key: str) -> str: if key.startswith("b2p:"): return (f"Locate the gaze target of the person with head box [{key[4:]}]. " "Output only its normalized point as (x,y), using integer coordinates from 0 to 1000.") return TEMPLATES[key]
if __name__ == "__main__": out, key, images = sys.argv[1], sys.argv[2], sys.argv[3:] os.makedirs(out, exist_ok=True) t0 = time.time() proc = li.load_processor(CKPT, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS) # transformers 5.4.0's Qwen2VLImageProcessor has no min_pixels attribute, so load_processor's hasattr guard # skips the limits; setting them afterwards does take effect (inference_config.json: 12544 / 451584). proc.image_processor.min_pixels, proc.image_processor.max_pixels = MIN_PIXELS, MAX_PIXELS model = li.load_model(CKPT, device="cpu", dtype=torch.float32) print(f"loaded {time.time()-t0:.0f}s", flush=True)
cap = {} orig_prepare, orig_run = model._prepare, model._run_backbone
def prepare(*a, **k): r = orig_prepare(*a, **k) cap["inputs_embeds"], cap["deepstack"], cap["prompt_len"] = r[0], r[5], r[3] return r
def run(inputs_embeds, position_ids, full_mask, attn_2d, vpm, deepstack): h = orig_run(inputs_embeds, position_ids, full_mask, attn_2d, vpm, deepstack) cap.update(position_ids=position_ids, full_mask=full_mask, hidden=h) return h
model._prepare, model._run_backbone = prepare, run prompt = prompt_for(key) results = {} for p in images: t0 = time.time() name = os.path.splitext(os.path.basename(p))[0] img = Image.open(p).convert("RGB") enc = li._encode_image(proc, img, prompt, "cpu") with torch.inference_mode(): o = model(input_ids=enc["input_ids"], attention_mask=enc.get("attention_mask"), pixel_values=enc["pixel_values"], image_grid_thw=enc["image_grid_thw"], answer_input_ids=None, compute_lm_loss=False, compute_auxiliary=True, compute_gaze_heatmap=True, auxiliary_heads=("heatmap", "head_mask", "point", "box"), return_predictions=True) pr = o["predictions"] r = {"prompt": prompt, "size": list(img.size), "grid_thw": enc["image_grid_thw"][0].tolist(), "n_ids": int(enc["input_ids"].shape[1]), "point": pr["point"][0].tolist(), "box": pr["box"][0].tolist(), "seconds": round(time.time() - t0, 1)} hm = pr["gaze_heatmap_logits"][0, 0].float() am, ex = li._heatmap_points(hm, model.config.heatmap_coordinate_mode) r.update(heatmap_argmax=am, heatmap_expect=ex) results[name] = r np.savez_compressed( f"{out}/{name}.npz", input_ids=enc["input_ids"].numpy(), pixel_values=enc["pixel_values"].numpy(), grid=enc["image_grid_thw"].numpy(), inputs_embeds=cap["inputs_embeds"].numpy(), deepstack=np.stack([d.numpy() for d in cap["deepstack"]]), position_ids=cap["position_ids"].numpy(), full_mask=cap["full_mask"].numpy(), hidden=cap["hidden"].numpy(), heatmap=hm.numpy(), head_mask=pr["head_mask_logits"][0, 0].float().numpy(), prompt_len=np.array(cap["prompt_len"])) print(f"{name:14s} grid {r['grid_thw']} ids {r['n_ids']} point {np.round(r['point'], 3).tolist()} box {np.round(r['box'], 3).tolist()} " f"hm-argmax {np.round(am, 3).tolist()} ({r['seconds']}s)", flush=True) json.dump(results, open(f"{out}/results.json", "w"), indent=1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""numpy versions of everything the page computes outside the ONNX graphs (the JS port is checkedagainst these, and these against transformers): vision position tables, M-RoPE ids and tables, mask."""from __future__ import annotations
import numpy as np
NUM_GRID = 48 # sqrt(num_position_embeddings 2304)MERGE = 2
def vision_tables(gh: int, gw: int): """gh, gw: patch grid (before the 2x2 merge). Returns idx [4,N] i64, w [4,N] f32 (bilinear position embedding lookups) and cos, sin [N,64] f32, all in merge order, as Qwen3VLVisionModel builds them.""" hs = np.linspace(0, NUM_GRID - 1, gh, dtype=np.float32) ws = np.linspace(0, NUM_GRID - 1, gw, dtype=np.float32) hf, wf = hs.astype(np.int32), ws.astype(np.int32) hc, wc = np.minimum(hf + 1, NUM_GRID - 1), np.minimum(wf + 1, NUM_GRID - 1) dh, dw = hs - hf, ws - wf idx = [(hf[:, None] * NUM_GRID + wf[None]), (hf[:, None] * NUM_GRID + wc[None]), (hc[:, None] * NUM_GRID + wf[None]), (hc[:, None] * NUM_GRID + wc[None])] wt = [((1 - dh)[:, None] * (1 - dw)[None]), ((1 - dh)[:, None] * dw[None]), (dh[:, None] * (1 - dw)[None]), (dh[:, None] * dw[None])]
def merge_order(a): # [gh,gw] -> (gh/2, gw/2, 2, 2) flattened return a.reshape(gh // MERGE, MERGE, gw // MERGE, MERGE).transpose(0, 2, 1, 3).reshape(-1)
idx = np.stack([merge_order(i) for i in idx]).astype(np.int64) wt = np.stack([merge_order(w) for w in wt]).astype(np.float32) rows = merge_order(np.broadcast_to(np.arange(gh)[:, None], (gh, gw))) cols = merge_order(np.broadcast_to(np.arange(gw)[None], (gh, gw))) inv = (1.0 / (10000.0 ** (np.arange(0, 32, 2, dtype=np.float32) / 32))).astype(np.float32) # head_dim//2 = 32 -> 16 freqs table = np.outer(np.arange(max(gh, gw), dtype=np.float32), inv).astype(np.float32) emb = np.concatenate([table[rows], table[cols]], axis=1) # [N, 32] emb = np.concatenate([emb, emb], axis=1) # [N, 64] return idx, wt, np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32)
def positions(n_before: int, gh: int, gw: int, n_after: int): """get_rope_index for [text * n_before][image gh x gw merged tokens][text * n_after] -> [3, S] int64. gh, gw here are merged-token grid sizes.""" t = np.arange(n_before) pos = [np.stack([t, t, t])] cur = n_before n = gh * gw pos.append(np.stack([np.full(n, cur), cur + np.repeat(np.arange(gh), gw), cur + np.tile(np.arange(gw), gh)])) cur += max(gh, gw) t = np.arange(n_after) + cur pos.append(np.stack([t, t, t])) return np.concatenate(pos, axis=1).astype(np.int64)
def text_tables(pos: np.ndarray, theta: float = 5e6, section=(24, 20, 20), dim: int = 128): """pos [3,S] -> cos, sin [S,128] float32 with interleaved M-RoPE (T H W T H W ... then T).""" inv = 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) # [64] freqs = pos[:, :, None].astype(np.float32) * inv[None, None, :] # [3,S,64] ft = freqs[0].copy() for d, off in ((1, 1), (2, 2)): sl = slice(off, section[d] * 3, 3) ft[:, sl] = freqs[d][:, sl] emb = np.concatenate([ft, ft], axis=-1) return np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32)
def mask(prompt_len: int, n_per: int = 9, n_groups: int = 3, total: int | None = None): """Additive attention mask [S,S]: causal, and the three query groups cannot see each other.""" s = total or prompt_len + n_per * n_groups NEG = np.float32(np.finfo(np.float32).min) m = np.triu(np.full((s, s), NEG, np.float32), 1) for i in range(n_groups): for j in range(n_groups): if i != j: m[prompt_len + i * n_per: prompt_len + (i + 1) * n_per, prompt_len + j * n_per: prompt_len + (j + 1) * n_per] = NEG return m123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Run the exported parts on ORT CPU for the reference photos and compare with the PyTorch reference.usage: verify_look.py MODEL_DIR [IMAGE_NAME ...] (MODEL_DIR holds vis_a/vis_a.onnx ... heads/heads.onnx)"""import gcimport globimport jsonimport osimport sysimport time
import numpy as npimport onnxruntime as ort
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}/work")import tables as T # noqa: E402
root = sys.argv[1]only = set(sys.argv[2:])ref = json.load(open(f"{SP}/ref/results.json"))data = {os.path.basename(f)[:-4]: np.load(f) for f in sorted(glob.glob(f"{SP}/ref/*.npz")) if not only or os.path.basename(f)[:-4] in only}IMG_ID = 151655so = ort.SessionOptions(); so.log_severity_level = 3; so.intra_op_num_threads = 4sess = lambda p: ort.InferenceSession(f"{root}/{p}/{p}.onnx", so, providers=["CPUExecutionProvider"])st = {}for k, z in data.items(): ids = z["input_ids"][0]; first = int(np.where(ids == IMG_ID)[0][0]); n = int((ids == IMG_ID).sum()) gh, gw = int(z["grid"][0, 1]), int(z["grid"][0, 2]); S = z["inputs_embeds"].shape[1]; P = int(z["prompt_len"]) idx, wt, vc, vs = T.vision_tables(gh, gw) pos = T.positions(first, gh // 2, gw // 2, S - first - n); tc, ts = T.text_tables(pos) st[k] = dict(first=first, n=n, gh=gh, gw=gw, S=S, P=P, idx=idx, wt=wt, vc=vc, vs=vs, tc=tc, ts=ts, mask=T.mask(P, total=S))t0 = time.time()s = sess("vis_a")for k, z in data.items(): d = st[k]; d["x"], d["d0"], d["d1"] = s.run(None, {"patches": z["pixel_values"], "pos_idx": d["idx"], "pos_w": d["wt"], "cos": d["vc"], "sin": d["vs"]})s = sess("vis_b")for k in data: d = st[k]; d["img"], d["d2"] = s.run(None, {"x": d["x"], "cos": d["vc"], "sin": d["vs"]})print(f"vision {time.time()-t0:.0f}s", flush=True)for k, z in data.items(): d = st[k]; h = z["inputs_embeds"].copy(); h[0, d["first"]:d["first"] + d["n"]] = d["img"] ds = np.zeros((3, d["S"], 2048), np.float32) for i, t in enumerate((d["d0"], d["d1"], d["d2"])): ds[i, d["first"]:d["first"] + d["n"]] = t d["h"], d["ds"] = h, dsfor p in ("lm_1", "lm_2", "lm_3", "lm_4"): s = sess(p) for k in data: d = st[k]; feed = {"hidden": d["h"], "cos": d["tc"], "sin": d["ts"], "mask": d["mask"]} if p == "lm_1": feed["ds"] = d["ds"] d["h"] = s.run(None, feed)[0] print(f"{p} {time.time()-t0:.0f}s", flush=True) del s; gc.collect()s = sess("heads")rows = []for k, z in data.items(): d = st[k]; q = d["h"][:, d["P"]:d["P"] + 27] vis = np.ascontiguousarray(d["h"][:, d["first"]:d["first"] + d["n"]].reshape(1, d["gh"] // 2, d["gw"] // 2, 2048)) point, box, hm, hmask = s.run(None, {"gaze": np.ascontiguousarray(q[:, 18:27]), "head": np.ascontiguousarray(q[:, 9:18]), "vis": vis}) r = ref[k] am = np.unravel_index(hm[0, 0].argmax(), hm[0, 0].shape) pd = np.abs(point[0] - np.array(r["point"])).max(); bd = np.abs(box[0] - np.array(r["box"])).max() hd = float(np.abs(hm[0, 0] - z["heatmap"]).max()); hrel = hd / float(np.abs(z["heatmap"]).max()) hid = float(np.abs(d["h"][0] - z["hidden"][0]).max()) rows.append((k, pd, bd, hrel)) print(f"{k:14s} point {np.round(point[0], 3).tolist()} ref {np.round(r['point'], 3).tolist()} (d {pd:.4f}) | box d {bd:.4f} | heatmap argmax {am[1]/64:.3f},{am[0]/64:.3f} " f"ref {r['heatmap_argmax'][0]:.3f},{r['heatmap_argmax'][1]:.3f} rel err {hrel:.3f} | hidden max diff {hid:.3f}", flush=True)print("worst point diff %.4f, box %.4f, heatmap rel %.3f" % (max(r[1] for r in rows), max(r[2] for r in rows), max(r[3] for r in rows)))123version https://git-lfs.github.com/spec/v1oid sha256:6f9208513962fdff828c20d414a191a9fd118b5e9af7d5ec82341c729eec08besize 245064414123version https://git-lfs.github.com/spec/v1oid sha256:03a35f279b183a2c8574b3a0f8bcd054cdb363a14c8ac3df4d275eff14a74328size 233778779.gitattributes+2
LICENSEAdded+203
README.mdAdded+89
heads.onnxAdded+3
ids.jsonAdded+1
lm_1.onnxAdded+3
lm_2.onnxAdded+3
lm_3.onnxAdded+3
lm_4.onnxAdded+3
manifest.jsonAdded+68
prompt.jsonAdded+1
prompt_rows.bf16Added+3
query_tokens.f32Added+3
scripts/export_look.pyAdded+229
scripts/make_data.pyAdded+61
scripts/pack.pyAdded+17
scripts/quant_mixed.pyAdded+23
scripts/quantize.pyAdded+77
scripts/ref_look.pyAdded+90
scripts/tables.pyAdded+72
scripts/verify_look.pyAdded+66
vis_a.onnxAdded+3
vis_b.onnxAdded+3