nnopt port: Bonsai-Image-Ternary-4B-OpenCL
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+19-32
- LICENSEAdded+177
- NOTICEAdded+15
- README.mdAdded+94
- config.jsonAdded+71
- sm8850-gpu-ternary/README.mdAdded+117
- sm8850-gpu-ternary/REPRO.mdAdded+181
- sm8850-gpu-ternary/build.shAdded+73
- sm8850-gpu-ternary/build/bin/bonsai_imageAdded+3
- sm8850-gpu-ternary/build/bin/kernels/bench.clAdded+19
- sm8850-gpu-ternary/build/bin/kernels/gemm.clAdded+323
- sm8850-gpu-ternary/build/bin/kernels/ops.clAdded+259
- sm8850-gpu-ternary/build/weights/.stampAdded+1
- sm8850-gpu-ternary/build/weights/dit.binAdded+3
- sm8850-gpu-ternary/build/weights/dit.idxAdded+229
- sm8850-gpu-ternary/build/weights/te.binAdded+3
- sm8850-gpu-ternary/build/weights/te.idxAdded+217
- sm8850-gpu-ternary/build/weights/tokenizer.jsonAdded
- sm8850-gpu-ternary/build/weights/vae.binAdded+3
- sm8850-gpu-ternary/build/weights/vae.idxAdded+138
- sm8850-gpu-ternary/demo/demo.jsonAdded+55
- sm8850-gpu-ternary/demo/original0.pngAdded
- sm8850-gpu-ternary/demo/original1.pngAdded
- sm8850-gpu-ternary/demo/original2.pngAdded
- sm8850-gpu-ternary/demo/phone0.pngAdded
- sm8850-gpu-ternary/demo/phone0_metrics.jsonAdded+1
- sm8850-gpu-ternary/demo/phone1.pngAdded
- sm8850-gpu-ternary/demo/phone1_metrics.jsonAdded+1
- sm8850-gpu-ternary/demo/phone2.pngAdded
- sm8850-gpu-ternary/demo/phone2_metrics.jsonAdded+1
- sm8850-gpu-ternary/deploy.shAdded+22
- sm8850-gpu-ternary/fetch.shAdded+27
- sm8850-gpu-ternary/paths.shAdded+11
- sm8850-gpu-ternary/port.jsonAdded+7
- sm8850-gpu-ternary/report.htmlAdded+112
- sm8850-gpu-ternary/report/reproduce.shAdded+11
- sm8850-gpu-ternary/report/results.csvAdded+53
- sm8850-gpu-ternary/report/results.jsonAdded+1330
- sm8850-gpu-ternary/repro/DockerfileAdded+8
- sm8850-gpu-ternary/repro/bench.pyAdded+729
- sm8850-gpu-ternary/repro/inputs/tensors/encoder_hidden_states.npyAdded+3
- sm8850-gpu-ternary/repro/inputs/tensors/latents.npyAdded+3
- sm8850-gpu-ternary/repro/inputs/tensors/prompt_ids.npyAdded+3
- sm8850-gpu-ternary/repro/inputs/tensors/timestep.npyAdded+3
- sm8850-gpu-ternary/repro/inputs/tensors/vae_latents.npyAdded+3
- sm8850-gpu-ternary/repro/plan.jsonAdded+68
- sm8850-gpu-ternary/run.shAdded+6
- sm8850-gpu-ternary/src/cl_loader.cppAdded+70
- sm8850-gpu-ternary/src/clrt.cppAdded+157
- sm8850-gpu-ternary/src/clrt.hAdded+55
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122*.bin filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.gguf filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text*.so filter=lfs diff=lfs merge=lfs -text*.bf16 filter=lfs diff=lfs merge=lfs -text*.f16 filter=lfs diff=lfs merge=lfs -text*.f32 filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.tkb filter=lfs diff=lfs merge=lfs -text*.tqb filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -textsm8850-gpu-ternary/build/bin/bonsai_image filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177 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
123456789101112131415This software is copyright 2026-present Prism ML, Inc. It is available under the Apache 2.0 license.If you publicly deploy or redistribute this software, we would appreciate attribution such as: "Created using Bonsai Image by Prism ML."
This software is built from FLUX.2 [klein] 4B, Copyright 2026 Black Forest Labs, which is available under the Apache 2.0 License: https://huggingface.co/black-forest-labs/FLUX.2-klein-4B/blob/main/LICENSE.md
The text encoder is built from Qwen3-4B, Copyright 2024 Alibaba Cloud, which is available under the Apache 2.0 License: https://huggingface.co/Qwen/Qwen3-4B/blob/main/LICENSE
---
This repository is a modified version of prism-ml/bonsai-image-ternary-4B-unpacked by Prism ML, revision 30bbc032dd26939bff95c3d523477ad5065c3e1a.
Changes, made by nnopt (https://nnopt.dev):- `sm8850-gpu-ternary/` (nnopt job NN-C9116E): included: build/weights/te.bin, dit.bin, vae.bin with their .idx files, tokenizer.json and .stamp, the exact packs verified on the phone (made from the original checkpoint by tools/convert.py; DiT linears stay ternary, 2-bit + bf16 scale per 128; text encoder and VAE bf16). The runtime code (src/, build.sh, deploy.sh, run.sh) is new, written by nnopt's agents for this device.
Created using Bonsai Image by Prism ML.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394---license: apache-2.0base_model: prism-ml/bonsai-image-ternary-4B-unpackedpipeline_tag: text-to-imagetags:- on-device- nnopt- opencl- android- gpu- adreno- ternary- text-to-image- galaxy-s26-plus---
# bonsai-image-ternary-4B on Samsung Galaxy S26+ (OpenCL)
Ported and verified on a real Samsung Galaxy S26+ by [nnopt.dev](https://nnopt.dev) — AI agents that port and optimize models for the hardware you ship.
The model is [prism-ml/bonsai-image-ternary-4B-unpacked](https://huggingface.co/prism-ml/bonsai-image-ternary-4B-unpacked) by Prism ML, and it is theirs. The OpenCL port in this repository is nnopt's work: nnopt job NN-C9116E.
Created using Bonsai Image by Prism ML.
| | ||---|---|| Device | Samsung Galaxy S26+, Android 16 || Chip | Snapdragon 8 Elite Gen 5 (SM8850) || Processor | GPU (Adreno 840) || Runtime | hand-written C++ OpenCL runtime (no other engine) || Precision | fp32 activations and accumulation; DiT block linears ternary 2-bit + bf16 scale per 128 kept packed; text encoder, VAE and other weights bf16 || Modality | text -> image || Weights | included: build/weights/te.bin, dit.bin, vae.bin with their .idx files, tokenizer.json and .stamp, the exact packs verified on the phone (made from the original checkpoint by tools/convert.py; DiT linears stay ternary, 2-bit + bf16 scale per 128; text encoder and VAE bf16) || nnopt job | NN-C9116E (port) || Folder | [`sm8850-gpu-ternary/`](https://huggingface.co/nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL/tree/main/sm8850-gpu-ternary) |
## Verified results
nnopt built the folder from a clean copy, deployed it to the device and checked it against the model's reference code on hidden inputs. The full report is `report.html` in the folder.
- Passed. Matches the reference 2 of 2 cases- Max abs error 0.062 (bar rtol 0.01, atol 0.01xrms)- Time per call 35,181 ms (35.2 s: Qwen3 text encoder 512 tokens + one ternary DiT step at 512x512 + VAE decode; transformer 10.0 s, vae decoder 4.0 s)- Load time 1.13 s- Peak memory 5,728 MB
## Use it
```mkdir Bonsai-Image-Ternary-4B-OpenCL && cd Bonsai-Image-Ternary-4B-OpenCLcurl -fsSL https://huggingface.co/nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL/resolve/main/config.json -o config.jsonhf download nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL --include "sm8850-gpu-ternary/*" --local-dir .cd sm8850-gpu-ternarybash fetch.shbash deploy.sh /data/local/tmp/nnopt/port # adb: program into DEST, weight packs into /data/local/tmp/nnopt/bonsai_image_weightsadb shell "cd /data/local/tmp/nnopt/port && sh ./run.sh --prompt 'A cat holding a sign that says hello world' \ --seed 0 --png /data/local/tmp/nnopt/cat.png --metrics /data/local/tmp/nnopt/cat.json"adb pull /data/local/tmp/nnopt/cat.png```
Needs: An Adreno phone with ~6 GB free RAM and ~7 GB free storage (tested: Galaxy S26+); adb. Rebuilding needs Linux x86-64 or macOS arm64 with git, curl, python3 (venv), unzip and the `hf` CLI.
Included weight files (verified on the phone):
| File | Size | sha256 ||---|---|---|| `sm8850-gpu-ternary/build/weights/te.bin` | 6,228,466,688 bytes | `b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4` || `sm8850-gpu-ternary/build/weights/dit.bin` | 1,367,734,272 bytes | `f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1` || `sm8850-gpu-ternary/build/weights/vae.bin` | 99,317,260 bytes | `54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5` || `sm8850-gpu-ternary/build/weights/te.idx` | 6,414 bytes | `eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b` || `sm8850-gpu-ternary/build/weights/dit.idx` | 7,614 bytes | `4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a` || `sm8850-gpu-ternary/build/weights/vae.idx` | 4,104 bytes | `d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07` || `sm8850-gpu-ternary/build/weights/tokenizer.json` | 4,561,647 bytes | `58e0ac44f0a640c2b4a1cfbea927ef695fd0c2b4d2e0e614e6a3e33684e89069` |
Optional: rebuild from the original weights instead.
```hf download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/weightsrm -f build/weights/.stamp && INPUTS_DIR="$PWD/inputs" bash build.sh # NDK r27d + numpy into .deps/, rebuilds the program and build/weights/```
Determinism checked: re-running tools/convert.py and tools/tokjson.py on the pinned original weights gives byte-identical files (same sha256 for te.bin, dit.bin, vae.bin, the .idx files, tokenizer.json).
`README.md` in the folder has every flag, the requirements and the known limits; `REPRO.md` (where present) reproduces the measurements.
## License
Apache 2.0, like prism-ml/bonsai-image-ternary-4B-unpacked: see LICENSE and NOTICE.
## Made with nnopt
[nnopt](https://nnopt.dev) is a platform where AI agents port, optimize and benchmark a model for a specific device. They write the runtime code on the real device, and a locked verification kit then checks the result against the model's own reference code before anything ships. Every number on this page comes from that check.
Want your model on your device? Start a job at [nnopt.dev](https://nnopt.dev).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071{ "nnopt_manifest": 1, "repo": "nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL", "model": { "name": "bonsai-image-ternary-4B", "source_repo": "prism-ml/bonsai-image-ternary-4B-unpacked", "source_revision": "30bbc032dd26939bff95c3d523477ad5065c3e1a", "authors": "Prism ML", "license": "apache-2.0" }, "variants": [ { "id": "sm8850-gpu-ternary", "device": "Samsung Galaxy S26+", "chip": "Snapdragon 8 Elite Gen 5 (SM8850)", "os": "Android 16", "processor": "GPU (Adreno 840)", "runtime": "hand-written C++ OpenCL runtime (no other engine)", "runtime_version": "OpenCL 3.0", "precision": "fp32 activations and accumulation; DiT block linears ternary 2-bit + bf16 scale per 128 kept packed; text encoder, VAE and other weights bf16", "weights": "included: build/weights/te.bin, dit.bin, vae.bin with their .idx files, tokenizer.json and .stamp, the exact packs verified on the phone (made from the original checkpoint by tools/convert.py; DiT linears stay ternary, 2-bit + bf16 scale per 128; text encoder and VAE bf16)", "nnopt_job": "NN-C9116E", "job_kind": "port", "verified": { "verdict": "Passed. Matches the reference 2 of 2 cases; Max abs error 0.062 (bar rtol 0.01, atol 0.01xrms)", "speed": "Time per call 35,181 ms (35.2 s: Qwen3 text encoder 512 tokens + one ternary DiT step at 512x512 + VAE decode; transformer 10.0 s, vae decoder 4.0 s); Load time 1.13 s; Peak memory 5,728 MB" }, "weight_files": [ { "path": "sm8850-gpu-ternary/build/weights/te.bin", "size": 6228466688, "sha256": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4" }, { "path": "sm8850-gpu-ternary/build/weights/dit.bin", "size": 1367734272, "sha256": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1" }, { "path": "sm8850-gpu-ternary/build/weights/vae.bin", "size": 99317260, "sha256": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5" }, { "path": "sm8850-gpu-ternary/build/weights/te.idx", "size": 6414, "sha256": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b" }, { "path": "sm8850-gpu-ternary/build/weights/dit.idx", "size": 7614, "sha256": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a" }, { "path": "sm8850-gpu-ternary/build/weights/vae.idx", "size": 4104, "sha256": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07" }, { "path": "sm8850-gpu-ternary/build/weights/tokenizer.json", "size": 4561647, "sha256": "58e0ac44f0a640c2b4a1cfbea927ef695fd0c2b4d2e0e614e6a3e33684e89069" } ], "rebuild_determinism": "Determinism checked: re-running tools/convert.py and tools/tokjson.py on the pinned original weights gives byte-identical files (same sha256 for te.bin, dit.bin, vae.bin, the .idx files, tokenizer.json).", "fetch": "sm8850-gpu-ternary/fetch.sh" } ], "license": "apache-2.0", "made_by": "nnopt (https://nnopt.dev)"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# bonsai-image-ternary-4B on the Galaxy S26+ GPU (hand-written OpenCL)
FLUX.2-klein-4B with a ternary diffusion transformer (prism-ml/bonsai-image-ternary-4B-unpacked), the wholetext-to-image pipeline on the Adreno 840 GPU of a Samsung Galaxy S26+ (Snapdragon 8 Elite Gen 5). It usesa C++ runtime over OpenCL written for this port, with no other inference engine on the phone.
- **Text encoder**: Qwen3-4B, 27 of 36 layers (prompt_embeds = hidden states of layers 9, 18 and 27). - The bf16 weights are streamed per layer from an mmapped pack; the next layer uploads on a second queue while the current one computes.- **Transformer**: 5 double and 20 single blocks. - Block linears are exactly ternary. They are kept packed on the GPU as 2-bit codes with one bf16 scale per 128 inputs (2.125 bits per weight). - They are decoded inside the GEMM's tile load and never dequantized to memory.- **VAE decoder**: its convolutions run as implicit-im2col GEMMs with bf16 weights.- **GEMM**: one tiled fp32 kernel. The activation operand is copied into an RGBA float image and read through the texture cache; the weight tile goes through local memory as half (exact for bf16 and ternary x bf16 scale).- **Precision**: fp32 activations and fp32 accumulation everywhere (the reference is fp32 on the CPU).- **On the CPU**: only the tokenizer (the customer's adreno-llms byte-level BPE), the noise (bit-compatible with `torch.randn` on the CPU), the FlowMatch Euler update and the PNG writer.
## Requirements- An Android arm64 phone with an Adreno GPU and the vendor OpenCL driver (/vendor/lib64/libOpenCL.so). - Tested on the Galaxy S26+ (Adreno 840, driver 0842.19.7). - About 6 GB of free RAM; peak RSS is 5.6 GB, including the mmapped text-encoder pages. - About 7 GB of free storage under /data/local/tmp.- Build host: Linux x86-64 or macOS arm64 with git, curl, python3 (with venv), unzip and adb. - build.sh fetches and pins the rest into `.deps/`: - Android NDK r27d (sha256-checked). - Khronos OpenCL-Headers v2024.10.24 (commit-checked). - numpy 2.1.3 in its own venv, for the weight converter.- Weights: the Hugging Face repo prism-ml/bonsai-image-ternary-4B-unpacked, downloaded into `$INPUTS_DIR/weights/`. - Example: `huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --local-dir inputs/weights`.
## Build, deploy, run```INPUTS_DIR=/path/to/inputs bash build.sh # program + weight packs (te/dit/vae .bin/.idx, ~7 GB) + tokenizer.jsonbash deploy.sh /data/local/tmp/nnopt/port # adb: program into DEST, weights into /data/local/tmp/nnopt/bonsai_image_weights````build.sh` converts the weights once (it keeps a stamp). `deploy.sh` pushes the weights only when that stamp changed.
### Prompt in, image out (512x512, 4 steps, guidance 1, like the diffusers pipeline)```adb shell "cd /data/local/tmp/nnopt/port && sh ./run.sh --prompt 'A cat holding a sign that says hello world' \ --seed 0 --png /data/local/tmp/nnopt/cat.png --metrics /data/local/tmp/nnopt/cat.json"adb pull /data/local/tmp/nnopt/cat.png```Flags:- `--prompt TEXT` or `--prompt-file F`.- `--seed S`: the same seed gives the same noise as `torch.Generator("cpu").manual_seed(S)`.- `--steps N`: default 4.- `--png OUT`.- `--metrics M.json`.- Environment `NNOPT_AHALF=1`: opt-in, not the original precision. The ternary transformer GEMMs read their activations as fp16 from the texture, with fp32 math. - Each step is about 16% faster (11.05 to 9.3 s). - On the public case noise_pred stays within tolerance. - Off by default.
### Tensors in, tensors out (the graded kernel contract)```sh ./run.sh --inputs IN_DIR [--repeat R] --out OUT_DIR --metrics M.json```Inputs:- `prompt_ids` int32 [1,16]: user tokens, spliced into the Qwen3 chat template and padded to 512.- `latents` f32 [1,1024,128].- `timestep` f32 [1], in [0,1].- `encoder_hidden_states` f32 [1,512,7680].- `vae_latents` f32 [1,1024,128].
Outputs (fp16):- `prompt_embeds` [1,512,7680].- `noise_pred` [1,1024,128]: one transformer step.- `image` [1,3,512,512]: VAE decode in [0,1].
### Check```nnopt-verify check --split public --bundle reference --port /data/local/tmp/nnopt/port --executor adb````bonsai_image --selftest` checks every GEMM variant on the GPU against the CPU and times the large GEMMs.
## Measured (Galaxy S26+, GPU clock capped at 902 MHz)| what | time ||---|---|| one graded call (text encoder + 1 DiT step + VAE) | 17.9 s (TE 3.25 s, DiT 11.0 s, VAE 3.65 s) || the same, back to back in the kit's benchmark (the phone heats up) | 19.5–24.5 s per request || full image, 4 steps, 512x512, prompt to PNG | 51.1 s (TE 3.2 s, 4 DiT steps 44.2 s, VAE 3.65 s); load 1.1 s; 52.6 s wall from adb || GEMM throughput (ternary and bf16, fp32 math, A through the texture path) | ~1000 GFLOP/s (VAE convs ~750) |
Accuracy:- Public check: 2 of 2 cases pass, 0 mismatching elements, min cosine 0.9999999989.- Demo images differ from the original fp32 CPU pipeline by 0.001–0.003 grey levels on average (out of 255).
## Known limits- 512x512 only: the RoPE position tables and the buffers are sized for a 32x32 latent grid.- Prompts are capped at 500 tokens: the 512-token template minus 12.- Guidance-distilled model, so there is no CFG and no negative prompt (as in the pipeline at guidance 1).- The tokenizer's Unicode classes are exact for ASCII and approximate beyond (see src/third_party/tokenizer.h).- Everything is fp32 math. The GEMMs run at about 40% of the GPU's fp32 peak (2.55 TFLOP/s measured). See NOTES.md for what is left.
## Verified by nnopt
**Passed** prism-ml/bonsai-image-ternary-4B-unpacked on Samsung Galaxy S26+ (2026-11-29). nnopt built this folder from a clean copy, deployed it to the device and ran it on hidden inputs; the full report is report.html.
| Check | Measured | Bar | Result ||---|---|---|---|| Outputs match your reference code | Max abs error 0.062 | rtol 0.01, atol 0.01×rms (very close) | pass || Runs on OpenCL | src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e); | the runtime you asked for | pass || Runs on the GPU | checked on every run: GPU opened, no NPU | the processor you asked for | pass |
| Speed | This port ||---|---|| Time per call | 35,181 ms || Load time | 1.13 s || Peak memory | 5,728 MB |
| Measurement | Median ||---|---|| Time per call | 35180.9 ms || Load time | 1126.4 ms || Peak memory | 5728.0 MB |
To get these results on your own device, follow REPRO.md.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181# Reproduce: prism-ml/bonsai-image-ternary-4B-unpacked on Samsung Galaxy S26+
nnopt ported this (NN-C9116E, 2026-11-29). Runtime: hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine), original. Follow the steps on the same device model and OS build; the results should land within the tolerances in the last table.
## 1. Device
| Property | nnopt ran on ||---|---|| Chip | Snapdragon 8 Elite Gen 5 || GPU | Adreno 840 || Memory | 12 GB || OS | Android 16 |
Keep the phone plugged in, screen on and awake (Developer options > Stay awake), no other apps open, and let it rest about 10 minutes before measuring (a warm phone throttles).
## 2. Tools
**Tested:** nnopt built this folder from scratch on 2026-11-29 in the public image `ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac` with only these packages installed: git, curl, python3, python3-venv, build-essential, unzip, xz-utils. build.sh fetched everything else itself (its downloads are listed under step 3), and that build is the one nnopt deployed and measured.
Any Linux x86-64 machine with those packages builds it. build.sh is written to build on macOS arm64 as well (Xcode command line tools, git, curl, python3); nnopt did not test that for this deliverable.
| Tool | Version | Get it ||---|---|---|| gcc | 13.3.0 | – || Python | 3.12.3 | https://www.python.org/downloads/ || git | 2.43.0 | – || curl | 8.5.0 | – |
To deploy and measure you also need adb (Android platform-tools) and python3 (3.8 or newer, no packages).
build.sh and deploy.sh read these environment variables:
- `ANDROID_NDK`: the Android NDK folder (same as ANDROID_NDK_HOME)- `BUILD`: set it before building- `DEPS`: set it before building- `INPUTS_DIR`: the folder step 3 fills with the model and inputs (one folder per source, as named there)- `OPENCL_ANDROID_INCLUDE`: the OpenCL headers' folder (the one holding CL/)- `ROOT`: set it before building- `WORK`: set it before building
The same machine in Docker (`repro/Dockerfile`: the public image and packages above, nothing else):
```docker build --platform linux/amd64 -t build-env reprodocker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:/src" -w /src -v "$PWD/inputs:/inputs:ro" -e INPUTS_DIR=/inputs build-env bash build.sh```
## 3. Model and inputs
**reference_code**: Hugging Face `prism-ml/bonsai-image-ternary-4B-unpacked` at revision `30bbc032dd26939bff95c3d523477ad5065c3e1a`.
```huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/reference_code```
| File | Size | sha256 ||---|---|---|| .gitattributes | 1.5 KB | `caf3ca02d5e883f643e939cbed54f94237f94c171797f0dfea5e25c7e33315b3` || LICENSE | 9.9 KB | `69849221bfb90053de2134ef5e6d540287b4b98062326492f1f96f5da685524b` || NOTICE.md | 623 B | `bbefa4a26b836efc040c1a0f155a425d1d833eae1b2534ffc414b1eada3cd922` || README.md | 1.7 KB | `b4a33cfe18326c5d2ec5bc55dce0b998574c338436aa3c3763510abd998e5fe7` || assets/bonsai-logo.svg | 510 B | `91b32517f47dad96a486b408b6b1d2a1cee554fe203dfd44e1df64329f79011f` || manifest.json | 3.6 KB | `f6733ec1651d12480bbfdca3b9ba7e55630ab843a68fcc7c8ed109a9770a9171` || model_index.json | 446 B | `51a76cb1cf3ed37423a1128c79c22faee8e6fbe7f5aaeb737f0a258930dbaac0` || scheduler/scheduler_config.json | 486 B | `067afb012cef64553a763447d1efd93daeffcc0123ca7e25b09f8de20b90762e` || text_encoder/config.json | 1.5 KB | `214b4c29a0d975e9fddf9994a5673f22cb2c4c5750352f9227c2c3251ebeab40` || text_encoder/generation_config.json | 214 B | `4347b1aeed2b2b78bc059920a0b7f5fec71482e1344952b76d7665d638d71f13` || text_encoder/model-00001-of-00002.safetensors | 4.6 GB | `8c0506e7f4936fa7e26183a4fd8da4e2bdbc5990ba64ae441f965d51228f36ea` || text_encoder/model-00002-of-00002.safetensors | 2.9 GB | `82f2bd839378541b0557bfabaf37c7d3d637071fdcb73302dedd7cf61162ce07` || text_encoder/model.safetensors.index.json | 32.1 KB | `06b3d5319b6d76d1a4a2433419180016cfd54ed62d086a5e6567a809f8c82634` || tokenizer/added_tokens.json | 707 B | `c0284b582e14987fbd3d5a2cb2bd139084371ed9acbae488829a1c900833c680` || tokenizer/chat_template.jinja | 4.1 KB | `a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8` || tokenizer/merges.txt | 1.6 MB | `8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5` || tokenizer/special_tokens_map.json | 613 B | `76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd` || tokenizer/tokenizer.json | 10.9 MB | `aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4` || tokenizer/tokenizer_config.json | 5.3 KB | `443bfa629eb16387a12edbf92a76f6a6f10b2af3b53d87ba1550adfcf45f7fa0` || tokenizer/vocab.json | 2.6 MB | `ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910` || … 4 more | | |
**weights**: Hugging Face `prism-ml/bonsai-image-ternary-4B-unpacked` at revision `30bbc032dd26939bff95c3d523477ad5065c3e1a`.
```huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/weights```
| File | Size | sha256 ||---|---|---|| .gitattributes | 1.5 KB | `caf3ca02d5e883f643e939cbed54f94237f94c171797f0dfea5e25c7e33315b3` || LICENSE | 9.9 KB | `69849221bfb90053de2134ef5e6d540287b4b98062326492f1f96f5da685524b` || NOTICE.md | 623 B | `bbefa4a26b836efc040c1a0f155a425d1d833eae1b2534ffc414b1eada3cd922` || README.md | 1.7 KB | `b4a33cfe18326c5d2ec5bc55dce0b998574c338436aa3c3763510abd998e5fe7` || assets/bonsai-logo.svg | 510 B | `91b32517f47dad96a486b408b6b1d2a1cee554fe203dfd44e1df64329f79011f` || manifest.json | 3.6 KB | `f6733ec1651d12480bbfdca3b9ba7e55630ab843a68fcc7c8ed109a9770a9171` || model_index.json | 446 B | `51a76cb1cf3ed37423a1128c79c22faee8e6fbe7f5aaeb737f0a258930dbaac0` || scheduler/scheduler_config.json | 486 B | `067afb012cef64553a763447d1efd93daeffcc0123ca7e25b09f8de20b90762e` || text_encoder/config.json | 1.5 KB | `214b4c29a0d975e9fddf9994a5673f22cb2c4c5750352f9227c2c3251ebeab40` || text_encoder/generation_config.json | 214 B | `4347b1aeed2b2b78bc059920a0b7f5fec71482e1344952b76d7665d638d71f13` || text_encoder/model-00001-of-00002.safetensors | 4.6 GB | `8c0506e7f4936fa7e26183a4fd8da4e2bdbc5990ba64ae441f965d51228f36ea` || text_encoder/model-00002-of-00002.safetensors | 2.9 GB | `82f2bd839378541b0557bfabaf37c7d3d637071fdcb73302dedd7cf61162ce07` || text_encoder/model.safetensors.index.json | 32.1 KB | `06b3d5319b6d76d1a4a2433419180016cfd54ed62d086a5e6567a809f8c82634` || tokenizer/added_tokens.json | 707 B | `c0284b582e14987fbd3d5a2cb2bd139084371ed9acbae488829a1c900833c680` || tokenizer/chat_template.jinja | 4.1 KB | `a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8` || tokenizer/merges.txt | 1.6 MB | `8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5` || tokenizer/special_tokens_map.json | 613 B | `76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd` || tokenizer/tokenizer.json | 10.9 MB | `aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4` || tokenizer/tokenizer_config.json | 5.3 KB | `443bfa629eb16387a12edbf92a76f6a6f10b2af3b53d87ba1550adfcf45f7fa0` || tokenizer/vocab.json | 2.6 MB | `ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910` || … 4 more | | |
build.sh also downloads:
| Download | Pinned ||---|---|| `curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP"` | yes: a checksum or a versioned link || `git clone -q --depth 1 --branch "$OCL_TAG" https://github.com/KhronosGroup/OpenCL-Headers.git "$OCL_INC"` | NO: a branch head |
Unpinned downloads can fetch a newer version than nnopt built with; if your build differs, pin them to the versions in build.sh's log.
## 4. Build
```INPUTS_DIR=$PWD/inputs bash build.sh```
`INPUTS_DIR` is the folder step 3 filled (one folder per source, as named there).
## 5. Connect the device
```adb devices```
One device should be listed as `device`. With several, set `export ANDROID_SERIAL=<serial>` first.
## 6. Deploy
```bash deploy.sh /data/local/tmp/nnopt/port```
## 7. Run one input by hand
```adb shell 'mkdir -p /data/local/tmp/nnopt/port-repro-io'adb push repro/inputs/tensors /data/local/tmp/nnopt/port-repro-io/adb shell 'cd /data/local/tmp/nnopt/port && sh ./run.sh --inputs /data/local/tmp/nnopt/port-repro-io/tensors --out /data/local/tmp/nnopt/port-repro-io/out --metrics /data/local/tmp/nnopt/port-repro-io/metrics.json'adb pull /data/local/tmp/nnopt/port-repro-io/out .adb pull /data/local/tmp/nnopt/port-repro-io/metrics.json .```
`out` is the output; `metrics.json` holds the program's own timings: `load_ms`, and per request `total_ms`.
## 8. Measure
```python3 repro/bench.py```
bench.py runs nnopt's settings: 2 warm-up runs, then 5 timed runs of 3 requests each. Each run is timed on the device's own clock, and a paired shorter run checks the program's own timings, as nnopt does. `--sustained 600` adds nnopt's 10-minute sustained run.
## 9. Check the outputs
```python3 repro/bench.py --check```
Runs the 1 public case in `repro/expected/` and compares with the reference outputs of your reference code: every value within 0.0001 relative plus 0.0001 × RMS (float16: 0.01 and 0.01), integers within 0 (int8: 1).
1 more public case left out to keep the download small.
nnopt's full check also used hidden inputs and teacher-forced comparisons; report.html has every number.
## Expected results
| Metric | nnopt (median) | Spread (p10 to p90) | Reproduced if within ||---|---|---|---|| Time per request (ms) | 35,181 | 32,839 to 38,323 | ±10% |
Each tolerance is half of nnopt's own spread between requests, at least ±10%. Numbers land outside it when the device is warm or throttling, runs another OS build or driver, has apps or battery saver running, or is not plugged in. bench.py prints the same table for your device and writes it to `repro/results/`.
`report/reproduce.sh` runs steps 8 and 9 in one go.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env bash# Builds the Android arm64 program and converts the checkpoint into the packs it reads.# INPUTS_DIR=/path/to/inputs bash build.sh (INPUTS_DIR/weights = the Hugging Face repo# prism-ml/bonsai-image-ternary-4B-unpacked, see README.md)# Fetches its own pinned tools into .deps/: Android NDK r27d, Khronos OpenCL-Headers v2024.10.24, numpy 2.1.3 (venv).set -euo pipefail. "$(dirname "$0")/paths.sh"cd "$ROOT"if [ "$WORK" != "$ROOT" ]; then echo "build.sh: $ROOT is read-only, using $WORK for .deps/ and build/"; fimkdir -p "$DEPS" "$BUILD"
# ---- Android NDK r27d (pinned, sha256 of Google's archive)NDK_REL=r27d; NDK_REV=27.3.13750724case "$(uname -s)" in Linux) NDK_ZIP=android-ndk-$NDK_REL-linux.zip; NDK_SHA=601246087a682d1944e1e16dd85bc6e49560fe8b6d61255be2829178c8ed15d9; HOSTTAG=linux-x86_64 ;; Darwin) NDK_ZIP=android-ndk-$NDK_REL-darwin.zip; NDK_SHA=e69092f9d2bfa5d1199039980a14eb91c03cc971ab5c6968fc08a8e6b84e7bb7; HOSTTAG=darwin-x86_64 ;; *) echo "build.sh: unsupported host $(uname -s)" >&2; exit 1 ;;esacif [ -n "${ANDROID_NDK:-}" ] && grep -q "Pkg.Revision = $NDK_REV" "$ANDROID_NDK/source.properties" 2>/dev/null; then NDK=$ANDROID_NDKelse NDK=$DEPS/android-ndk-$NDK_REL if ! grep -q "Pkg.Revision = $NDK_REV" "$NDK/source.properties" 2>/dev/null; then rm -rf "$NDK" curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP" echo "$NDK_SHA $DEPS/$NDK_ZIP" | shasum -a 256 -c - (cd "$DEPS" && unzip -q "$NDK_ZIP" && rm "$NDK_ZIP") fifiCXX=$NDK/toolchains/llvm/prebuilt/$HOSTTAG/bin/aarch64-linux-android29-clang++
# ---- OpenCL headers (the program dlopens the vendor libOpenCL.so on the phone, no loader needed)OCL_TAG=v2024.10.24; OCL_COMMIT=4ea6df132107e3b4b9407f903204b5522fdffcd6if [ -n "${OPENCL_ANDROID_INCLUDE:-}" ] && [ -f "$OPENCL_ANDROID_INCLUDE/CL/cl.h" ]; then OCL_INC=$OPENCL_ANDROID_INCLUDEelse OCL_INC=$DEPS/OpenCL-Headers if [ "$(git -C "$OCL_INC" rev-parse HEAD 2>/dev/null || true)" != "$OCL_COMMIT" ]; then rm -rf "$OCL_INC" git clone -q --depth 1 --branch "$OCL_TAG" https://github.com/KhronosGroup/OpenCL-Headers.git "$OCL_INC" [ "$(git -C "$OCL_INC" rev-parse HEAD)" = "$OCL_COMMIT" ] || { echo "build.sh: OpenCL-Headers $OCL_TAG is not $OCL_COMMIT" >&2; exit 1; } fifi
# ---- programmkdir -p "$BUILD/bin""$CXX" -O2 -std=c++17 -I"$OCL_INC" -Wall -static-libstdc++ src/*.cpp src/third_party/*.cpp -ldl -o "$BUILD/bin/bonsai_image"rm -rf "$BUILD/bin/kernels" && cp -R src/kernels "$BUILD/bin/kernels"echo "build.sh: built $BUILD/bin/bonsai_image"
# ---- weights: convert the checkpoint once (stamp = converter + checkpoint file sizes)if [ -z "${INPUTS_DIR:-}" ] || [ ! -d "$INPUTS_DIR/weights/transformer" ]; then if [ -f "$BUILD/weights/.stamp" ]; then echo "build.sh: INPUTS_DIR unset, keeping the converted weights in $BUILD/weights"; exit 0; fi echo "build.sh: set INPUTS_DIR to a folder whose weights/ holds prism-ml/bonsai-image-ternary-4B-unpacked (README.md)" >&2 exit 2fiVENV=$DEPS/venvif ! "$VENV/bin/python" -c 'import numpy; assert numpy.__version__ == "2.1.3"' 2>/dev/null; then rm -rf "$VENV" python3 -m venv "$VENV" PIP_CONSTRAINT= PIP_EXTRA_INDEX_URL= PIP_INDEX_URL= "$VENV/bin/pip" install -q --disable-pip-version-check numpy==2.1.3fiW=$INPUTS_DIR/weightsSTAMP=$( { shasum -a 256 tools/convert.py; for f in transformer/diffusion_pytorch_model.safetensors vae/diffusion_pytorch_model.safetensors \ text_encoder/model-00001-of-00002.safetensors text_encoder/model-00002-of-00002.safetensors; do printf '%s %s\n' "$f" "$(wc -c < "$W/$f" | tr -d ' ')"; done; } | shasum -a 256 | cut -c1-16)if [ "$(cat "$BUILD/weights/.stamp" 2>/dev/null || true)" != "$STAMP" ]; then rm -rf "$BUILD/weights"; mkdir -p "$BUILD/weights" "$VENV/bin/python" -I tools/convert.py "$W" "$BUILD/weights" echo "$STAMP" > "$BUILD/weights/.stamp"fi"$VENV/bin/python" -I tools/tokjson.py "$W/tokenizer/tokenizer.json" "$BUILD/weights/tokenizer.json"echo "build.sh: weights ready in $BUILD/weights ($STAMP)"123version https://git-lfs.github.com/spec/v1oid sha256:9f6bfcedf5b42981a250ea06a020ffe92b9399a8f8eff578e525406396867909size 140961612345678910111213141516171819// Peak probe for --selftest: 8 independent float4 FMA chains per work-item, no memory traffic in the loop.#ifdef HALF#pragma OPENCL EXTENSION cl_khr_fp16 : enable#define T4 half4#define T half#else#define T4 float4#define T float#endif__kernel void fma_peak(__global float* out, const T a, const T b, const int iters) { const int g = get_global_id(0); T4 x0 = (T)g * (T)1e-6f, x1 = x0 + (T)1, x2 = x0 + (T)2, x3 = x0 + (T)3, x4 = x0 + (T)4, x5 = x0 + (T)5, x6 = x0 + (T)6, x7 = x0 + (T)7; for (int i = 0; i < iters; ++i) { x0 = mad(x0, a, b); x1 = mad(x1, a, b); x2 = mad(x2, a, b); x3 = mad(x3, a, b); x4 = mad(x4, a, b); x5 = mad(x5, a, b); x6 = mad(x6, a, b); x7 = mad(x7, a, b); } const T4 s = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7; out[g] = (float)(s.x + s.y + s.z + s.w);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323// Tiled GEMM, fp32 accumulation: C[M,N] = epilogue(A[M,K] . B(K,N)).// Compile-time variants (one program each):// A_MODE 0: A dense fp32 row-major [M][lda]// A_MODE 1: implicit im2col of a 3x3/pad 1 conv over an NHWC fp32 image [H][W][Cin], k = (ky*3+kx)*Cin + c// A_MODE 2: as 1, with a nearest 2x upsample fused in (the source image is [H/2][W/2][Cin])// A_MODE 3: A read through an RGBA float image2d [M rows][K/4 texels] (texture path), only B goes through local;// batches side by side (column offset b*sA) or stacked (row offset b*aoff)// A_MODE 4, 5: modes 1, 2 with the NHWC source read through an RGBA float image2d [H*Cin/4][W] (texel (x, y*Cin/4 + c/4))// B_MODE 0: fp32 [N][ldb] (k contiguous) B_MODE 1: fp32 [K][ldb] (n contiguous)// B_MODE 2: bf16 [N][ldb] (k contiguous) B_MODE 3: ternary, 2 bits per weight packed 16 per uint// ([N][K/16] words, code c -> c-1) times a bf16 scale per 128 k ([N][K/128])// Epilogue: v = alpha*acc (+ bias[n]); if res: v = res[m,n] + (gate ? gate[n] : 1) * v.// Tile (16*TM)x(16*TN)x16, work-group 16x16, TMxTN outputs per work-item; batch over get_group_id(2).#ifndef TM#define TM 4#endif#ifndef TN#define TN 4#endif#define BM (16 * TM)#define BN (16 * TN)// KP: k passes of 16 per tile (BK = 16*KP); NT B modes and dense A only#ifndef KP#define KP 1#endif#define BK (16 * KP)#if KP > 1 && (B_MODE == 1 || A_MODE == 1 || A_MODE == 2 || A_MODE == 4 || A_MODE == 5)#error KP > 1 needs an NT B mode and a dense A#endif// HB: weight tiles (bf16 or ternary x bf16 scale: exact in fp16) held as half in local memory; each work-item then// reads its TN contiguous columns in one load (columns tx*TN + c instead of tx*4 + j*64 + c)#ifndef HB#define HB (B_MODE == 2 || B_MODE == 3)#endif#if HB#pragma OPENCL EXTENSION cl_khr_fp16 : enable#endif#ifndef DBG#define DBG 0#endif#ifndef SWAP#define SWAP 0#endif#ifndef PF#define PF 1#endif
#define AIMG (A_MODE >= 3)// output row of accumulator row i#if AIMG#define ROW(i) (m0 + ty * TM + (i))#else#define ROW(i) (m0 + ((i) >> 2) * 64 + ty * 4 + ((i) & 3))#endif
inline float bf16f(ushort u) { return as_float(((uint)u) << 16); }
// A tile element quad: row am, k = k0 + lq .. +3inline float4 load_a(__global const float* A, const int M, const int lda, const int am, const int k0, const int lq, const int convH, const int convW, const int convLogW, const int convCin) { float4 av = 0;#if A_MODE == 0 || A_MODE == 3 if (am < M) av = vload4(0, A + am * lda + k0 + lq);#else const int ay = am >> convLogW, ax = am & (convW - 1); const int tap = k0 / convCin, c0 = k0 - tap * convCin; const int ky = tap / 3, kx = tap - ky * 3; const int yy = ay + ky - 1, xx = ax + kx - 1; if (am < M && yy >= 0 && yy < convH && xx >= 0 && xx < convW) {#if A_MODE == 1 av = vload4(0, A + (yy * convW + xx) * convCin + c0 + lq);#else av = vload4(0, A + ((yy >> 1) * (convW >> 1) + (xx >> 1)) * convCin + c0 + lq);#endif }#endif return av;}
// B tile quad: NT modes give column n0 + lrow at k = k0 + lq .. +3; NN mode gives k row idx / (BN/4), 4 columnsinline float4 load_b(__global const void* Bv, __global const ushort* Bscale, const int N, const int K, const int ldb, const int boff, const int n0, const int k0, const int lrow, const int lq, const int idx) { float4 bv = 0;#if B_MODE == 1 const int kk = idx / (BN / 4), nq = (idx - kk * (BN / 4)) << 2; const int nn = n0 + nq; if (nn < N) bv = vload4(0, (__global const float*)Bv + boff + (k0 + kk) * ldb + nn);#else const int bn = n0 + lrow; if (bn < N) {#if B_MODE == 0 bv = vload4(0, (__global const float*)Bv + boff + bn * ldb + k0 + lq);#elif B_MODE == 2 ushort4 u = vload4(0, (__global const ushort*)Bv + boff + bn * ldb + k0 + lq); bv = (float4)(bf16f(u.x), bf16f(u.y), bf16f(u.z), bf16f(u.w));#else const uint w = ((__global const uint*)Bv)[boff + bn * (K >> 4) + (k0 >> 4)]; const float s = bf16f(Bscale[bn * (K >> 7) + (k0 >> 7)]); const uint q = w >> (lq * 2); bv = (float4)((float)((int)(q & 3u) - 1), (float)((int)((q >> 2) & 3u) - 1), (float)((int)((q >> 4) & 3u) - 1), (float)((int)((q >> 6) & 3u) - 1)) * s;#endif }#endif return bv;}
__kernel __attribute__((reqd_work_group_size(16, 16, 1)))void gemm(const int M, const int N, const int K,#if AIMG __read_only image2d_t Aimg, const int aoff,#else __global const float* A, const int aoff,#endif const int lda, const int sA, __global const void* Bv, const int boff0, const int ldb, const int sB, const int bdiv, __global const ushort* Bscale, __global float* C, const int coff, const int ldc, const int sC, const float alpha, __global const float* bias, const int has_bias, __global const float* res, const int roff, const int ldr, const int has_res, __global const float* gate, const int goff, const int has_gate, const int convH, const int convW, const int convLogW, const int convCin) {#if !AIMG __local float As[BK][BM + 4];#endif#if HB __local half Bs[BK][BN + 8];#else __local float Bs[BK][BN + 4];#endif#if SWAP // lanes of a wave walk rows (A texels unique per lane, B local reads broadcast) const int tx = get_local_id(1), ty = get_local_id(0);#else const int tx = get_local_id(0), ty = get_local_id(1);#endif const int t = get_local_id(1) * 16 + get_local_id(0); const int n0 = get_group_id(0) * BN, m0 = get_group_id(1) * BM; const int b = get_group_id(2);#if AIMG const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;#else A += aoff + b * sA;#endif C += coff + b * sC; res += roff + b * sC; gate += goff; const int boff = boff0 + (b / bdiv) * sB;
float4 acc[TM][TN / 4];#pragma unroll for (int i = 0; i < TM; ++i)#pragma unroll for (int j = 0; j < TN / 4; ++j) acc[i][j] = 0;
const int lr = t >> 2, lq = (t & 3) << 2; // tile row 0..63 (+64 per extra pass), k quad 0,4,8,12
// global -> registers for tile k0 (av: A rows, bv: B columns or rows), then registers -> local float4 av[KP][TM / 4], bv[KP][TN / 4];#if AIMG#define LOAD_A(k0)#else#define LOAD_A(k0) \ _Pragma("unroll") for (int q = 0; q < KP; ++q) \ _Pragma("unroll") for (int p = 0; p < TM / 4; ++p) av[q][p] = load_a(A, M, lda, m0 + lr + p * 64, (k0) + 16 * q, lq, \ convH, convW, convLogW, convCin);#endif#define LOAD_TILES(k0) \ { \ LOAD_A(k0) \ _Pragma("unroll") for (int q = 0; q < KP; ++q) \ _Pragma("unroll") for (int p = 0; p < TN / 4; ++p) bv[q][p] = load_b(Bv, Bscale, N, K, ldb, boff, n0, (k0) + 16 * q, \ lr + p * 64, lq, t + p * 256); \ } LOAD_TILES(0); for (int k0 = 0; k0 < K; k0 += BK) {#if !AIMG#pragma unroll for (int q = 0; q < KP; ++q)#pragma unroll for (int p = 0; p < TM / 4; ++p) { const int lrow = lr + p * 64, kq = lq + 16 * q; As[kq + 0][lrow] = av[q][p].x; As[kq + 1][lrow] = av[q][p].y; As[kq + 2][lrow] = av[q][p].z; As[kq + 3][lrow] = av[q][p].w; }#endif#pragma unroll for (int q = 0; q < KP; ++q)#pragma unroll for (int p = 0; p < TN / 4; ++p) {#if B_MODE == 1 const int idx = t + p * 256; const int kk = idx / (BN / 4), nq = (idx - kk * (BN / 4)) << 2; vstore4(bv[q][p], 0, &Bs[kk][nq]);#else const int lrow = lr + p * 64, kq = lq + 16 * q;#if HB vstore_half(bv[q][p].x, 0, &Bs[kq + 0][lrow]); vstore_half(bv[q][p].y, 0, &Bs[kq + 1][lrow]); vstore_half(bv[q][p].z, 0, &Bs[kq + 2][lrow]); vstore_half(bv[q][p].w, 0, &Bs[kq + 3][lrow]);#else Bs[kq + 0][lrow] = bv[q][p].x; Bs[kq + 1][lrow] = bv[q][p].y; Bs[kq + 2][lrow] = bv[q][p].z; Bs[kq + 3][lrow] = bv[q][p].w;#endif#endif } barrier(CLK_LOCAL_MEM_FENCE);#if PF if (k0 + BK < K) LOAD_TILES(k0 + BK);#endif
#if AIMG // 4 k per texel: a[i] = A[row i][k0 + 4*k4 .. +3]#if HB#define LOAD_BB(k, j) vload_half4(0, &Bs[k][tx * TN + (j) * 4])#else#define LOAD_BB(k, j) vload4(0, &Bs[k][tx * 4 + (j) * 64])#endif#define AIMG_STEP(kk, comp) \ { \ float4 bb[TN / 4]; \ _Pragma("unroll") for (int j = 0; j < TN / 4; ++j) bb[j] = LOAD_BB(k4 * 4 + kk, j); \ _Pragma("unroll") for (int i = 0; i < TM; ++i) \ _Pragma("unroll") for (int j = 0; j < TN / 4; ++j) acc[i][j] = mad((float4)a[i].comp, bb[j], acc[i][j]); \ }#if A_MODE == 3 // batch b: columns from b*sA (blocks side by side) or rows from b*aoff (blocks stacked) const int y0 = m0 + ty * TM + b * aoff, x0 = (k0 >> 2) + b * (sA >> 2);#define A_TEXEL(i, k4) read_imagef(Aimg, smp, (int2)(x0 + (k4), y0 + (i)))#else // the TM pixels of this work-item are consecutive in one image row (TM divides W): one source row, x = xb + i; // rows outside the padding read the zero border (y < 0), columns outside it are zeroed by the select int y0, xb; { const int tap = k0 / convCin, c0 = k0 - tap * convCin; const int ky = tap / 3, kx = tap - ky * 3; const int mb = m0 + ty * TM; int yy = (mb >> convLogW) + ky - 1; const bool ok = mb < M && yy >= 0 && yy < convH;#if A_MODE == 5 yy >>= 1;#endif y0 = ok ? yy * (convCin >> 2) + (c0 >> 2) : -8; xb = (mb & (convW - 1)) + kx - 1; }#if A_MODE == 5#define A_TEXEL(i, k4) select((float4)0, read_imagef(Aimg, smp, (int2)((xb + (i)) >> 1, y0 + (k4))), (int4)(-((uint)(xb + (i)) < (uint)convW)))#else#define A_TEXEL(i, k4) select((float4)0, read_imagef(Aimg, smp, (int2)(xb + (i), y0 + (k4))), (int4)(-((uint)(xb + (i)) < (uint)convW)))#endif#endif#pragma unroll for (int k4 = 0; k4 < BK / 4; ++k4) { float4 a[TM];#pragma unroll for (int i = 0; i < TM; ++i) a[i] = A_TEXEL(i, k4); AIMG_STEP(0, x) AIMG_STEP(1, y) AIMG_STEP(2, z) AIMG_STEP(3, w) }#else#pragma unroll for (int k = 0; k < BK; ++k) { float4 a[TM / 4], bb[TN / 4];#if DBG == 1 // timing probe only: no local reads in the inner loop for (int i = 0; i < TM / 4; ++i) a[i] = (float4)(k + i, 1, 2, 3) * 1e-3f; for (int j = 0; j < TN / 4; ++j) bb[j] = (float4)(j, 1, k, 3) * 1e-3f;#else for (int i = 0; i < TM / 4; ++i) a[i] = vload4(0, &As[k][ty * 4 + i * 64]);#if HB for (int j = 0; j < TN / 4; ++j) bb[j] = vload_half4(0, &Bs[k][tx * TN + j * 4]);#else for (int j = 0; j < TN / 4; ++j) bb[j] = vload4(0, &Bs[k][tx * 4 + j * 64]);#endif#endif#pragma unroll for (int i = 0; i < TM / 4; ++i)#pragma unroll for (int j = 0; j < TN / 4; ++j) { acc[i * 4 + 0][j] = mad((float4)a[i].x, bb[j], acc[i * 4 + 0][j]); acc[i * 4 + 1][j] = mad((float4)a[i].y, bb[j], acc[i * 4 + 1][j]); acc[i * 4 + 2][j] = mad((float4)a[i].z, bb[j], acc[i * 4 + 2][j]); acc[i * 4 + 3][j] = mad((float4)a[i].w, bb[j], acc[i * 4 + 3][j]); } }#endif barrier(CLK_LOCAL_MEM_FENCE);#if !PF if (k0 + BK < K) LOAD_TILES(k0 + BK);#endif }
// ---- epilogue: row m0 + (i/4)*64 + ty*4 + i%4, column nb + c (vector ops only, so acc stays in registers)#pragma unroll for (int j = 0; j < TN / 4; ++j) {#if HB const int nb = n0 + tx * TN + j * 4;#else const int nb = n0 + j * 64 + tx * 4;#endif if (nb >= N) continue; const bool full = nb + 3 < N; float4 bia = 0, gt = 1; if (full) { if (has_bias) bia = vload4(0, bias + nb); if (has_gate) gt = vload4(0, gate + nb); } else { if (has_bias) bia = (float4)(bias[nb], nb + 1 < N ? bias[nb + 1] : 0, nb + 2 < N ? bias[nb + 2] : 0, 0); if (has_gate) gt = (float4)(gate[nb], nb + 1 < N ? gate[nb + 1] : 1, nb + 2 < N ? gate[nb + 2] : 1, 1); }#pragma unroll for (int i = 0; i < TM; ++i) { const int m = ROW(i); if (m < M) { float4 o = alpha * acc[i][j] + bia; if (full) { if (has_res) o = vload4(0, res + m * ldr + nb) + gt * o; vstore4(o, 0, C + m * ldc + nb); } else { if (has_res) o = (float4)(res[m * ldr + nb], nb + 1 < N ? res[m * ldr + nb + 1] : 0, nb + 2 < N ? res[m * ldr + nb + 2] : 0, 0) + gt * o; C[m * ldc + nb] = o.x; if (nb + 1 < N) C[m * ldc + nb + 1] = o.y; if (nb + 2 < N) C[m * ldc + nb + 2] = o.z; } } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259// Row-wise and elementwise kernels (fp32 everywhere). Work-group of 256 unless noted.
inline float wg_sum256(float v, __local float* red) { const int l = get_local_id(0); red[l] = v; barrier(CLK_LOCAL_MEM_FENCE); for (int s = 128; s > 0; s >>= 1) { if (l < s) red[l] += red[l + s]; barrier(CLK_LOCAL_MEM_FENCE); } const float r = red[0]; barrier(CLK_LOCAL_MEM_FENCE); return r;}inline float wg_max256(float v, __local float* red) { const int l = get_local_id(0); red[l] = v; barrier(CLK_LOCAL_MEM_FENCE); for (int s = 128; s > 0; s >>= 1) { if (l < s) red[l] = fmax(red[l], red[l + s]); barrier(CLK_LOCAL_MEM_FENCE); } const float r = red[0]; barrier(CLK_LOCAL_MEM_FENCE); return r;}
// Qwen3RMSNorm: w * (x * rsqrt(mean(x^2) + eps)); one group per row, D <= 256*16__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void rmsnorm(__global const float* x, const int xoff, const int ldx, __global float* out, const int ooff, const int ldo, __global const float* w, const int D, const float eps) { __local float red[256]; const int r = get_group_id(0), l = get_local_id(0); x += xoff + r * ldx; out += ooff + r * ldo; float ss = 0; for (int i = l; i < D; i += 256) { const float v = x[i]; ss += v * v; } ss = wg_sum256(ss, red); const float rs = rsqrt(ss / D + eps); for (int i = l; i < D; i += 256) out[i] = w[i] * (x[i] * rs);}
// Per-head RMSNorm (head_dim 128, weight w) then rotate-half RoPE (Qwen3), in place.// Rows: r = s*nheads + h at x[off + s*ld + h*128]. cos/sin tables [S][128]. Work-group 128.__kernel __attribute__((reqd_work_group_size(128, 1, 1)))void headnorm_rope_half(__global float* x, const int off, const int ld, const int nheads, __global const float* w, __global const float* cs, __global const float* sn, const float eps) { __local float red[128]; __local float xn[128]; const int r = get_group_id(0), l = get_local_id(0); const int s = r / nheads, h = r - s * nheads; __global float* p = x + off + s * ld + h * 128; const float v = p[l]; red[l] = v * v; barrier(CLK_LOCAL_MEM_FENCE); for (int st = 64; st > 0; st >>= 1) { if (l < st) red[l] += red[l + st]; barrier(CLK_LOCAL_MEM_FENCE); } const float rs = rsqrt(red[0] / 128.f + eps); const float y = w[l] * (v * rs); xn[l] = y; barrier(CLK_LOCAL_MEM_FENCE); const float rot = l < 64 ? -xn[l + 64] : xn[l - 64]; p[l] = y * cs[s * 128 + l] + rot * sn[s * 128 + l];}
// Per-head RMSNorm then interleaved-pair RoPE (FLUX.2), in place. Rows s < split use w1, others w2.__kernel __attribute__((reqd_work_group_size(128, 1, 1)))void headnorm_rope_tab(__global float* x, const int off, const int ld, const int nheads, const int split, __global const float* w1, __global const float* w2, __global const float* cs, __global const float* sn, const float eps) { __local float red[128]; __local float xn[128]; const int r = get_group_id(0), l = get_local_id(0); const int s = r / nheads, h = r - s * nheads; __global float* p = x + off + s * ld + h * 128; const float v = p[l]; red[l] = v * v; barrier(CLK_LOCAL_MEM_FENCE); for (int st = 64; st > 0; st >>= 1) { if (l < st) red[l] += red[l + st]; barrier(CLK_LOCAL_MEM_FENCE); } const float rs = rsqrt(red[0] / 128.f + eps); const float y = (s < split ? w1[l] : w2[l]) * (v * rs); xn[l] = y; barrier(CLK_LOCAL_MEM_FENCE); const float rot = (l & 1) ? xn[l - 1] : -xn[l + 1]; p[l] = y * cs[s * 128 + l] + rot * sn[s * 128 + l];}
// In-place softmax(scale * row) over ncols; grid (rows, batch). mask 1: key j allowed iff j <= row && j < valid.__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void softmax_rows(__global float* S, const int ld, const int rows, const int ncols, const float scale, const int mask, const int valid) { __local float red[256]; const int r = get_group_id(0), b = get_group_id(1), l = get_local_id(0); __global float* p = S + (b * rows + r) * ld; const int lim = mask ? min(r + 1, valid) : ncols; float mx = -FLT_MAX; for (int j = l; j < lim; j += 256) mx = fmax(mx, p[j] * scale); mx = wg_max256(mx, red); float sum = 0; for (int j = l; j < lim; j += 256) sum += exp(p[j] * scale - mx); sum = wg_sum256(sum, red); const float inv = 1.f / sum; for (int j = l; j < ncols; j += 256) p[j] = j < lim ? exp(p[j] * scale - mx) * inv : 0.f;}
// softmax_rows for batches b0.. of S, writing P into an RGBA float image (texel (j/4, (b-b0)*rows + r)) instead of// back into S (the A operand of the texture-path P.V GEMM). ncols % 4 == 0. grid (rows*256, nb)__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void softmax_rows_img(__global const float* S, const int ld, const int rows, const int ncols, const float scale, const int mask, const int valid, const int b0, __write_only image2d_t img) { __local float red[256]; const int r = get_group_id(0), bl = get_group_id(1), l = get_local_id(0); __global const float* p = S + ((b0 + bl) * rows + r) * ld; const int lim = mask ? min(r + 1, valid) : ncols; float mx = -FLT_MAX; for (int j = l; j < lim; j += 256) mx = fmax(mx, p[j] * scale); mx = wg_max256(mx, red); float sum = 0; for (int j = l; j < lim; j += 256) sum += exp(p[j] * scale - mx); sum = wg_sum256(sum, red); const float inv = 1.f / sum; for (int j4 = l; j4 < (ncols >> 2); j4 += 256) { const float4 e = exp(vload4(j4, p) * scale - mx) * inv; const int4 jj = (int4)(j4 * 4) + (int4)(0, 1, 2, 3); write_imagef(img, (int2)(j4, bl * rows + r), select((float4)0, e, jj < (int4)lim)); }}
// out[m][j] = silu(in[m][j]) * in[m][j + H]; grid (H, M)__kernel void silu_mul(__global const float* in, const int ioff, const int ldi, const int H, __global float* out, const int ooff, const int ldo) { const int j = get_global_id(0), m = get_global_id(1); if (j >= H) return; const float g = in[ioff + m * ldi + j], u = in[ioff + m * ldi + j + H]; out[ooff + m * ldo + j] = g / (1.f + exp(-g)) * u;}
__kernel void silu(__global const float* in, __global float* out, const int n) { const int i = get_global_id(0); if (i < n) { const float v = in[i]; out[i] = v / (1.f + exp(-v)); }}
// LayerNorm without affine, then out = xn * (1 + scale) + shift; one group per row.__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void layernorm_mod(__global const float* x, const int xoff, const int ldx, __global float* out, const int ooff, const int ldo, const int D, __global const float* mod, const int shoff, const int scoff, const float eps) { __local float red[256]; const int r = get_group_id(0), l = get_local_id(0); x += xoff + r * ldx; out += ooff + r * ldo; float s = 0; for (int i = l; i < D; i += 256) s += x[i]; const float mean = wg_sum256(s, red) / D; float v = 0; for (int i = l; i < D; i += 256) { const float d = x[i] - mean; v += d * d; } const float rstd = rsqrt(wg_sum256(v, red) / D + eps); for (int i = l; i < D; i += 256) out[i] = (x[i] - mean) * rstd * (1.f + mod[scoff + i]) + mod[shoff + i];}
// GroupNorm on NHWC [HW][C], G groups. Partial sums over pixel chunks; pass 0: sum x, pass 1: sum (x-mean)^2.// grid (nchunk*256, G); each group handles pixels [chunk*cp, (chunk+1)*cp).__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void gn_partial(__global const float* x, const int HW, const int C, const int cg, const int cp, __global const float* stats, const int pass, __global float* part) { __local float red[256]; const int chunk = get_group_id(0), g = get_group_id(1), l = get_local_id(0); const int nchunk = get_num_groups(0); const float mean = pass ? stats[g * 2] : 0.f; const int n = cp * cg; const int p0 = chunk * cp; float s = 0; for (int i = l; i < n; i += 256) { const int pp = p0 + i / cg, c = g * cg + (i % cg); if (pp < HW) { const float v = x[pp * C + c] - mean; s += pass ? v * v : v; } } s = wg_sum256(s, red); if (l == 0) part[g * nchunk + chunk] = s;}
// gn_partial with coalesced reads: one group per chunk of cp pixels covers every channel quad (work-item l: quad// l % C4, pixels p0 + l / C4 step 256 / C4), then lane g < G sums its group's quads. Needs C4 | 256, cg % 4 == 0.__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void gn_partial4(__global const float* x, const int HW, const int C, const int cg, const int cp, __global const float* stats, const int pass, __global float* part, const int G) { __local float red[256]; const int chunk = get_group_id(0), l = get_local_id(0), nchunk = get_num_groups(0); const int C4 = C >> 2, q4 = cg >> 2, R = 256 / C4; const int c4 = l % C4, r = l / C4; const float mean = pass ? stats[(c4 / q4) * 2] : 0.f; const int p0 = chunk * cp, pend = min(p0 + cp, HW); float4 s = 0; for (int pp = p0 + r; pp < pend; pp += R) { const float4 v = vload4(c4, x + pp * C) - mean; s += pass ? v * v : v; } red[l] = (s.x + s.y) + (s.z + s.w); barrier(CLK_LOCAL_MEM_FENCE); if (l < G) { float t = 0; for (int rr = 0; rr < R; ++rr) for (int q = 0; q < q4; ++q) t += red[rr * C4 + l * q4 + q]; part[l * nchunk + chunk] = t; }}
// stats[g] = (mean, rstd) from the partials; pass 0 writes mean, pass 1 writes rstd. grid (256, G)__kernel __attribute__((reqd_work_group_size(256, 1, 1)))void gn_final(__global const float* part, const int nchunk, const float count, const float eps, const int pass, __global float* stats) { __local float red[256]; const int g = get_group_id(1), l = get_local_id(0); float s = 0; for (int i = l; i < nchunk; i += 256) s += part[g * nchunk + i]; s = wg_sum256(s, red); if (l == 0) { if (pass == 0) stats[g * 2] = s / count; else stats[g * 2 + 1] = rsqrt(s / count + eps); }}
// out = (x - mean) * rstd * gamma + beta, optional SiLU; grid (C, HW)__kernel void gn_apply(__global const float* x, __global float* out, const int C, const int cg, __global const float* stats, __global const float* gamma, __global const float* beta, const int act) { const int c = get_global_id(0), p = get_global_id(1); if (c >= C) return; const int g = c / cg; float v = (x[p * C + c] - stats[g * 2]) * stats[g * 2 + 1] * gamma[c] + beta[c]; if (act) v = v / (1.f + exp(-v)); out[p * C + c] = v;}
// dst[r][c] = src[r][c] for a rows x cols block; grid (cols, rows)__kernel void copy2d(__global const float* src, const int soff, const int lds, __global float* dst, const int doff, const int ldd, const int cols) { const int c = get_global_id(0), r = get_global_id(1); if (c < cols) dst[doff + r * ldd + c] = src[soff + r * lds + c];}
// dense fp32 rows -> RGBA float image [rows][K4] (A operand of the image-path GEMM)__kernel void to_image(__global const float* src, const int off, const int ld, const int K4, __write_only image2d_t dst) { const int c = get_global_id(0), r = get_global_id(1); if (c < K4) write_imagef(dst, (int2)(c, r), vload4(0, src + off + r * ld + c * 4));}
// NHWC fp32 [H][W][Cin] -> RGBA float image, texel (x, y*C4 + c4) (A operand of the image-path conv GEMM)__kernel void to_image_conv(__global const float* src, const int C4, const int logW, __write_only image2d_t dst) { const int c4 = get_global_id(0), p = get_global_id(1); if (c4 < C4) write_imagef(dst, (int2)(p & ((1 << logW) - 1), (p >> logW) * C4 + c4), vload4(p * C4 + c4, src));}
// fused qkv rows [S][ld] (q | k | v, each nh x 128) -> [3][nh][S][128]__kernel void split_heads(__global const float* src, const int ld, __global float* dst, const int S, const int nh, const int D) { const int d4 = get_global_id(0), s = get_global_id(1), wh = get_global_id(2); // wh = which * nh + head const int which = wh / nh, h = wh - which * nh; vstore4(vload4(0, src + s * ld + which * D + h * 128 + d4 * 4), 0, dst + (wh * S + s) * 128 + d4 * 4);}1809cc2e7232d7b0f123version https://git-lfs.github.com/spec/v1oid sha256:f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1size 1367734272123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229context_embedder bf16 0 47185920double_stream_modulation_img.linear bf16 47185920 113246208double_stream_modulation_txt.linear bf16 160432128 113246208norm_out.linear bf16 273678336 37748736proj_out bf16 311427072 786432single_stream_modulation.linear bf16 312213504 56623104time_guidance_embed.timestep_embedder.linear_1 bf16 368836608 1572864time_guidance_embed.timestep_embedder.linear_2 bf16 370409472 18874368x_embedder bf16 389283840 786432d0.qkv tern 390070272 7077888d0.qkv.s bf16 397148160 442368d0.add_qkv tern 397590528 7077888d0.add_qkv.s bf16 404668416 442368d0.out tern 405110784 2359296d0.out.s bf16 407470080 147456d0.add_out tern 407617536 2359296d0.add_out.s bf16 409976832 147456d0.ff_in tern 410124288 14155776d0.ff_in.s bf16 424280064 884736d0.ff_out tern 425164800 7077888d0.ff_out.s bf16 432242688 442368d0.ffc_in tern 432685056 14155776d0.ffc_in.s bf16 446840832 884736d0.ffc_out tern 447725568 7077888d0.ffc_out.s bf16 454803456 442368d0.norm_q f32 455245824 512d0.norm_k f32 455246336 512d0.norm_added_q f32 455246848 512d0.norm_added_k f32 455247360 512d1.qkv tern 455247872 7077888d1.qkv.s bf16 462325760 442368d1.add_qkv tern 462768128 7077888d1.add_qkv.s bf16 469846016 442368d1.out tern 470288384 2359296d1.out.s bf16 472647680 147456d1.add_out tern 472795136 2359296d1.add_out.s bf16 475154432 147456d1.ff_in tern 475301888 14155776d1.ff_in.s bf16 489457664 884736d1.ff_out tern 490342400 7077888d1.ff_out.s bf16 497420288 442368d1.ffc_in tern 497862656 14155776d1.ffc_in.s bf16 512018432 884736d1.ffc_out tern 512903168 7077888d1.ffc_out.s bf16 519981056 442368d1.norm_q f32 520423424 512d1.norm_k f32 520423936 512d1.norm_added_q f32 520424448 512d1.norm_added_k f32 520424960 512d2.qkv tern 520425472 7077888d2.qkv.s bf16 527503360 442368d2.add_qkv tern 527945728 7077888d2.add_qkv.s bf16 535023616 442368d2.out tern 535465984 2359296d2.out.s bf16 537825280 147456d2.add_out tern 537972736 2359296d2.add_out.s bf16 540332032 147456d2.ff_in tern 540479488 14155776d2.ff_in.s bf16 554635264 884736d2.ff_out tern 555520000 7077888d2.ff_out.s bf16 562597888 442368d2.ffc_in tern 563040256 14155776d2.ffc_in.s bf16 577196032 884736d2.ffc_out tern 578080768 7077888d2.ffc_out.s bf16 585158656 442368d2.norm_q f32 585601024 512d2.norm_k f32 585601536 512d2.norm_added_q f32 585602048 512d2.norm_added_k f32 585602560 512d3.qkv tern 585603072 7077888d3.qkv.s bf16 592680960 442368d3.add_qkv tern 593123328 7077888d3.add_qkv.s bf16 600201216 442368d3.out tern 600643584 2359296d3.out.s bf16 603002880 147456d3.add_out tern 603150336 2359296d3.add_out.s bf16 605509632 147456d3.ff_in tern 605657088 14155776d3.ff_in.s bf16 619812864 884736d3.ff_out tern 620697600 7077888d3.ff_out.s bf16 627775488 442368d3.ffc_in tern 628217856 14155776d3.ffc_in.s bf16 642373632 884736d3.ffc_out tern 643258368 7077888d3.ffc_out.s bf16 650336256 442368d3.norm_q f32 650778624 512d3.norm_k f32 650779136 512d3.norm_added_q f32 650779648 512d3.norm_added_k f32 650780160 512d4.qkv tern 650780672 7077888d4.qkv.s bf16 657858560 442368d4.add_qkv tern 658300928 7077888d4.add_qkv.s bf16 665378816 442368d4.out tern 665821184 2359296d4.out.s bf16 668180480 147456d4.add_out tern 668327936 2359296d4.add_out.s bf16 670687232 147456d4.ff_in tern 670834688 14155776d4.ff_in.s bf16 684990464 884736d4.ff_out tern 685875200 7077888d4.ff_out.s bf16 692953088 442368d4.ffc_in tern 693395456 14155776d4.ffc_in.s bf16 707551232 884736d4.ffc_out tern 708435968 7077888d4.ffc_out.s bf16 715513856 442368d4.norm_q f32 715956224 512d4.norm_k f32 715956736 512d4.norm_added_q f32 715957248 512d4.norm_added_k f32 715957760 512s0.qkv_mlp tern 715958272 21233664s0.qkv_mlp.s bf16 737191936 1327104s0.out tern 738519040 9437184s0.out.s bf16 747956224 589824s0.norm_q f32 748546048 512s0.norm_k f32 748546560 512s1.qkv_mlp tern 748547072 21233664s1.qkv_mlp.s bf16 769780736 1327104s1.out tern 771107840 9437184s1.out.s bf16 780545024 589824s1.norm_q f32 781134848 512s1.norm_k f32 781135360 512s2.qkv_mlp tern 781135872 21233664s2.qkv_mlp.s bf16 802369536 1327104s2.out tern 803696640 9437184s2.out.s bf16 813133824 589824s2.norm_q f32 813723648 512s2.norm_k f32 813724160 512s3.qkv_mlp tern 813724672 21233664s3.qkv_mlp.s bf16 834958336 1327104s3.out tern 836285440 9437184s3.out.s bf16 845722624 589824s3.norm_q f32 846312448 512s3.norm_k f32 846312960 512s4.qkv_mlp tern 846313472 21233664s4.qkv_mlp.s bf16 867547136 1327104s4.out tern 868874240 9437184s4.out.s bf16 878311424 589824s4.norm_q f32 878901248 512s4.norm_k f32 878901760 512s5.qkv_mlp tern 878902272 21233664s5.qkv_mlp.s bf16 900135936 1327104s5.out tern 901463040 9437184s5.out.s bf16 910900224 589824s5.norm_q f32 911490048 512s5.norm_k f32 911490560 512s6.qkv_mlp tern 911491072 21233664s6.qkv_mlp.s bf16 932724736 1327104s6.out tern 934051840 9437184s6.out.s bf16 943489024 589824s6.norm_q f32 944078848 512s6.norm_k f32 944079360 512s7.qkv_mlp tern 944079872 21233664s7.qkv_mlp.s bf16 965313536 1327104s7.out tern 966640640 9437184s7.out.s bf16 976077824 589824s7.norm_q f32 976667648 512s7.norm_k f32 976668160 512s8.qkv_mlp tern 976668672 21233664s8.qkv_mlp.s bf16 997902336 1327104s8.out tern 999229440 9437184s8.out.s bf16 1008666624 589824s8.norm_q f32 1009256448 512s8.norm_k f32 1009256960 512s9.qkv_mlp tern 1009257472 21233664s9.qkv_mlp.s bf16 1030491136 1327104s9.out tern 1031818240 9437184s9.out.s bf16 1041255424 589824s9.norm_q f32 1041845248 512s9.norm_k f32 1041845760 512s10.qkv_mlp tern 1041846272 21233664s10.qkv_mlp.s bf16 1063079936 1327104s10.out tern 1064407040 9437184s10.out.s bf16 1073844224 589824s10.norm_q f32 1074434048 512s10.norm_k f32 1074434560 512s11.qkv_mlp tern 1074435072 21233664s11.qkv_mlp.s bf16 1095668736 1327104s11.out tern 1096995840 9437184s11.out.s bf16 1106433024 589824s11.norm_q f32 1107022848 512s11.norm_k f32 1107023360 512s12.qkv_mlp tern 1107023872 21233664s12.qkv_mlp.s bf16 1128257536 1327104s12.out tern 1129584640 9437184s12.out.s bf16 1139021824 589824s12.norm_q f32 1139611648 512s12.norm_k f32 1139612160 512s13.qkv_mlp tern 1139612672 21233664s13.qkv_mlp.s bf16 1160846336 1327104s13.out tern 1162173440 9437184s13.out.s bf16 1171610624 589824s13.norm_q f32 1172200448 512s13.norm_k f32 1172200960 512s14.qkv_mlp tern 1172201472 21233664s14.qkv_mlp.s bf16 1193435136 1327104s14.out tern 1194762240 9437184s14.out.s bf16 1204199424 589824s14.norm_q f32 1204789248 512s14.norm_k f32 1204789760 512s15.qkv_mlp tern 1204790272 21233664s15.qkv_mlp.s bf16 1226023936 1327104s15.out tern 1227351040 9437184s15.out.s bf16 1236788224 589824s15.norm_q f32 1237378048 512s15.norm_k f32 1237378560 512s16.qkv_mlp tern 1237379072 21233664s16.qkv_mlp.s bf16 1258612736 1327104s16.out tern 1259939840 9437184s16.out.s bf16 1269377024 589824s16.norm_q f32 1269966848 512s16.norm_k f32 1269967360 512s17.qkv_mlp tern 1269967872 21233664s17.qkv_mlp.s bf16 1291201536 1327104s17.out tern 1292528640 9437184s17.out.s bf16 1301965824 589824s17.norm_q f32 1302555648 512s17.norm_k f32 1302556160 512s18.qkv_mlp tern 1302556672 21233664s18.qkv_mlp.s bf16 1323790336 1327104s18.out tern 1325117440 9437184s18.out.s bf16 1334554624 589824s18.norm_q f32 1335144448 512s18.norm_k f32 1335144960 512s19.qkv_mlp tern 1335145472 21233664s19.qkv_mlp.s bf16 1356379136 1327104s19.out tern 1357706240 9437184s19.out.s bf16 1367143424 589824s19.norm_q f32 1367733248 512s19.norm_k f32 1367733760 512123version https://git-lfs.github.com/spec/v1oid sha256:b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4size 6228466688123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217embed bf16 0 777912320l0.qkv bf16 777912320 31457280l0.o bf16 809369600 20971520l0.gu bf16 830341120 99614720l0.down bf16 929955840 49807360l0.ln1 f32 979763200 10240l0.ln2 f32 979773440 10240l0.qn f32 979783680 512l0.kn f32 979784192 512l1.qkv bf16 979784704 31457280l1.o bf16 1011241984 20971520l1.gu bf16 1032213504 99614720l1.down bf16 1131828224 49807360l1.ln1 f32 1181635584 10240l1.ln2 f32 1181645824 10240l1.qn f32 1181656064 512l1.kn f32 1181656576 512l2.qkv bf16 1181657088 31457280l2.o bf16 1213114368 20971520l2.gu bf16 1234085888 99614720l2.down bf16 1333700608 49807360l2.ln1 f32 1383507968 10240l2.ln2 f32 1383518208 10240l2.qn f32 1383528448 512l2.kn f32 1383528960 512l3.qkv bf16 1383529472 31457280l3.o bf16 1414986752 20971520l3.gu bf16 1435958272 99614720l3.down bf16 1535572992 49807360l3.ln1 f32 1585380352 10240l3.ln2 f32 1585390592 10240l3.qn f32 1585400832 512l3.kn f32 1585401344 512l4.qkv bf16 1585401856 31457280l4.o bf16 1616859136 20971520l4.gu bf16 1637830656 99614720l4.down bf16 1737445376 49807360l4.ln1 f32 1787252736 10240l4.ln2 f32 1787262976 10240l4.qn f32 1787273216 512l4.kn f32 1787273728 512l5.qkv bf16 1787274240 31457280l5.o bf16 1818731520 20971520l5.gu bf16 1839703040 99614720l5.down bf16 1939317760 49807360l5.ln1 f32 1989125120 10240l5.ln2 f32 1989135360 10240l5.qn f32 1989145600 512l5.kn f32 1989146112 512l6.qkv bf16 1989146624 31457280l6.o bf16 2020603904 20971520l6.gu bf16 2041575424 99614720l6.down bf16 2141190144 49807360l6.ln1 f32 2190997504 10240l6.ln2 f32 2191007744 10240l6.qn f32 2191017984 512l6.kn f32 2191018496 512l7.qkv bf16 2191019008 31457280l7.o bf16 2222476288 20971520l7.gu bf16 2243447808 99614720l7.down bf16 2343062528 49807360l7.ln1 f32 2392869888 10240l7.ln2 f32 2392880128 10240l7.qn f32 2392890368 512l7.kn f32 2392890880 512l8.qkv bf16 2392891392 31457280l8.o bf16 2424348672 20971520l8.gu bf16 2445320192 99614720l8.down bf16 2544934912 49807360l8.ln1 f32 2594742272 10240l8.ln2 f32 2594752512 10240l8.qn f32 2594762752 512l8.kn f32 2594763264 512l9.qkv bf16 2594763776 31457280l9.o bf16 2626221056 20971520l9.gu bf16 2647192576 99614720l9.down bf16 2746807296 49807360l9.ln1 f32 2796614656 10240l9.ln2 f32 2796624896 10240l9.qn f32 2796635136 512l9.kn f32 2796635648 512l10.qkv bf16 2796636160 31457280l10.o bf16 2828093440 20971520l10.gu bf16 2849064960 99614720l10.down bf16 2948679680 49807360l10.ln1 f32 2998487040 10240l10.ln2 f32 2998497280 10240l10.qn f32 2998507520 512l10.kn f32 2998508032 512l11.qkv bf16 2998508544 31457280l11.o bf16 3029965824 20971520l11.gu bf16 3050937344 99614720l11.down bf16 3150552064 49807360l11.ln1 f32 3200359424 10240l11.ln2 f32 3200369664 10240l11.qn f32 3200379904 512l11.kn f32 3200380416 512l12.qkv bf16 3200380928 31457280l12.o bf16 3231838208 20971520l12.gu bf16 3252809728 99614720l12.down bf16 3352424448 49807360l12.ln1 f32 3402231808 10240l12.ln2 f32 3402242048 10240l12.qn f32 3402252288 512l12.kn f32 3402252800 512l13.qkv bf16 3402253312 31457280l13.o bf16 3433710592 20971520l13.gu bf16 3454682112 99614720l13.down bf16 3554296832 49807360l13.ln1 f32 3604104192 10240l13.ln2 f32 3604114432 10240l13.qn f32 3604124672 512l13.kn f32 3604125184 512l14.qkv bf16 3604125696 31457280l14.o bf16 3635582976 20971520l14.gu bf16 3656554496 99614720l14.down bf16 3756169216 49807360l14.ln1 f32 3805976576 10240l14.ln2 f32 3805986816 10240l14.qn f32 3805997056 512l14.kn f32 3805997568 512l15.qkv bf16 3805998080 31457280l15.o bf16 3837455360 20971520l15.gu bf16 3858426880 99614720l15.down bf16 3958041600 49807360l15.ln1 f32 4007848960 10240l15.ln2 f32 4007859200 10240l15.qn f32 4007869440 512l15.kn f32 4007869952 512l16.qkv bf16 4007870464 31457280l16.o bf16 4039327744 20971520l16.gu bf16 4060299264 99614720l16.down bf16 4159913984 49807360l16.ln1 f32 4209721344 10240l16.ln2 f32 4209731584 10240l16.qn f32 4209741824 512l16.kn f32 4209742336 512l17.qkv bf16 4209742848 31457280l17.o bf16 4241200128 20971520l17.gu bf16 4262171648 99614720l17.down bf16 4361786368 49807360l17.ln1 f32 4411593728 10240l17.ln2 f32 4411603968 10240l17.qn f32 4411614208 512l17.kn f32 4411614720 512l18.qkv bf16 4411615232 31457280l18.o bf16 4443072512 20971520l18.gu bf16 4464044032 99614720l18.down bf16 4563658752 49807360l18.ln1 f32 4613466112 10240l18.ln2 f32 4613476352 10240l18.qn f32 4613486592 512l18.kn f32 4613487104 512l19.qkv bf16 4613487616 31457280l19.o bf16 4644944896 20971520l19.gu bf16 4665916416 99614720l19.down bf16 4765531136 49807360l19.ln1 f32 4815338496 10240l19.ln2 f32 4815348736 10240l19.qn f32 4815358976 512l19.kn f32 4815359488 512l20.qkv bf16 4815360000 31457280l20.o bf16 4846817280 20971520l20.gu bf16 4867788800 99614720l20.down bf16 4967403520 49807360l20.ln1 f32 5017210880 10240l20.ln2 f32 5017221120 10240l20.qn f32 5017231360 512l20.kn f32 5017231872 512l21.qkv bf16 5017232384 31457280l21.o bf16 5048689664 20971520l21.gu bf16 5069661184 99614720l21.down bf16 5169275904 49807360l21.ln1 f32 5219083264 10240l21.ln2 f32 5219093504 10240l21.qn f32 5219103744 512l21.kn f32 5219104256 512l22.qkv bf16 5219104768 31457280l22.o bf16 5250562048 20971520l22.gu bf16 5271533568 99614720l22.down bf16 5371148288 49807360l22.ln1 f32 5420955648 10240l22.ln2 f32 5420965888 10240l22.qn f32 5420976128 512l22.kn f32 5420976640 512l23.qkv bf16 5420977152 31457280l23.o bf16 5452434432 20971520l23.gu bf16 5473405952 99614720l23.down bf16 5573020672 49807360l23.ln1 f32 5622828032 10240l23.ln2 f32 5622838272 10240l23.qn f32 5622848512 512l23.kn f32 5622849024 512l24.qkv bf16 5622849536 31457280l24.o bf16 5654306816 20971520l24.gu bf16 5675278336 99614720l24.down bf16 5774893056 49807360l24.ln1 f32 5824700416 10240l24.ln2 f32 5824710656 10240l24.qn f32 5824720896 512l24.kn f32 5824721408 512l25.qkv bf16 5824721920 31457280l25.o bf16 5856179200 20971520l25.gu bf16 5877150720 99614720l25.down bf16 5976765440 49807360l25.ln1 f32 6026572800 10240l25.ln2 f32 6026583040 10240l25.qn f32 6026593280 512l25.kn f32 6026593792 512l26.qkv bf16 6026594304 31457280l26.o bf16 6058051584 20971520l26.gu bf16 6079023104 99614720l26.down bf16 6178637824 49807360l26.ln1 f32 6228445184 10240l26.ln2 f32 6228455424 10240l26.qn f32 6228465664 512l26.kn f32 6228466176 512123version https://git-lfs.github.com/spec/v1oid sha256:54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5size 99317260123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138bn.mean f32 0 512bn.var f32 512 512pqc bf16 1024 2048pqc.b f32 3072 128conv_in bf16 3328 294912conv_in.b f32 298240 2048mid.r0.n1.g f32 300288 2048mid.r0.n1.b f32 302336 2048mid.r0.c1 bf16 304384 4718592mid.r0.c1.b f32 5022976 2048mid.r0.n2.g f32 5025024 2048mid.r0.n2.b f32 5027072 2048mid.r0.c2 bf16 5029120 4718592mid.r0.c2.b f32 9747712 2048mid.attn.gn.g f32 9749760 2048mid.attn.gn.b f32 9751808 2048mid.attn.qkv bf16 9753856 1572864mid.attn.qkv.b f32 11326720 6144mid.attn.out bf16 11332864 524288mid.attn.out.b f32 11857152 2048mid.r1.n1.g f32 11859200 2048mid.r1.n1.b f32 11861248 2048mid.r1.c1 bf16 11863296 4718592mid.r1.c1.b f32 16581888 2048mid.r1.n2.g f32 16583936 2048mid.r1.n2.b f32 16585984 2048mid.r1.c2 bf16 16588032 4718592mid.r1.c2.b f32 21306624 2048up0.r0.n1.g f32 21308672 2048up0.r0.n1.b f32 21310720 2048up0.r0.c1 bf16 21312768 4718592up0.r0.c1.b f32 26031360 2048up0.r0.n2.g f32 26033408 2048up0.r0.n2.b f32 26035456 2048up0.r0.c2 bf16 26037504 4718592up0.r0.c2.b f32 30756096 2048up0.r1.n1.g f32 30758144 2048up0.r1.n1.b f32 30760192 2048up0.r1.c1 bf16 30762240 4718592up0.r1.c1.b f32 35480832 2048up0.r1.n2.g f32 35482880 2048up0.r1.n2.b f32 35484928 2048up0.r1.c2 bf16 35486976 4718592up0.r1.c2.b f32 40205568 2048up0.r2.n1.g f32 40207616 2048up0.r2.n1.b f32 40209664 2048up0.r2.c1 bf16 40211712 4718592up0.r2.c1.b f32 44930304 2048up0.r2.n2.g f32 44932352 2048up0.r2.n2.b f32 44934400 2048up0.r2.c2 bf16 44936448 4718592up0.r2.c2.b f32 49655040 2048up0.us bf16 49657088 4718592up0.us.b f32 54375680 2048up1.r0.n1.g f32 54377728 2048up1.r0.n1.b f32 54379776 2048up1.r0.c1 bf16 54381824 4718592up1.r0.c1.b f32 59100416 2048up1.r0.n2.g f32 59102464 2048up1.r0.n2.b f32 59104512 2048up1.r0.c2 bf16 59106560 4718592up1.r0.c2.b f32 63825152 2048up1.r1.n1.g f32 63827200 2048up1.r1.n1.b f32 63829248 2048up1.r1.c1 bf16 63831296 4718592up1.r1.c1.b f32 68549888 2048up1.r1.n2.g f32 68551936 2048up1.r1.n2.b f32 68553984 2048up1.r1.c2 bf16 68556032 4718592up1.r1.c2.b f32 73274624 2048up1.r2.n1.g f32 73276672 2048up1.r2.n1.b f32 73278720 2048up1.r2.c1 bf16 73280768 4718592up1.r2.c1.b f32 77999360 2048up1.r2.n2.g f32 78001408 2048up1.r2.n2.b f32 78003456 2048up1.r2.c2 bf16 78005504 4718592up1.r2.c2.b f32 82724096 2048up1.us bf16 82726144 4718592up1.us.b f32 87444736 2048up2.r0.n1.g f32 87446784 2048up2.r0.n1.b f32 87448832 2048up2.r0.c1 bf16 87450880 2359296up2.r0.c1.b f32 89810176 1024up2.r0.n2.g f32 89811200 1024up2.r0.n2.b f32 89812224 1024up2.r0.c2 bf16 89813248 1179648up2.r0.c2.b f32 90992896 1024up2.r0.sc bf16 90993920 262144up2.r0.sc.b f32 91256064 1024up2.r1.n1.g f32 91257088 1024up2.r1.n1.b f32 91258112 1024up2.r1.c1 bf16 91259136 1179648up2.r1.c1.b f32 92438784 1024up2.r1.n2.g f32 92439808 1024up2.r1.n2.b f32 92440832 1024up2.r1.c2 bf16 92441856 1179648up2.r1.c2.b f32 93621504 1024up2.r2.n1.g f32 93622528 1024up2.r2.n1.b f32 93623552 1024up2.r2.c1 bf16 93624576 1179648up2.r2.c1.b f32 94804224 1024up2.r2.n2.g f32 94805248 1024up2.r2.n2.b f32 94806272 1024up2.r2.c2 bf16 94807296 1179648up2.r2.c2.b f32 95986944 1024up2.us bf16 95987968 1179648up2.us.b f32 97167616 1024up3.r0.n1.g f32 97168640 1024up3.r0.n1.b f32 97169664 1024up3.r0.c1 bf16 97170688 589824up3.r0.c1.b f32 97760512 512up3.r0.n2.g f32 97761024 512up3.r0.n2.b f32 97761536 512up3.r0.c2 bf16 97762048 294912up3.r0.c2.b f32 98056960 512up3.r0.sc bf16 98057472 65536up3.r0.sc.b f32 98123008 512up3.r1.n1.g f32 98123520 512up3.r1.n1.b f32 98124032 512up3.r1.c1 bf16 98124544 294912up3.r1.c1.b f32 98419456 512up3.r1.n2.g f32 98419968 512up3.r1.n2.b f32 98420480 512up3.r1.c2 bf16 98420992 294912up3.r1.c2.b f32 98715904 512up3.r2.n1.g f32 98716416 512up3.r2.n1.b f32 98716928 512up3.r2.c1 bf16 98717440 294912up3.r2.c1.b f32 99012352 512up3.r2.n2.g f32 99012864 512up3.r2.n2.b f32 99013376 512up3.r2.c2 bf16 99013888 294912up3.r2.c2.b f32 99308800 512norm_out.g f32 99309312 512norm_out.b f32 99309824 512conv_out bf16 99310336 6912conv_out.b f32 99317248 1212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "input": { "text": "A cat holding a sign that says hello world", "files": [] }, "source": "chosen by the agent: the classic FLUX text-rendering prompt (the model card gives no example prompt), plus two short scene prompts; the customer asked for at most 3 short prompts", "output": { "text": "512x512 PNG, 4 steps, guidance 1, seed 0", "files": [ "demo/phone0.png" ] }, "seconds": 52.6, "device": "Samsung Galaxy S26+ (Adreno 840)", "command": "adb shell \"cd /data/local/tmp/nnopt/port && sh ./run.sh --prompt 'A cat holding a sign that says hello world' --seed 0 --png /data/local/tmp/nnopt/demo0.png --metrics /data/local/tmp/nnopt/demo0.json\"", "runs": [ { "inputs": { "text": "A cat holding a sign that says hello world" }, "outputs": { "image": "demo/phone0.png" }, "reference": { "image": "demo/original0.png" }, "metrics": "demo/phone0_metrics.json" }, { "inputs": { "text": "A red fox sitting in a snowy forest at sunrise" }, "outputs": { "image": "demo/phone1.png" }, "reference": { "image": "demo/original1.png" }, "metrics": "demo/phone1_metrics.json" }, { "inputs": { "text": "A cozy wooden cabin beside a mountain lake, watercolor painting" }, "outputs": { "image": "demo/phone2.png" }, "reference": { "image": "demo/original2.png" }, "metrics": "demo/phone2_metrics.json" } ], "reference_note": "original*.png: stock diffusers Flux2KleinPipeline, fp32 on the build host's CPU, same prompt, 512x512, 4 steps, guidance 1, seed 0"}1{"load_ms": 1070.3, "runs": [{"total_ms": 51078.7, "phases_ms": {"text_encoder": 3226.7, "transformer": 44182.6, "vae_decoder": 3669.4}}], "prompt_tokens": 9, "steps": 4, "seed": 0, "peak_mem_mb": 5517}1{"load_ms": 1074.0, "runs": [{"total_ms": 51139.0, "phases_ms": {"text_encoder": 3248.9, "transformer": 44250.2, "vae_decoder": 3639.9}}], "prompt_tokens": 10, "steps": 4, "seed": 0, "peak_mem_mb": 5631}1{"load_ms": 1202.6, "runs": [{"total_ms": 51141.2, "phases_ms": {"text_encoder": 3222.5, "transformer": 44269.9, "vae_decoder": 3648.8}}], "prompt_tokens": 12, "steps": 4, "seed": 0, "peak_mem_mb": 5569}12345678910111213141516171819202122#!/usr/bin/env bash# bash deploy.sh DEST: installs the program into DEST on the phone (adb) and the weight packs into# /data/local/tmp/nnopt/bonsai_image_weights (listed in port.json external_files; pushed only when they changed).set -euo pipefailDEST=${1:?usage: deploy.sh DEST}. "$(dirname "$0")/paths.sh"cd "$ROOT"WDEV=/data/local/tmp/nnopt/bonsai_image_weights[ -x "$BUILD/bin/bonsai_image" ] || { echo "deploy.sh: run build.sh first" >&2; exit 1; }[ -f "$BUILD/weights/.stamp" ] || { echo "deploy.sh: converted weights missing, run build.sh with INPUTS_DIR" >&2; exit 1; }adb shell "mkdir -p '$DEST' '$WDEV'"adb shell "rm -rf '$DEST/bin'" || trueadb push "$BUILD/bin" "$DEST/" > /dev/nulladb push run.sh port.json "$BUILD/weights/tokenizer.json" "$DEST/" > /dev/nullSTAMP=$(cat "$BUILD/weights/.stamp")if [ "$(adb shell "cat '$WDEV/.stamp' 2>/dev/null" | tr -d '\r' || true)" != "$STAMP" ]; then adb shell "rm -f '$WDEV/.stamp'" || true for f in te.idx te.bin dit.idx dit.bin vae.idx vae.bin; do adb push "$BUILD/weights/$f" "$WDEV/$f" > /dev/null; done adb push "$BUILD/weights/.stamp" "$WDEV/.stamp" > /dev/nullfiadb shell "chmod 755 '$DEST/run.sh' '$DEST/bin/bonsai_image'"echo "deploy.sh: installed into $DEST (weights in $WDEV)"123456789101112131415161718192021222324252627#!/usr/bin/env bash# Run once after downloading this folder: bash fetch.sh# The converted weight packs are in build/weights/; this makes the runner executable.set -euo pipefailcd "$(dirname "$0")"REPO=nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL
# The repository's manifest first (Hugging Face counts a download when config.json is requested).curl -fsSL "https://huggingface.co/$REPO/resolve/main/config.json" -o ../config.json
sha256_of() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d" " -f1; else shasum -a 256 "$1" | cut -d" " -f1; fi; }get() { # get URL FILE SHA256: download once, check the sha256 if [ -f "$2" ] && [ "$(sha256_of "$2")" = "$3" ]; then return 0; fi mkdir -p "$(dirname "$2")" curl -fL --retry 3 -o "$2.part" "$1" [ "$(sha256_of "$2.part")" = "$3" ] || { echo "fetch.sh: sha256 mismatch for $1" >&2; rm -f "$2.part"; exit 1; } mv "$2.part" "$2"}git_at() { # git_at URL COMMIT DIR: the exact commit, shallow if [ "$(git -C "$3" rev-parse HEAD 2>/dev/null || true)" = "$2" ]; then return 0; fi rm -rf "$3"; mkdir -p "$3" git -C "$3" init -q && git -C "$3" remote add origin "$1" git -C "$3" fetch -q --depth 1 origin "$2" && git -C "$3" -c advice.detachedHead=false checkout -q FETCH_HEAD}
chmod +x build/bin/bonsai_imageecho "fetch.sh: done. Next: bash deploy.sh /data/local/tmp/nnopt/port"1234567891011# Sourced by build.sh and deploy.sh: where .deps/ and build/ live. Next to this file when it is writable, else under# $HOME/.cache/bonsai-image-ocl/<hash of this folder's path> (a read-only checkout or a shared copy).ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)if [ -w "$ROOT" ]; then WORK=$ROOTelse H=$(printf '%s' "$ROOT" | python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest()[:12])') WORK=$HOME/.cache/bonsai-image-ocl/$HfiDEPS=$WORK/.depsBUILD=$WORK/build1234567{"contract": 1, "model_type": "kernel", "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)", "precision": "DiT block linears ternary 2-bit + bf16 scale per 128 (packed on the GPU); text encoder, VAE and other DiT weights bf16; fp32 activations and accumulation", "external_files": ["/data/local/tmp/nnopt/bonsai_image_weights/te.bin", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx", "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx", "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx"], "measure": {"unit": "call", "scope": "one call = Qwen3 text encoder (27 layers, 512 tokens) + one ternary DiT step at 512x512 + VAE decode of a 64x64x32 latent, all on the GPU"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>nnopt report · prism-ml/bonsai-image-ternary-4B-unpacked</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans+Condensed:wght@600;700&family=IBM+Plex+Sans:wght@400;500;600&display=swap"><style>:root { --bg: #f3f5f2; --panel: #ffffff; --ink: #17201d; --ink-2: #33403b; --muted: #5a6762; --line: #cfd8d3; --accent: #0b6e79; --accent-soft: #dcefee; --keep: #1d7a3e; --keep-soft: #dcf1e2; --stop: #b3261e; --stop-soft: #f9dedb; --warn: #9a5b00; --warn-soft: #fbecd2; --grid: #e3e9e5; --display: "IBM Plex Sans Condensed", "Arial Narrow", system-ui, sans-serif; --body: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif; --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace; color-scheme: light;}@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833; --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80; --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark; }}:root[data-theme="dark"] { --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833; --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80; --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark;}* { box-sizing: border-box; }body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--body); }.wrap { max-width: 1040px; margin: 0 auto; padding: 28px 20px 80px; display: grid; gap: 36px; }h1, h2, h3 { font-family: var(--display); margin: 0; line-height: 1.15; text-wrap: balance; }h1 { font-size: clamp(28px, 4.5vw, 40px); font-weight: 700; letter-spacing: -0.01em; }h2 { font-size: 22px; font-weight: 600; }h3 { font-size: 16px; font-weight: 600; }p { margin: 0; max-width: 72ch; }code, .mono { font-family: var(--mono); font-size: 0.88em; }.eyebrow { font: 500 12px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }.sub { color: var(--muted); font-size: 13px; }section { display: grid; gap: 14px; min-width: 0; }header { display: grid; gap: 10px; }.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }.tile { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; display: grid; gap: 4px; min-width: 0; }.tile .v { font: 700 26px/1.1 var(--display); font-variant-numeric: tabular-nums; }.tile .k { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }.tile.pass { border-color: var(--keep); background: var(--keep-soft); }.tile.fail { border-color: var(--stop); background: var(--stop-soft); }.tile.na { border-style: dashed; }.badge { display: inline-flex; align-items: center; gap: 6px; font: 600 12px/1 var(--mono); padding: 4px 8px; border-radius: 99px; border: 1px solid currentColor; white-space: nowrap; }.badge.pass { color: var(--keep); } .badge.fail { color: var(--stop); } .badge.skip { color: var(--muted); } .badge.warn { color: var(--warn); }.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 4px 0; overflow-x: auto; }table { border-collapse: collapse; width: 100%; font-size: 14px; }th, td { text-align: left; padding: 8px 14px; border-bottom: 1px solid var(--line); vertical-align: top; }tr:last-child td { border-bottom: 0; }th { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }td.num { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }.flags { display: grid; gap: 6px; }.flag { border-left: 3px solid var(--warn); background: var(--warn-soft); padding: 8px 12px; border-radius: 4px; font-size: 14px; }.flag.bad { border-color: var(--stop); background: var(--stop-soft); }.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 12px; }.chart { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px 8px; display: grid; gap: 6px; min-width: 0; }.chart svg { width: 100%; height: auto; display: block; overflow: visible; }.chart .ln { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }.chart .pt { fill: var(--accent); stroke: var(--panel); stroke-width: 2; }.chart .hit { fill: transparent; }.chart .hit:hover + .pt, .chart .pt:hover { r: 5; }.chart .gl { stroke: var(--grid); stroke-width: 1; }.chart text { fill: var(--muted); font: 11px var(--mono); }details { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 14px; }summary { cursor: pointer; font-weight: 500; }pre { font: 12px/1.5 var(--mono); white-space: pre-wrap; word-break: break-word; margin: 10px 0 0; color: var(--ink-2); }.kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; font-size: 14px; }.kv dt { color: var(--muted); font: 500 12px/1.9 var(--mono); text-transform: uppercase; letter-spacing: .05em; }.kv dd { margin: 0; font-family: var(--mono); font-size: 13px; word-break: break-all; }footer { color: var(--muted); font-size: 12px; }.figs { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }figure { margin: 0; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px; display: grid; gap: 8px; min-width: 0; }figure svg { width: 100%; height: auto; display: block; border-radius: 4px; }figure .frame { fill: var(--grid); }figcaption { font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }.box { fill: none; stroke-width: 2; vector-effect: non-scaling-stroke; }.box.ref { stroke: var(--ink); stroke-dasharray: 6 4; }.box.ref.missed { stroke: var(--stop); stroke-width: 3; }.box.port { stroke: var(--accent); }.box.port.extra { stroke: var(--warn); stroke-width: 3; }.box.borderline { stroke: var(--muted); stroke-width: 1; opacity: .7; }.legend { display: flex; flex-wrap: wrap; gap: 6px 18px; font: 12px var(--mono); color: var(--muted); }.legend i { display: inline-block; width: 18px; height: 0; vertical-align: middle; margin-right: 6px; border-top: 2px solid; }.vlm { display: grid; grid-template-columns: minmax(120px, 200px) 1fr; gap: 12px; align-items: start; }.vlm img { width: 100%; border-radius: 4px; display: block; }.said { display: grid; gap: 6px; font-size: 14px; }.said .who { font: 500 11px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }.said p { white-space: pre-wrap; word-break: break-word; }mark { background: var(--stop-soft); color: var(--ink); border-bottom: 2px solid var(--stop); padding: 0 1px; }h4 { font: 600 14px/1.2 var(--display); margin: 0; }.phone { border-top: 2px solid var(--line); padding-top: 24px; gap: 22px; }.phone > .ph { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }@media (max-width: 560px) { .vlm { grid-template-columns: 1fr; } }@media print { body { background: #fff; } .wrap { padding: 0; } }</style></head><body><main class="wrap"><header><span class="eyebrow">nnopt verification report · Kernel or layer</span><h1>prism-ml/bonsai-image-ternary-4B-unpacked on galaxy-s26-plus</h1><p class="sub">Job NN-C9116E · 2026-11-29 04:24 UTC ·nnopt-verify 0.1.0 · reference bundle <span class="mono">a9435c0dbbdc329e</span></p></header><div class="tiles"><div class="tile pass"><span class="k">Correctness</span><span class="v">PASS</span><span class=sub>very_close precision policy</span></div><div class="tile na"><span class="k">Speed target</span><span class="v">no target</span></div><div class="tile pass"><span class="k">Runtime</span><span class="v">PASS</span><span class=sub>OpenCL, as asked</span></div><div class="tile "><span class="k">Latency per call</span><span class="v">35181 ms</span><span class=sub>warm, median</span></div><div class="tile "><span class="k">Peak memory</span><span class="v">5728 MB</span><span class=sub>process tree</span></div><div class="tile "><span class="k">Load time</span><span class="v">1126 ms</span></div></div><section><h2>Correctness</h2><p>The port ran on 6 inputs (4 hidden, generated fresh for this job and never shown to theporting agent) and was compared with the reference outputs captured from your code. Thresholds are for the<b>very_close</b> precision policy.</p><div class="panel"><table><thead><tr><th>Check</th><th>Value</th><th>Threshold</th><th>Result</th></tr></thead><tbody><tr><td>All cases ran<div class=sub>6/6 cases produced valid output</div></td><td class=num>1.00</td><td class=num>>= 1.00</td><td><span class="badge pass">✓ PASS</span></td></tr><tr><td>Outputs within tolerance<div class=sub>6/6 cases within tolerance: rtol 0.01, atol 0.01×rms (very close)</div></td><td class=num>6/6 cases</td><td class=num>>= 1.00</td><td><span class="badge pass">✓ PASS</span></td></tr><tr><td>Max abs error<div class=sub>worst |port - ref| over all outputs</div></td><td class=num>0.062</td><td class=num></td><td><span class="badge skip">SKIPPED</span></td></tr><tr><td>Max relative error<div class=sub>worst |port - ref| / |ref| (ref != 0)</div></td><td class=num>1.9e+02</td><td class=num></td><td><span class="badge skip">SKIPPED</span></td></tr><tr><td>Min cosine similarity<div class=sub>lowest cosine similarity of an output</div></td><td class=num>1.000000</td><td class=num></td><td><span class="badge skip">SKIPPED</span></td></tr></tbody></table></div><details><summary>Per-case results (6 cases)</summary><div class="panel" style="margin-top:10px"><table><thead><tr><th>Case</th><th>Split</th><th>Within tolerance</th><th>Max abs error</th><th>Max rel error</th><th>Cosine</th><th>Elements off</th></tr></thead><tbody><tr><td class=num>p000</td><td>public · builtin</td><td class=num>yes</td><td class=num>0.031</td><td class=num>1.1e+02</td><td class=num>1.000</td><td class=num>0</td></tr><tr><td class=num>p001</td><td>public · builtin</td><td class=num>yes</td><td class=num>0.031</td><td class=num>37</td><td class=num>1.000</td><td class=num>0</td></tr><tr><td class=num>h000</td><td>hidden · generated</td><td class=num>yes</td><td class=num>0.062</td><td class=num>31</td><td class=num>1.000</td><td class=num>0</td></tr><tr><td class=num>h001</td><td>hidden · generated</td><td class=num>yes</td><td class=num>0.031</td><td class=num>38</td><td class=num>1.000</td><td class=num>0</td></tr><tr><td class=num>h002</td><td>hidden · generated</td><td class=num>yes</td><td class=num>0.062</td><td class=num>1.9e+02</td><td class=num>1.000</td><td class=num>0</td></tr><tr><td class=num>h003</td><td>hidden · generated</td><td class=num>yes</td><td class=num>0.031</td><td class=num>54</td><td class=num>1.000</td><td class=num>0</td></tr></tbody></table></div></details></section><section><h2>Runtime</h2><p>Asked for <b>hand-written OpenCL runtime in C++, no other engine on the phone</b>. Clean build, the port's own code and build log: uses OpenCL.</p><ul><li class="mono">src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e);</li><li class="mono">src/ops.cpp:35: cl_int e; aimg = clCreateImage(rt->ctx, CL_MEM_READ_WRITE, &f, &d, nullptr, &e); CLCHK(e);</li></ul></section><section><h2>Speed and memory</h2><p>2 warm-up runs, then 5 timed runs of 3 requests each (the firstrequest of each run is cold). Timed on the device's own clock.</p><div class="panel"><table><thead><tr><th>Metric (warm requests)</th><th>Median</th><th>p10</th><th>p90</th><th>n</th></tr></thead><tbody><tr><td>Request time</td><td class=num>35181 ms</td><td class=num>32839 ms</td><td class=num>38323 ms</td><td class=num>10</td></tr><tr><td>Request time (cold)</td><td class=num>27238 ms</td><td class=num>26861 ms</td><td class=num>28414 ms</td><td class=num>5</td></tr><tr><td>Load time</td><td class=num>1126 ms</td><td class=num>1065 ms</td><td class=num>1157 ms</td><td class=num>5</td></tr><tr><td>Process wall time</td><td class=num>102172 ms</td><td class=num>94708 ms</td><td class=num>103457 ms</td><td class=num>5</td></tr><tr><td>Peak RSS (process tree)</td><td class=num>5672 MB</td><td></td><td></td><td></td></tr><tr><td>Peak VmHWM (process tree)</td><td class=num>5728 MB</td><td></td><td></td><td></td></tr><tr><td>Peak memory (self-reported)</td><td class=num>5726 MB</td><td></td><td></td><td></td></tr></tbody></table></div><p class="sub">External cross-check (paired --repeat 3 vs 1, 5 pairs, device clock): Request time: 30670 ms. Graded values are capped by it.</p></section><section><h2>Environment and reproducibility</h2><dl class="kv"><dt>os</dt><dd>android</dd><dt>gpu</dt><dd>Adreno 840</dd><dt>soc</dt><dd>Snapdragon 8 Elite Gen 5</dd><dt>brand</dt><dd>Samsung</dd><dt>device</dt><dd>Samsung Galaxy S26+</dd><dt>ram_gb</dt><dd>12</dd><dt>android</dt><dd>16</dd><dt>gpu_apis</dt><dd>['OpenCL', 'Vulkan']</dd><dt>released</dt><dd>2026-02</dd><dt>roofline</dt><dd>{'npu': {'job': 'NN-174CC0', 'source': 'measured by lab/npu probe (NN-174CC0) on 2026-10-31: fp16 weight stream 69.93 GB/s (bw_l24), fp16 matmul 18.325 TFLOPS, int8 matmul 29.023 TOPS; LiteRT 2.3.1 + Qualcomm dispatch, QAIRT 2.50, burst', 'measured': True, 'measured_at': '2026-10-31', 'measured_by': 'probe', 'peak_int8_tops': 29.023, 'peak_fp16_tflops': 18.325, 'mem_bandwidth_gbps': 69.93, 'mem_bandwidth_int8_gbps': 70.46}, 'spec': {'source': 'spec-sheet estimate, not yet measured: LPDDR5X-10667 64-bit; Adreno 840 compute is a rough estimate', 'peak_int8_tops': 6.0, 'peak_fp16_tflops': 6.0, 'mem_bandwidth_gbps': 85.3}, 'source': 'measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)', 'measured': True, 'device_best': {'cpu_job': 'NN-DA0137', 'gpu_job': 'NN-DA0137', 'cpu_read_gbps': 74.03, 'gpu_read_gbps': 73.18, 'cpu_measured_at': '2026-10-23T04:46:29+00:00', 'gpu_measured_at': '2026-10-23T04:46:29+00:00'}, 'measured_at': '2026-11-06', 'measured_by': 'device', 'device_probe': {'job': 'NN-10306A', 'measured_at': '2026-11-06T19:04:04+00:00', 'cpu_read_gbps': 62.33, 'gpu_read_gbps': 73.06}, 'peak_int8_tops': 6.0, 'peak_fp16_tflops': 6.0, 'mem_bandwidth_gbps': 73.06}</dd><dt>model_id</dt><dd>m2q</dd><dt>version_id</dt><dd>36</dd><dt>name</dt><dd>Samsung Galaxy S26+</dd><dt>processor</dt><dd>gpu</dd><dt>executor</dt><dd>adb</dd><dt>reference python</dt><dd>3.12.3</dd><dt>reference numpy</dt><dd>2.5.4</dd><dt>reference nnopt_verify</dt><dd>0.1.0</dd><dt>reference platform</dt><dd>Linux-7.0.0-1014-gcp-x86_64-with-glibc2.39</dd></dl><p class="sub">REPRO.md, next to this report, lists the tools, the model and every step to get these numbers on your own device; reproduce.sh runs the measurement. results.csv and results.json hold every number in this report.</p></section><footer>Generated by nnopt-verify 0.1.0. Correctness is graded on all inputs; speed figures are medians of warm requests unless marked cold.</footer></main></body></html>1234567891011#!/bin/sh# Reproduce nnopt's numbers on your own device (REPRO.md). Build and deploy first (REPRO.md, steps 4 to 6).# Needs python3, and adb (Android; ANDROID_SERIAL with several phones) or ssh (SSH_TARGET=user@host).here=$(cd "$(dirname "$0")" && pwd)root=$here; [ -d "$root/repro" ] || root=$(dirname "$here")cd "$root" || exit 2if [ ! -f repro/bench.py ]; then echo "no repro/ folder next to REPRO.md"; exit 2; firc=0python3 repro/bench.py "$@" || rc=$?python3 repro/bench.py --check "$@" || rc=$?exit $rc1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253section,name,value,unit_or_op,threshold,passed
grade,correctness,True,,,True
grade,speed_target_met,,,,
check,cases_completed,1.0,>=,1.0,True
check,outputs_match,1.0,>=,1.0,True
check,max_abs_error,0.0625,<=,,
check,max_rel_error,189.40449438202248,<=,,
check,min_cosine,0.9999999987530607,>=,,
check_metric,cases_passed,6,,,
check_metric,cases,6,,,
check_metric,max_abs_error,0.0625,,,
check_metric,max_rel_error,189.40449438202248,,,
check_metric,min_cosine,0.9999999987530607,,,
check_metric,max_mismatch_frac,0.0,,,
check_metric,nonfinite,0,,,
check_metric,tier,very_close,,,
check_metric,bar,"rtol 0.01, atol 0.01×rms (very close)",,,
check_metric,outputs,"['image', 'noise_pred', 'prompt_embeds']",,,
bench,latency_ms.median,35180.9,ms,,
bench,latency_ms.p10,32838.7,ms,,
bench,latency_ms.p90,38323.2,ms,,
bench,latency_ms.min,29772.4,ms,,
bench,latency_ms.max,39676.0,ms,,
bench,latency_ms.n,10,ms,,
bench,cold_latency_ms.median,27237.6,ms,,
bench,cold_latency_ms.p10,26861.1,ms,,
bench,cold_latency_ms.p90,28414.0,ms,,
bench,cold_latency_ms.min,26784.8,ms,,
bench,cold_latency_ms.max,28732.7,ms,,
bench,cold_latency_ms.n,5,ms,,
bench,load_ms.median,1126.4,ms,,
bench,load_ms.p10,1064.96,ms,,
bench,load_ms.p90,1156.74,ms,,
bench,load_ms.min,1044.0,ms,,
bench,load_ms.max,1161.7,ms,,
bench,load_ms.n,5,ms,,
bench,wall_ms.median,102172.0,ms,,
bench,wall_ms.p10,94708.2,ms,,
bench,wall_ms.p90,103457.0,ms,,
bench,wall_ms.min,91246.5,ms,,
bench,wall_ms.max,103537.0,ms,,
bench,wall_ms.n,5,ms,,
bench,peak_rss_mb,5672.0,MB,,
bench,peak_hwm_mb,5728.0,MB,,
bench,self_reported_peak_mem_mb,5726.0,MB,,
graded,latency_ms,35180.9,ms,,
graded,cold_latency_ms,27237.6,ms,,
graded,load_ms,1126.4,ms,,
graded,wall_ms,102172.0,ms,,
graded,peak_mem_mb,5728.0,MB,,
roofline,mem_bandwidth_gbps,73.06,,,
roofline,peak_gflops,6000.0,,,
roofline,figures,"{'processor': 'gpu', 'figures': 'gpu', 'source': 'measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)'}",,,1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330{ "kit_version": "0.1.0", "job": { "job_id": "NN-C9116E", "kind": "port", "model": "prism-ml/bonsai-image-ternary-4B-unpacked", "environment": "galaxy-s26-plus", "outcome": "passed", "failure_reason": null, "fingerprint": { "name": "Samsung Galaxy S26+", "soc": "Snapdragon 8 Elite Gen 5", "gpu": "Adreno 840", "os": "Android", "phone": "a fresh phone of the same model (the agent's phone's session was ending)" }, "backend": { "requested": "hand-written OpenCL runtime in C++, no other engine on the phone", "required": [ "OpenCL" ], "avoided": [], "passed": true, "reason": "uses OpenCL", "evidence": { "OpenCL": [ "src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e);", "src/ops.cpp:35: cl_int e; aimg = clCreateImage(rt->ctx, CL_MEM_READ_WRITE, &f, &d, nullptr, &e); CLCHK(e);" ] } }, "decoding": null }, "grade": { "correctness": true, "speed_target_met": null, "details": { "kit_version": "0.1.0", "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3", "model_type": "kernel", "precision": "very_close", "split": "all", "final": true, "correctness": { "passed": true, "failed_checks": [], "flags": [], "metrics": { "cases_passed": 6, "cases": 6, "max_abs_error": 0.0625, "max_rel_error": 189.40449438202248, "min_cosine": 0.9999999987530607, "max_mismatch_frac": 0.0, "nonfinite": 0, "tier": "very_close", "bar": "rtol 0.01, atol 0.01\u00d7rms (very close)", "outputs": [ "image", "noise_pred", "prompt_embeds" ] }, "errors": [] }, "benchmark": { "latency_ms": 35180.9, "load_ms": 1126.4, "peak_mem_mb": 5728.0, "flags": [] } } }, "check": { "kind": "check", "model_type": "kernel", "precision": "very_close", "split": "all", "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3", "port": { "dir": "/data/local/tmp/nnopt/port", "port_json": { "contract": 1, "model_type": "kernel", "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)", "precision": "DiT block linears ternary 2-bit + bf16 scale per 128 (packed on the GPU); text encoder, VAE and other DiT weights bf16; fp32 activations and accumulation", "external_files": [ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx", "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx", "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx" ], "measure": { "unit": "call", "scope": "one call = Qwen3 text encoder (27 layers, 512 tokens) + one ternary DiT step at 512x512 + VAE decode of a 64x64x32 latent, all on the GPU" } }, "tree_sha256": "9af2993c42cd482ccffba308b53a24e7819164771d455f0f2f68f8faac724c85", "external_sha256": { "/data/local/tmp/nnopt/bonsai_image_weights/te.bin": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b", "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a", "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07" } }, "executor": { "executor": "adb", "os": "android" }, "thresholds": { "fp32_rtol": 0.0001, "fp32_atol_scale": 0.0001, "fp16_rtol": 0.01, "fp16_atol_scale": 0.01, "int8_max_abs_diff": 1, "int_max_abs_diff": 0, "max_mismatch_frac": 0.0 }, "checks": [ { "name": "cases_completed", "value": 1.0, "op": ">=", "threshold": 1.0, "passed": true, "detail": "6/6 cases produced valid output" }, { "name": "outputs_match", "value": 1.0, "op": ">=", "threshold": 1.0, "passed": true, "detail": "6/6 cases within tolerance: rtol 0.01, atol 0.01\u00d7rms (very close)", "display": "6/6 cases" }, { "name": "max_abs_error", "value": 0.0625, "op": "<=", "threshold": null, "passed": null, "skipped": true, "detail": "worst |port - ref| over all outputs" }, { "name": "max_rel_error", "value": 189.40449438202248, "op": "<=", "threshold": null, "passed": null, "skipped": true, "detail": "worst |port - ref| / |ref| (ref != 0)" }, { "name": "min_cosine", "value": 0.9999999987530607, "op": ">=", "threshold": null, "passed": null, "skipped": true, "detail": "lowest cosine similarity of an output" } ], "metrics": { "cases_passed": 6, "cases": 6, "max_abs_error": 0.0625, "max_rel_error": 189.40449438202248, "min_cosine": 0.9999999987530607, "max_mismatch_frac": 0.0, "nonfinite": 0, "tier": "very_close", "bar": "rtol 0.01, atol 0.01\u00d7rms (very close)", "outputs": [ "image", "noise_pred", "prompt_embeds" ] }, "cases": [ { "id": "p000", "split": "public", "origin": "builtin", "compute": { "rc": 0, "wall_ms": 21230.0, "peak_rss_mb": 5204.0 }, "passed": true, "max_abs_error": 0.03125, "max_rel_error": 113.375, "cosine": 0.9999999990347779, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.0009689922480620155, "cosine": 0.9999999999105549, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 4.7272727272727275, "cosine": 0.9999999990347779, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.03125, "max_rel_error": 113.375, "cosine": 0.9999999999703847, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] }, { "id": "p001", "split": "public", "origin": "builtin", "compute": { "rc": 0, "wall_ms": 23460.0, "peak_rss_mb": 5558.0 }, "passed": true, "max_abs_error": 0.03125, "max_rel_error": 37.25, "cosine": 0.999999999197379, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.000975609756097561, "cosine": 0.9999999999110489, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 0.12, "cosine": 0.999999999197379, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.03125, "max_rel_error": 37.25, "cosine": 0.9999999999472156, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] }, { "id": "h000", "split": "hidden", "origin": "generated", "compute": { "rc": 0, "wall_ms": 23320.0, "peak_rss_mb": 5506.0 }, "passed": true, "max_abs_error": 0.0625, "max_rel_error": 31.4375, "cosine": 0.9999999989172967, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.0009746588693957114, "cosine": 0.999999999913716, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 0.9811320754716981, "cosine": 0.9999999989172967, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.0625, "max_rel_error": 31.4375, "cosine": 0.9999999999522909, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] }, { "id": "h001", "split": "hidden", "origin": "generated", "compute": { "rc": 0, "wall_ms": 23410.0, "peak_rss_mb": 5375.0 }, "passed": true, "max_abs_error": 0.03125, "max_rel_error": 38.0, "cosine": 0.9999999991483752, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.0009737098344693282, "cosine": 0.9999999999137019, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 0.1419753086419753, "cosine": 0.9999999991483752, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.03125, "max_rel_error": 38.0, "cosine": 0.9999999999651432, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] }, { "id": "h002", "split": "hidden", "origin": "generated", "compute": { "rc": 0, "wall_ms": 24750.0, "peak_rss_mb": 5466.0 }, "passed": true, "max_abs_error": 0.0625, "max_rel_error": 189.40449438202248, "cosine": 0.9999999990230362, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.0009765625, "cosine": 0.9999999999234104, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 1.540983606557377, "cosine": 0.9999999990230362, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.0625, "max_rel_error": 189.40449438202248, "cosine": 0.9999999999087043, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] }, { "id": "h003", "split": "hidden", "origin": "generated", "compute": { "rc": 0, "wall_ms": 25630.0, "peak_rss_mb": 5458.0 }, "passed": true, "max_abs_error": 0.03125, "max_rel_error": 54.333333333333336, "cosine": 0.9999999987530607, "mismatch_frac": 0.0, "nonfinite": 0, "outputs": [ { "name": "image", "dtype": "float16", "shape": [ 1, 3, 512, 512 ], "max_abs_error": 0.00048828125, "max_rel_error": 0.0009718172983479105, "cosine": 0.9999999999205494, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "noise_pred", "dtype": "float16", "shape": [ 1, 1024, 128 ], "max_abs_error": 0.001953125, "max_rel_error": 0.4587628865979381, "cosine": 0.9999999987530607, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true }, { "name": "prompt_embeds", "dtype": "float16", "shape": [ 1, 512, 7680 ], "max_abs_error": 0.03125, "max_rel_error": 54.333333333333336, "cosine": 0.999999999949425, "mismatch_frac": 0.0, "nonfinite": 0, "passed": true } ] } ], "flags": [], "errors": [], "passed": true, "started_at": "2026-11-29T04:01:06Z", "reference_check": { "verdict": "ok", "ok": true, "cases_checked": 6, "bad": 0, "message": null, "bad_cases": [] }, "processor": { "lock": "gpu", "checked": true, "used": [ "cpu", "gpu" ], "seen": { "gpu": [ "/dev/kgsl-3d0@bonsai_image", "libOpenCL.so@bonsai_image", "libOpenCL_adreno.so@bonsai_image" ], "npu": [] }, "gpu_busy_max_pct": 100, "violation": null }, "seconds": 166.09, "speed": { "metric": "latency_ms", "value": 21879.0, "unit": "ms", "cases": 6, "total_ms": 20000.0, "load_ms": 1000.0, "per": "call", "scope": "one call = Qwen3 text encoder (27 layers, 512 tokens) + one ternary DiT step at 512x512 + VAE decode of a 64x64x32 latent, all on the GPU", "phases_ms": { "text_encoder": 4000.0, "transformer": 10000.0, "vae_decoder": 4000.0 } }, "samples": "/out/samples/samples.json" }, "bench": { "kind": "bench", "model_type": "kernel", "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3", "case": "p000", "port": { "dir": "/data/local/tmp/nnopt/port", "port_json": { "contract": 1, "model_type": "kernel", "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)", "precision": "DiT block linears ternary 2-bit + bf16 scale per 128 (packed on the GPU); text encoder, VAE and other DiT weights bf16; fp32 activations and accumulation", "external_files": [ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx", "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx", "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx" ], "measure": { "unit": "call", "scope": "one call = Qwen3 text encoder (27 layers, 512 tokens) + one ternary DiT step at 512x512 + VAE decode of a 64x64x32 latent, all on the GPU" } }, "tree_sha256": "9af2993c42cd482ccffba308b53a24e7819164771d455f0f2f68f8faac724c85", "external_sha256": { "/data/local/tmp/nnopt/bonsai_image_weights/te.bin": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b", "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a", "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07" } }, "executor": { "executor": "adb", "os": "android" }, "environment": { "os": "Android", "gpu": "Adreno 840", "soc": "Snapdragon 8 Elite Gen 5", "brand": "Samsung", "device": "Samsung Galaxy S26+", "ram_gb": 12, "android": "16", "gpu_apis": [ "OpenCL", "Vulkan" ], "released": "2026-02", "roofline": { "npu": { "job": "NN-174CC0", "source": "measured by lab/npu probe (NN-174CC0) on 2026-10-31: fp16 weight stream 69.93 GB/s (bw_l24), fp16 matmul 18.325 TFLOPS, int8 matmul 29.023 TOPS; LiteRT 2.3.1 + Qualcomm dispatch, QAIRT 2.50, burst", "measured": true, "measured_at": "2026-10-31", "measured_by": "probe", "peak_int8_tops": 29.023, "peak_fp16_tflops": 18.325, "mem_bandwidth_gbps": 69.93, "mem_bandwidth_int8_gbps": 70.46 }, "spec": { "source": "spec-sheet estimate, not yet measured: LPDDR5X-10667 64-bit; Adreno 840 compute is a rough estimate", "peak_int8_tops": 6.0, "peak_fp16_tflops": 6.0, "mem_bandwidth_gbps": 85.3 }, "source": "measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)", "measured": true, "device_best": { "cpu_job": "NN-DA0137", "gpu_job": "NN-DA0137", "cpu_read_gbps": 74.03, "gpu_read_gbps": 73.18, "cpu_measured_at": "2026-10-23T04:46:29+00:00", "gpu_measured_at": "2026-10-23T04:46:29+00:00" }, "measured_at": "2026-11-06", "measured_by": "device", "device_probe": { "job": "NN-10306A", "measured_at": "2026-11-06T19:04:04+00:00", "cpu_read_gbps": 62.33, "gpu_read_gbps": 73.06 }, "peak_int8_tops": 6.0, "peak_fp16_tflops": 6.0, "mem_bandwidth_gbps": 73.06 }, "model_id": "m2q", "version_id": "36", "name": "Samsung Galaxy S26+", "processor": "gpu" }, "model_facts": { "params": 3959590948, "source": "nnopt scoping" }, "config": { "warmup": 2, "runs": 5, "repeat": 3, "max_new_tokens": 128, "external_check": true, "sustained_s": 0.0, "sustained_repeat": 10, "sample_interval_s": 2.0, "mem_interval_ms": 200, "timeout_s": 1800.0, "case": null, "prompt_tokens": null, "batch": 1, "external_min_s": 2.0, "external_max_repeat": 500, "resolution": null, "seconds": 10.0, "time_budget_s": 9734.4, "adapt": true, "cool_wait_s": 600.0, "rest_s": 3.0 }, "precision": "very_close", "flags": [], "errors": [], "method": { "warmup": 2, "runs": 5, "repeat": 3, "adapted": false, "first_run_s": 19.5, "time_budget_s": 9734, "estimate_s": 708 }, "started_at": "2026-11-29T04:03:52Z", "inputs": { "tensors": [ { "name": "prompt_ids", "shape": [ 1, 16 ], "dtype": "int32" }, { "name": "latents", "shape": [ 1, 1024, 128 ], "dtype": "float32" }, { "name": "timestep", "shape": [ 1 ], "dtype": "float32" }, { "name": "encoder_hidden_states", "shape": [ 1, 512, 7680 ], "dtype": "float32" }, { "name": "vae_latents", "shape": [ 1, 1024, 128 ], "dtype": "float32" } ] }, "cooldown": { "waited_s": 224.0, "start": { "temp_c": 54.8, "capped": [ "policy0 3187/3628 MHz", "policy6 3398/4742 MHz" ], "limits": { "policy0": 3187200, "policy6": 3398400 }, "status": 2 }, "end": { "temp_c": 42.6, "capped": [ "policy0 3187/3628 MHz", "policy6 3398/4742 MHz" ], "limits": { "policy0": 3187200, "policy6": 3398400 }, "status": 0 }, "why": "plateau" }, "repeat_used": 3, "timed_telemetry": { "samples": 879, "seconds": 984.0, "max_temp_c": { "min": 105.0, "max": 105.0, "mean": 105.0 }, "gpu_temp_c": { "min": 41.8, "max": 75.6, "mean": 57.53 }, "cpu_temp_c": { "min": 105.0, "max": 105.0, "mean": 105.0 }, "gpu_mhz": null, "cpu_mhz_max": { "min": 883.2, "max": 3398.0, "mean": 1658.0 }, "gpu_busy_pct": { "min": 0.0, "max": 100.0, "mean": 77.61 }, "power_w": null, "power_source": null, "ram_used_mb": null }, "cpu_caps": { "runs": 5, "capped": 0, "waited_s": 132.3, "caps": [] }, "runs": [ { "wall_ms": 91246.5, "load_ms": 1126.4, "peak_rss_mb": 5611.0, "peak_hwm_mb": 5628.0, "self_peak_mem_mb": 5626.0, "requests": [ { "total_ms": 26784.8, "latency_ms": 26784.8 }, { "total_ms": 29772.4, "latency_ms": 29772.4 }, { "total_ms": 33179.4, "latency_ms": 33179.4 } ], "cpu": { "temp_c": 50.8, "capped": [], "status": 2, "waited_s": 0.0 } }, { "wall_ms": 99900.7, "load_ms": 1096.4, "peak_rss_mb": 5658.0, "peak_hwm_mb": 5728.0, "self_peak_mem_mb": 5726.0, "requests": [ { "total_ms": 27237.6, "latency_ms": 27237.6 }, { "total_ms": 34554.6, "latency_ms": 34554.6 }, { "total_ms": 36635.8, "latency_ms": 36635.8 } ], "cpu": { "temp_c": 46.9, "capped": [], "status": 2, "waited_s": 24.3 } }, { "wall_ms": 103537.0, "load_ms": 1149.3, "peak_rss_mb": 5660.0, "peak_hwm_mb": 5697.0, "self_peak_mem_mb": 5695.0, "requests": [ { "total_ms": 26975.5, "latency_ms": 26975.5 }, { "total_ms": 35348.4, "latency_ms": 35348.4 }, { "total_ms": 39676.0, "latency_ms": 39676.0 } ], "cpu": { "temp_c": 47.1, "capped": [], "status": 2, "waited_s": 29.8 } }, { "wall_ms": 102172.0, "load_ms": 1161.7, "peak_rss_mb": 5671.0, "peak_hwm_mb": 5702.0, "self_peak_mem_mb": 5700.0, "requests": [ { "total_ms": 27935.9, "latency_ms": 27935.9 }, { "total_ms": 35009.2, "latency_ms": 35009.2 }, { "total_ms": 37649.6, "latency_ms": 37649.6 } ], "cpu": { "temp_c": 47.3, "capped": [], "status": 2, "waited_s": 41.8 } }, { "wall_ms": 103337.0, "load_ms": 1044.0, "peak_rss_mb": 5672.0, "peak_hwm_mb": 5676.0, "self_peak_mem_mb": 5674.0, "requests": [ { "total_ms": 28732.7, "latency_ms": 28732.7 }, { "total_ms": 35013.4, "latency_ms": 35013.4 }, { "total_ms": 38172.9, "latency_ms": 38172.9 } ], "cpu": { "temp_c": 47.3, "capped": [], "status": 2, "waited_s": 36.4 } } ], "summary": { "latency_ms": { "n": 10, "median": 35180.9, "mean": 35501.2, "min": 29772.4, "max": 39676.0, "p10": 32838.7, "p90": 38323.2 }, "cold_latency_ms": { "n": 5, "median": 27237.6, "mean": 27533.3, "min": 26784.8, "max": 28732.7, "p10": 26861.1, "p90": 28414.0 }, "load_ms": { "n": 5, "median": 1126.4, "mean": 1115.56, "min": 1044.0, "max": 1161.7, "p10": 1064.96, "p90": 1156.74 }, "wall_ms": { "n": 5, "median": 102172.0, "mean": 100039.0, "min": 91246.5, "max": 103537.0, "p10": 94708.2, "p90": 103457.0 }, "peak_rss_mb": 5672.0, "peak_hwm_mb": 5728.0, "self_reported_peak_mem_mb": 5726.0 }, "external": { "available": true, "method": "paired --repeat 3 vs 1", "pairs": 5, "latency_ms": 30670.0 }, "graded": { "latency_ms": 35180.9, "cold_latency_ms": 27237.6, "load_ms": 1126.4, "wall_ms": 102172.0, "peak_mem_mb": 5728.0 }, "roofline": { "mem_bandwidth_gbps": 73.06, "peak_gflops": 6000.0, "figures": { "processor": "gpu", "figures": "gpu", "source": "measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)" } }, "processor": { "lock": "gpu", "checked": true, "used": [ "cpu", "gpu" ], "seen": { "gpu": [ "/dev/kgsl-3d0@bonsai_image", "libOpenCL.so@bonsai_image", "libOpenCL_adreno.so@bonsai_image" ], "npu": [] }, "gpu_busy_max_pct": 100, "violation": null }, "seconds": 1222.14 }, "reference": { "format": "nnopt-reference-bundle", "version": 1, "job_id": "NN-C9116E", "model_type": "kernel", "precision_policy": "very_close", "model": { "kind": "contract", "program": "/work/reference_runner" }, "runner": { "kind": "contract", "program": "/work/reference_runner" }, "params": { "inputs": [ { "name": "prompt_ids", "shape": [ 1, 16 ], "dtype": "int32", "range": [ 0, 151642 ] }, { "name": "latents", "shape": [ 1, 1024, 128 ], "dtype": "float32" }, { "name": "timestep", "shape": [ 1 ], "dtype": "float32", "range": [ 0.0, 1.0 ] }, { "name": "encoder_hidden_states", "shape": [ 1, 512, 7680 ], "dtype": "float32" }, { "name": "vae_latents", "shape": [ 1, 1024, 128 ], "dtype": "float32" } ], "format": "NumPy .npy 1.0, C order, little-endian", "public_seeds": [ 201, 202 ], "outputs": [ { "name": "image", "shape": [ 1, 3, 512, 512 ], "dtype": "float16" }, { "name": "noise_pred", "shape": [ 1, 1024, 128 ], "dtype": "float16" }, { "name": "prompt_embeds", "shape": [ 1, 512, 7680 ], "dtype": "float16" } ] }, "tools": { "python": "3.12.3", "numpy": "2.5.4", "nnopt_verify": "0.1.0", "platform": "Linux-7.0.0-1014-gcp-x86_64-with-glibc2.39" }, "created_at": "2026-11-29T01:48:31Z", "cases": [ { "id": "p000", "split": "public", "origin": "builtin", "files": { "input:prompt_ids": "inputs/p000/prompt_ids.npy", "input:latents": "inputs/p000/latents.npy", "input:timestep": "inputs/p000/timestep.npy", "input:encoder_hidden_states": "inputs/p000/encoder_hidden_states.npy", "input:vae_latents": "inputs/p000/vae_latents.npy", "output:image": "outputs/p000/image.npy", "output:noise_pred": "outputs/p000/noise_pred.npy", "output:prompt_embeds": "outputs/p000/prompt_embeds.npy", "output": "outputs/p000.json" }, "meta": {} }, { "id": "p001", "split": "public", "origin": "builtin", "files": { "input:prompt_ids": "inputs/p001/prompt_ids.npy", "input:latents": "inputs/p001/latents.npy", "input:timestep": "inputs/p001/timestep.npy", "input:encoder_hidden_states": "inputs/p001/encoder_hidden_states.npy", "input:vae_latents": "inputs/p001/vae_latents.npy", "output:image": "outputs/p001/image.npy", "output:noise_pred": "outputs/p001/noise_pred.npy", "output:prompt_embeds": "outputs/p001/prompt_embeds.npy", "output": "outputs/p001.json" }, "meta": {} }, { "id": "h000", "split": "hidden", "origin": "generated", "files": { "input:prompt_ids": "inputs/h000/prompt_ids.npy", "input:latents": "inputs/h000/latents.npy", "input:timestep": "inputs/h000/timestep.npy", "input:encoder_hidden_states": "inputs/h000/encoder_hidden_states.npy", "input:vae_latents": "inputs/h000/vae_latents.npy", "output:image": "outputs/h000/image.npy", "output:noise_pred": "outputs/h000/noise_pred.npy", "output:prompt_embeds": "outputs/h000/prompt_embeds.npy", "output": "outputs/h000.json" }, "meta": {} }, { "id": "h001", "split": "hidden", "origin": "generated", "files": { "input:prompt_ids": "inputs/h001/prompt_ids.npy", "input:latents": "inputs/h001/latents.npy", "input:timestep": "inputs/h001/timestep.npy", "input:encoder_hidden_states": "inputs/h001/encoder_hidden_states.npy", "input:vae_latents": "inputs/h001/vae_latents.npy", "output:image": "outputs/h001/image.npy", "output:noise_pred": "outputs/h001/noise_pred.npy", "output:prompt_embeds": "outputs/h001/prompt_embeds.npy", "output": "outputs/h001.json" }, "meta": {} }, { "id": "h002", "split": "hidden", "origin": "generated", "files": { "input:prompt_ids": "inputs/h002/prompt_ids.npy", "input:latents": "inputs/h002/latents.npy", "input:timestep": "inputs/h002/timestep.npy", "input:encoder_hidden_states": "inputs/h002/encoder_hidden_states.npy", "input:vae_latents": "inputs/h002/vae_latents.npy", "output:image": "outputs/h002/image.npy", "output:noise_pred": "outputs/h002/noise_pred.npy", "output:prompt_embeds": "outputs/h002/prompt_embeds.npy", "output": "outputs/h002.json" }, "meta": {} }, { "id": "h003", "split": "hidden", "origin": "generated", "files": { "input:prompt_ids": "inputs/h003/prompt_ids.npy", "input:latents": "inputs/h003/latents.npy", "input:timestep": "inputs/h003/timestep.npy", "input:encoder_hidden_states": "inputs/h003/encoder_hidden_states.npy", "input:vae_latents": "inputs/h003/vae_latents.npy", "output:image": "outputs/h003/image.npy", "output:noise_pred": "outputs/h003/noise_pred.npy", "output:prompt_embeds": "outputs/h003/prompt_embeds.npy", "output": "outputs/h003.json" }, "meta": {} } ], "splits": { "public": [ "p000", "p001" ], "hidden": [ "h000", "h001", "h002", "h003" ] }, "notes": [], "determinism": { "outputs_bit_identical": true }, "oracle_check": { "verdict": "ok", "ok": true, "cases_checked": 6, "bad": 0, "message": null, "bad_cases": [] }, "frozen_at": "2026-11-29T01:55:56Z" }}12345678# The machine nnopt built this deliverable on from scratch (REPRO.md, Tools): a public image and these# packages, nothing of nnopt. build.sh fetches everything else itself. Build and use it:# docker build --platform linux/amd64 -t build-env repro# docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:/src" -w /src -v "$PWD/inputs:/inputs:ro" -e INPUTS_DIR=/inputs build-env bash build.shFROM ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33acENV DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 LC_ALL=C.UTF-8RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git curl python3 python3-venv build-essential unzip xz-utils \ && rm -rf /var/lib/apt/lists/*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729#!/usr/bin/env python3"""Reproduce nnopt's numbers on your own device: the speed with nnopt's exact settings and, with --check, the outputson the public cases. See ../REPRO.md.
Needs python3 (3.8 or newer, no packages), sh, and adb (Android phones) or ssh and scp (a Jetson or Mac over thenetwork). plan.json next to this file holds the settings nnopt measured with and nnopt's numbers to compare against.
python3 repro/bench.py # speed, nnopt's settings, compared with nnopt's numbers python3 repro/bench.py --check # outputs on the public cases, compared with the expected outputs python3 repro/bench.py --deploy # run deploy.sh into --dir first python3 repro/bench.py --sustained 600 # then run back to back for 10 minutes (throttling) python3 repro/bench.py --plan repro/galaxy-s24/plan.json # measured on several phones: your phone's numbers
Connection: --serial SERIAL (adb; or $ANDROID_SERIAL), --ssh USER@HOST (or $SSH_TARGET), --local (this machine).--dir is where deploy.sh installed the program on the device (default: plan.json's device_dir).Exit code: 0 everything within tolerance, 1 something outside it, 2 an error."""
from __future__ import annotations
import argparseimport astimport jsonimport mathimport osimport reimport shleximport shutilimport statisticsimport structimport subprocessimport sysimport tempfileimport timefrom array import arrayfrom pathlib import Path
HERE = Path(__file__).resolve().parentROOT = HERE.parent # the deliverable: build.sh, deploy.sh, REPRO.mdTOKEN_TYPES = ("text_to_text", "vision_language")OUT_EXT = {"text_to_text": ".json", "speech_to_text": ".json", "text_to_speech": ".wav", "vision_detection": ".json", "vision_language": ".json", "kernel": "", "audio_generation": ".wav"}
class Fail(Exception): pass
# ---------------------------------------------------------------- the device
class Device: def __init__(self, kind: str, serial: str | None = None, target: str | None = None): self.kind, self.serial, self.target = kind, serial, target tool = {"adb": "adb", "ssh": "ssh", "local": "sh"}[kind] if shutil.which(tool) is None: raise Fail(f"{tool} is not installed or not on PATH (REPRO.md, Tools)") if kind == "ssh" and not target: raise Fail("--ssh USER@HOST (or SSH_TARGET) is needed for this device")
def describe(self) -> str: return {"adb": f"adb{' -s ' + self.serial if self.serial else ''}", "ssh": f"ssh {self.target}", "local": "this machine"}[self.kind]
def _adb(self) -> list[str]: return ["adb"] + (["-s", self.serial] if self.serial else [])
def sh(self, script: str, timeout: float = 600) -> tuple[int, str]: argv = {"adb": self._adb() + ["shell", script], "ssh": ["ssh", "-o", "BatchMode=yes", self.target or "", script], "local": ["sh", "-c", script]}[self.kind] try: p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: return 124, f"timed out after {timeout:.0f} s" return p.returncode, p.stdout + p.stderr
def push(self, local: Path, remote: str) -> None: argv = {"adb": self._adb() + ["push", str(local), remote], "ssh": ["scp", "-q", "-r", str(local), f"{self.target}:{remote}"], "local": ["cp", "-R", str(local), remote]}[self.kind] p = subprocess.run(argv, capture_output=True, text=True) if p.returncode != 0: raise Fail(f"could not copy {local.name} to the device: {(p.stdout + p.stderr).strip()[-300:]}")
def pull(self, remote: str, local: Path) -> bool: argv = {"adb": self._adb() + ["pull", remote, str(local)], "ssh": ["scp", "-q", "-r", f"{self.target}:{remote}", str(local)], "local": ["cp", "-R", remote, str(local)]}[self.kind] return subprocess.run(argv, capture_output=True, text=True).returncode == 0
# Runs one command on the device: times it with the device's own clock and samples the memory (RSS) of its process# tree, as nnopt does. Prints "REPRO START_NS END_NS EXIT PEAK_RSS_KB".WRAP = r"""d={io}; t={tag}now() {{ v=$(date +%s%N 2>/dev/null); case "$v" in ''|*N*) perl -MTime::HiRes=time -e 'printf("%.0f\n", time()*1e9)' 2>/dev/null || echo "$(date +%s)000000000";; *) echo "$v";; esac; }}if [ -d /system/bin ]; then o="PID,PPID,RSS"; else o="pid,ppid,rss"; firm -f "$d/$t.rc" "$d/$t.end"s=$(now)( cd {dir} && {env}sh ./run.sh {args} > "$d/$t.log" 2>&1; r=$?; now > "$d/$t.end"; echo $r > "$d/$t.rc" ) &root=$!; peak=0while [ ! -f "$d/$t.rc" ]; do m=$(ps -A -o $o 2>/dev/null | awk -v r=$root 'NR>1 {{ p[$1]=$2; k[$1]=$3 }} END {{ s=0; for (x in p) {{ q=x; n=0; while (q != "" && q != r && n < 64) {{ q=p[q]; n++ }} if (q == r) s+=k[x] }} print s+0 }}') [ "${{m:-0}}" -gt "$peak" ] 2>/dev/null && peak=$m sleep 0.2doneecho "REPRO $s $(cat "$d/$t.end") $(cat "$d/$t.rc") $peak""""_MARK = re.compile(r"^REPRO (\d+) (\d+) (-?\d+) (\d+)\s*$", re.M)
def q(s: str) -> str: return shlex.quote(s)
class Session: """The program deployed in `folder` on the device, inputs staged in `folder`-repro-io."""
def __init__(self, dev: Device, folder: str, model_type: str, tmp: Path): self.dev, self.dir, self.mt, self.tmp = dev, folder.rstrip("/"), model_type, tmp self.io = self.dir + "-repro-io" self.n = 0 rc, out = dev.sh(f"test -f {q(self.dir)}/run.sh && mkdir -p {q(self.io)} && echo ok", 60) if "ok" not in out: raise Fail(f"no run.sh in {self.dir} on the device: deploy first (bash deploy.sh {self.dir}, or --deploy)")
def stage(self, local: Path) -> str: remote = f"{self.io}/{local.name}" self.dev.push(local, remote if local.is_file() else self.io + "/") return remote
def run(self, args: dict, *, repeat: int = 1, fetch_out: bool = False, timeout: float = 3600, env: dict | None = None) -> dict: self.n += 1 tag = f"r{self.n}" out = f"{self.io}/{tag}.out{OUT_EXT[self.mt]}" met = f"{self.io}/{tag}.metrics.json" line = command(self.mt, args, out=out, metrics=met, repeat=repeat) exports = "".join(f"{k}={q(str(v))} " for k, v in (env or {}).items()) rc, text = self.dev.sh(WRAP.format(io=q(self.io), tag=tag, dir=q(self.dir), args=line, env=exports), timeout) m = _MARK.search(text) res = {"command": "sh ./run.sh " + line, "exit": int(m.group(3)) if m else rc, "wall_ms": None, "peak_rss_mb": None, "metrics": None, "out": None} if m: res["wall_ms"] = (int(m.group(2)) - int(m.group(1))) / 1e6 res["peak_rss_mb"] = int(m.group(4)) / 1024 or None mloc = self.tmp / f"{tag}.metrics.json" if self.dev.pull(met, mloc) and mloc.is_file(): try: res["metrics"] = json.loads(mloc.read_text()) except ValueError: pass if fetch_out: oloc = self.tmp / Path(out).name if self.dev.pull(out, oloc) and oloc.exists(): res["out"] = oloc if res["exit"] != 0: _, log = self.dev.sh(f"tail -c 2000 {q(self.io)}/{tag}.log", 60) res["log"] = log return res
def close(self) -> None: self.dev.sh(f"rm -rf {q(self.io)}", 120)
def command(mt: str, a: dict, *, out: str, metrics: str, repeat: int = 1) -> str: """run.sh's arguments for one request (CONTRACT.md).""" mode = a.get("mode", "generate") args: list[str] = [] if mt == "audio_generation": args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0)), "--seconds", f"{float(a.get('seconds') or 10):.6f}".rstrip("0").rstrip(".")] elif mt == "vision_detection": for im in a["images"]: args += ["--image", q(im)] elif mt in TOKEN_TYPES: if mt == "vision_language": args += ["--image", q(a["image"])] args += ["--prompt-file", q(a["input"]), "--max-new-tokens", str(int(a["max_new_tokens"]))] if a.get("ignore_eos"): args.append("--ignore-eos") elif mt == "speech_to_text": args = ["--audio", q(a["input"])] elif mt == "kernel": args = ["--inputs", q(a["input"])] else: # text_to_speech args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0))] args += ["--out", q(out), "--metrics", q(metrics)] if repeat > 1: args += ["--repeat", str(int(repeat))] return " ".join(args)
# ---------------------------------------------------------------- numbers
def derive(mt: str, r: dict, audio_s: float | None, batch: int = 1) -> dict: """One request's numbers from the port's metrics, as nnopt computes them.""" t = float(r.get("total_ms") or 0) d: dict = {"total_ms": t} if mt == "vision_detection": d.update(latency_ms=t, per_image_ms=t / batch, fps=batch * 1000 / t if t > 0 else None) elif mt in TOKEN_TYPES: ttft, n, p = float(r.get("ttft_ms") or 0), int(r.get("new_tokens") or 0), int(r.get("prompt_tokens") or 0) dec = t - ttft d.update(ttft_ms=ttft, tokens_per_s=(n - 1) / (dec / 1000) if dec > 0 and n > 1 else None, prefill_tokens_per_s=p / (ttft / 1000) if ttft > 0 else None, e2e_tokens_per_s=n / (t / 1000) if t > 0 else None) elif mt == "speech_to_text": d.update(latency_ms=t, real_time_factor=t / 1000 / audio_s if audio_s else None) elif mt == "kernel": d["latency_ms"] = t elif mt == "audio_generation": n, first = int(r.get("frames") or 1), float(r.get("ttfa_ms") or 0) per = (t - first) / (n - 1) if n > 1 else t audio_ms = 1000 * audio_s / n if audio_s else None d.update(time_to_first_audio_ms=first, latency_ms=t, ms_per_frame=per, real_time_factor=per / audio_ms if audio_ms else None) else: # text_to_speech d.update(time_to_first_audio_ms=r.get("ttfa_ms"), latency_ms=t, real_time_factor=t / 1000 / audio_s if audio_s else None) return d
def pct(values: list[float], p: float) -> float: v = sorted(values) if len(v) == 1: return v[0] k = (len(v) - 1) * p / 100 f = math.floor(k) return v[f] + (v[min(f + 1, len(v) - 1)] - v[f]) * (k - f)
def stats(values) -> dict | None: v = [float(x) for x in values if x is not None and math.isfinite(float(x))] if not v: return None return {"median": statistics.median(v), "p10": pct(v, 10), "p90": pct(v, 90), "n": len(v)}
def fmt(x) -> str: if x is None: return "–" a = abs(x) return f"{x:.0f}" if a >= 1000 else f"{x:.1f}" if a >= 10 else f"{x:.3g}"
def wav_info(path: Path) -> tuple[int, int, int, int, bytes]: """(sample rate, channels, bits, format, data) of a RIFF WAV (PCM or float).""" b = path.read_bytes() if b[:4] != b"RIFF" or b[8:12] != b"WAVE": raise Fail(f"{path.name} is not a WAV file") i, rate, ch, bits, fmt_tag, data = 12, 0, 0, 0, 0, b"" while i + 8 <= len(b): cid, size = b[i:i + 4], struct.unpack("<I", b[i + 4:i + 8])[0] body = b[i + 8:i + 8 + size] if cid == b"fmt ": fmt_tag, ch, rate = struct.unpack("<HHI", body[:8]) bits = struct.unpack("<H", body[14:16])[0] if fmt_tag == 0xFFFE and len(body) >= 26: # WAVE_FORMAT_EXTENSIBLE: the real format is in the GUID fmt_tag = struct.unpack("<H", body[24:26])[0] elif cid == b"data": data = body i += 8 + size + (size & 1) if not rate or not ch or not bits: raise Fail(f"{path.name}: no WAV format chunk") return rate, ch, bits, fmt_tag, data
def wav_seconds(path: Path) -> float: rate, ch, bits, _, data = wav_info(path) return len(data) / (ch * bits // 8) / rate
def wav_rms(path: Path) -> float: rate, ch, bits, tag, data = wav_info(path) if tag == 3 and bits == 32: a = array("f") elif bits == 16: a = array("h") else: return float("nan") a.frombytes(data[: len(data) // a.itemsize * a.itemsize]) if sys.byteorder == "big": a.byteswap() scale = 1.0 if a.typecode == "f" else 32768.0 return math.sqrt(sum((x / scale) ** 2 for x in a) / len(a)) if len(a) else 0.0
# ---------------------------------------------------------------- speed
def speed(sess: Session, plan: dict, args: argparse.Namespace) -> dict | None: if not plan.get("settings") or not plan.get("inputs"): print("nnopt did not measure the speed of this deliverable (see REPRO.md)") return None mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"] warmup = args.warmup if args.warmup is not None else int(st["warmup"]) runs = args.runs if args.runs is not None else int(st["runs"]) repeat = int(st["repeat"]) batch = int(st.get("batch") or 1) req: dict = {"mode": plan.get("mode", "generate")} for k in ("max_new_tokens", "ignore_eos", "seed", "seconds"): if st.get(k) is not None: req[k] = st[k] staged = {k: sess.stage(HERE / v) for k, v in inp.items() if isinstance(v, str)} if "images" in inp: req["images"] = [sess.stage(HERE / v) for v in inp["images"]] req.update({k: v for k, v in staged.items()}) audio_s = None if mt == "speech_to_text": audio_s = wav_seconds(HERE / inp["input"]) elif mt == "audio_generation": audio_s = float(st.get("seconds") or 10) rest = float(st.get("rest_s") or 0) print(f"{warmup} warm-up run{'s' * (warmup != 1)}, {runs} timed run{'s' * (runs != 1)} of {repeat} " f"request{'s' * (repeat != 1)} each{settings_text(mt, st)}") for i in range(warmup): r = sess.run(req, repeat=1, timeout=args.timeout) _ok(r, f"warm-up {i + 1}") print(f" warm-up {i + 1}/{warmup}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" warm-up {i + 1} done") timed, pairs, peak = [], [], [] for i in range(runs): if rest: time.sleep(rest) r = sess.run(req, repeat=repeat, fetch_out=(i == 0), timeout=args.timeout) _ok(r, f"timed run {i + 1}") met = r["metrics"] or {} if not isinstance(met.get("runs"), list) or len(met["runs"]) != repeat: raise Fail(f"timed run {i + 1}: the metrics file needs {repeat} entries in \"runs\" (--repeat {repeat})") if i == 0 and mt == "text_to_speech" and r["out"]: audio_s = wav_seconds(r["out"]) reqs = [derive(mt, x, audio_s, batch) for x in met["runs"]] timed.append({"wall_ms": r["wall_ms"], "load_ms": met.get("load_ms"), "requests": reqs, "self_peak_mem_mb": met.get("peak_mem_mb")}) if r["peak_rss_mb"]: peak.append(r["peak_rss_mb"]) line = f" timed run {i + 1}/{runs}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" timed run {i + 1}" if plan.get("external_check", True): p_req, p_rep = paired(mt, req, repeat, plan) pr = sess.run(p_req, repeat=p_rep, timeout=args.timeout) if pr["exit"] == 0 and pr["wall_ms"] and r["wall_ms"]: pairs.append(r["wall_ms"] - pr["wall_ms"]) print(line) warm = [x for t in timed for x in (t["requests"][1:] if len(t["requests"]) > 1 else t["requests"])] keys = sorted({k for x in warm for k, v in x.items() if v is not None}) summary = {k: stats(x.get(k) for x in warm) for k in keys} summary["load_ms"] = stats(t["load_ms"] for t in timed) graded = {k: s["median"] for k, s in summary.items() if s} if peak: graded["peak_mem_mb"] = max(peak) ext = external(mt, pairs, st, repeat, batch, audio_s, plan) if ext: graded.update(ext_cap(mt, graded, ext)) return {"runs": timed, "summary": summary, "graded": graded, "external": ext}
def settings_text(mt: str, st: dict) -> str: bits = [] if mt in TOKEN_TYPES: bits.append(f"{st['max_new_tokens']} new tokens per request" + (" (--ignore-eos)" if st.get("ignore_eos") else "")) if st.get("prompt_tokens"): bits.append(f"a ~{st['prompt_tokens']}-token prompt") if mt == "vision_detection" and int(st.get("batch") or 1) > 1: bits.append(f"{st['batch']} images per request") if st.get("resolution"): bits.append(f"{st['resolution']} input") if mt == "audio_generation": bits.append(f"{st.get('seconds')} s of audio per request") return (": " + ", ".join(bits)) if bits else ""
def paired(mt: str, req: dict, repeat: int, plan: dict) -> tuple[dict, int]: """The same request with the least work (one new token; one audio frame), or at --repeat 1: the difference in wall time is the device-clock speed, which keeps the port's own timings honest.""" if mt in TOKEN_TYPES: return {**req, "max_new_tokens": 1}, repeat if mt == "audio_generation" and plan.get("frame_seconds"): return {**req, "seconds": plan["frame_seconds"]}, repeat return req, 1
def external(mt, pairs, st, repeat, batch, audio_s, plan) -> dict | None: if not pairs: return None d = statistics.median(pairs) if d <= 0: return None if mt in TOKEN_TYPES: return {"tokens_per_s": (int(st["max_new_tokens"]) - 1) * repeat / (d / 1000)} if mt == "audio_generation": fs = plan.get("frame_seconds") n = (max(1, round(float(st.get("seconds") or 10) / fs)) - 1) * repeat if fs else 0 return {"ms_per_frame": d / n, "real_time_factor": d / n / (1000 * fs)} if n > 0 else None if repeat < 2: return None per = d / (repeat - 1) out = {"latency_ms": per} if mt == "vision_detection": out["fps"] = batch * 1000 / per if audio_s: out["real_time_factor"] = per / 1000 / audio_s return out
def ext_cap(mt: str, g: dict, ext: dict, tol: float = 0.15) -> dict: """nnopt's rule: a self-reported speed more than 15% better than the device-clock measurement is replaced by it.""" out = {} if mt in TOKEN_TYPES and ext.get("tokens_per_s") and g.get("tokens_per_s"): if g["tokens_per_s"] > ext["tokens_per_s"] * (1 + tol): out["tokens_per_s"] = ext["tokens_per_s"] elif mt == "audio_generation" and ext.get("ms_per_frame") and g.get("ms_per_frame"): if ext["ms_per_frame"] > g["ms_per_frame"] * (1 + tol): out.update(ms_per_frame=ext["ms_per_frame"], real_time_factor=ext.get("real_time_factor")) elif ext.get("latency_ms") and g.get("latency_ms"): ratio = ext["latency_ms"] / g["latency_ms"] if ratio > 1 + tol: for k in ("latency_ms", "real_time_factor", "time_to_first_audio_ms", "per_image_ms"): if g.get(k) is not None: out[k] = g[k] * ratio if g.get("fps"): out["fps"] = g["fps"] / ratio return out
def compare(plan: dict, mine: dict) -> tuple[list[list[str]], bool]: rows, ok = [], True for c in plan.get("compare") or []: got, ref, tol = mine["graded"].get(c["key"]), c.get("nnopt"), float(c.get("tolerance_pct") or 10) if got is None or not ref: rows.append([c["label"], fmt(got), fmt(ref), "–", "not measured"]) continue diff = 100 * (got - ref) / ref within = abs(diff) <= tol ok &= within or c.get("informational", False) rows.append([c["label"] + (f" ({c['unit']})" if c.get("unit") else ""), fmt(got), fmt(ref), f"{diff:+.1f}%", ("yes" if within else "NO") + f" (±{tol:g}%)"]) return rows, ok
def table(head: list[str], rows: list[list[str]]) -> str: w = [max(len(str(r[i])) for r in [head] + rows) for i in range(len(head))] line = lambda r: " ".join(str(x).ljust(w[i]) for i, x in enumerate(r)) # noqa: E731 return "\n".join([line(head), line(["-" * n for n in w])] + [line(r) for r in rows])
def sustained(sess: Session, plan: dict, seconds: float, args: argparse.Namespace) -> dict: mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"] key = (plan.get("compare") or [{}])[0].get("key") req = {"mode": plan.get("mode", "generate"), **{k: st[k] for k in ("max_new_tokens", "ignore_eos", "seed", "seconds") if st.get(k) is not None}} req.update({k: f"{sess.io}/{Path(v).name}" for k, v in inp.items() if isinstance(v, str)}) if "images" in inp: req["images"] = [f"{sess.io}/{Path(v).name}" for v in inp["images"]] audio_s = wav_seconds(HERE / inp["input"]) if mt == "speech_to_text" else ( float(st.get("seconds") or 10) if mt == "audio_generation" else None) series, t0 = [], time.monotonic() print(f"sustained run: {seconds:.0f} s back to back") while time.monotonic() - t0 < seconds: r = sess.run(req, repeat=int(st.get("sustained_repeat") or st["repeat"]), timeout=args.timeout) _ok(r, "sustained run") reqs = [derive(mt, x, audio_s, int(st.get("batch") or 1)) for x in (r["metrics"] or {}).get("runs") or []] s = stats(x.get(key) for x in reqs[1:] or reqs) if s: series.append((time.monotonic() - t0, s["median"])) print(f" {series[-1][0]:5.0f} s {fmt(s['median'])}") if len(series) < 2: return {"series": series} first = statistics.median(v for t, v in series if t <= series[0][0] + 60) last = statistics.median(v for t, v in series if t >= series[-1][0] - 60) return {"series": series, "first_minute": first, "last_minute": last, "ratio": last / first if first else None}
# ---------------------------------------------------------------- outputs
def words(text: str) -> list[str]: return re.sub(r"[^\w\s']", " ", text.lower()).split()
def edits(a: list, b: list) -> int: prev = list(range(len(b) + 1)) for i, x in enumerate(a, 1): cur = [i] for j, y in enumerate(b, 1): cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))) prev = cur return prev[-1]
def iou(a: list, b: list) -> float: ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) inter = ix * iy union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter return inter / union if union > 0 else 0.0
NPY = {"f4": ("f", 4), "f8": ("d", 8), "i1": ("b", 1), "u1": ("B", 1), "i2": ("h", 2), "u2": ("H", 2), "i4": ("i", 4), "u4": ("I", 4), "i8": ("q", 8), "u8": ("Q", 8), "b1": ("B", 1)}
def read_npy(path: Path) -> tuple[str, list[float]]: """A NumPy .npy file (format 1.0/2.0, C order) as (dtype, flat values), with the standard library only.""" b = path.read_bytes() if b[:6] != b"\x93NUMPY": raise Fail(f"{path.name} is not a .npy file") hl, off = (struct.unpack("<H", b[8:10])[0], 10) if b[6] == 1 else (struct.unpack("<I", b[8:12])[0], 12) head = ast.literal_eval(b[off:off + hl].decode("latin1")) descr, data = head["descr"], b[off + hl:] if head.get("fortran_order"): raise Fail(f"{path.name}: Fortran order is not supported") kind = descr.lstrip("<>|=") if kind == "f2": n = len(data) // 2 return kind, list(struct.unpack(("<" if descr[0] != ">" else ">") + "e" * n, data[:2 * n])) if kind not in NPY: raise Fail(f"{path.name}: dtype {descr} is not supported here") code, size = NPY[kind] a = array(code) if a.itemsize != size: raise Fail(f"{path.name}: this Python has no {size}-byte {code} type") a.frombytes(data[: len(data) // size * size]) if (descr[0] == ">") != (sys.byteorder == "big") and size > 1: a.byteswap() return kind, list(a)
def check(sess: Session, plan: dict, args: argparse.Namespace) -> bool: c = plan.get("check") or {} cases, rules, mt = c.get("cases") or [], c.get("rules") or {}, plan["model_type"] if not cases: print("no public cases to check outputs against") return True print(f"{len(cases)} public case{'s' * (len(cases) != 1)}: {c.get('what', 'expected outputs')}") ok, rows = True, [] tot = {"edits": 0, "words": 0, "matched": 0, "ref": 0, "ours": 0, "prefix": [], "tok": 0} for case in cases: base = HERE / case["dir"] req: dict = {"mode": "generate"} for k in ("input", "image"): if case.get(k): req[k] = sess.stage(base / case[k]) if mt == "vision_detection": req["images"] = [req.pop("input")] exp_path = base / case["expected"] if case.get("expected") else None exp = json.loads(exp_path.read_text()) if exp_path and exp_path.suffix == ".json" else None if mt in TOKEN_TYPES: req["max_new_tokens"] = max(1, len(exp["tokens"])) if mt in ("text_to_speech", "audio_generation"): req["seed"] = case.get("seed", 0) if mt == "audio_generation": req["seconds"] = case.get("seconds", 10) r = sess.run(req, repeat=1, fetch_out=True, timeout=args.timeout) if r["exit"] != 0 or not r["out"]: ok = False rows.append([case["id"], "run failed", (r.get("log") or "")[-120:].replace("\n", " ")]) continue if mt in TOKEN_TYPES: got = json.loads(Path(r["out"]).read_text()) same_prompt = got.get("prompt_tokens") == exp["prompt_tokens"] n = 0 for a, b in zip(got.get("tokens") or [], exp["tokens"]): if a != b: break n += 1 frac = n / max(1, len(exp["tokens"])) tot["prefix"].append(frac) tot["tok"] += same_prompt rows.append([case["id"], "prompt tokens " + ("match" if same_prompt else "DIFFER"), f"{n}/{len(exp['tokens'])} new tokens identical before the first difference"]) elif mt == "speech_to_text": got = json.loads(Path(r["out"]).read_text()).get("text", "") e = edits(words(got), words(exp["text"])) tot["edits"] += e tot["words"] += len(words(exp["text"])) rows.append([case["id"], f"{e} word edit{'s' * (e != 1)}", got[:60]]) elif mt == "text_to_speech": mine, ref = wav_seconds(Path(r["out"])), float(case["expected_seconds"]) within = abs(mine / ref - 1) <= float(rules.get("duration_ratio_tolerance", 0.05)) ok &= within rows.append([case["id"], f"{mine:.2f} s of audio (expected {ref:.2f} s)", "ok" if within else "DIFFERS"]) elif mt == "vision_detection": got = json.loads(Path(r["out"]).read_text()) thr, margin, need = float(rules.get("score_threshold", 0.3)), float(rules.get("score_margin", 0.05)), float( rules.get("iou_match", 0.5)) ref = [(b, cl) for b, s, cl in zip(exp["boxes"], exp["scores"], exp["classes"]) if s >= thr] ours = [(b, cl) for b, s, cl in zip(got.get("boxes", []), got.get("scores", []), got.get("classes", [])) if s >= thr - margin] used, m = set(), 0 for b, cl in ref: best = max(((iou(b, ob), j) for j, (ob, oc) in enumerate(ours) if oc == cl and j not in used), default=(0.0, -1)) if best[0] >= need: used.add(best[1]) m += 1 tot["matched"] += m tot["ref"] += len(ref) tot["ours"] += len([1 for b, s in zip(got.get("boxes", []), got.get("scores", [])) if s >= thr]) rows.append([case["id"], f"{m}/{len(ref)} expected objects found", f"{len(ours)} detected"]) elif mt == "kernel": bad, total, worst = 0, 0, 0.0 for t in case["outputs"]: pulled = Path(r["out"]) / f"{t['name']}.npy" if not pulled.is_file(): ok = False rows.append([case["id"], f"no {t['name']}.npy written", ""]) continue kind, mine = read_npy(pulled) _, ref = read_npy(base / t["expected"]) if len(mine) != len(ref): ok = False rows.append([case["id"], f"{t['name']}: {len(mine)} values, expected {len(ref)}", ""]) continue if kind.startswith("f"): rt, at = (float(rules.get("fp16_rtol", 1e-2)), float(rules.get("fp16_atol_scale", 1e-2))) \ if kind == "f2" or t.get("dtype") == "float16" else \ (float(rules.get("fp32_rtol", 1e-4)), float(rules.get("fp32_atol_scale", 1e-4))) rms = math.sqrt(sum(x * x for x in ref) / len(ref)) if ref else 0.0 for a, b in zip(mine, ref): d = abs(a - b) worst = max(worst, d) bad += not (d <= at * rms + rt * abs(b)) else: lim = float(rules.get("int8_max_abs_diff", 1) if kind in ("i1", "u1") else rules.get("int_max_abs_diff", 0)) for a, b in zip(mine, ref): worst = max(worst, abs(a - b)) bad += abs(a - b) > lim total += len(ref) frac = bad / total if total else 0.0 within = frac <= float(rules.get("max_mismatch_frac", 0.0)) ok &= within rows.append([case["id"], f"{bad} of {total} values outside tolerance", f"largest difference {worst:.3g}"]) else: # audio_generation: free-running audio is random; length and level are what can be checked dur, rms = wav_seconds(Path(r["out"])), wav_rms(Path(r["out"])) want = float(case.get("seconds", 10)) within = abs(dur - want) <= 0.05 * want + 0.1 and (math.isnan(rms) or rms >= float(rules.get("free_run_min_rms", 0.001))) ok &= within rows.append([case["id"], f"{dur:.2f} s of audio, RMS {rms:.3g}", "ok" if within else "DIFFERS"]) print(table(["case", "result", ""], rows)) if mt in TOKEN_TYPES and tot["prefix"]: mean, need = statistics.mean(tot["prefix"]), float(rules.get("greedy_prefix_min", 0.75)) tok_ok = tot["tok"] == len(tot["prefix"]) ok &= tok_ok and mean >= need print(f"prompt tokens identical on {tot['tok']}/{len(tot['prefix'])} cases (needed: all); greedy prefix " f"{mean:.2f} (needed: {need:g} or more)") if mt == "speech_to_text" and tot["words"]: wer, need = tot["edits"] / tot["words"], float(rules.get("wer_vs_reference_max", 0.02)) ok &= wer <= need print(f"word error rate against the expected transcripts {wer:.3f} (needed: {need:g} or less)") if mt == "vision_detection" and tot["ref"]: rec, prec = tot["matched"] / tot["ref"], tot["matched"] / max(1, tot["ours"]) need_r, need_p = float(rules.get("recall_min", 0.97)), float(rules.get("precision_min", 0.97)) ok &= rec >= need_r and prec >= need_p print(f"recall {rec:.3f} (needed {need_r:g}), precision {prec:.3f} (needed {need_p:g})") print("outputs: " + ("REPRODUCED" if ok else "NOT reproduced")) return ok
def _ok(r: dict, what: str) -> None: if r["exit"] != 0: raise Fail(f"{what} failed (exit {r['exit']}): {(r.get('log') or '').strip()[-800:]}\ncommand: {r['command']}")
# ---------------------------------------------------------------- main
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description="Reproduce nnopt's numbers on your own device (REPRO.md).") ap.add_argument("--plan", default=str(HERE / "plan.json")) ap.add_argument("--serial", help="the phone's serial (adb devices); default $ANDROID_SERIAL") ap.add_argument("--ssh", help="USER@HOST of a Jetson or Mac; default $SSH_TARGET") ap.add_argument("--local", action="store_true", help="the program runs on this machine") ap.add_argument("--dir", help="where deploy.sh installed the program on the device") ap.add_argument("--deploy", action="store_true", help="run bash deploy.sh DIR first") ap.add_argument("--check", action="store_true", help="check the outputs on the public cases instead of the speed") ap.add_argument("--warmup", type=int) ap.add_argument("--runs", type=int) ap.add_argument("--sustained", type=float, default=0.0, help="seconds of back-to-back runs after the timed runs") ap.add_argument("--timeout", type=float, default=3600.0, help="seconds per run") ap.add_argument("--json", help="also write the results to this file") a = ap.parse_args(argv) if not Path(a.plan).is_file(): # measured on several phones: each has its own plan (repro/<phone>/plan.json) mine = sorted(p.parent.name for p in HERE.glob("*/plan.json")) print(f"error: no {a.plan}" + (f"; nnopt measured this on several phones: pass --plan repro/<phone>/plan.json " f"for yours, <phone> one of: {', '.join(mine)}" if mine else ""), file=sys.stderr) return 2 plan = json.loads(Path(a.plan).read_text()) kind = "local" if a.local else "ssh" if a.ssh else "adb" if a.serial else plan.get("connection", "adb") serial = a.serial or (os.environ.get("ANDROID_SERIAL") if kind == "adb" else None) target = a.ssh or (os.environ.get("SSH_TARGET") if kind == "ssh" else None) folder = a.dir or plan["device_dir"] try: dev = Device(kind, serial=serial, target=target) if a.deploy: print(f"deploy: bash deploy.sh {folder}") env = {**os.environ, "NNOPT_PORT_DIR": folder, **({"ANDROID_SERIAL": serial} if serial else {})} if subprocess.run(["bash", "deploy.sh", folder], cwd=ROOT, env=env).returncode != 0: raise Fail("deploy.sh failed") print(f"{plan.get('title', 'nnopt reproduction')} · {dev.describe()} · {folder}") with tempfile.TemporaryDirectory(prefix="nnopt-repro-") as tmp: sess = Session(dev, folder, plan["model_type"], Path(tmp)) try: if a.check: ok = check(sess, plan, a) result = {"check": ok} elif (mine := speed(sess, plan, a)) is None: ok, result = True, {"speed": None} else: rows, ok = compare(plan, mine) print() print(table(["metric", "yours", "nnopt", "diff", "within"], rows)) if mine["graded"].get("peak_mem_mb"): print(f"peak memory (process tree RSS): {fmt(mine['graded']['peak_mem_mb'])} MB") result = {"speed": mine, "compared": rows, "within": ok} if a.sustained > 0: result["sustained"] = s = sustained(sess, plan, a.sustained, a) if s.get("ratio"): print(f"sustained: last minute / first minute = {s['ratio']:.2f}") print("speed: " + ("REPRODUCED" if ok else "NOT reproduced (see REPRO.md, Expected results)")) finally: sess.close() out = Path(a.json) if a.json else HERE / "results" / time.strftime("run-%Y%m%d-%H%M%S.json") out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(result, indent=1, default=str) + "\n") print(f"results: {out}") return 0 if ok else 1 except Fail as e: print(f"error: {e}", file=sys.stderr) return 2
if __name__ == "__main__": sys.exit(main())123version https://git-lfs.github.com/spec/v1oid sha256:9560806c6ebef457554c2ef6924ec2e833a6d29a8684fb5883f05d4acabbcd85size 15728768123version https://git-lfs.github.com/spec/v1oid sha256:c2a77ead969fe3b28d9310112ff6b6ae3c133ab571b78065283a18a080fd2137size 524416123version https://git-lfs.github.com/spec/v1oid sha256:d4bc73b0afd77afeabea56b8f0b2877cb2a5aad11423c4ce7604c12417d99aa9size 192123version https://git-lfs.github.com/spec/v1oid sha256:f4ae3c6d214471a218324d43af536acfd499898d4120967cf343402080b8b6ecsize 132123version https://git-lfs.github.com/spec/v1oid sha256:4f2c0ae257bb0a8e8bdc09414d22e4a9d3f280d1b1408c79ebd60fef0a721a78size 5244161234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768{ "format": "nnopt-repro", "version": 1, "title": "prism-ml/bonsai-image-ternary-4B-unpacked on Samsung Galaxy S26+", "kind": "port", "model_type": "kernel", "mode": "compute", "connection": "adb", "device_dir": "/data/local/tmp/nnopt/port", "settings": { "warmup": 2, "runs": 5, "repeat": 3, "rest_s": 3.0, "sustained_repeat": 10 }, "inputs": { "input": "inputs/tensors" }, "external_check": true, "compare": [ { "key": "latency_ms", "label": "Time per request", "unit": "ms", "nnopt": 35180.9, "p10": 32838.7, "p90": 38323.2, "tolerance_pct": 10 } ], "check": { "cases": [ { "id": "p000", "dir": "expected/p000", "input": "inputs", "outputs": [ { "name": "image", "dtype": "float16", "expected": "expected/image.npy" }, { "name": "noise_pred", "dtype": "float16", "expected": "expected/noise_pred.npy" }, { "name": "prompt_embeds", "dtype": "float16", "expected": "expected/prompt_embeds.npy" } ] } ], "rules": { "fp32_rtol": 0.0001, "fp32_atol_scale": 0.0001, "fp16_rtol": 0.01, "fp16_atol_scale": 0.01, "int8_max_abs_diff": 1, "int_max_abs_diff": 0, "max_mismatch_frac": 0.0 }, "what": "the reference outputs of your reference code" }}123456# Entry point on the phone: sh ./run.sh --inputs IN_DIR [--repeat R] --out OUT_DIR --metrics M.jsoncd "$(dirname "$0")"export LD_LIBRARY_PATH=/vendor/lib64:${LD_LIBRARY_PATH:-}CACHE=/data/local/tmp/nnopt/bonsai_image_cachemkdir -p "$CACHE" 2>/dev/null || CACHE=${TMPDIR:-/data/local/tmp}/bonsai_image_cacheexec ./bin/bonsai_image --weights /data/local/tmp/nnopt/bonsai_image_weights --cache "$CACHE" "$@"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970// Resolves the OpenCL API from the vendor libOpenCL.so at run time (no ICD loader needed at build time).#define CL_TARGET_OPENCL_VERSION 300#include <CL/cl.h>#include <dlfcn.h>#include <cstdio>#include <cstdlib>
static void* cl_lib() { static void* h = nullptr; if (!h) { const char* names[] = {"libOpenCL.so", "/vendor/lib64/libOpenCL.so", "/system/vendor/lib64/libOpenCL.so", "libOpenCL_adreno.so", "/vendor/lib64/libOpenCL_adreno.so"}; for (const char* n : names) { h = dlopen(n, RTLD_NOW | RTLD_LOCAL); if (h) break; } if (!h) { fprintf(stderr, "cannot dlopen libOpenCL.so: %s\n", dlerror()); exit(3); } } return h;}static void* cl_sym(const char* name) { void* p = dlsym(cl_lib(), name); if (!p) { fprintf(stderr, "OpenCL symbol missing: %s\n", name); exit(3); } return p;}
#define FWD(ret, name, params, args) \ extern "C" ret CL_API_CALL name params { \ typedef ret(CL_API_CALL * fn_t) params; \ static fn_t fn = (fn_t)cl_sym(#name); \ return fn args; \ }
FWD(cl_int, clGetPlatformIDs, (cl_uint a, cl_platform_id* b, cl_uint* c), (a, b, c))FWD(cl_int, clGetDeviceIDs, (cl_platform_id a, cl_device_type b, cl_uint c, cl_device_id* d, cl_uint* e), (a, b, c, d, e))FWD(cl_int, clGetDeviceInfo, (cl_device_id a, cl_device_info b, size_t c, void* d, size_t* e), (a, b, c, d, e))FWD(cl_context, clCreateContext, (const cl_context_properties* a, cl_uint b, const cl_device_id* c, void(CL_CALLBACK* d)(const char*, const void*, size_t, void*), void* e, cl_int* f), (a, b, c, d, e, f))FWD(cl_command_queue, clCreateCommandQueueWithProperties, (cl_context a, cl_device_id b, const cl_queue_properties* c, cl_int* d), (a, b, c, d))FWD(cl_mem, clCreateBuffer, (cl_context a, cl_mem_flags b, size_t c, void* d, cl_int* e), (a, b, c, d, e))FWD(cl_int, clReleaseMemObject, (cl_mem a), (a))FWD(cl_program, clCreateProgramWithSource, (cl_context a, cl_uint b, const char** c, const size_t* d, cl_int* e), (a, b, c, d, e))FWD(cl_program, clCreateProgramWithBinary, (cl_context a, cl_uint b, const cl_device_id* c, const size_t* d, const unsigned char** e, cl_int* f, cl_int* g), (a, b, c, d, e, f, g))FWD(cl_int, clBuildProgram, (cl_program a, cl_uint b, const cl_device_id* c, const char* d, void(CL_CALLBACK* e)(cl_program, void*), void* f), (a, b, c, d, e, f))FWD(cl_int, clGetProgramBuildInfo, (cl_program a, cl_device_id b, cl_program_build_info c, size_t d, void* e, size_t* f), (a, b, c, d, e, f))FWD(cl_int, clGetProgramInfo, (cl_program a, cl_program_info b, size_t c, void* d, size_t* e), (a, b, c, d, e))FWD(cl_kernel, clCreateKernel, (cl_program a, const char* b, cl_int* c), (a, b, c))FWD(cl_int, clSetKernelArg, (cl_kernel a, cl_uint b, size_t c, const void* d), (a, b, c, d))FWD(cl_int, clGetKernelWorkGroupInfo, (cl_kernel a, cl_device_id b, cl_kernel_work_group_info c, size_t d, void* e, size_t* f), (a, b, c, d, e, f))FWD(cl_int, clEnqueueNDRangeKernel, (cl_command_queue a, cl_kernel b, cl_uint c, const size_t* d, const size_t* e, const size_t* f, cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))FWD(cl_int, clEnqueueWriteBuffer, (cl_command_queue a, cl_mem b, cl_bool c, size_t d, size_t e, const void* f, cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))FWD(cl_int, clEnqueueReadBuffer, (cl_command_queue a, cl_mem b, cl_bool c, size_t d, size_t e, void* f, cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))FWD(cl_int, clEnqueueCopyBuffer, (cl_command_queue a, cl_mem b, cl_mem c, size_t d, size_t e, size_t f, cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))FWD(void*, clEnqueueMapBuffer, (cl_command_queue a, cl_mem b, cl_bool c, cl_map_flags d, size_t e, size_t f, cl_uint g, const cl_event* h, cl_event* i, cl_int* j), (a, b, c, d, e, f, g, h, i, j))FWD(cl_int, clEnqueueUnmapMemObject, (cl_command_queue a, cl_mem b, void* c, cl_uint d, const cl_event* e, cl_event* f), (a, b, c, d, e, f))FWD(cl_mem, clCreateImage, (cl_context a, cl_mem_flags b, const cl_image_format* c, const cl_image_desc* d, void* e, cl_int* f), (a, b, c, d, e, f))FWD(cl_int, clFinish, (cl_command_queue a), (a))FWD(cl_int, clFlush, (cl_command_queue a), (a))FWD(cl_int, clWaitForEvents, (cl_uint a, const cl_event* b), (a, b))FWD(cl_int, clGetEventProfilingInfo, (cl_event a, cl_profiling_info b, size_t c, void* d, size_t* e), (a, b, c, d, e))FWD(cl_int, clReleaseEvent, (cl_event a), (a))FWD(cl_int, clReleaseKernel, (cl_kernel a), (a))FWD(cl_int, clReleaseProgram, (cl_program a), (a))FWD(cl_int, clReleaseCommandQueue, (cl_command_queue a), (a))FWD(cl_int, clReleaseContext, (cl_context a), (a))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157#include "clrt.h"#include <time.h>#include <sys/stat.h>#include <fstream>#include <sstream>#include <algorithm>
double now_ms() { timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec * 1e-6;}
static std::string read_file(const std::string& p) { std::ifstream f(p, std::ios::binary); if (!f) { fprintf(stderr, "cannot read %s\n", p.c_str()); exit(2); } std::stringstream ss; ss << f.rdbuf(); return ss.str();}
static uint64_t fnv1a(const std::string& s, uint64_t h = 1469598103934665603ULL) { for (unsigned char c : s) { h ^= c; h *= 1099511628211ULL; } return h;}
void ClRt::init(const std::string& kdir, const std::string& cdir) { kernel_dir = kdir; cache_dir = cdir; cl_uint np = 0; CLCHK(clGetPlatformIDs(1, &plat, &np)); CLCHK(clGetDeviceIDs(plat, CL_DEVICE_TYPE_GPU, 1, &dev, nullptr)); char buf[512]; CLCHK(clGetDeviceInfo(dev, CL_DEVICE_NAME, sizeof buf, buf, nullptr)); dev_name = buf; CLCHK(clGetDeviceInfo(dev, CL_DRIVER_VERSION, sizeof buf, buf, nullptr)); drv_ver = buf; cl_ulong ma = 0; CLCHK(clGetDeviceInfo(dev, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof ma, &ma, nullptr)); max_alloc = ma; cl_int e; ctx = clCreateContext(nullptr, 1, &dev, nullptr, nullptr, &e); CLCHK(e); profile = getenv("NNOPT_PROFILE") != nullptr; sync_each = getenv("NNOPT_SYNC") != nullptr; cl_queue_properties props[] = {CL_QUEUE_PROPERTIES, profile ? (cl_queue_properties)CL_QUEUE_PROFILING_ENABLE : 0, 0}; q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e); qup = clCreateCommandQueueWithProperties(ctx, dev, nullptr, &e); CLCHK(e); fprintf(stderr, "[cl] %s | %s | max_alloc %zu MB\n", dev_name.c_str(), drv_ver.c_str(), max_alloc >> 20); mkdir(cache_dir.c_str(), 0755);}
cl_program ClRt::build(const std::string& file, const std::string& opts) { std::string src = read_file(kernel_dir + "/" + file); uint64_t h = fnv1a(src); h = fnv1a(opts, h); h = fnv1a(dev_name, h); h = fnv1a(drv_ver, h); char name[64]; snprintf(name, sizeof name, "/%016llx.bin", (unsigned long long)h); std::string cpath = cache_dir + name; cl_int e, be; cl_program p = nullptr; { std::ifstream f(cpath, std::ios::binary); if (f) { std::stringstream ss; ss << f.rdbuf(); std::string bin = ss.str(); size_t len = bin.size(); const unsigned char* bp = (const unsigned char*)bin.data(); p = clCreateProgramWithBinary(ctx, 1, &dev, &len, &bp, &be, &e); if (e != CL_SUCCESS || be != CL_SUCCESS || clBuildProgram(p, 1, &dev, opts.c_str(), nullptr, nullptr) != CL_SUCCESS) { if (p) clReleaseProgram(p); p = nullptr; } } } if (p) return p; double t0 = now_ms(); const char* s = src.c_str(); size_t sl = src.size(); p = clCreateProgramWithSource(ctx, 1, &s, &sl, &e); CLCHK(e); e = clBuildProgram(p, 1, &dev, opts.c_str(), nullptr, nullptr); if (e != CL_SUCCESS) { size_t ll = 0; clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &ll); std::string log(ll, 0); clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, ll, &log[0], nullptr); fprintf(stderr, "build of %s [%s] failed (%d):\n%s\n", file.c_str(), opts.c_str(), e, log.c_str()); exit(5); } size_t bl = 0; CLCHK(clGetProgramInfo(p, CL_PROGRAM_BINARY_SIZES, sizeof bl, &bl, nullptr)); std::vector<unsigned char> bin(bl); unsigned char* bp = bin.data(); CLCHK(clGetProgramInfo(p, CL_PROGRAM_BINARIES, sizeof bp, &bp, nullptr)); std::string tmp = cpath + ".tmp"; { std::ofstream f(tmp, std::ios::binary); f.write((const char*)bin.data(), bl); } rename(tmp.c_str(), cpath.c_str()); fprintf(stderr, "[cl] built %s [%s] in %.0f ms\n", file.c_str(), opts.c_str(), now_ms() - t0); return p;}
cl_kernel ClRt::kernel(cl_program p, const char* name) { cl_int e; cl_kernel k = clCreateKernel(p, name, &e); if (e != CL_SUCCESS) { fprintf(stderr, "clCreateKernel %s failed %d\n", name, e); exit(5); } if (getenv("NNOPT_KINFO")) { cl_ulong pm = 0; size_t wg = 0; clGetKernelWorkGroupInfo(k, dev, CL_KERNEL_PRIVATE_MEM_SIZE, sizeof pm, &pm, nullptr); clGetKernelWorkGroupInfo(k, dev, CL_KERNEL_WORK_GROUP_SIZE, sizeof wg, &wg, nullptr); fprintf(stderr, "[kinfo] %s private %llu B, max wg %zu\n", name, (unsigned long long)pm, wg); } return k;}
cl_mem ClRt::buf(size_t bytes, cl_mem_flags flags) { if (bytes == 0) bytes = 16; if (bytes > max_alloc) { fprintf(stderr, "buffer of %zu bytes exceeds max alloc %zu\n", bytes, max_alloc); exit(4); } cl_int e; cl_mem m = clCreateBuffer(ctx, flags, bytes, nullptr, &e); if (e != CL_SUCCESS) { fprintf(stderr, "clCreateBuffer(%zu) failed %d (allocated so far %zu MB)\n", bytes, e, bytes_alloc >> 20); exit(4); } bytes_alloc += bytes; return m;}void ClRt::release(cl_mem m) { if (m) clReleaseMemObject(m); }
void ClRt::write(cl_mem m, const void* src, size_t bytes, size_t off, bool blocking) { CLCHK(clEnqueueWriteBuffer(q, m, blocking ? CL_TRUE : CL_FALSE, off, bytes, src, 0, nullptr, nullptr));}void ClRt::upload(cl_mem m, const void* src, size_t bytes) { CLCHK(clEnqueueWriteBuffer(qup, m, CL_TRUE, 0, bytes, src, 0, nullptr, nullptr));}void ClRt::read(cl_mem m, void* dst, size_t bytes, size_t off) { CLCHK(clEnqueueReadBuffer(q, m, CL_TRUE, off, bytes, dst, 0, nullptr, nullptr));}
void ClRt::launch(cl_kernel k, const char* name, int dims, const size_t* gws, const size_t* lws, double flops) { cl_event ev = nullptr; cl_int e = clEnqueueNDRangeKernel(q, k, dims, nullptr, gws, lws, 0, nullptr, profile ? &ev : nullptr); if (e != CL_SUCCESS) { fprintf(stderr, "launch %s failed %d (gws %zu,%zu,%zu lws %zu,%zu,%zu)\n", name, e, gws[0], dims > 1 ? gws[1] : 1, dims > 2 ? gws[2] : 1, lws ? lws[0] : 0, lws && dims > 1 ? lws[1] : 0, lws && dims > 2 ? lws[2] : 0); exit(4); } if (profile) { pending.push_back({name, ev}); prof[name].flops += flops; if (pending.size() > 2000) flush_prof(); } if (sync_each) { e = clFinish(q); if (e != CL_SUCCESS) { fprintf(stderr, "kernel %s failed at finish: %d\n", name, e); exit(4); } }}
void ClRt::flush_prof() { if (pending.empty()) return; clFinish(q); for (auto& pe : pending) { cl_ulong s = 0, en = 0; clGetEventProfilingInfo(pe.second, CL_PROFILING_COMMAND_START, sizeof s, &s, nullptr); clGetEventProfilingInfo(pe.second, CL_PROFILING_COMMAND_END, sizeof en, &en, nullptr); auto& p = prof[pe.first]; p.ms += (en - s) * 1e-6; p.calls++; clReleaseEvent(pe.second); } pending.clear();}
void ClRt::print_prof() { if (!profile) return; flush_prof(); std::vector<std::pair<std::string, Prof>> v(prof.begin(), prof.end()); std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second.ms > b.second.ms; }); double tot = 0; for (auto& x : v) tot += x.second.ms; fprintf(stderr, "%-28s %7s %10s %9s %6s %8s\n", "kernel", "calls", "total_ms", "mean_us", "share", "GFLOP/s"); for (auto& x : v) fprintf(stderr, "%-28s %7d %10.2f %9.1f %5.1f%% %8.1f\n", x.first.c_str(), x.second.calls, x.second.ms, 1e3 * x.second.ms / std::max(1, x.second.calls), 100 * x.second.ms / tot, x.second.ms > 0 ? x.second.flops / (x.second.ms * 1e6) : 0); fprintf(stderr, "total kernel time %.1f ms\n", tot); prof.clear();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// Minimal OpenCL runtime helpers: context/queue, program build with a binary cache, buffers, launches.#pragma once#define CL_TARGET_OPENCL_VERSION 300#include <CL/cl.h>#include <cstdio>#include <cstdlib>#include <cstdint>#include <string>#include <vector>#include <map>
#define CLCHK(x) do { cl_int _e = (x); if (_e != CL_SUCCESS) { fprintf(stderr, "OpenCL error %d at %s:%d: %s\n", _e, __FILE__, __LINE__, #x); exit(4); } } while (0)
double now_ms();
struct ClRt { cl_platform_id plat = nullptr; cl_device_id dev = nullptr; cl_context ctx = nullptr; cl_command_queue q = nullptr; cl_command_queue qup = nullptr; // second queue: weight uploads that overlap the kernels on q std::string dev_name, drv_ver, cache_dir, kernel_dir; size_t max_alloc = 0; bool profile = false; bool sync_each = false; // debugging: clFinish after every launch struct Prof { double ms = 0; int calls = 0; double flops = 0; }; std::map<std::string, Prof> prof; std::vector<std::pair<std::string, cl_event>> pending; std::vector<cl_mem> owned; size_t bytes_alloc = 0;
void init(const std::string& kernel_dir, const std::string& cache_dir); cl_program build(const std::string& file, const std::string& opts); cl_kernel kernel(cl_program p, const char* name); cl_mem buf(size_t bytes, cl_mem_flags flags = CL_MEM_READ_WRITE); void release(cl_mem m); void write(cl_mem m, const void* src, size_t bytes, size_t off = 0, bool blocking = true); void read(cl_mem m, void* dst, size_t bytes, size_t off = 0); // blocking write on the upload queue; the caller makes sure no kernel still uses m void upload(cl_mem m, const void* src, size_t bytes); void finish() { CLCHK(clFinish(q)); } void launch(cl_kernel k, const char* name, int dims, const size_t* gws, const size_t* lws, double flops = 0); void flush_prof(); void print_prof();};
// set kernel args from a parameter packinline void set_args_i(cl_kernel, int) {}template <typename T, typename... R>inline void set_args_i(cl_kernel k, int i, const T& a, const R&... r) { CLCHK(clSetKernelArg(k, i, sizeof(T), &a)); set_args_i(k, i + 1, r...);}template <typename... A>inline void set_args(cl_kernel k, const A&... a) { set_args_i(k, 0, a...); }.gitattributes+19-32
LICENSEAdded+177
NOTICEAdded+15
README.mdAdded+94
config.jsonAdded+71
sm8850-gpu-ternary/README.mdAdded+117
sm8850-gpu-ternary/REPRO.mdAdded+181
sm8850-gpu-ternary/build.shAdded+73
sm8850-gpu-ternary/build/bin/bonsai_imageAdded+3
sm8850-gpu-ternary/build/bin/kernels/bench.clAdded+19
sm8850-gpu-ternary/build/bin/kernels/gemm.clAdded+323
sm8850-gpu-ternary/build/bin/kernels/ops.clAdded+259
sm8850-gpu-ternary/build/weights/.stampAdded+1
sm8850-gpu-ternary/build/weights/dit.binAdded+3
sm8850-gpu-ternary/build/weights/dit.idxAdded+229
sm8850-gpu-ternary/build/weights/te.binAdded+3
sm8850-gpu-ternary/build/weights/te.idxAdded+217
sm8850-gpu-ternary/build/weights/tokenizer.jsonAdded
sm8850-gpu-ternary/build/weights/vae.binAdded+3
sm8850-gpu-ternary/build/weights/vae.idxAdded+138
sm8850-gpu-ternary/demo/demo.jsonAdded+55
sm8850-gpu-ternary/demo/original0.pngAdded

Large File Pointer Details
- SHA256: 691b0eaac7a204687ccf4c135f37d20d71b2f3e0d1e1331d27c859e563662580
- Pointer size: 131 Bytes
- Size of remote file: 359 kB
sm8850-gpu-ternary/demo/original1.pngAdded

Large File Pointer Details
- SHA256: 9172d66f3c784d9adf757986e6e6b369801f34510e8d9ff584a5845eeb06f8a4
- Pointer size: 131 Bytes
- Size of remote file: 449 kB
sm8850-gpu-ternary/demo/original2.pngAdded

Large File Pointer Details
- SHA256: 5091faebb4301430f75ba259a857d892cfd46f9db6b36bb6d52499f247f5c99d
- Pointer size: 131 Bytes
- Size of remote file: 553 kB
sm8850-gpu-ternary/demo/phone0.pngAdded

Large File Pointer Details
- SHA256: 4ce2181ec7735863b1ad56c993134fd0f22e26706d553f517029107333e72947
- Pointer size: 131 Bytes
- Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone0_metrics.jsonAdded+1
sm8850-gpu-ternary/demo/phone1.pngAdded

Large File Pointer Details
- SHA256: fdaa8ddf8957e2c0219a0dd126b9f26505f2561966152acafcc556a4b5bada62
- Pointer size: 131 Bytes
- Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone1_metrics.jsonAdded+1
sm8850-gpu-ternary/demo/phone2.pngAdded

Large File Pointer Details
- SHA256: 8239278e8347e0e4e3c2bb6e8d7abce2f4871150b4ed9a52295b13b3388b6ec4
- Pointer size: 131 Bytes
- Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone2_metrics.jsonAdded+1
sm8850-gpu-ternary/deploy.shAdded+22
sm8850-gpu-ternary/fetch.shAdded+27
sm8850-gpu-ternary/paths.shAdded+11
sm8850-gpu-ternary/port.jsonAdded+7
sm8850-gpu-ternary/report.htmlAdded+112
sm8850-gpu-ternary/report/reproduce.shAdded+11
sm8850-gpu-ternary/report/results.csvAdded+53
sm8850-gpu-ternary/report/results.jsonAdded+1330
sm8850-gpu-ternary/repro/DockerfileAdded+8
sm8850-gpu-ternary/repro/bench.pyAdded+729
sm8850-gpu-ternary/repro/inputs/tensors/encoder_hidden_states.npyAdded+3
sm8850-gpu-ternary/repro/inputs/tensors/latents.npyAdded+3
sm8850-gpu-ternary/repro/inputs/tensors/prompt_ids.npyAdded+3
sm8850-gpu-ternary/repro/inputs/tensors/timestep.npyAdded+3
sm8850-gpu-ternary/repro/inputs/tensors/vae_latents.npyAdded+3
sm8850-gpu-ternary/repro/plan.jsonAdded+68
sm8850-gpu-ternary/run.shAdded+6
sm8850-gpu-ternary/src/cl_loader.cppAdded+70
sm8850-gpu-ternary/src/clrt.cppAdded+157
sm8850-gpu-ternary/src/clrt.hAdded+55