a8nova commited on
Commit
c1d5205
·
verified ·
1 Parent(s): aac7269

nnopt port: Bonsai-Image-Ternary-4B-OpenCL

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +19 -32
  2. LICENSE +177 -0
  3. NOTICE +15 -0
  4. README.md +94 -0
  5. config.json +71 -0
  6. sm8850-gpu-ternary/README.md +117 -0
  7. sm8850-gpu-ternary/REPRO.md +181 -0
  8. sm8850-gpu-ternary/build.sh +73 -0
  9. sm8850-gpu-ternary/build/bin/bonsai_image +3 -0
  10. sm8850-gpu-ternary/build/bin/kernels/bench.cl +19 -0
  11. sm8850-gpu-ternary/build/bin/kernels/gemm.cl +323 -0
  12. sm8850-gpu-ternary/build/bin/kernels/ops.cl +259 -0
  13. sm8850-gpu-ternary/build/weights/.stamp +1 -0
  14. sm8850-gpu-ternary/build/weights/dit.bin +3 -0
  15. sm8850-gpu-ternary/build/weights/dit.idx +229 -0
  16. sm8850-gpu-ternary/build/weights/te.bin +3 -0
  17. sm8850-gpu-ternary/build/weights/te.idx +217 -0
  18. sm8850-gpu-ternary/build/weights/tokenizer.json +0 -0
  19. sm8850-gpu-ternary/build/weights/vae.bin +3 -0
  20. sm8850-gpu-ternary/build/weights/vae.idx +138 -0
  21. sm8850-gpu-ternary/demo/demo.json +55 -0
  22. sm8850-gpu-ternary/demo/original0.png +3 -0
  23. sm8850-gpu-ternary/demo/original1.png +3 -0
  24. sm8850-gpu-ternary/demo/original2.png +3 -0
  25. sm8850-gpu-ternary/demo/phone0.png +3 -0
  26. sm8850-gpu-ternary/demo/phone0_metrics.json +1 -0
  27. sm8850-gpu-ternary/demo/phone1.png +3 -0
  28. sm8850-gpu-ternary/demo/phone1_metrics.json +1 -0
  29. sm8850-gpu-ternary/demo/phone2.png +3 -0
  30. sm8850-gpu-ternary/demo/phone2_metrics.json +1 -0
  31. sm8850-gpu-ternary/deploy.sh +22 -0
  32. sm8850-gpu-ternary/fetch.sh +27 -0
  33. sm8850-gpu-ternary/paths.sh +11 -0
  34. sm8850-gpu-ternary/port.json +7 -0
  35. sm8850-gpu-ternary/report.html +112 -0
  36. sm8850-gpu-ternary/report/reproduce.sh +11 -0
  37. sm8850-gpu-ternary/report/results.csv +53 -0
  38. sm8850-gpu-ternary/report/results.json +1330 -0
  39. sm8850-gpu-ternary/repro/Dockerfile +8 -0
  40. sm8850-gpu-ternary/repro/bench.py +729 -0
  41. sm8850-gpu-ternary/repro/inputs/tensors/encoder_hidden_states.npy +3 -0
  42. sm8850-gpu-ternary/repro/inputs/tensors/latents.npy +3 -0
  43. sm8850-gpu-ternary/repro/inputs/tensors/prompt_ids.npy +3 -0
  44. sm8850-gpu-ternary/repro/inputs/tensors/timestep.npy +3 -0
  45. sm8850-gpu-ternary/repro/inputs/tensors/vae_latents.npy +3 -0
  46. sm8850-gpu-ternary/repro/plan.json +68 -0
  47. sm8850-gpu-ternary/run.sh +6 -0
  48. sm8850-gpu-ternary/src/cl_loader.cpp +70 -0
  49. sm8850-gpu-ternary/src/clrt.cpp +157 -0
  50. sm8850-gpu-ternary/src/clrt.h +55 -0
.gitattributes CHANGED
@@ -1,35 +1,22 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
1
  *.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.tflite filter=lfs diff=lfs merge=lfs -text
3
+ *.gguf filter=lfs diff=lfs merge=lfs -text
4
+ *.onnx filter=lfs diff=lfs merge=lfs -text
5
+ *.npz filter=lfs diff=lfs merge=lfs -text
6
+ *.wav filter=lfs diff=lfs merge=lfs -text
7
+ *.so filter=lfs diff=lfs merge=lfs -text
8
+ *.bf16 filter=lfs diff=lfs merge=lfs -text
9
+ *.f16 filter=lfs diff=lfs merge=lfs -text
10
+ *.f32 filter=lfs diff=lfs merge=lfs -text
11
+ *.npy filter=lfs diff=lfs merge=lfs -text
12
+ *.tkb filter=lfs diff=lfs merge=lfs -text
13
+ *.tqb filter=lfs diff=lfs merge=lfs -text
14
+ *.png filter=lfs diff=lfs merge=lfs -text
15
+ *.jpg filter=lfs diff=lfs merge=lfs -text
16
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
17
+ *.pdf filter=lfs diff=lfs merge=lfs -text
18
  *.zip filter=lfs diff=lfs merge=lfs -text
19
+ *.gz filter=lfs diff=lfs merge=lfs -text
20
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
21
+ *.pt filter=lfs diff=lfs merge=lfs -text
22
+ sm8850-gpu-ternary/build/bin/bonsai_image filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
NOTICE ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This software is copyright 2026-present Prism ML, Inc. It is available under the Apache 2.0 license.
2
+ If you publicly deploy or redistribute this software, we would appreciate attribution such as: "Created using Bonsai Image by Prism ML."
3
+
4
+ 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
5
+
6
+ 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
7
+
8
+ ---
9
+
10
+ This repository is a modified version of prism-ml/bonsai-image-ternary-4B-unpacked by Prism ML, revision 30bbc032dd26939bff95c3d523477ad5065c3e1a.
11
+
12
+ Changes, made by nnopt (https://nnopt.dev):
13
+ - `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.
14
+
15
+ Created using Bonsai Image by Prism ML.
README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: prism-ml/bonsai-image-ternary-4B-unpacked
4
+ pipeline_tag: text-to-image
5
+ tags:
6
+ - on-device
7
+ - nnopt
8
+ - opencl
9
+ - android
10
+ - gpu
11
+ - adreno
12
+ - ternary
13
+ - text-to-image
14
+ - galaxy-s26-plus
15
+ ---
16
+
17
+ # bonsai-image-ternary-4B on Samsung Galaxy S26+ (OpenCL)
18
+
19
+ 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.
20
+
21
+ 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.
22
+
23
+ Created using Bonsai Image by Prism ML.
24
+
25
+ | | |
26
+ |---|---|
27
+ | Device | Samsung Galaxy S26+, Android 16 |
28
+ | Chip | Snapdragon 8 Elite Gen 5 (SM8850) |
29
+ | Processor | GPU (Adreno 840) |
30
+ | Runtime | hand-written C++ OpenCL runtime (no other engine) |
31
+ | Precision | fp32 activations and accumulation; DiT block linears ternary 2-bit + bf16 scale per 128 kept packed; text encoder, VAE and other weights bf16 |
32
+ | Modality | text -> image |
33
+ | 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) |
34
+ | nnopt job | NN-C9116E (port) |
35
+ | Folder | [`sm8850-gpu-ternary/`](https://huggingface.co/nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL/tree/main/sm8850-gpu-ternary) |
36
+
37
+ ## Verified results
38
+
39
+ 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.
40
+
41
+ - Passed. Matches the reference 2 of 2 cases
42
+ - Max abs error 0.062 (bar rtol 0.01, atol 0.01xrms)
43
+ - 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)
44
+ - Load time 1.13 s
45
+ - Peak memory 5,728 MB
46
+
47
+ ## Use it
48
+
49
+ ```
50
+ mkdir Bonsai-Image-Ternary-4B-OpenCL && cd Bonsai-Image-Ternary-4B-OpenCL
51
+ curl -fsSL https://huggingface.co/nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL/resolve/main/config.json -o config.json
52
+ hf download nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL --include "sm8850-gpu-ternary/*" --local-dir .
53
+ cd sm8850-gpu-ternary
54
+ bash fetch.sh
55
+ bash deploy.sh /data/local/tmp/nnopt/port # adb: program into DEST, weight packs into /data/local/tmp/nnopt/bonsai_image_weights
56
+ adb shell "cd /data/local/tmp/nnopt/port && sh ./run.sh --prompt 'A cat holding a sign that says hello world' \
57
+ --seed 0 --png /data/local/tmp/nnopt/cat.png --metrics /data/local/tmp/nnopt/cat.json"
58
+ adb pull /data/local/tmp/nnopt/cat.png
59
+ ```
60
+
61
+ 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.
62
+
63
+ Included weight files (verified on the phone):
64
+
65
+ | File | Size | sha256 |
66
+ |---|---|---|
67
+ | `sm8850-gpu-ternary/build/weights/te.bin` | 6,228,466,688 bytes | `b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4` |
68
+ | `sm8850-gpu-ternary/build/weights/dit.bin` | 1,367,734,272 bytes | `f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1` |
69
+ | `sm8850-gpu-ternary/build/weights/vae.bin` | 99,317,260 bytes | `54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5` |
70
+ | `sm8850-gpu-ternary/build/weights/te.idx` | 6,414 bytes | `eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b` |
71
+ | `sm8850-gpu-ternary/build/weights/dit.idx` | 7,614 bytes | `4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a` |
72
+ | `sm8850-gpu-ternary/build/weights/vae.idx` | 4,104 bytes | `d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07` |
73
+ | `sm8850-gpu-ternary/build/weights/tokenizer.json` | 4,561,647 bytes | `58e0ac44f0a640c2b4a1cfbea927ef695fd0c2b4d2e0e614e6a3e33684e89069` |
74
+
75
+ Optional: rebuild from the original weights instead.
76
+
77
+ ```
78
+ hf download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/weights
79
+ rm -f build/weights/.stamp && INPUTS_DIR="$PWD/inputs" bash build.sh # NDK r27d + numpy into .deps/, rebuilds the program and build/weights/
80
+ ```
81
+
82
+ 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).
83
+
84
+ `README.md` in the folder has every flag, the requirements and the known limits; `REPRO.md` (where present) reproduces the measurements.
85
+
86
+ ## License
87
+
88
+ Apache 2.0, like prism-ml/bonsai-image-ternary-4B-unpacked: see LICENSE and NOTICE.
89
+
90
+ ## Made with nnopt
91
+
92
+ [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.
93
+
94
+ Want your model on your device? Start a job at [nnopt.dev](https://nnopt.dev).
config.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nnopt_manifest": 1,
3
+ "repo": "nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL",
4
+ "model": {
5
+ "name": "bonsai-image-ternary-4B",
6
+ "source_repo": "prism-ml/bonsai-image-ternary-4B-unpacked",
7
+ "source_revision": "30bbc032dd26939bff95c3d523477ad5065c3e1a",
8
+ "authors": "Prism ML",
9
+ "license": "apache-2.0"
10
+ },
11
+ "variants": [
12
+ {
13
+ "id": "sm8850-gpu-ternary",
14
+ "device": "Samsung Galaxy S26+",
15
+ "chip": "Snapdragon 8 Elite Gen 5 (SM8850)",
16
+ "os": "Android 16",
17
+ "processor": "GPU (Adreno 840)",
18
+ "runtime": "hand-written C++ OpenCL runtime (no other engine)",
19
+ "runtime_version": "OpenCL 3.0",
20
+ "precision": "fp32 activations and accumulation; DiT block linears ternary 2-bit + bf16 scale per 128 kept packed; text encoder, VAE and other weights bf16",
21
+ "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)",
22
+ "nnopt_job": "NN-C9116E",
23
+ "job_kind": "port",
24
+ "verified": {
25
+ "verdict": "Passed. Matches the reference 2 of 2 cases; Max abs error 0.062 (bar rtol 0.01, atol 0.01xrms)",
26
+ "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"
27
+ },
28
+ "weight_files": [
29
+ {
30
+ "path": "sm8850-gpu-ternary/build/weights/te.bin",
31
+ "size": 6228466688,
32
+ "sha256": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4"
33
+ },
34
+ {
35
+ "path": "sm8850-gpu-ternary/build/weights/dit.bin",
36
+ "size": 1367734272,
37
+ "sha256": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1"
38
+ },
39
+ {
40
+ "path": "sm8850-gpu-ternary/build/weights/vae.bin",
41
+ "size": 99317260,
42
+ "sha256": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5"
43
+ },
44
+ {
45
+ "path": "sm8850-gpu-ternary/build/weights/te.idx",
46
+ "size": 6414,
47
+ "sha256": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b"
48
+ },
49
+ {
50
+ "path": "sm8850-gpu-ternary/build/weights/dit.idx",
51
+ "size": 7614,
52
+ "sha256": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a"
53
+ },
54
+ {
55
+ "path": "sm8850-gpu-ternary/build/weights/vae.idx",
56
+ "size": 4104,
57
+ "sha256": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07"
58
+ },
59
+ {
60
+ "path": "sm8850-gpu-ternary/build/weights/tokenizer.json",
61
+ "size": 4561647,
62
+ "sha256": "58e0ac44f0a640c2b4a1cfbea927ef695fd0c2b4d2e0e614e6a3e33684e89069"
63
+ }
64
+ ],
65
+ "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).",
66
+ "fetch": "sm8850-gpu-ternary/fetch.sh"
67
+ }
68
+ ],
69
+ "license": "apache-2.0",
70
+ "made_by": "nnopt (https://nnopt.dev)"
71
+ }
sm8850-gpu-ternary/README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # bonsai-image-ternary-4B on the Galaxy S26+ GPU (hand-written OpenCL)
2
+
3
+ FLUX.2-klein-4B with a ternary diffusion transformer (prism-ml/bonsai-image-ternary-4B-unpacked), the whole
4
+ text-to-image pipeline on the Adreno 840 GPU of a Samsung Galaxy S26+ (Snapdragon 8 Elite Gen 5). It uses
5
+ a C++ runtime over OpenCL written for this port, with no other inference engine on the phone.
6
+
7
+ - **Text encoder**: Qwen3-4B, 27 of 36 layers (prompt_embeds = hidden states of layers 9, 18 and 27).
8
+ - The bf16 weights are streamed per layer from an mmapped pack; the next layer uploads on a second queue while the current one computes.
9
+ - **Transformer**: 5 double and 20 single blocks.
10
+ - 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).
11
+ - They are decoded inside the GEMM's tile load and never dequantized to memory.
12
+ - **VAE decoder**: its convolutions run as implicit-im2col GEMMs with bf16 weights.
13
+ - **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).
14
+ - **Precision**: fp32 activations and fp32 accumulation everywhere (the reference is fp32 on the CPU).
15
+ - **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.
16
+
17
+ ## Requirements
18
+ - An Android arm64 phone with an Adreno GPU and the vendor OpenCL driver (/vendor/lib64/libOpenCL.so).
19
+ - Tested on the Galaxy S26+ (Adreno 840, driver 0842.19.7).
20
+ - About 6 GB of free RAM; peak RSS is 5.6 GB, including the mmapped text-encoder pages.
21
+ - About 7 GB of free storage under /data/local/tmp.
22
+ - Build host: Linux x86-64 or macOS arm64 with git, curl, python3 (with venv), unzip and adb.
23
+ - build.sh fetches and pins the rest into `.deps/`:
24
+ - Android NDK r27d (sha256-checked).
25
+ - Khronos OpenCL-Headers v2024.10.24 (commit-checked).
26
+ - numpy 2.1.3 in its own venv, for the weight converter.
27
+ - Weights: the Hugging Face repo prism-ml/bonsai-image-ternary-4B-unpacked, downloaded into `$INPUTS_DIR/weights/`.
28
+ - Example: `huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --local-dir inputs/weights`.
29
+
30
+ ## Build, deploy, run
31
+ ```
32
+ INPUTS_DIR=/path/to/inputs bash build.sh # program + weight packs (te/dit/vae .bin/.idx, ~7 GB) + tokenizer.json
33
+ bash deploy.sh /data/local/tmp/nnopt/port # adb: program into DEST, weights into /data/local/tmp/nnopt/bonsai_image_weights
34
+ ```
35
+ `build.sh` converts the weights once (it keeps a stamp). `deploy.sh` pushes the weights only when that stamp changed.
36
+
37
+ ### Prompt in, image out (512x512, 4 steps, guidance 1, like the diffusers pipeline)
38
+ ```
39
+ adb shell "cd /data/local/tmp/nnopt/port && sh ./run.sh --prompt 'A cat holding a sign that says hello world' \
40
+ --seed 0 --png /data/local/tmp/nnopt/cat.png --metrics /data/local/tmp/nnopt/cat.json"
41
+ adb pull /data/local/tmp/nnopt/cat.png
42
+ ```
43
+ Flags:
44
+ - `--prompt TEXT` or `--prompt-file F`.
45
+ - `--seed S`: the same seed gives the same noise as `torch.Generator("cpu").manual_seed(S)`.
46
+ - `--steps N`: default 4.
47
+ - `--png OUT`.
48
+ - `--metrics M.json`.
49
+ - 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.
50
+ - Each step is about 16% faster (11.05 to 9.3 s).
51
+ - On the public case noise_pred stays within tolerance.
52
+ - Off by default.
53
+
54
+ ### Tensors in, tensors out (the graded kernel contract)
55
+ ```
56
+ sh ./run.sh --inputs IN_DIR [--repeat R] --out OUT_DIR --metrics M.json
57
+ ```
58
+ Inputs:
59
+ - `prompt_ids` int32 [1,16]: user tokens, spliced into the Qwen3 chat template and padded to 512.
60
+ - `latents` f32 [1,1024,128].
61
+ - `timestep` f32 [1], in [0,1].
62
+ - `encoder_hidden_states` f32 [1,512,7680].
63
+ - `vae_latents` f32 [1,1024,128].
64
+
65
+ Outputs (fp16):
66
+ - `prompt_embeds` [1,512,7680].
67
+ - `noise_pred` [1,1024,128]: one transformer step.
68
+ - `image` [1,3,512,512]: VAE decode in [0,1].
69
+
70
+ ### Check
71
+ ```
72
+ nnopt-verify check --split public --bundle reference --port /data/local/tmp/nnopt/port --executor adb
73
+ ```
74
+ `bonsai_image --selftest` checks every GEMM variant on the GPU against the CPU and times the large GEMMs.
75
+
76
+ ## Measured (Galaxy S26+, GPU clock capped at 902 MHz)
77
+ | what | time |
78
+ |---|---|
79
+ | one graded call (text encoder + 1 DiT step + VAE) | 17.9 s (TE 3.25 s, DiT 11.0 s, VAE 3.65 s) |
80
+ | the same, back to back in the kit's benchmark (the phone heats up) | 19.5–24.5 s per request |
81
+ | 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 |
82
+ | GEMM throughput (ternary and bf16, fp32 math, A through the texture path) | ~1000 GFLOP/s (VAE convs ~750) |
83
+
84
+ Accuracy:
85
+ - Public check: 2 of 2 cases pass, 0 mismatching elements, min cosine 0.9999999989.
86
+ - Demo images differ from the original fp32 CPU pipeline by 0.001–0.003 grey levels on average (out of 255).
87
+
88
+ ## Known limits
89
+ - 512x512 only: the RoPE position tables and the buffers are sized for a 32x32 latent grid.
90
+ - Prompts are capped at 500 tokens: the 512-token template minus 12.
91
+ - Guidance-distilled model, so there is no CFG and no negative prompt (as in the pipeline at guidance 1).
92
+ - The tokenizer's Unicode classes are exact for ASCII and approximate beyond (see src/third_party/tokenizer.h).
93
+ - 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.
94
+
95
+ ## Verified by nnopt
96
+
97
+ **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.
98
+
99
+ | Check | Measured | Bar | Result |
100
+ |---|---|---|---|
101
+ | Outputs match your reference code | Max abs error 0.062 | rtol 0.01, atol 0.01×rms (very close) | pass |
102
+ | Runs on OpenCL | src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e); | the runtime you asked for | pass |
103
+ | Runs on the GPU | checked on every run: GPU opened, no NPU | the processor you asked for | pass |
104
+
105
+ | Speed | This port |
106
+ |---|---|
107
+ | Time per call | 35,181 ms |
108
+ | Load time | 1.13 s |
109
+ | Peak memory | 5,728 MB |
110
+
111
+ | Measurement | Median |
112
+ |---|---|
113
+ | Time per call | 35180.9 ms |
114
+ | Load time | 1126.4 ms |
115
+ | Peak memory | 5728.0 MB |
116
+
117
+ To get these results on your own device, follow REPRO.md.
sm8850-gpu-ternary/REPRO.md ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproduce: prism-ml/bonsai-image-ternary-4B-unpacked on Samsung Galaxy S26+
2
+
3
+ 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.
4
+
5
+ ## 1. Device
6
+
7
+ | Property | nnopt ran on |
8
+ |---|---|
9
+ | Chip | Snapdragon 8 Elite Gen 5 |
10
+ | GPU | Adreno 840 |
11
+ | Memory | 12 GB |
12
+ | OS | Android 16 |
13
+
14
+ 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).
15
+
16
+ ## 2. Tools
17
+
18
+ **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.
19
+
20
+ 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.
21
+
22
+ | Tool | Version | Get it |
23
+ |---|---|---|
24
+ | gcc | 13.3.0 | – |
25
+ | Python | 3.12.3 | https://www.python.org/downloads/ |
26
+ | git | 2.43.0 | – |
27
+ | curl | 8.5.0 | – |
28
+
29
+ To deploy and measure you also need adb (Android platform-tools) and python3 (3.8 or newer, no packages).
30
+
31
+ build.sh and deploy.sh read these environment variables:
32
+
33
+ - `ANDROID_NDK`: the Android NDK folder (same as ANDROID_NDK_HOME)
34
+ - `BUILD`: set it before building
35
+ - `DEPS`: set it before building
36
+ - `INPUTS_DIR`: the folder step 3 fills with the model and inputs (one folder per source, as named there)
37
+ - `OPENCL_ANDROID_INCLUDE`: the OpenCL headers' folder (the one holding CL/)
38
+ - `ROOT`: set it before building
39
+ - `WORK`: set it before building
40
+
41
+ The same machine in Docker (`repro/Dockerfile`: the public image and packages above, nothing else):
42
+
43
+ ```
44
+ docker build --platform linux/amd64 -t build-env repro
45
+ 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.sh
46
+ ```
47
+
48
+ ## 3. Model and inputs
49
+
50
+ **reference_code**: Hugging Face `prism-ml/bonsai-image-ternary-4B-unpacked` at revision `30bbc032dd26939bff95c3d523477ad5065c3e1a`.
51
+
52
+ ```
53
+ huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/reference_code
54
+ ```
55
+
56
+ | File | Size | sha256 |
57
+ |---|---|---|
58
+ | .gitattributes | 1.5 KB | `caf3ca02d5e883f643e939cbed54f94237f94c171797f0dfea5e25c7e33315b3` |
59
+ | LICENSE | 9.9 KB | `69849221bfb90053de2134ef5e6d540287b4b98062326492f1f96f5da685524b` |
60
+ | NOTICE.md | 623 B | `bbefa4a26b836efc040c1a0f155a425d1d833eae1b2534ffc414b1eada3cd922` |
61
+ | README.md | 1.7 KB | `b4a33cfe18326c5d2ec5bc55dce0b998574c338436aa3c3763510abd998e5fe7` |
62
+ | assets/bonsai-logo.svg | 510 B | `91b32517f47dad96a486b408b6b1d2a1cee554fe203dfd44e1df64329f79011f` |
63
+ | manifest.json | 3.6 KB | `f6733ec1651d12480bbfdca3b9ba7e55630ab843a68fcc7c8ed109a9770a9171` |
64
+ | model_index.json | 446 B | `51a76cb1cf3ed37423a1128c79c22faee8e6fbe7f5aaeb737f0a258930dbaac0` |
65
+ | scheduler/scheduler_config.json | 486 B | `067afb012cef64553a763447d1efd93daeffcc0123ca7e25b09f8de20b90762e` |
66
+ | text_encoder/config.json | 1.5 KB | `214b4c29a0d975e9fddf9994a5673f22cb2c4c5750352f9227c2c3251ebeab40` |
67
+ | text_encoder/generation_config.json | 214 B | `4347b1aeed2b2b78bc059920a0b7f5fec71482e1344952b76d7665d638d71f13` |
68
+ | text_encoder/model-00001-of-00002.safetensors | 4.6 GB | `8c0506e7f4936fa7e26183a4fd8da4e2bdbc5990ba64ae441f965d51228f36ea` |
69
+ | text_encoder/model-00002-of-00002.safetensors | 2.9 GB | `82f2bd839378541b0557bfabaf37c7d3d637071fdcb73302dedd7cf61162ce07` |
70
+ | text_encoder/model.safetensors.index.json | 32.1 KB | `06b3d5319b6d76d1a4a2433419180016cfd54ed62d086a5e6567a809f8c82634` |
71
+ | tokenizer/added_tokens.json | 707 B | `c0284b582e14987fbd3d5a2cb2bd139084371ed9acbae488829a1c900833c680` |
72
+ | tokenizer/chat_template.jinja | 4.1 KB | `a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8` |
73
+ | tokenizer/merges.txt | 1.6 MB | `8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5` |
74
+ | tokenizer/special_tokens_map.json | 613 B | `76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd` |
75
+ | tokenizer/tokenizer.json | 10.9 MB | `aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4` |
76
+ | tokenizer/tokenizer_config.json | 5.3 KB | `443bfa629eb16387a12edbf92a76f6a6f10b2af3b53d87ba1550adfcf45f7fa0` |
77
+ | tokenizer/vocab.json | 2.6 MB | `ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910` |
78
+ | … 4 more | | |
79
+
80
+ **weights**: Hugging Face `prism-ml/bonsai-image-ternary-4B-unpacked` at revision `30bbc032dd26939bff95c3d523477ad5065c3e1a`.
81
+
82
+ ```
83
+ huggingface-cli download prism-ml/bonsai-image-ternary-4B-unpacked --revision 30bbc032dd26939bff95c3d523477ad5065c3e1a --local-dir inputs/weights
84
+ ```
85
+
86
+ | File | Size | sha256 |
87
+ |---|---|---|
88
+ | .gitattributes | 1.5 KB | `caf3ca02d5e883f643e939cbed54f94237f94c171797f0dfea5e25c7e33315b3` |
89
+ | LICENSE | 9.9 KB | `69849221bfb90053de2134ef5e6d540287b4b98062326492f1f96f5da685524b` |
90
+ | NOTICE.md | 623 B | `bbefa4a26b836efc040c1a0f155a425d1d833eae1b2534ffc414b1eada3cd922` |
91
+ | README.md | 1.7 KB | `b4a33cfe18326c5d2ec5bc55dce0b998574c338436aa3c3763510abd998e5fe7` |
92
+ | assets/bonsai-logo.svg | 510 B | `91b32517f47dad96a486b408b6b1d2a1cee554fe203dfd44e1df64329f79011f` |
93
+ | manifest.json | 3.6 KB | `f6733ec1651d12480bbfdca3b9ba7e55630ab843a68fcc7c8ed109a9770a9171` |
94
+ | model_index.json | 446 B | `51a76cb1cf3ed37423a1128c79c22faee8e6fbe7f5aaeb737f0a258930dbaac0` |
95
+ | scheduler/scheduler_config.json | 486 B | `067afb012cef64553a763447d1efd93daeffcc0123ca7e25b09f8de20b90762e` |
96
+ | text_encoder/config.json | 1.5 KB | `214b4c29a0d975e9fddf9994a5673f22cb2c4c5750352f9227c2c3251ebeab40` |
97
+ | text_encoder/generation_config.json | 214 B | `4347b1aeed2b2b78bc059920a0b7f5fec71482e1344952b76d7665d638d71f13` |
98
+ | text_encoder/model-00001-of-00002.safetensors | 4.6 GB | `8c0506e7f4936fa7e26183a4fd8da4e2bdbc5990ba64ae441f965d51228f36ea` |
99
+ | text_encoder/model-00002-of-00002.safetensors | 2.9 GB | `82f2bd839378541b0557bfabaf37c7d3d637071fdcb73302dedd7cf61162ce07` |
100
+ | text_encoder/model.safetensors.index.json | 32.1 KB | `06b3d5319b6d76d1a4a2433419180016cfd54ed62d086a5e6567a809f8c82634` |
101
+ | tokenizer/added_tokens.json | 707 B | `c0284b582e14987fbd3d5a2cb2bd139084371ed9acbae488829a1c900833c680` |
102
+ | tokenizer/chat_template.jinja | 4.1 KB | `a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8` |
103
+ | tokenizer/merges.txt | 1.6 MB | `8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5` |
104
+ | tokenizer/special_tokens_map.json | 613 B | `76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd` |
105
+ | tokenizer/tokenizer.json | 10.9 MB | `aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4` |
106
+ | tokenizer/tokenizer_config.json | 5.3 KB | `443bfa629eb16387a12edbf92a76f6a6f10b2af3b53d87ba1550adfcf45f7fa0` |
107
+ | tokenizer/vocab.json | 2.6 MB | `ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910` |
108
+ | … 4 more | | |
109
+
110
+ build.sh also downloads:
111
+
112
+ | Download | Pinned |
113
+ |---|---|
114
+ | `curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP"` | yes: a checksum or a versioned link |
115
+ | `git clone -q --depth 1 --branch "$OCL_TAG" https://github.com/KhronosGroup/OpenCL-Headers.git "$OCL_INC"` | NO: a branch head |
116
+
117
+ 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.
118
+
119
+ ## 4. Build
120
+
121
+ ```
122
+ INPUTS_DIR=$PWD/inputs bash build.sh
123
+ ```
124
+
125
+ `INPUTS_DIR` is the folder step 3 filled (one folder per source, as named there).
126
+
127
+ ## 5. Connect the device
128
+
129
+ ```
130
+ adb devices
131
+ ```
132
+
133
+ One device should be listed as `device`. With several, set `export ANDROID_SERIAL=<serial>` first.
134
+
135
+ ## 6. Deploy
136
+
137
+ ```
138
+ bash deploy.sh /data/local/tmp/nnopt/port
139
+ ```
140
+
141
+ ## 7. Run one input by hand
142
+
143
+ ```
144
+ adb shell 'mkdir -p /data/local/tmp/nnopt/port-repro-io'
145
+ adb push repro/inputs/tensors /data/local/tmp/nnopt/port-repro-io/
146
+ 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'
147
+ adb pull /data/local/tmp/nnopt/port-repro-io/out .
148
+ adb pull /data/local/tmp/nnopt/port-repro-io/metrics.json .
149
+ ```
150
+
151
+ `out` is the output; `metrics.json` holds the program's own timings: `load_ms`, and per request `total_ms`.
152
+
153
+ ## 8. Measure
154
+
155
+ ```
156
+ python3 repro/bench.py
157
+ ```
158
+
159
+ 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.
160
+
161
+ ## 9. Check the outputs
162
+
163
+ ```
164
+ python3 repro/bench.py --check
165
+ ```
166
+
167
+ 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).
168
+
169
+ 1 more public case left out to keep the download small.
170
+
171
+ nnopt's full check also used hidden inputs and teacher-forced comparisons; report.html has every number.
172
+
173
+ ## Expected results
174
+
175
+ | Metric | nnopt (median) | Spread (p10 to p90) | Reproduced if within |
176
+ |---|---|---|---|
177
+ | Time per request (ms) | 35,181 | 32,839 to 38,323 | ±10% |
178
+
179
+ 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/`.
180
+
181
+ `report/reproduce.sh` runs steps 8 and 9 in one go.
sm8850-gpu-ternary/build.sh ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Builds the Android arm64 program and converts the checkpoint into the packs it reads.
3
+ # INPUTS_DIR=/path/to/inputs bash build.sh (INPUTS_DIR/weights = the Hugging Face repo
4
+ # prism-ml/bonsai-image-ternary-4B-unpacked, see README.md)
5
+ # Fetches its own pinned tools into .deps/: Android NDK r27d, Khronos OpenCL-Headers v2024.10.24, numpy 2.1.3 (venv).
6
+ set -euo pipefail
7
+ . "$(dirname "$0")/paths.sh"
8
+ cd "$ROOT"
9
+ if [ "$WORK" != "$ROOT" ]; then echo "build.sh: $ROOT is read-only, using $WORK for .deps/ and build/"; fi
10
+ mkdir -p "$DEPS" "$BUILD"
11
+
12
+ # ---- Android NDK r27d (pinned, sha256 of Google's archive)
13
+ NDK_REL=r27d; NDK_REV=27.3.13750724
14
+ case "$(uname -s)" in
15
+ Linux) NDK_ZIP=android-ndk-$NDK_REL-linux.zip; NDK_SHA=601246087a682d1944e1e16dd85bc6e49560fe8b6d61255be2829178c8ed15d9; HOSTTAG=linux-x86_64 ;;
16
+ Darwin) NDK_ZIP=android-ndk-$NDK_REL-darwin.zip; NDK_SHA=e69092f9d2bfa5d1199039980a14eb91c03cc971ab5c6968fc08a8e6b84e7bb7; HOSTTAG=darwin-x86_64 ;;
17
+ *) echo "build.sh: unsupported host $(uname -s)" >&2; exit 1 ;;
18
+ esac
19
+ if [ -n "${ANDROID_NDK:-}" ] && grep -q "Pkg.Revision = $NDK_REV" "$ANDROID_NDK/source.properties" 2>/dev/null; then
20
+ NDK=$ANDROID_NDK
21
+ else
22
+ NDK=$DEPS/android-ndk-$NDK_REL
23
+ if ! grep -q "Pkg.Revision = $NDK_REV" "$NDK/source.properties" 2>/dev/null; then
24
+ rm -rf "$NDK"
25
+ curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP"
26
+ echo "$NDK_SHA $DEPS/$NDK_ZIP" | shasum -a 256 -c -
27
+ (cd "$DEPS" && unzip -q "$NDK_ZIP" && rm "$NDK_ZIP")
28
+ fi
29
+ fi
30
+ CXX=$NDK/toolchains/llvm/prebuilt/$HOSTTAG/bin/aarch64-linux-android29-clang++
31
+
32
+ # ---- OpenCL headers (the program dlopens the vendor libOpenCL.so on the phone, no loader needed)
33
+ OCL_TAG=v2024.10.24; OCL_COMMIT=4ea6df132107e3b4b9407f903204b5522fdffcd6
34
+ if [ -n "${OPENCL_ANDROID_INCLUDE:-}" ] && [ -f "$OPENCL_ANDROID_INCLUDE/CL/cl.h" ]; then
35
+ OCL_INC=$OPENCL_ANDROID_INCLUDE
36
+ else
37
+ OCL_INC=$DEPS/OpenCL-Headers
38
+ if [ "$(git -C "$OCL_INC" rev-parse HEAD 2>/dev/null || true)" != "$OCL_COMMIT" ]; then
39
+ rm -rf "$OCL_INC"
40
+ git clone -q --depth 1 --branch "$OCL_TAG" https://github.com/KhronosGroup/OpenCL-Headers.git "$OCL_INC"
41
+ [ "$(git -C "$OCL_INC" rev-parse HEAD)" = "$OCL_COMMIT" ] || { echo "build.sh: OpenCL-Headers $OCL_TAG is not $OCL_COMMIT" >&2; exit 1; }
42
+ fi
43
+ fi
44
+
45
+ # ---- program
46
+ mkdir -p "$BUILD/bin"
47
+ "$CXX" -O2 -std=c++17 -I"$OCL_INC" -Wall -static-libstdc++ src/*.cpp src/third_party/*.cpp -ldl -o "$BUILD/bin/bonsai_image"
48
+ rm -rf "$BUILD/bin/kernels" && cp -R src/kernels "$BUILD/bin/kernels"
49
+ echo "build.sh: built $BUILD/bin/bonsai_image"
50
+
51
+ # ---- weights: convert the checkpoint once (stamp = converter + checkpoint file sizes)
52
+ if [ -z "${INPUTS_DIR:-}" ] || [ ! -d "$INPUTS_DIR/weights/transformer" ]; then
53
+ if [ -f "$BUILD/weights/.stamp" ]; then echo "build.sh: INPUTS_DIR unset, keeping the converted weights in $BUILD/weights"; exit 0; fi
54
+ echo "build.sh: set INPUTS_DIR to a folder whose weights/ holds prism-ml/bonsai-image-ternary-4B-unpacked (README.md)" >&2
55
+ exit 2
56
+ fi
57
+ VENV=$DEPS/venv
58
+ if ! "$VENV/bin/python" -c 'import numpy; assert numpy.__version__ == "2.1.3"' 2>/dev/null; then
59
+ rm -rf "$VENV"
60
+ python3 -m venv "$VENV"
61
+ PIP_CONSTRAINT= PIP_EXTRA_INDEX_URL= PIP_INDEX_URL= "$VENV/bin/pip" install -q --disable-pip-version-check numpy==2.1.3
62
+ fi
63
+ W=$INPUTS_DIR/weights
64
+ STAMP=$( { shasum -a 256 tools/convert.py; for f in transformer/diffusion_pytorch_model.safetensors vae/diffusion_pytorch_model.safetensors \
65
+ text_encoder/model-00001-of-00002.safetensors text_encoder/model-00002-of-00002.safetensors; do
66
+ printf '%s %s\n' "$f" "$(wc -c < "$W/$f" | tr -d ' ')"; done; } | shasum -a 256 | cut -c1-16)
67
+ if [ "$(cat "$BUILD/weights/.stamp" 2>/dev/null || true)" != "$STAMP" ]; then
68
+ rm -rf "$BUILD/weights"; mkdir -p "$BUILD/weights"
69
+ "$VENV/bin/python" -I tools/convert.py "$W" "$BUILD/weights"
70
+ echo "$STAMP" > "$BUILD/weights/.stamp"
71
+ fi
72
+ "$VENV/bin/python" -I tools/tokjson.py "$W/tokenizer/tokenizer.json" "$BUILD/weights/tokenizer.json"
73
+ echo "build.sh: weights ready in $BUILD/weights ($STAMP)"
sm8850-gpu-ternary/build/bin/bonsai_image ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f6bfcedf5b42981a250ea06a020ffe92b9399a8f8eff578e525406396867909
3
+ size 1409616
sm8850-gpu-ternary/build/bin/kernels/bench.cl ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Peak probe for --selftest: 8 independent float4 FMA chains per work-item, no memory traffic in the loop.
2
+ #ifdef HALF
3
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
4
+ #define T4 half4
5
+ #define T half
6
+ #else
7
+ #define T4 float4
8
+ #define T float
9
+ #endif
10
+ __kernel void fma_peak(__global float* out, const T a, const T b, const int iters) {
11
+ const int g = get_global_id(0);
12
+ 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;
13
+ for (int i = 0; i < iters; ++i) {
14
+ x0 = mad(x0, a, b); x1 = mad(x1, a, b); x2 = mad(x2, a, b); x3 = mad(x3, a, b);
15
+ x4 = mad(x4, a, b); x5 = mad(x5, a, b); x6 = mad(x6, a, b); x7 = mad(x7, a, b);
16
+ }
17
+ const T4 s = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7;
18
+ out[g] = (float)(s.x + s.y + s.z + s.w);
19
+ }
sm8850-gpu-ternary/build/bin/kernels/gemm.cl ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Tiled GEMM, fp32 accumulation: C[M,N] = epilogue(A[M,K] . B(K,N)).
2
+ // Compile-time variants (one program each):
3
+ // A_MODE 0: A dense fp32 row-major [M][lda]
4
+ // 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
5
+ // A_MODE 2: as 1, with a nearest 2x upsample fused in (the source image is [H/2][W/2][Cin])
6
+ // A_MODE 3: A read through an RGBA float image2d [M rows][K/4 texels] (texture path), only B goes through local;
7
+ // batches side by side (column offset b*sA) or stacked (row offset b*aoff)
8
+ // 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))
9
+ // B_MODE 0: fp32 [N][ldb] (k contiguous) B_MODE 1: fp32 [K][ldb] (n contiguous)
10
+ // B_MODE 2: bf16 [N][ldb] (k contiguous) B_MODE 3: ternary, 2 bits per weight packed 16 per uint
11
+ // ([N][K/16] words, code c -> c-1) times a bf16 scale per 128 k ([N][K/128])
12
+ // Epilogue: v = alpha*acc (+ bias[n]); if res: v = res[m,n] + (gate ? gate[n] : 1) * v.
13
+ // Tile (16*TM)x(16*TN)x16, work-group 16x16, TMxTN outputs per work-item; batch over get_group_id(2).
14
+ #ifndef TM
15
+ #define TM 4
16
+ #endif
17
+ #ifndef TN
18
+ #define TN 4
19
+ #endif
20
+ #define BM (16 * TM)
21
+ #define BN (16 * TN)
22
+ // KP: k passes of 16 per tile (BK = 16*KP); NT B modes and dense A only
23
+ #ifndef KP
24
+ #define KP 1
25
+ #endif
26
+ #define BK (16 * KP)
27
+ #if KP > 1 && (B_MODE == 1 || A_MODE == 1 || A_MODE == 2 || A_MODE == 4 || A_MODE == 5)
28
+ #error KP > 1 needs an NT B mode and a dense A
29
+ #endif
30
+ // HB: weight tiles (bf16 or ternary x bf16 scale: exact in fp16) held as half in local memory; each work-item then
31
+ // reads its TN contiguous columns in one load (columns tx*TN + c instead of tx*4 + j*64 + c)
32
+ #ifndef HB
33
+ #define HB (B_MODE == 2 || B_MODE == 3)
34
+ #endif
35
+ #if HB
36
+ #pragma OPENCL EXTENSION cl_khr_fp16 : enable
37
+ #endif
38
+ #ifndef DBG
39
+ #define DBG 0
40
+ #endif
41
+ #ifndef SWAP
42
+ #define SWAP 0
43
+ #endif
44
+ #ifndef PF
45
+ #define PF 1
46
+ #endif
47
+
48
+ #define AIMG (A_MODE >= 3)
49
+ // output row of accumulator row i
50
+ #if AIMG
51
+ #define ROW(i) (m0 + ty * TM + (i))
52
+ #else
53
+ #define ROW(i) (m0 + ((i) >> 2) * 64 + ty * 4 + ((i) & 3))
54
+ #endif
55
+
56
+ inline float bf16f(ushort u) { return as_float(((uint)u) << 16); }
57
+
58
+ // A tile element quad: row am, k = k0 + lq .. +3
59
+ inline float4 load_a(__global const float* A, const int M, const int lda, const int am, const int k0, const int lq,
60
+ const int convH, const int convW, const int convLogW, const int convCin) {
61
+ float4 av = 0;
62
+ #if A_MODE == 0 || A_MODE == 3
63
+ if (am < M) av = vload4(0, A + am * lda + k0 + lq);
64
+ #else
65
+ const int ay = am >> convLogW, ax = am & (convW - 1);
66
+ const int tap = k0 / convCin, c0 = k0 - tap * convCin;
67
+ const int ky = tap / 3, kx = tap - ky * 3;
68
+ const int yy = ay + ky - 1, xx = ax + kx - 1;
69
+ if (am < M && yy >= 0 && yy < convH && xx >= 0 && xx < convW) {
70
+ #if A_MODE == 1
71
+ av = vload4(0, A + (yy * convW + xx) * convCin + c0 + lq);
72
+ #else
73
+ av = vload4(0, A + ((yy >> 1) * (convW >> 1) + (xx >> 1)) * convCin + c0 + lq);
74
+ #endif
75
+ }
76
+ #endif
77
+ return av;
78
+ }
79
+
80
+ // B tile quad: NT modes give column n0 + lrow at k = k0 + lq .. +3; NN mode gives k row idx / (BN/4), 4 columns
81
+ inline float4 load_b(__global const void* Bv, __global const ushort* Bscale, const int N, const int K, const int ldb,
82
+ const int boff, const int n0, const int k0, const int lrow, const int lq, const int idx) {
83
+ float4 bv = 0;
84
+ #if B_MODE == 1
85
+ const int kk = idx / (BN / 4), nq = (idx - kk * (BN / 4)) << 2;
86
+ const int nn = n0 + nq;
87
+ if (nn < N) bv = vload4(0, (__global const float*)Bv + boff + (k0 + kk) * ldb + nn);
88
+ #else
89
+ const int bn = n0 + lrow;
90
+ if (bn < N) {
91
+ #if B_MODE == 0
92
+ bv = vload4(0, (__global const float*)Bv + boff + bn * ldb + k0 + lq);
93
+ #elif B_MODE == 2
94
+ ushort4 u = vload4(0, (__global const ushort*)Bv + boff + bn * ldb + k0 + lq);
95
+ bv = (float4)(bf16f(u.x), bf16f(u.y), bf16f(u.z), bf16f(u.w));
96
+ #else
97
+ const uint w = ((__global const uint*)Bv)[boff + bn * (K >> 4) + (k0 >> 4)];
98
+ const float s = bf16f(Bscale[bn * (K >> 7) + (k0 >> 7)]);
99
+ const uint q = w >> (lq * 2);
100
+ bv = (float4)((float)((int)(q & 3u) - 1), (float)((int)((q >> 2) & 3u) - 1),
101
+ (float)((int)((q >> 4) & 3u) - 1), (float)((int)((q >> 6) & 3u) - 1)) * s;
102
+ #endif
103
+ }
104
+ #endif
105
+ return bv;
106
+ }
107
+
108
+ __kernel __attribute__((reqd_work_group_size(16, 16, 1)))
109
+ void gemm(const int M, const int N, const int K,
110
+ #if AIMG
111
+ __read_only image2d_t Aimg, const int aoff,
112
+ #else
113
+ __global const float* A, const int aoff,
114
+ #endif
115
+ const int lda, const int sA,
116
+ __global const void* Bv, const int boff0, const int ldb, const int sB, const int bdiv,
117
+ __global const ushort* Bscale,
118
+ __global float* C, const int coff, const int ldc, const int sC,
119
+ const float alpha,
120
+ __global const float* bias, const int has_bias,
121
+ __global const float* res, const int roff, const int ldr, const int has_res,
122
+ __global const float* gate, const int goff, const int has_gate,
123
+ const int convH, const int convW, const int convLogW, const int convCin) {
124
+ #if !AIMG
125
+ __local float As[BK][BM + 4];
126
+ #endif
127
+ #if HB
128
+ __local half Bs[BK][BN + 8];
129
+ #else
130
+ __local float Bs[BK][BN + 4];
131
+ #endif
132
+ #if SWAP // lanes of a wave walk rows (A texels unique per lane, B local reads broadcast)
133
+ const int tx = get_local_id(1), ty = get_local_id(0);
134
+ #else
135
+ const int tx = get_local_id(0), ty = get_local_id(1);
136
+ #endif
137
+ const int t = get_local_id(1) * 16 + get_local_id(0);
138
+ const int n0 = get_group_id(0) * BN, m0 = get_group_id(1) * BM;
139
+ const int b = get_group_id(2);
140
+ #if AIMG
141
+ const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;
142
+ #else
143
+ A += aoff + b * sA;
144
+ #endif
145
+ C += coff + b * sC;
146
+ res += roff + b * sC;
147
+ gate += goff;
148
+ const int boff = boff0 + (b / bdiv) * sB;
149
+
150
+ float4 acc[TM][TN / 4];
151
+ #pragma unroll
152
+ for (int i = 0; i < TM; ++i)
153
+ #pragma unroll
154
+ for (int j = 0; j < TN / 4; ++j) acc[i][j] = 0;
155
+
156
+ const int lr = t >> 2, lq = (t & 3) << 2; // tile row 0..63 (+64 per extra pass), k quad 0,4,8,12
157
+
158
+ // global -> registers for tile k0 (av: A rows, bv: B columns or rows), then registers -> local
159
+ float4 av[KP][TM / 4], bv[KP][TN / 4];
160
+ #if AIMG
161
+ #define LOAD_A(k0)
162
+ #else
163
+ #define LOAD_A(k0) \
164
+ _Pragma("unroll") for (int q = 0; q < KP; ++q) \
165
+ _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, \
166
+ convH, convW, convLogW, convCin);
167
+ #endif
168
+ #define LOAD_TILES(k0) \
169
+ { \
170
+ LOAD_A(k0) \
171
+ _Pragma("unroll") for (int q = 0; q < KP; ++q) \
172
+ _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, \
173
+ lr + p * 64, lq, t + p * 256); \
174
+ }
175
+ LOAD_TILES(0);
176
+ for (int k0 = 0; k0 < K; k0 += BK) {
177
+ #if !AIMG
178
+ #pragma unroll
179
+ for (int q = 0; q < KP; ++q)
180
+ #pragma unroll
181
+ for (int p = 0; p < TM / 4; ++p) {
182
+ const int lrow = lr + p * 64, kq = lq + 16 * q;
183
+ 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;
184
+ }
185
+ #endif
186
+ #pragma unroll
187
+ for (int q = 0; q < KP; ++q)
188
+ #pragma unroll
189
+ for (int p = 0; p < TN / 4; ++p) {
190
+ #if B_MODE == 1
191
+ const int idx = t + p * 256;
192
+ const int kk = idx / (BN / 4), nq = (idx - kk * (BN / 4)) << 2;
193
+ vstore4(bv[q][p], 0, &Bs[kk][nq]);
194
+ #else
195
+ const int lrow = lr + p * 64, kq = lq + 16 * q;
196
+ #if HB
197
+ vstore_half(bv[q][p].x, 0, &Bs[kq + 0][lrow]); vstore_half(bv[q][p].y, 0, &Bs[kq + 1][lrow]);
198
+ vstore_half(bv[q][p].z, 0, &Bs[kq + 2][lrow]); vstore_half(bv[q][p].w, 0, &Bs[kq + 3][lrow]);
199
+ #else
200
+ 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;
201
+ #endif
202
+ #endif
203
+ }
204
+ barrier(CLK_LOCAL_MEM_FENCE);
205
+ #if PF
206
+ if (k0 + BK < K) LOAD_TILES(k0 + BK);
207
+ #endif
208
+
209
+ #if AIMG
210
+ // 4 k per texel: a[i] = A[row i][k0 + 4*k4 .. +3]
211
+ #if HB
212
+ #define LOAD_BB(k, j) vload_half4(0, &Bs[k][tx * TN + (j) * 4])
213
+ #else
214
+ #define LOAD_BB(k, j) vload4(0, &Bs[k][tx * 4 + (j) * 64])
215
+ #endif
216
+ #define AIMG_STEP(kk, comp) \
217
+ { \
218
+ float4 bb[TN / 4]; \
219
+ _Pragma("unroll") for (int j = 0; j < TN / 4; ++j) bb[j] = LOAD_BB(k4 * 4 + kk, j); \
220
+ _Pragma("unroll") for (int i = 0; i < TM; ++i) \
221
+ _Pragma("unroll") for (int j = 0; j < TN / 4; ++j) acc[i][j] = mad((float4)a[i].comp, bb[j], acc[i][j]); \
222
+ }
223
+ #if A_MODE == 3
224
+ // batch b: columns from b*sA (blocks side by side) or rows from b*aoff (blocks stacked)
225
+ const int y0 = m0 + ty * TM + b * aoff, x0 = (k0 >> 2) + b * (sA >> 2);
226
+ #define A_TEXEL(i, k4) read_imagef(Aimg, smp, (int2)(x0 + (k4), y0 + (i)))
227
+ #else
228
+ // the TM pixels of this work-item are consecutive in one image row (TM divides W): one source row, x = xb + i;
229
+ // rows outside the padding read the zero border (y < 0), columns outside it are zeroed by the select
230
+ int y0, xb;
231
+ {
232
+ const int tap = k0 / convCin, c0 = k0 - tap * convCin;
233
+ const int ky = tap / 3, kx = tap - ky * 3;
234
+ const int mb = m0 + ty * TM;
235
+ int yy = (mb >> convLogW) + ky - 1;
236
+ const bool ok = mb < M && yy >= 0 && yy < convH;
237
+ #if A_MODE == 5
238
+ yy >>= 1;
239
+ #endif
240
+ y0 = ok ? yy * (convCin >> 2) + (c0 >> 2) : -8;
241
+ xb = (mb & (convW - 1)) + kx - 1;
242
+ }
243
+ #if A_MODE == 5
244
+ #define A_TEXEL(i, k4) select((float4)0, read_imagef(Aimg, smp, (int2)((xb + (i)) >> 1, y0 + (k4))), (int4)(-((uint)(xb + (i)) < (uint)convW)))
245
+ #else
246
+ #define A_TEXEL(i, k4) select((float4)0, read_imagef(Aimg, smp, (int2)(xb + (i), y0 + (k4))), (int4)(-((uint)(xb + (i)) < (uint)convW)))
247
+ #endif
248
+ #endif
249
+ #pragma unroll
250
+ for (int k4 = 0; k4 < BK / 4; ++k4) {
251
+ float4 a[TM];
252
+ #pragma unroll
253
+ for (int i = 0; i < TM; ++i) a[i] = A_TEXEL(i, k4);
254
+ AIMG_STEP(0, x) AIMG_STEP(1, y) AIMG_STEP(2, z) AIMG_STEP(3, w)
255
+ }
256
+ #else
257
+ #pragma unroll
258
+ for (int k = 0; k < BK; ++k) {
259
+ float4 a[TM / 4], bb[TN / 4];
260
+ #if DBG == 1 // timing probe only: no local reads in the inner loop
261
+ for (int i = 0; i < TM / 4; ++i) a[i] = (float4)(k + i, 1, 2, 3) * 1e-3f;
262
+ for (int j = 0; j < TN / 4; ++j) bb[j] = (float4)(j, 1, k, 3) * 1e-3f;
263
+ #else
264
+ for (int i = 0; i < TM / 4; ++i) a[i] = vload4(0, &As[k][ty * 4 + i * 64]);
265
+ #if HB
266
+ for (int j = 0; j < TN / 4; ++j) bb[j] = vload_half4(0, &Bs[k][tx * TN + j * 4]);
267
+ #else
268
+ for (int j = 0; j < TN / 4; ++j) bb[j] = vload4(0, &Bs[k][tx * 4 + j * 64]);
269
+ #endif
270
+ #endif
271
+ #pragma unroll
272
+ for (int i = 0; i < TM / 4; ++i)
273
+ #pragma unroll
274
+ for (int j = 0; j < TN / 4; ++j) {
275
+ acc[i * 4 + 0][j] = mad((float4)a[i].x, bb[j], acc[i * 4 + 0][j]);
276
+ acc[i * 4 + 1][j] = mad((float4)a[i].y, bb[j], acc[i * 4 + 1][j]);
277
+ acc[i * 4 + 2][j] = mad((float4)a[i].z, bb[j], acc[i * 4 + 2][j]);
278
+ acc[i * 4 + 3][j] = mad((float4)a[i].w, bb[j], acc[i * 4 + 3][j]);
279
+ }
280
+ }
281
+ #endif
282
+ barrier(CLK_LOCAL_MEM_FENCE);
283
+ #if !PF
284
+ if (k0 + BK < K) LOAD_TILES(k0 + BK);
285
+ #endif
286
+ }
287
+
288
+ // ---- epilogue: row m0 + (i/4)*64 + ty*4 + i%4, column nb + c (vector ops only, so acc stays in registers)
289
+ #pragma unroll
290
+ for (int j = 0; j < TN / 4; ++j) {
291
+ #if HB
292
+ const int nb = n0 + tx * TN + j * 4;
293
+ #else
294
+ const int nb = n0 + j * 64 + tx * 4;
295
+ #endif
296
+ if (nb >= N) continue;
297
+ const bool full = nb + 3 < N;
298
+ float4 bia = 0, gt = 1;
299
+ if (full) {
300
+ if (has_bias) bia = vload4(0, bias + nb);
301
+ if (has_gate) gt = vload4(0, gate + nb);
302
+ } else {
303
+ if (has_bias) bia = (float4)(bias[nb], nb + 1 < N ? bias[nb + 1] : 0, nb + 2 < N ? bias[nb + 2] : 0, 0);
304
+ if (has_gate) gt = (float4)(gate[nb], nb + 1 < N ? gate[nb + 1] : 1, nb + 2 < N ? gate[nb + 2] : 1, 1);
305
+ }
306
+ #pragma unroll
307
+ for (int i = 0; i < TM; ++i) {
308
+ const int m = ROW(i);
309
+ if (m < M) {
310
+ float4 o = alpha * acc[i][j] + bia;
311
+ if (full) {
312
+ if (has_res) o = vload4(0, res + m * ldr + nb) + gt * o;
313
+ vstore4(o, 0, C + m * ldc + nb);
314
+ } else {
315
+ 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;
316
+ C[m * ldc + nb] = o.x;
317
+ if (nb + 1 < N) C[m * ldc + nb + 1] = o.y;
318
+ if (nb + 2 < N) C[m * ldc + nb + 2] = o.z;
319
+ }
320
+ }
321
+ }
322
+ }
323
+ }
sm8850-gpu-ternary/build/bin/kernels/ops.cl ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Row-wise and elementwise kernels (fp32 everywhere). Work-group of 256 unless noted.
2
+
3
+ inline float wg_sum256(float v, __local float* red) {
4
+ const int l = get_local_id(0);
5
+ red[l] = v;
6
+ barrier(CLK_LOCAL_MEM_FENCE);
7
+ for (int s = 128; s > 0; s >>= 1) {
8
+ if (l < s) red[l] += red[l + s];
9
+ barrier(CLK_LOCAL_MEM_FENCE);
10
+ }
11
+ const float r = red[0];
12
+ barrier(CLK_LOCAL_MEM_FENCE);
13
+ return r;
14
+ }
15
+ inline float wg_max256(float v, __local float* red) {
16
+ const int l = get_local_id(0);
17
+ red[l] = v;
18
+ barrier(CLK_LOCAL_MEM_FENCE);
19
+ for (int s = 128; s > 0; s >>= 1) {
20
+ if (l < s) red[l] = fmax(red[l], red[l + s]);
21
+ barrier(CLK_LOCAL_MEM_FENCE);
22
+ }
23
+ const float r = red[0];
24
+ barrier(CLK_LOCAL_MEM_FENCE);
25
+ return r;
26
+ }
27
+
28
+ // Qwen3RMSNorm: w * (x * rsqrt(mean(x^2) + eps)); one group per row, D <= 256*16
29
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
30
+ void rmsnorm(__global const float* x, const int xoff, const int ldx, __global float* out, const int ooff, const int ldo,
31
+ __global const float* w, const int D, const float eps) {
32
+ __local float red[256];
33
+ const int r = get_group_id(0), l = get_local_id(0);
34
+ x += xoff + r * ldx; out += ooff + r * ldo;
35
+ float ss = 0;
36
+ for (int i = l; i < D; i += 256) { const float v = x[i]; ss += v * v; }
37
+ ss = wg_sum256(ss, red);
38
+ const float rs = rsqrt(ss / D + eps);
39
+ for (int i = l; i < D; i += 256) out[i] = w[i] * (x[i] * rs);
40
+ }
41
+
42
+ // Per-head RMSNorm (head_dim 128, weight w) then rotate-half RoPE (Qwen3), in place.
43
+ // Rows: r = s*nheads + h at x[off + s*ld + h*128]. cos/sin tables [S][128]. Work-group 128.
44
+ __kernel __attribute__((reqd_work_group_size(128, 1, 1)))
45
+ void headnorm_rope_half(__global float* x, const int off, const int ld, const int nheads,
46
+ __global const float* w, __global const float* cs, __global const float* sn, const float eps) {
47
+ __local float red[128];
48
+ __local float xn[128];
49
+ const int r = get_group_id(0), l = get_local_id(0);
50
+ const int s = r / nheads, h = r - s * nheads;
51
+ __global float* p = x + off + s * ld + h * 128;
52
+ const float v = p[l];
53
+ red[l] = v * v;
54
+ barrier(CLK_LOCAL_MEM_FENCE);
55
+ for (int st = 64; st > 0; st >>= 1) { if (l < st) red[l] += red[l + st]; barrier(CLK_LOCAL_MEM_FENCE); }
56
+ const float rs = rsqrt(red[0] / 128.f + eps);
57
+ const float y = w[l] * (v * rs);
58
+ xn[l] = y;
59
+ barrier(CLK_LOCAL_MEM_FENCE);
60
+ const float rot = l < 64 ? -xn[l + 64] : xn[l - 64];
61
+ p[l] = y * cs[s * 128 + l] + rot * sn[s * 128 + l];
62
+ }
63
+
64
+ // Per-head RMSNorm then interleaved-pair RoPE (FLUX.2), in place. Rows s < split use w1, others w2.
65
+ __kernel __attribute__((reqd_work_group_size(128, 1, 1)))
66
+ void headnorm_rope_tab(__global float* x, const int off, const int ld, const int nheads, const int split,
67
+ __global const float* w1, __global const float* w2,
68
+ __global const float* cs, __global const float* sn, const float eps) {
69
+ __local float red[128];
70
+ __local float xn[128];
71
+ const int r = get_group_id(0), l = get_local_id(0);
72
+ const int s = r / nheads, h = r - s * nheads;
73
+ __global float* p = x + off + s * ld + h * 128;
74
+ const float v = p[l];
75
+ red[l] = v * v;
76
+ barrier(CLK_LOCAL_MEM_FENCE);
77
+ for (int st = 64; st > 0; st >>= 1) { if (l < st) red[l] += red[l + st]; barrier(CLK_LOCAL_MEM_FENCE); }
78
+ const float rs = rsqrt(red[0] / 128.f + eps);
79
+ const float y = (s < split ? w1[l] : w2[l]) * (v * rs);
80
+ xn[l] = y;
81
+ barrier(CLK_LOCAL_MEM_FENCE);
82
+ const float rot = (l & 1) ? xn[l - 1] : -xn[l + 1];
83
+ p[l] = y * cs[s * 128 + l] + rot * sn[s * 128 + l];
84
+ }
85
+
86
+ // In-place softmax(scale * row) over ncols; grid (rows, batch). mask 1: key j allowed iff j <= row && j < valid.
87
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
88
+ void softmax_rows(__global float* S, const int ld, const int rows, const int ncols, const float scale,
89
+ const int mask, const int valid) {
90
+ __local float red[256];
91
+ const int r = get_group_id(0), b = get_group_id(1), l = get_local_id(0);
92
+ __global float* p = S + (b * rows + r) * ld;
93
+ const int lim = mask ? min(r + 1, valid) : ncols;
94
+ float mx = -FLT_MAX;
95
+ for (int j = l; j < lim; j += 256) mx = fmax(mx, p[j] * scale);
96
+ mx = wg_max256(mx, red);
97
+ float sum = 0;
98
+ for (int j = l; j < lim; j += 256) sum += exp(p[j] * scale - mx);
99
+ sum = wg_sum256(sum, red);
100
+ const float inv = 1.f / sum;
101
+ for (int j = l; j < ncols; j += 256) p[j] = j < lim ? exp(p[j] * scale - mx) * inv : 0.f;
102
+ }
103
+
104
+ // softmax_rows for batches b0.. of S, writing P into an RGBA float image (texel (j/4, (b-b0)*rows + r)) instead of
105
+ // back into S (the A operand of the texture-path P.V GEMM). ncols % 4 == 0. grid (rows*256, nb)
106
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
107
+ void softmax_rows_img(__global const float* S, const int ld, const int rows, const int ncols, const float scale,
108
+ const int mask, const int valid, const int b0, __write_only image2d_t img) {
109
+ __local float red[256];
110
+ const int r = get_group_id(0), bl = get_group_id(1), l = get_local_id(0);
111
+ __global const float* p = S + ((b0 + bl) * rows + r) * ld;
112
+ const int lim = mask ? min(r + 1, valid) : ncols;
113
+ float mx = -FLT_MAX;
114
+ for (int j = l; j < lim; j += 256) mx = fmax(mx, p[j] * scale);
115
+ mx = wg_max256(mx, red);
116
+ float sum = 0;
117
+ for (int j = l; j < lim; j += 256) sum += exp(p[j] * scale - mx);
118
+ sum = wg_sum256(sum, red);
119
+ const float inv = 1.f / sum;
120
+ for (int j4 = l; j4 < (ncols >> 2); j4 += 256) {
121
+ const float4 e = exp(vload4(j4, p) * scale - mx) * inv;
122
+ const int4 jj = (int4)(j4 * 4) + (int4)(0, 1, 2, 3);
123
+ write_imagef(img, (int2)(j4, bl * rows + r), select((float4)0, e, jj < (int4)lim));
124
+ }
125
+ }
126
+
127
+ // out[m][j] = silu(in[m][j]) * in[m][j + H]; grid (H, M)
128
+ __kernel void silu_mul(__global const float* in, const int ioff, const int ldi, const int H,
129
+ __global float* out, const int ooff, const int ldo) {
130
+ const int j = get_global_id(0), m = get_global_id(1);
131
+ if (j >= H) return;
132
+ const float g = in[ioff + m * ldi + j], u = in[ioff + m * ldi + j + H];
133
+ out[ooff + m * ldo + j] = g / (1.f + exp(-g)) * u;
134
+ }
135
+
136
+ __kernel void silu(__global const float* in, __global float* out, const int n) {
137
+ const int i = get_global_id(0);
138
+ if (i < n) { const float v = in[i]; out[i] = v / (1.f + exp(-v)); }
139
+ }
140
+
141
+ // LayerNorm without affine, then out = xn * (1 + scale) + shift; one group per row.
142
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
143
+ void layernorm_mod(__global const float* x, const int xoff, const int ldx, __global float* out, const int ooff,
144
+ const int ldo, const int D, __global const float* mod, const int shoff, const int scoff,
145
+ const float eps) {
146
+ __local float red[256];
147
+ const int r = get_group_id(0), l = get_local_id(0);
148
+ x += xoff + r * ldx; out += ooff + r * ldo;
149
+ float s = 0;
150
+ for (int i = l; i < D; i += 256) s += x[i];
151
+ const float mean = wg_sum256(s, red) / D;
152
+ float v = 0;
153
+ for (int i = l; i < D; i += 256) { const float d = x[i] - mean; v += d * d; }
154
+ const float rstd = rsqrt(wg_sum256(v, red) / D + eps);
155
+ for (int i = l; i < D; i += 256) out[i] = (x[i] - mean) * rstd * (1.f + mod[scoff + i]) + mod[shoff + i];
156
+ }
157
+
158
+ // GroupNorm on NHWC [HW][C], G groups. Partial sums over pixel chunks; pass 0: sum x, pass 1: sum (x-mean)^2.
159
+ // grid (nchunk*256, G); each group handles pixels [chunk*cp, (chunk+1)*cp).
160
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
161
+ void gn_partial(__global const float* x, const int HW, const int C, const int cg, const int cp,
162
+ __global const float* stats, const int pass, __global float* part) {
163
+ __local float red[256];
164
+ const int chunk = get_group_id(0), g = get_group_id(1), l = get_local_id(0);
165
+ const int nchunk = get_num_groups(0);
166
+ const float mean = pass ? stats[g * 2] : 0.f;
167
+ const int n = cp * cg;
168
+ const int p0 = chunk * cp;
169
+ float s = 0;
170
+ for (int i = l; i < n; i += 256) {
171
+ const int pp = p0 + i / cg, c = g * cg + (i % cg);
172
+ if (pp < HW) {
173
+ const float v = x[pp * C + c] - mean;
174
+ s += pass ? v * v : v;
175
+ }
176
+ }
177
+ s = wg_sum256(s, red);
178
+ if (l == 0) part[g * nchunk + chunk] = s;
179
+ }
180
+
181
+ // gn_partial with coalesced reads: one group per chunk of cp pixels covers every channel quad (work-item l: quad
182
+ // l % C4, pixels p0 + l / C4 step 256 / C4), then lane g < G sums its group's quads. Needs C4 | 256, cg % 4 == 0.
183
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
184
+ void gn_partial4(__global const float* x, const int HW, const int C, const int cg, const int cp,
185
+ __global const float* stats, const int pass, __global float* part, const int G) {
186
+ __local float red[256];
187
+ const int chunk = get_group_id(0), l = get_local_id(0), nchunk = get_num_groups(0);
188
+ const int C4 = C >> 2, q4 = cg >> 2, R = 256 / C4;
189
+ const int c4 = l % C4, r = l / C4;
190
+ const float mean = pass ? stats[(c4 / q4) * 2] : 0.f;
191
+ const int p0 = chunk * cp, pend = min(p0 + cp, HW);
192
+ float4 s = 0;
193
+ for (int pp = p0 + r; pp < pend; pp += R) {
194
+ const float4 v = vload4(c4, x + pp * C) - mean;
195
+ s += pass ? v * v : v;
196
+ }
197
+ red[l] = (s.x + s.y) + (s.z + s.w);
198
+ barrier(CLK_LOCAL_MEM_FENCE);
199
+ if (l < G) {
200
+ float t = 0;
201
+ for (int rr = 0; rr < R; ++rr)
202
+ for (int q = 0; q < q4; ++q) t += red[rr * C4 + l * q4 + q];
203
+ part[l * nchunk + chunk] = t;
204
+ }
205
+ }
206
+
207
+ // stats[g] = (mean, rstd) from the partials; pass 0 writes mean, pass 1 writes rstd. grid (256, G)
208
+ __kernel __attribute__((reqd_work_group_size(256, 1, 1)))
209
+ void gn_final(__global const float* part, const int nchunk, const float count, const float eps, const int pass,
210
+ __global float* stats) {
211
+ __local float red[256];
212
+ const int g = get_group_id(1), l = get_local_id(0);
213
+ float s = 0;
214
+ for (int i = l; i < nchunk; i += 256) s += part[g * nchunk + i];
215
+ s = wg_sum256(s, red);
216
+ if (l == 0) {
217
+ if (pass == 0) stats[g * 2] = s / count;
218
+ else stats[g * 2 + 1] = rsqrt(s / count + eps);
219
+ }
220
+ }
221
+
222
+ // out = (x - mean) * rstd * gamma + beta, optional SiLU; grid (C, HW)
223
+ __kernel void gn_apply(__global const float* x, __global float* out, const int C, const int cg,
224
+ __global const float* stats, __global const float* gamma, __global const float* beta,
225
+ const int act) {
226
+ const int c = get_global_id(0), p = get_global_id(1);
227
+ if (c >= C) return;
228
+ const int g = c / cg;
229
+ float v = (x[p * C + c] - stats[g * 2]) * stats[g * 2 + 1] * gamma[c] + beta[c];
230
+ if (act) v = v / (1.f + exp(-v));
231
+ out[p * C + c] = v;
232
+ }
233
+
234
+ // dst[r][c] = src[r][c] for a rows x cols block; grid (cols, rows)
235
+ __kernel void copy2d(__global const float* src, const int soff, const int lds, __global float* dst, const int doff,
236
+ const int ldd, const int cols) {
237
+ const int c = get_global_id(0), r = get_global_id(1);
238
+ if (c < cols) dst[doff + r * ldd + c] = src[soff + r * lds + c];
239
+ }
240
+
241
+ // dense fp32 rows -> RGBA float image [rows][K4] (A operand of the image-path GEMM)
242
+ __kernel void to_image(__global const float* src, const int off, const int ld, const int K4, __write_only image2d_t dst) {
243
+ const int c = get_global_id(0), r = get_global_id(1);
244
+ if (c < K4) write_imagef(dst, (int2)(c, r), vload4(0, src + off + r * ld + c * 4));
245
+ }
246
+
247
+ // NHWC fp32 [H][W][Cin] -> RGBA float image, texel (x, y*C4 + c4) (A operand of the image-path conv GEMM)
248
+ __kernel void to_image_conv(__global const float* src, const int C4, const int logW, __write_only image2d_t dst) {
249
+ const int c4 = get_global_id(0), p = get_global_id(1);
250
+ if (c4 < C4) write_imagef(dst, (int2)(p & ((1 << logW) - 1), (p >> logW) * C4 + c4), vload4(p * C4 + c4, src));
251
+ }
252
+
253
+ // fused qkv rows [S][ld] (q | k | v, each nh x 128) -> [3][nh][S][128]
254
+ __kernel void split_heads(__global const float* src, const int ld, __global float* dst, const int S, const int nh,
255
+ const int D) {
256
+ const int d4 = get_global_id(0), s = get_global_id(1), wh = get_global_id(2); // wh = which * nh + head
257
+ const int which = wh / nh, h = wh - which * nh;
258
+ vstore4(vload4(0, src + s * ld + which * D + h * 128 + d4 * 4), 0, dst + (wh * S + s) * 128 + d4 * 4);
259
+ }
sm8850-gpu-ternary/build/weights/.stamp ADDED
@@ -0,0 +1 @@
 
 
1
+ 809cc2e7232d7b0f
sm8850-gpu-ternary/build/weights/dit.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1
3
+ size 1367734272
sm8850-gpu-ternary/build/weights/dit.idx ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ context_embedder bf16 0 47185920
2
+ double_stream_modulation_img.linear bf16 47185920 113246208
3
+ double_stream_modulation_txt.linear bf16 160432128 113246208
4
+ norm_out.linear bf16 273678336 37748736
5
+ proj_out bf16 311427072 786432
6
+ single_stream_modulation.linear bf16 312213504 56623104
7
+ time_guidance_embed.timestep_embedder.linear_1 bf16 368836608 1572864
8
+ time_guidance_embed.timestep_embedder.linear_2 bf16 370409472 18874368
9
+ x_embedder bf16 389283840 786432
10
+ d0.qkv tern 390070272 7077888
11
+ d0.qkv.s bf16 397148160 442368
12
+ d0.add_qkv tern 397590528 7077888
13
+ d0.add_qkv.s bf16 404668416 442368
14
+ d0.out tern 405110784 2359296
15
+ d0.out.s bf16 407470080 147456
16
+ d0.add_out tern 407617536 2359296
17
+ d0.add_out.s bf16 409976832 147456
18
+ d0.ff_in tern 410124288 14155776
19
+ d0.ff_in.s bf16 424280064 884736
20
+ d0.ff_out tern 425164800 7077888
21
+ d0.ff_out.s bf16 432242688 442368
22
+ d0.ffc_in tern 432685056 14155776
23
+ d0.ffc_in.s bf16 446840832 884736
24
+ d0.ffc_out tern 447725568 7077888
25
+ d0.ffc_out.s bf16 454803456 442368
26
+ d0.norm_q f32 455245824 512
27
+ d0.norm_k f32 455246336 512
28
+ d0.norm_added_q f32 455246848 512
29
+ d0.norm_added_k f32 455247360 512
30
+ d1.qkv tern 455247872 7077888
31
+ d1.qkv.s bf16 462325760 442368
32
+ d1.add_qkv tern 462768128 7077888
33
+ d1.add_qkv.s bf16 469846016 442368
34
+ d1.out tern 470288384 2359296
35
+ d1.out.s bf16 472647680 147456
36
+ d1.add_out tern 472795136 2359296
37
+ d1.add_out.s bf16 475154432 147456
38
+ d1.ff_in tern 475301888 14155776
39
+ d1.ff_in.s bf16 489457664 884736
40
+ d1.ff_out tern 490342400 7077888
41
+ d1.ff_out.s bf16 497420288 442368
42
+ d1.ffc_in tern 497862656 14155776
43
+ d1.ffc_in.s bf16 512018432 884736
44
+ d1.ffc_out tern 512903168 7077888
45
+ d1.ffc_out.s bf16 519981056 442368
46
+ d1.norm_q f32 520423424 512
47
+ d1.norm_k f32 520423936 512
48
+ d1.norm_added_q f32 520424448 512
49
+ d1.norm_added_k f32 520424960 512
50
+ d2.qkv tern 520425472 7077888
51
+ d2.qkv.s bf16 527503360 442368
52
+ d2.add_qkv tern 527945728 7077888
53
+ d2.add_qkv.s bf16 535023616 442368
54
+ d2.out tern 535465984 2359296
55
+ d2.out.s bf16 537825280 147456
56
+ d2.add_out tern 537972736 2359296
57
+ d2.add_out.s bf16 540332032 147456
58
+ d2.ff_in tern 540479488 14155776
59
+ d2.ff_in.s bf16 554635264 884736
60
+ d2.ff_out tern 555520000 7077888
61
+ d2.ff_out.s bf16 562597888 442368
62
+ d2.ffc_in tern 563040256 14155776
63
+ d2.ffc_in.s bf16 577196032 884736
64
+ d2.ffc_out tern 578080768 7077888
65
+ d2.ffc_out.s bf16 585158656 442368
66
+ d2.norm_q f32 585601024 512
67
+ d2.norm_k f32 585601536 512
68
+ d2.norm_added_q f32 585602048 512
69
+ d2.norm_added_k f32 585602560 512
70
+ d3.qkv tern 585603072 7077888
71
+ d3.qkv.s bf16 592680960 442368
72
+ d3.add_qkv tern 593123328 7077888
73
+ d3.add_qkv.s bf16 600201216 442368
74
+ d3.out tern 600643584 2359296
75
+ d3.out.s bf16 603002880 147456
76
+ d3.add_out tern 603150336 2359296
77
+ d3.add_out.s bf16 605509632 147456
78
+ d3.ff_in tern 605657088 14155776
79
+ d3.ff_in.s bf16 619812864 884736
80
+ d3.ff_out tern 620697600 7077888
81
+ d3.ff_out.s bf16 627775488 442368
82
+ d3.ffc_in tern 628217856 14155776
83
+ d3.ffc_in.s bf16 642373632 884736
84
+ d3.ffc_out tern 643258368 7077888
85
+ d3.ffc_out.s bf16 650336256 442368
86
+ d3.norm_q f32 650778624 512
87
+ d3.norm_k f32 650779136 512
88
+ d3.norm_added_q f32 650779648 512
89
+ d3.norm_added_k f32 650780160 512
90
+ d4.qkv tern 650780672 7077888
91
+ d4.qkv.s bf16 657858560 442368
92
+ d4.add_qkv tern 658300928 7077888
93
+ d4.add_qkv.s bf16 665378816 442368
94
+ d4.out tern 665821184 2359296
95
+ d4.out.s bf16 668180480 147456
96
+ d4.add_out tern 668327936 2359296
97
+ d4.add_out.s bf16 670687232 147456
98
+ d4.ff_in tern 670834688 14155776
99
+ d4.ff_in.s bf16 684990464 884736
100
+ d4.ff_out tern 685875200 7077888
101
+ d4.ff_out.s bf16 692953088 442368
102
+ d4.ffc_in tern 693395456 14155776
103
+ d4.ffc_in.s bf16 707551232 884736
104
+ d4.ffc_out tern 708435968 7077888
105
+ d4.ffc_out.s bf16 715513856 442368
106
+ d4.norm_q f32 715956224 512
107
+ d4.norm_k f32 715956736 512
108
+ d4.norm_added_q f32 715957248 512
109
+ d4.norm_added_k f32 715957760 512
110
+ s0.qkv_mlp tern 715958272 21233664
111
+ s0.qkv_mlp.s bf16 737191936 1327104
112
+ s0.out tern 738519040 9437184
113
+ s0.out.s bf16 747956224 589824
114
+ s0.norm_q f32 748546048 512
115
+ s0.norm_k f32 748546560 512
116
+ s1.qkv_mlp tern 748547072 21233664
117
+ s1.qkv_mlp.s bf16 769780736 1327104
118
+ s1.out tern 771107840 9437184
119
+ s1.out.s bf16 780545024 589824
120
+ s1.norm_q f32 781134848 512
121
+ s1.norm_k f32 781135360 512
122
+ s2.qkv_mlp tern 781135872 21233664
123
+ s2.qkv_mlp.s bf16 802369536 1327104
124
+ s2.out tern 803696640 9437184
125
+ s2.out.s bf16 813133824 589824
126
+ s2.norm_q f32 813723648 512
127
+ s2.norm_k f32 813724160 512
128
+ s3.qkv_mlp tern 813724672 21233664
129
+ s3.qkv_mlp.s bf16 834958336 1327104
130
+ s3.out tern 836285440 9437184
131
+ s3.out.s bf16 845722624 589824
132
+ s3.norm_q f32 846312448 512
133
+ s3.norm_k f32 846312960 512
134
+ s4.qkv_mlp tern 846313472 21233664
135
+ s4.qkv_mlp.s bf16 867547136 1327104
136
+ s4.out tern 868874240 9437184
137
+ s4.out.s bf16 878311424 589824
138
+ s4.norm_q f32 878901248 512
139
+ s4.norm_k f32 878901760 512
140
+ s5.qkv_mlp tern 878902272 21233664
141
+ s5.qkv_mlp.s bf16 900135936 1327104
142
+ s5.out tern 901463040 9437184
143
+ s5.out.s bf16 910900224 589824
144
+ s5.norm_q f32 911490048 512
145
+ s5.norm_k f32 911490560 512
146
+ s6.qkv_mlp tern 911491072 21233664
147
+ s6.qkv_mlp.s bf16 932724736 1327104
148
+ s6.out tern 934051840 9437184
149
+ s6.out.s bf16 943489024 589824
150
+ s6.norm_q f32 944078848 512
151
+ s6.norm_k f32 944079360 512
152
+ s7.qkv_mlp tern 944079872 21233664
153
+ s7.qkv_mlp.s bf16 965313536 1327104
154
+ s7.out tern 966640640 9437184
155
+ s7.out.s bf16 976077824 589824
156
+ s7.norm_q f32 976667648 512
157
+ s7.norm_k f32 976668160 512
158
+ s8.qkv_mlp tern 976668672 21233664
159
+ s8.qkv_mlp.s bf16 997902336 1327104
160
+ s8.out tern 999229440 9437184
161
+ s8.out.s bf16 1008666624 589824
162
+ s8.norm_q f32 1009256448 512
163
+ s8.norm_k f32 1009256960 512
164
+ s9.qkv_mlp tern 1009257472 21233664
165
+ s9.qkv_mlp.s bf16 1030491136 1327104
166
+ s9.out tern 1031818240 9437184
167
+ s9.out.s bf16 1041255424 589824
168
+ s9.norm_q f32 1041845248 512
169
+ s9.norm_k f32 1041845760 512
170
+ s10.qkv_mlp tern 1041846272 21233664
171
+ s10.qkv_mlp.s bf16 1063079936 1327104
172
+ s10.out tern 1064407040 9437184
173
+ s10.out.s bf16 1073844224 589824
174
+ s10.norm_q f32 1074434048 512
175
+ s10.norm_k f32 1074434560 512
176
+ s11.qkv_mlp tern 1074435072 21233664
177
+ s11.qkv_mlp.s bf16 1095668736 1327104
178
+ s11.out tern 1096995840 9437184
179
+ s11.out.s bf16 1106433024 589824
180
+ s11.norm_q f32 1107022848 512
181
+ s11.norm_k f32 1107023360 512
182
+ s12.qkv_mlp tern 1107023872 21233664
183
+ s12.qkv_mlp.s bf16 1128257536 1327104
184
+ s12.out tern 1129584640 9437184
185
+ s12.out.s bf16 1139021824 589824
186
+ s12.norm_q f32 1139611648 512
187
+ s12.norm_k f32 1139612160 512
188
+ s13.qkv_mlp tern 1139612672 21233664
189
+ s13.qkv_mlp.s bf16 1160846336 1327104
190
+ s13.out tern 1162173440 9437184
191
+ s13.out.s bf16 1171610624 589824
192
+ s13.norm_q f32 1172200448 512
193
+ s13.norm_k f32 1172200960 512
194
+ s14.qkv_mlp tern 1172201472 21233664
195
+ s14.qkv_mlp.s bf16 1193435136 1327104
196
+ s14.out tern 1194762240 9437184
197
+ s14.out.s bf16 1204199424 589824
198
+ s14.norm_q f32 1204789248 512
199
+ s14.norm_k f32 1204789760 512
200
+ s15.qkv_mlp tern 1204790272 21233664
201
+ s15.qkv_mlp.s bf16 1226023936 1327104
202
+ s15.out tern 1227351040 9437184
203
+ s15.out.s bf16 1236788224 589824
204
+ s15.norm_q f32 1237378048 512
205
+ s15.norm_k f32 1237378560 512
206
+ s16.qkv_mlp tern 1237379072 21233664
207
+ s16.qkv_mlp.s bf16 1258612736 1327104
208
+ s16.out tern 1259939840 9437184
209
+ s16.out.s bf16 1269377024 589824
210
+ s16.norm_q f32 1269966848 512
211
+ s16.norm_k f32 1269967360 512
212
+ s17.qkv_mlp tern 1269967872 21233664
213
+ s17.qkv_mlp.s bf16 1291201536 1327104
214
+ s17.out tern 1292528640 9437184
215
+ s17.out.s bf16 1301965824 589824
216
+ s17.norm_q f32 1302555648 512
217
+ s17.norm_k f32 1302556160 512
218
+ s18.qkv_mlp tern 1302556672 21233664
219
+ s18.qkv_mlp.s bf16 1323790336 1327104
220
+ s18.out tern 1325117440 9437184
221
+ s18.out.s bf16 1334554624 589824
222
+ s18.norm_q f32 1335144448 512
223
+ s18.norm_k f32 1335144960 512
224
+ s19.qkv_mlp tern 1335145472 21233664
225
+ s19.qkv_mlp.s bf16 1356379136 1327104
226
+ s19.out tern 1357706240 9437184
227
+ s19.out.s bf16 1367143424 589824
228
+ s19.norm_q f32 1367733248 512
229
+ s19.norm_k f32 1367733760 512
sm8850-gpu-ternary/build/weights/te.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4
3
+ size 6228466688
sm8850-gpu-ternary/build/weights/te.idx ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ embed bf16 0 777912320
2
+ l0.qkv bf16 777912320 31457280
3
+ l0.o bf16 809369600 20971520
4
+ l0.gu bf16 830341120 99614720
5
+ l0.down bf16 929955840 49807360
6
+ l0.ln1 f32 979763200 10240
7
+ l0.ln2 f32 979773440 10240
8
+ l0.qn f32 979783680 512
9
+ l0.kn f32 979784192 512
10
+ l1.qkv bf16 979784704 31457280
11
+ l1.o bf16 1011241984 20971520
12
+ l1.gu bf16 1032213504 99614720
13
+ l1.down bf16 1131828224 49807360
14
+ l1.ln1 f32 1181635584 10240
15
+ l1.ln2 f32 1181645824 10240
16
+ l1.qn f32 1181656064 512
17
+ l1.kn f32 1181656576 512
18
+ l2.qkv bf16 1181657088 31457280
19
+ l2.o bf16 1213114368 20971520
20
+ l2.gu bf16 1234085888 99614720
21
+ l2.down bf16 1333700608 49807360
22
+ l2.ln1 f32 1383507968 10240
23
+ l2.ln2 f32 1383518208 10240
24
+ l2.qn f32 1383528448 512
25
+ l2.kn f32 1383528960 512
26
+ l3.qkv bf16 1383529472 31457280
27
+ l3.o bf16 1414986752 20971520
28
+ l3.gu bf16 1435958272 99614720
29
+ l3.down bf16 1535572992 49807360
30
+ l3.ln1 f32 1585380352 10240
31
+ l3.ln2 f32 1585390592 10240
32
+ l3.qn f32 1585400832 512
33
+ l3.kn f32 1585401344 512
34
+ l4.qkv bf16 1585401856 31457280
35
+ l4.o bf16 1616859136 20971520
36
+ l4.gu bf16 1637830656 99614720
37
+ l4.down bf16 1737445376 49807360
38
+ l4.ln1 f32 1787252736 10240
39
+ l4.ln2 f32 1787262976 10240
40
+ l4.qn f32 1787273216 512
41
+ l4.kn f32 1787273728 512
42
+ l5.qkv bf16 1787274240 31457280
43
+ l5.o bf16 1818731520 20971520
44
+ l5.gu bf16 1839703040 99614720
45
+ l5.down bf16 1939317760 49807360
46
+ l5.ln1 f32 1989125120 10240
47
+ l5.ln2 f32 1989135360 10240
48
+ l5.qn f32 1989145600 512
49
+ l5.kn f32 1989146112 512
50
+ l6.qkv bf16 1989146624 31457280
51
+ l6.o bf16 2020603904 20971520
52
+ l6.gu bf16 2041575424 99614720
53
+ l6.down bf16 2141190144 49807360
54
+ l6.ln1 f32 2190997504 10240
55
+ l6.ln2 f32 2191007744 10240
56
+ l6.qn f32 2191017984 512
57
+ l6.kn f32 2191018496 512
58
+ l7.qkv bf16 2191019008 31457280
59
+ l7.o bf16 2222476288 20971520
60
+ l7.gu bf16 2243447808 99614720
61
+ l7.down bf16 2343062528 49807360
62
+ l7.ln1 f32 2392869888 10240
63
+ l7.ln2 f32 2392880128 10240
64
+ l7.qn f32 2392890368 512
65
+ l7.kn f32 2392890880 512
66
+ l8.qkv bf16 2392891392 31457280
67
+ l8.o bf16 2424348672 20971520
68
+ l8.gu bf16 2445320192 99614720
69
+ l8.down bf16 2544934912 49807360
70
+ l8.ln1 f32 2594742272 10240
71
+ l8.ln2 f32 2594752512 10240
72
+ l8.qn f32 2594762752 512
73
+ l8.kn f32 2594763264 512
74
+ l9.qkv bf16 2594763776 31457280
75
+ l9.o bf16 2626221056 20971520
76
+ l9.gu bf16 2647192576 99614720
77
+ l9.down bf16 2746807296 49807360
78
+ l9.ln1 f32 2796614656 10240
79
+ l9.ln2 f32 2796624896 10240
80
+ l9.qn f32 2796635136 512
81
+ l9.kn f32 2796635648 512
82
+ l10.qkv bf16 2796636160 31457280
83
+ l10.o bf16 2828093440 20971520
84
+ l10.gu bf16 2849064960 99614720
85
+ l10.down bf16 2948679680 49807360
86
+ l10.ln1 f32 2998487040 10240
87
+ l10.ln2 f32 2998497280 10240
88
+ l10.qn f32 2998507520 512
89
+ l10.kn f32 2998508032 512
90
+ l11.qkv bf16 2998508544 31457280
91
+ l11.o bf16 3029965824 20971520
92
+ l11.gu bf16 3050937344 99614720
93
+ l11.down bf16 3150552064 49807360
94
+ l11.ln1 f32 3200359424 10240
95
+ l11.ln2 f32 3200369664 10240
96
+ l11.qn f32 3200379904 512
97
+ l11.kn f32 3200380416 512
98
+ l12.qkv bf16 3200380928 31457280
99
+ l12.o bf16 3231838208 20971520
100
+ l12.gu bf16 3252809728 99614720
101
+ l12.down bf16 3352424448 49807360
102
+ l12.ln1 f32 3402231808 10240
103
+ l12.ln2 f32 3402242048 10240
104
+ l12.qn f32 3402252288 512
105
+ l12.kn f32 3402252800 512
106
+ l13.qkv bf16 3402253312 31457280
107
+ l13.o bf16 3433710592 20971520
108
+ l13.gu bf16 3454682112 99614720
109
+ l13.down bf16 3554296832 49807360
110
+ l13.ln1 f32 3604104192 10240
111
+ l13.ln2 f32 3604114432 10240
112
+ l13.qn f32 3604124672 512
113
+ l13.kn f32 3604125184 512
114
+ l14.qkv bf16 3604125696 31457280
115
+ l14.o bf16 3635582976 20971520
116
+ l14.gu bf16 3656554496 99614720
117
+ l14.down bf16 3756169216 49807360
118
+ l14.ln1 f32 3805976576 10240
119
+ l14.ln2 f32 3805986816 10240
120
+ l14.qn f32 3805997056 512
121
+ l14.kn f32 3805997568 512
122
+ l15.qkv bf16 3805998080 31457280
123
+ l15.o bf16 3837455360 20971520
124
+ l15.gu bf16 3858426880 99614720
125
+ l15.down bf16 3958041600 49807360
126
+ l15.ln1 f32 4007848960 10240
127
+ l15.ln2 f32 4007859200 10240
128
+ l15.qn f32 4007869440 512
129
+ l15.kn f32 4007869952 512
130
+ l16.qkv bf16 4007870464 31457280
131
+ l16.o bf16 4039327744 20971520
132
+ l16.gu bf16 4060299264 99614720
133
+ l16.down bf16 4159913984 49807360
134
+ l16.ln1 f32 4209721344 10240
135
+ l16.ln2 f32 4209731584 10240
136
+ l16.qn f32 4209741824 512
137
+ l16.kn f32 4209742336 512
138
+ l17.qkv bf16 4209742848 31457280
139
+ l17.o bf16 4241200128 20971520
140
+ l17.gu bf16 4262171648 99614720
141
+ l17.down bf16 4361786368 49807360
142
+ l17.ln1 f32 4411593728 10240
143
+ l17.ln2 f32 4411603968 10240
144
+ l17.qn f32 4411614208 512
145
+ l17.kn f32 4411614720 512
146
+ l18.qkv bf16 4411615232 31457280
147
+ l18.o bf16 4443072512 20971520
148
+ l18.gu bf16 4464044032 99614720
149
+ l18.down bf16 4563658752 49807360
150
+ l18.ln1 f32 4613466112 10240
151
+ l18.ln2 f32 4613476352 10240
152
+ l18.qn f32 4613486592 512
153
+ l18.kn f32 4613487104 512
154
+ l19.qkv bf16 4613487616 31457280
155
+ l19.o bf16 4644944896 20971520
156
+ l19.gu bf16 4665916416 99614720
157
+ l19.down bf16 4765531136 49807360
158
+ l19.ln1 f32 4815338496 10240
159
+ l19.ln2 f32 4815348736 10240
160
+ l19.qn f32 4815358976 512
161
+ l19.kn f32 4815359488 512
162
+ l20.qkv bf16 4815360000 31457280
163
+ l20.o bf16 4846817280 20971520
164
+ l20.gu bf16 4867788800 99614720
165
+ l20.down bf16 4967403520 49807360
166
+ l20.ln1 f32 5017210880 10240
167
+ l20.ln2 f32 5017221120 10240
168
+ l20.qn f32 5017231360 512
169
+ l20.kn f32 5017231872 512
170
+ l21.qkv bf16 5017232384 31457280
171
+ l21.o bf16 5048689664 20971520
172
+ l21.gu bf16 5069661184 99614720
173
+ l21.down bf16 5169275904 49807360
174
+ l21.ln1 f32 5219083264 10240
175
+ l21.ln2 f32 5219093504 10240
176
+ l21.qn f32 5219103744 512
177
+ l21.kn f32 5219104256 512
178
+ l22.qkv bf16 5219104768 31457280
179
+ l22.o bf16 5250562048 20971520
180
+ l22.gu bf16 5271533568 99614720
181
+ l22.down bf16 5371148288 49807360
182
+ l22.ln1 f32 5420955648 10240
183
+ l22.ln2 f32 5420965888 10240
184
+ l22.qn f32 5420976128 512
185
+ l22.kn f32 5420976640 512
186
+ l23.qkv bf16 5420977152 31457280
187
+ l23.o bf16 5452434432 20971520
188
+ l23.gu bf16 5473405952 99614720
189
+ l23.down bf16 5573020672 49807360
190
+ l23.ln1 f32 5622828032 10240
191
+ l23.ln2 f32 5622838272 10240
192
+ l23.qn f32 5622848512 512
193
+ l23.kn f32 5622849024 512
194
+ l24.qkv bf16 5622849536 31457280
195
+ l24.o bf16 5654306816 20971520
196
+ l24.gu bf16 5675278336 99614720
197
+ l24.down bf16 5774893056 49807360
198
+ l24.ln1 f32 5824700416 10240
199
+ l24.ln2 f32 5824710656 10240
200
+ l24.qn f32 5824720896 512
201
+ l24.kn f32 5824721408 512
202
+ l25.qkv bf16 5824721920 31457280
203
+ l25.o bf16 5856179200 20971520
204
+ l25.gu bf16 5877150720 99614720
205
+ l25.down bf16 5976765440 49807360
206
+ l25.ln1 f32 6026572800 10240
207
+ l25.ln2 f32 6026583040 10240
208
+ l25.qn f32 6026593280 512
209
+ l25.kn f32 6026593792 512
210
+ l26.qkv bf16 6026594304 31457280
211
+ l26.o bf16 6058051584 20971520
212
+ l26.gu bf16 6079023104 99614720
213
+ l26.down bf16 6178637824 49807360
214
+ l26.ln1 f32 6228445184 10240
215
+ l26.ln2 f32 6228455424 10240
216
+ l26.qn f32 6228465664 512
217
+ l26.kn f32 6228466176 512
sm8850-gpu-ternary/build/weights/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
sm8850-gpu-ternary/build/weights/vae.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5
3
+ size 99317260
sm8850-gpu-ternary/build/weights/vae.idx ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ bn.mean f32 0 512
2
+ bn.var f32 512 512
3
+ pqc bf16 1024 2048
4
+ pqc.b f32 3072 128
5
+ conv_in bf16 3328 294912
6
+ conv_in.b f32 298240 2048
7
+ mid.r0.n1.g f32 300288 2048
8
+ mid.r0.n1.b f32 302336 2048
9
+ mid.r0.c1 bf16 304384 4718592
10
+ mid.r0.c1.b f32 5022976 2048
11
+ mid.r0.n2.g f32 5025024 2048
12
+ mid.r0.n2.b f32 5027072 2048
13
+ mid.r0.c2 bf16 5029120 4718592
14
+ mid.r0.c2.b f32 9747712 2048
15
+ mid.attn.gn.g f32 9749760 2048
16
+ mid.attn.gn.b f32 9751808 2048
17
+ mid.attn.qkv bf16 9753856 1572864
18
+ mid.attn.qkv.b f32 11326720 6144
19
+ mid.attn.out bf16 11332864 524288
20
+ mid.attn.out.b f32 11857152 2048
21
+ mid.r1.n1.g f32 11859200 2048
22
+ mid.r1.n1.b f32 11861248 2048
23
+ mid.r1.c1 bf16 11863296 4718592
24
+ mid.r1.c1.b f32 16581888 2048
25
+ mid.r1.n2.g f32 16583936 2048
26
+ mid.r1.n2.b f32 16585984 2048
27
+ mid.r1.c2 bf16 16588032 4718592
28
+ mid.r1.c2.b f32 21306624 2048
29
+ up0.r0.n1.g f32 21308672 2048
30
+ up0.r0.n1.b f32 21310720 2048
31
+ up0.r0.c1 bf16 21312768 4718592
32
+ up0.r0.c1.b f32 26031360 2048
33
+ up0.r0.n2.g f32 26033408 2048
34
+ up0.r0.n2.b f32 26035456 2048
35
+ up0.r0.c2 bf16 26037504 4718592
36
+ up0.r0.c2.b f32 30756096 2048
37
+ up0.r1.n1.g f32 30758144 2048
38
+ up0.r1.n1.b f32 30760192 2048
39
+ up0.r1.c1 bf16 30762240 4718592
40
+ up0.r1.c1.b f32 35480832 2048
41
+ up0.r1.n2.g f32 35482880 2048
42
+ up0.r1.n2.b f32 35484928 2048
43
+ up0.r1.c2 bf16 35486976 4718592
44
+ up0.r1.c2.b f32 40205568 2048
45
+ up0.r2.n1.g f32 40207616 2048
46
+ up0.r2.n1.b f32 40209664 2048
47
+ up0.r2.c1 bf16 40211712 4718592
48
+ up0.r2.c1.b f32 44930304 2048
49
+ up0.r2.n2.g f32 44932352 2048
50
+ up0.r2.n2.b f32 44934400 2048
51
+ up0.r2.c2 bf16 44936448 4718592
52
+ up0.r2.c2.b f32 49655040 2048
53
+ up0.us bf16 49657088 4718592
54
+ up0.us.b f32 54375680 2048
55
+ up1.r0.n1.g f32 54377728 2048
56
+ up1.r0.n1.b f32 54379776 2048
57
+ up1.r0.c1 bf16 54381824 4718592
58
+ up1.r0.c1.b f32 59100416 2048
59
+ up1.r0.n2.g f32 59102464 2048
60
+ up1.r0.n2.b f32 59104512 2048
61
+ up1.r0.c2 bf16 59106560 4718592
62
+ up1.r0.c2.b f32 63825152 2048
63
+ up1.r1.n1.g f32 63827200 2048
64
+ up1.r1.n1.b f32 63829248 2048
65
+ up1.r1.c1 bf16 63831296 4718592
66
+ up1.r1.c1.b f32 68549888 2048
67
+ up1.r1.n2.g f32 68551936 2048
68
+ up1.r1.n2.b f32 68553984 2048
69
+ up1.r1.c2 bf16 68556032 4718592
70
+ up1.r1.c2.b f32 73274624 2048
71
+ up1.r2.n1.g f32 73276672 2048
72
+ up1.r2.n1.b f32 73278720 2048
73
+ up1.r2.c1 bf16 73280768 4718592
74
+ up1.r2.c1.b f32 77999360 2048
75
+ up1.r2.n2.g f32 78001408 2048
76
+ up1.r2.n2.b f32 78003456 2048
77
+ up1.r2.c2 bf16 78005504 4718592
78
+ up1.r2.c2.b f32 82724096 2048
79
+ up1.us bf16 82726144 4718592
80
+ up1.us.b f32 87444736 2048
81
+ up2.r0.n1.g f32 87446784 2048
82
+ up2.r0.n1.b f32 87448832 2048
83
+ up2.r0.c1 bf16 87450880 2359296
84
+ up2.r0.c1.b f32 89810176 1024
85
+ up2.r0.n2.g f32 89811200 1024
86
+ up2.r0.n2.b f32 89812224 1024
87
+ up2.r0.c2 bf16 89813248 1179648
88
+ up2.r0.c2.b f32 90992896 1024
89
+ up2.r0.sc bf16 90993920 262144
90
+ up2.r0.sc.b f32 91256064 1024
91
+ up2.r1.n1.g f32 91257088 1024
92
+ up2.r1.n1.b f32 91258112 1024
93
+ up2.r1.c1 bf16 91259136 1179648
94
+ up2.r1.c1.b f32 92438784 1024
95
+ up2.r1.n2.g f32 92439808 1024
96
+ up2.r1.n2.b f32 92440832 1024
97
+ up2.r1.c2 bf16 92441856 1179648
98
+ up2.r1.c2.b f32 93621504 1024
99
+ up2.r2.n1.g f32 93622528 1024
100
+ up2.r2.n1.b f32 93623552 1024
101
+ up2.r2.c1 bf16 93624576 1179648
102
+ up2.r2.c1.b f32 94804224 1024
103
+ up2.r2.n2.g f32 94805248 1024
104
+ up2.r2.n2.b f32 94806272 1024
105
+ up2.r2.c2 bf16 94807296 1179648
106
+ up2.r2.c2.b f32 95986944 1024
107
+ up2.us bf16 95987968 1179648
108
+ up2.us.b f32 97167616 1024
109
+ up3.r0.n1.g f32 97168640 1024
110
+ up3.r0.n1.b f32 97169664 1024
111
+ up3.r0.c1 bf16 97170688 589824
112
+ up3.r0.c1.b f32 97760512 512
113
+ up3.r0.n2.g f32 97761024 512
114
+ up3.r0.n2.b f32 97761536 512
115
+ up3.r0.c2 bf16 97762048 294912
116
+ up3.r0.c2.b f32 98056960 512
117
+ up3.r0.sc bf16 98057472 65536
118
+ up3.r0.sc.b f32 98123008 512
119
+ up3.r1.n1.g f32 98123520 512
120
+ up3.r1.n1.b f32 98124032 512
121
+ up3.r1.c1 bf16 98124544 294912
122
+ up3.r1.c1.b f32 98419456 512
123
+ up3.r1.n2.g f32 98419968 512
124
+ up3.r1.n2.b f32 98420480 512
125
+ up3.r1.c2 bf16 98420992 294912
126
+ up3.r1.c2.b f32 98715904 512
127
+ up3.r2.n1.g f32 98716416 512
128
+ up3.r2.n1.b f32 98716928 512
129
+ up3.r2.c1 bf16 98717440 294912
130
+ up3.r2.c1.b f32 99012352 512
131
+ up3.r2.n2.g f32 99012864 512
132
+ up3.r2.n2.b f32 99013376 512
133
+ up3.r2.c2 bf16 99013888 294912
134
+ up3.r2.c2.b f32 99308800 512
135
+ norm_out.g f32 99309312 512
136
+ norm_out.b f32 99309824 512
137
+ conv_out bf16 99310336 6912
138
+ conv_out.b f32 99317248 12
sm8850-gpu-ternary/demo/demo.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input": {
3
+ "text": "A cat holding a sign that says hello world",
4
+ "files": []
5
+ },
6
+ "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",
7
+ "output": {
8
+ "text": "512x512 PNG, 4 steps, guidance 1, seed 0",
9
+ "files": [
10
+ "demo/phone0.png"
11
+ ]
12
+ },
13
+ "seconds": 52.6,
14
+ "device": "Samsung Galaxy S26+ (Adreno 840)",
15
+ "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\"",
16
+ "runs": [
17
+ {
18
+ "inputs": {
19
+ "text": "A cat holding a sign that says hello world"
20
+ },
21
+ "outputs": {
22
+ "image": "demo/phone0.png"
23
+ },
24
+ "reference": {
25
+ "image": "demo/original0.png"
26
+ },
27
+ "metrics": "demo/phone0_metrics.json"
28
+ },
29
+ {
30
+ "inputs": {
31
+ "text": "A red fox sitting in a snowy forest at sunrise"
32
+ },
33
+ "outputs": {
34
+ "image": "demo/phone1.png"
35
+ },
36
+ "reference": {
37
+ "image": "demo/original1.png"
38
+ },
39
+ "metrics": "demo/phone1_metrics.json"
40
+ },
41
+ {
42
+ "inputs": {
43
+ "text": "A cozy wooden cabin beside a mountain lake, watercolor painting"
44
+ },
45
+ "outputs": {
46
+ "image": "demo/phone2.png"
47
+ },
48
+ "reference": {
49
+ "image": "demo/original2.png"
50
+ },
51
+ "metrics": "demo/phone2_metrics.json"
52
+ }
53
+ ],
54
+ "reference_note": "original*.png: stock diffusers Flux2KleinPipeline, fp32 on the build host's CPU, same prompt, 512x512, 4 steps, guidance 1, seed 0"
55
+ }
sm8850-gpu-ternary/demo/original0.png ADDED

Git LFS Details

  • SHA256: 691b0eaac7a204687ccf4c135f37d20d71b2f3e0d1e1331d27c859e563662580
  • Pointer size: 131 Bytes
  • Size of remote file: 359 kB
sm8850-gpu-ternary/demo/original1.png ADDED

Git LFS Details

  • SHA256: 9172d66f3c784d9adf757986e6e6b369801f34510e8d9ff584a5845eeb06f8a4
  • Pointer size: 131 Bytes
  • Size of remote file: 449 kB
sm8850-gpu-ternary/demo/original2.png ADDED

Git LFS Details

  • SHA256: 5091faebb4301430f75ba259a857d892cfd46f9db6b36bb6d52499f247f5c99d
  • Pointer size: 131 Bytes
  • Size of remote file: 553 kB
sm8850-gpu-ternary/demo/phone0.png ADDED

Git LFS Details

  • SHA256: 4ce2181ec7735863b1ad56c993134fd0f22e26706d553f517029107333e72947
  • Pointer size: 131 Bytes
  • Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone0_metrics.json ADDED
@@ -0,0 +1 @@
 
 
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}
sm8850-gpu-ternary/demo/phone1.png ADDED

Git LFS Details

  • SHA256: fdaa8ddf8957e2c0219a0dd126b9f26505f2561966152acafcc556a4b5bada62
  • Pointer size: 131 Bytes
  • Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone1_metrics.json ADDED
@@ -0,0 +1 @@
 
 
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}
sm8850-gpu-ternary/demo/phone2.png ADDED

Git LFS Details

  • SHA256: 8239278e8347e0e4e3c2bb6e8d7abce2f4871150b4ed9a52295b13b3388b6ec4
  • Pointer size: 131 Bytes
  • Size of remote file: 787 kB
sm8850-gpu-ternary/demo/phone2_metrics.json ADDED
@@ -0,0 +1 @@
 
 
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}
sm8850-gpu-ternary/deploy.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # bash deploy.sh DEST: installs the program into DEST on the phone (adb) and the weight packs into
3
+ # /data/local/tmp/nnopt/bonsai_image_weights (listed in port.json external_files; pushed only when they changed).
4
+ set -euo pipefail
5
+ DEST=${1:?usage: deploy.sh DEST}
6
+ . "$(dirname "$0")/paths.sh"
7
+ cd "$ROOT"
8
+ WDEV=/data/local/tmp/nnopt/bonsai_image_weights
9
+ [ -x "$BUILD/bin/bonsai_image" ] || { echo "deploy.sh: run build.sh first" >&2; exit 1; }
10
+ [ -f "$BUILD/weights/.stamp" ] || { echo "deploy.sh: converted weights missing, run build.sh with INPUTS_DIR" >&2; exit 1; }
11
+ adb shell "mkdir -p '$DEST' '$WDEV'"
12
+ adb shell "rm -rf '$DEST/bin'" || true
13
+ adb push "$BUILD/bin" "$DEST/" > /dev/null
14
+ adb push run.sh port.json "$BUILD/weights/tokenizer.json" "$DEST/" > /dev/null
15
+ STAMP=$(cat "$BUILD/weights/.stamp")
16
+ if [ "$(adb shell "cat '$WDEV/.stamp' 2>/dev/null" | tr -d '\r' || true)" != "$STAMP" ]; then
17
+ adb shell "rm -f '$WDEV/.stamp'" || true
18
+ 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
19
+ adb push "$BUILD/weights/.stamp" "$WDEV/.stamp" > /dev/null
20
+ fi
21
+ adb shell "chmod 755 '$DEST/run.sh' '$DEST/bin/bonsai_image'"
22
+ echo "deploy.sh: installed into $DEST (weights in $WDEV)"
sm8850-gpu-ternary/fetch.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run once after downloading this folder: bash fetch.sh
3
+ # The converted weight packs are in build/weights/; this makes the runner executable.
4
+ set -euo pipefail
5
+ cd "$(dirname "$0")"
6
+ REPO=nnopt-dev/Bonsai-Image-Ternary-4B-OpenCL
7
+
8
+ # The repository's manifest first (Hugging Face counts a download when config.json is requested).
9
+ curl -fsSL "https://huggingface.co/$REPO/resolve/main/config.json" -o ../config.json
10
+
11
+ 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; }
12
+ get() { # get URL FILE SHA256: download once, check the sha256
13
+ if [ -f "$2" ] && [ "$(sha256_of "$2")" = "$3" ]; then return 0; fi
14
+ mkdir -p "$(dirname "$2")"
15
+ curl -fL --retry 3 -o "$2.part" "$1"
16
+ [ "$(sha256_of "$2.part")" = "$3" ] || { echo "fetch.sh: sha256 mismatch for $1" >&2; rm -f "$2.part"; exit 1; }
17
+ mv "$2.part" "$2"
18
+ }
19
+ git_at() { # git_at URL COMMIT DIR: the exact commit, shallow
20
+ if [ "$(git -C "$3" rev-parse HEAD 2>/dev/null || true)" = "$2" ]; then return 0; fi
21
+ rm -rf "$3"; mkdir -p "$3"
22
+ git -C "$3" init -q && git -C "$3" remote add origin "$1"
23
+ git -C "$3" fetch -q --depth 1 origin "$2" && git -C "$3" -c advice.detachedHead=false checkout -q FETCH_HEAD
24
+ }
25
+
26
+ chmod +x build/bin/bonsai_image
27
+ echo "fetch.sh: done. Next: bash deploy.sh /data/local/tmp/nnopt/port"
sm8850-gpu-ternary/paths.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sourced by build.sh and deploy.sh: where .deps/ and build/ live. Next to this file when it is writable, else under
2
+ # $HOME/.cache/bonsai-image-ocl/<hash of this folder's path> (a read-only checkout or a shared copy).
3
+ ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
4
+ if [ -w "$ROOT" ]; then
5
+ WORK=$ROOT
6
+ else
7
+ H=$(printf '%s' "$ROOT" | python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest()[:12])')
8
+ WORK=$HOME/.cache/bonsai-image-ocl/$H
9
+ fi
10
+ DEPS=$WORK/.deps
11
+ BUILD=$WORK/build
sm8850-gpu-ternary/port.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {"contract": 1, "model_type": "kernel",
2
+ "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)",
3
+ "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",
4
+ "external_files": ["/data/local/tmp/nnopt/bonsai_image_weights/te.bin", "/data/local/tmp/nnopt/bonsai_image_weights/te.idx",
5
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin", "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx",
6
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin", "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx"],
7
+ "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"}}
sm8850-gpu-ternary/report.html ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>nnopt report · prism-ml/bonsai-image-ternary-4B-unpacked</title>
4
+ <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
5
+ <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">
6
+ <style>
7
+ :root {
8
+ --bg: #f3f5f2; --panel: #ffffff; --ink: #17201d; --ink-2: #33403b; --muted: #5a6762; --line: #cfd8d3;
9
+ --accent: #0b6e79; --accent-soft: #dcefee; --keep: #1d7a3e; --keep-soft: #dcf1e2; --stop: #b3261e;
10
+ --stop-soft: #f9dedb; --warn: #9a5b00; --warn-soft: #fbecd2; --grid: #e3e9e5;
11
+ --display: "IBM Plex Sans Condensed", "Arial Narrow", system-ui, sans-serif;
12
+ --body: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
13
+ --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace;
14
+ color-scheme: light;
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root:not([data-theme="light"]) {
18
+ --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833;
19
+ --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80;
20
+ --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark;
21
+ }
22
+ }
23
+ :root[data-theme="dark"] {
24
+ --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833;
25
+ --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80;
26
+ --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark;
27
+ }
28
+ * { box-sizing: border-box; }
29
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--body); }
30
+ .wrap { max-width: 1040px; margin: 0 auto; padding: 28px 20px 80px; display: grid; gap: 36px; }
31
+ h1, h2, h3 { font-family: var(--display); margin: 0; line-height: 1.15; text-wrap: balance; }
32
+ h1 { font-size: clamp(28px, 4.5vw, 40px); font-weight: 700; letter-spacing: -0.01em; }
33
+ h2 { font-size: 22px; font-weight: 600; }
34
+ h3 { font-size: 16px; font-weight: 600; }
35
+ p { margin: 0; max-width: 72ch; }
36
+ code, .mono { font-family: var(--mono); font-size: 0.88em; }
37
+ .eyebrow { font: 500 12px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }
38
+ .sub { color: var(--muted); font-size: 13px; }
39
+ section { display: grid; gap: 14px; min-width: 0; }
40
+ header { display: grid; gap: 10px; }
41
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
42
+ .tile { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; display: grid; gap: 4px; min-width: 0; }
43
+ .tile .v { font: 700 26px/1.1 var(--display); font-variant-numeric: tabular-nums; }
44
+ .tile .k { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
45
+ .tile.pass { border-color: var(--keep); background: var(--keep-soft); }
46
+ .tile.fail { border-color: var(--stop); background: var(--stop-soft); }
47
+ .tile.na { border-style: dashed; }
48
+ .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; }
49
+ .badge.pass { color: var(--keep); } .badge.fail { color: var(--stop); } .badge.skip { color: var(--muted); } .badge.warn { color: var(--warn); }
50
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 4px 0; overflow-x: auto; }
51
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
52
+ th, td { text-align: left; padding: 8px 14px; border-bottom: 1px solid var(--line); vertical-align: top; }
53
+ tr:last-child td { border-bottom: 0; }
54
+ th { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
55
+ td.num { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
56
+ .flags { display: grid; gap: 6px; }
57
+ .flag { border-left: 3px solid var(--warn); background: var(--warn-soft); padding: 8px 12px; border-radius: 4px; font-size: 14px; }
58
+ .flag.bad { border-color: var(--stop); background: var(--stop-soft); }
59
+ .charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 12px; }
60
+ .chart { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px 8px; display: grid; gap: 6px; min-width: 0; }
61
+ .chart svg { width: 100%; height: auto; display: block; overflow: visible; }
62
+ .chart .ln { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
63
+ .chart .pt { fill: var(--accent); stroke: var(--panel); stroke-width: 2; }
64
+ .chart .hit { fill: transparent; }
65
+ .chart .hit:hover + .pt, .chart .pt:hover { r: 5; }
66
+ .chart .gl { stroke: var(--grid); stroke-width: 1; }
67
+ .chart text { fill: var(--muted); font: 11px var(--mono); }
68
+ details { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 14px; }
69
+ summary { cursor: pointer; font-weight: 500; }
70
+ pre { font: 12px/1.5 var(--mono); white-space: pre-wrap; word-break: break-word; margin: 10px 0 0; color: var(--ink-2); }
71
+ .kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; font-size: 14px; }
72
+ .kv dt { color: var(--muted); font: 500 12px/1.9 var(--mono); text-transform: uppercase; letter-spacing: .05em; }
73
+ .kv dd { margin: 0; font-family: var(--mono); font-size: 13px; word-break: break-all; }
74
+ footer { color: var(--muted); font-size: 12px; }
75
+ .figs { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
76
+ figure { margin: 0; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px; display: grid; gap: 8px; min-width: 0; }
77
+ figure svg { width: 100%; height: auto; display: block; border-radius: 4px; }
78
+ figure .frame { fill: var(--grid); }
79
+ figcaption { font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }
80
+ .box { fill: none; stroke-width: 2; vector-effect: non-scaling-stroke; }
81
+ .box.ref { stroke: var(--ink); stroke-dasharray: 6 4; }
82
+ .box.ref.missed { stroke: var(--stop); stroke-width: 3; }
83
+ .box.port { stroke: var(--accent); }
84
+ .box.port.extra { stroke: var(--warn); stroke-width: 3; }
85
+ .box.borderline { stroke: var(--muted); stroke-width: 1; opacity: .7; }
86
+ .legend { display: flex; flex-wrap: wrap; gap: 6px 18px; font: 12px var(--mono); color: var(--muted); }
87
+ .legend i { display: inline-block; width: 18px; height: 0; vertical-align: middle; margin-right: 6px; border-top: 2px solid; }
88
+ .vlm { display: grid; grid-template-columns: minmax(120px, 200px) 1fr; gap: 12px; align-items: start; }
89
+ .vlm img { width: 100%; border-radius: 4px; display: block; }
90
+ .said { display: grid; gap: 6px; font-size: 14px; }
91
+ .said .who { font: 500 11px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
92
+ .said p { white-space: pre-wrap; word-break: break-word; }
93
+ mark { background: var(--stop-soft); color: var(--ink); border-bottom: 2px solid var(--stop); padding: 0 1px; }
94
+ h4 { font: 600 14px/1.2 var(--display); margin: 0; }
95
+ .phone { border-top: 2px solid var(--line); padding-top: 24px; gap: 22px; }
96
+ .phone > .ph { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
97
+ @media (max-width: 560px) { .vlm { grid-template-columns: 1fr; } }
98
+ @media print { body { background: #fff; } .wrap { padding: 0; } }
99
+ </style></head><body><main class="wrap"><header><span class="eyebrow">nnopt verification report · Kernel or layer</span>
100
+ <h1>prism-ml/bonsai-image-ternary-4B-unpacked on galaxy-s26-plus</h1>
101
+ <p class="sub">Job NN-C9116E · 2026-11-29 04:24 UTC ·
102
+ nnopt-verify 0.1.0 · reference bundle <span class="mono">a9435c0dbbdc329e</span></p>
103
+ </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>
104
+ <p>The port ran on 6 inputs (4 hidden, generated fresh for this job and never shown to the
105
+ porting agent) and was compared with the reference outputs captured from your code. Thresholds are for the
106
+ <b>very_close</b> precision policy.</p>
107
+ <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>&gt;= 1.00</td><td><span class="badge pass">&#10003; 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>&gt;= 1.00</td><td><span class="badge pass">&#10003; 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>
108
+ <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>
109
+ <ul><li class="mono">src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &amp;e); CLCHK(e);</li><li class="mono">src/ops.cpp:35: cl_int e; aimg = clCreateImage(rt-&gt;ctx, CL_MEM_READ_WRITE, &amp;f, &amp;d, nullptr, &amp;e); CLCHK(e);</li></ul></section><section><h2>Speed and memory</h2>
110
+ <p>2 warm-up runs, then 5 timed runs of 3 requests each (the first
111
+ request of each run is cold). Timed on the device's own clock.</p>
112
+ <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>[&#x27;OpenCL&#x27;, &#x27;Vulkan&#x27;]</dd><dt>released</dt><dd>2026-02</dd><dt>roofline</dt><dd>{&#x27;npu&#x27;: {&#x27;job&#x27;: &#x27;NN-174CC0&#x27;, &#x27;source&#x27;: &#x27;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&#x27;, &#x27;measured&#x27;: True, &#x27;measured_at&#x27;: &#x27;2026-10-31&#x27;, &#x27;measured_by&#x27;: &#x27;probe&#x27;, &#x27;peak_int8_tops&#x27;: 29.023, &#x27;peak_fp16_tflops&#x27;: 18.325, &#x27;mem_bandwidth_gbps&#x27;: 69.93, &#x27;mem_bandwidth_int8_gbps&#x27;: 70.46}, &#x27;spec&#x27;: {&#x27;source&#x27;: &#x27;spec-sheet estimate, not yet measured: LPDDR5X-10667 64-bit; Adreno 840 compute is a rough estimate&#x27;, &#x27;peak_int8_tops&#x27;: 6.0, &#x27;peak_fp16_tflops&#x27;: 6.0, &#x27;mem_bandwidth_gbps&#x27;: 85.3}, &#x27;source&#x27;: &#x27;measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)&#x27;, &#x27;measured&#x27;: True, &#x27;device_best&#x27;: {&#x27;cpu_job&#x27;: &#x27;NN-DA0137&#x27;, &#x27;gpu_job&#x27;: &#x27;NN-DA0137&#x27;, &#x27;cpu_read_gbps&#x27;: 74.03, &#x27;gpu_read_gbps&#x27;: 73.18, &#x27;cpu_measured_at&#x27;: &#x27;2026-10-23T04:46:29+00:00&#x27;, &#x27;gpu_measured_at&#x27;: &#x27;2026-10-23T04:46:29+00:00&#x27;}, &#x27;measured_at&#x27;: &#x27;2026-11-06&#x27;, &#x27;measured_by&#x27;: &#x27;device&#x27;, &#x27;device_probe&#x27;: {&#x27;job&#x27;: &#x27;NN-10306A&#x27;, &#x27;measured_at&#x27;: &#x27;2026-11-06T19:04:04+00:00&#x27;, &#x27;cpu_read_gbps&#x27;: 62.33, &#x27;gpu_read_gbps&#x27;: 73.06}, &#x27;peak_int8_tops&#x27;: 6.0, &#x27;peak_fp16_tflops&#x27;: 6.0, &#x27;mem_bandwidth_gbps&#x27;: 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>
sm8850-gpu-ternary/report/reproduce.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Reproduce nnopt's numbers on your own device (REPRO.md). Build and deploy first (REPRO.md, steps 4 to 6).
3
+ # Needs python3, and adb (Android; ANDROID_SERIAL with several phones) or ssh (SSH_TARGET=user@host).
4
+ here=$(cd "$(dirname "$0")" && pwd)
5
+ root=$here; [ -d "$root/repro" ] || root=$(dirname "$here")
6
+ cd "$root" || exit 2
7
+ if [ ! -f repro/bench.py ]; then echo "no repro/ folder next to REPRO.md"; exit 2; fi
8
+ rc=0
9
+ python3 repro/bench.py "$@" || rc=$?
10
+ python3 repro/bench.py --check "$@" || rc=$?
11
+ exit $rc
sm8850-gpu-ternary/report/results.csv ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ section,name,value,unit_or_op,threshold,passed
2
+ grade,correctness,True,,,True
3
+ grade,speed_target_met,,,,
4
+ check,cases_completed,1.0,>=,1.0,True
5
+ check,outputs_match,1.0,>=,1.0,True
6
+ check,max_abs_error,0.0625,<=,,
7
+ check,max_rel_error,189.40449438202248,<=,,
8
+ check,min_cosine,0.9999999987530607,>=,,
9
+ check_metric,cases_passed,6,,,
10
+ check_metric,cases,6,,,
11
+ check_metric,max_abs_error,0.0625,,,
12
+ check_metric,max_rel_error,189.40449438202248,,,
13
+ check_metric,min_cosine,0.9999999987530607,,,
14
+ check_metric,max_mismatch_frac,0.0,,,
15
+ check_metric,nonfinite,0,,,
16
+ check_metric,tier,very_close,,,
17
+ check_metric,bar,"rtol 0.01, atol 0.01×rms (very close)",,,
18
+ check_metric,outputs,"['image', 'noise_pred', 'prompt_embeds']",,,
19
+ bench,latency_ms.median,35180.9,ms,,
20
+ bench,latency_ms.p10,32838.7,ms,,
21
+ bench,latency_ms.p90,38323.2,ms,,
22
+ bench,latency_ms.min,29772.4,ms,,
23
+ bench,latency_ms.max,39676.0,ms,,
24
+ bench,latency_ms.n,10,ms,,
25
+ bench,cold_latency_ms.median,27237.6,ms,,
26
+ bench,cold_latency_ms.p10,26861.1,ms,,
27
+ bench,cold_latency_ms.p90,28414.0,ms,,
28
+ bench,cold_latency_ms.min,26784.8,ms,,
29
+ bench,cold_latency_ms.max,28732.7,ms,,
30
+ bench,cold_latency_ms.n,5,ms,,
31
+ bench,load_ms.median,1126.4,ms,,
32
+ bench,load_ms.p10,1064.96,ms,,
33
+ bench,load_ms.p90,1156.74,ms,,
34
+ bench,load_ms.min,1044.0,ms,,
35
+ bench,load_ms.max,1161.7,ms,,
36
+ bench,load_ms.n,5,ms,,
37
+ bench,wall_ms.median,102172.0,ms,,
38
+ bench,wall_ms.p10,94708.2,ms,,
39
+ bench,wall_ms.p90,103457.0,ms,,
40
+ bench,wall_ms.min,91246.5,ms,,
41
+ bench,wall_ms.max,103537.0,ms,,
42
+ bench,wall_ms.n,5,ms,,
43
+ bench,peak_rss_mb,5672.0,MB,,
44
+ bench,peak_hwm_mb,5728.0,MB,,
45
+ bench,self_reported_peak_mem_mb,5726.0,MB,,
46
+ graded,latency_ms,35180.9,ms,,
47
+ graded,cold_latency_ms,27237.6,ms,,
48
+ graded,load_ms,1126.4,ms,,
49
+ graded,wall_ms,102172.0,ms,,
50
+ graded,peak_mem_mb,5728.0,MB,,
51
+ roofline,mem_bandwidth_gbps,73.06,,,
52
+ roofline,peak_gflops,6000.0,,,
53
+ 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)'}",,,
sm8850-gpu-ternary/report/results.json ADDED
@@ -0,0 +1,1330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kit_version": "0.1.0",
3
+ "job": {
4
+ "job_id": "NN-C9116E",
5
+ "kind": "port",
6
+ "model": "prism-ml/bonsai-image-ternary-4B-unpacked",
7
+ "environment": "galaxy-s26-plus",
8
+ "outcome": "passed",
9
+ "failure_reason": null,
10
+ "fingerprint": {
11
+ "name": "Samsung Galaxy S26+",
12
+ "soc": "Snapdragon 8 Elite Gen 5",
13
+ "gpu": "Adreno 840",
14
+ "os": "Android",
15
+ "phone": "a fresh phone of the same model (the agent's phone's session was ending)"
16
+ },
17
+ "backend": {
18
+ "requested": "hand-written OpenCL runtime in C++, no other engine on the phone",
19
+ "required": [
20
+ "OpenCL"
21
+ ],
22
+ "avoided": [],
23
+ "passed": true,
24
+ "reason": "uses OpenCL",
25
+ "evidence": {
26
+ "OpenCL": [
27
+ "src/clrt.cpp:38: q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e);",
28
+ "src/ops.cpp:35: cl_int e; aimg = clCreateImage(rt->ctx, CL_MEM_READ_WRITE, &f, &d, nullptr, &e); CLCHK(e);"
29
+ ]
30
+ }
31
+ },
32
+ "decoding": null
33
+ },
34
+ "grade": {
35
+ "correctness": true,
36
+ "speed_target_met": null,
37
+ "details": {
38
+ "kit_version": "0.1.0",
39
+ "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3",
40
+ "model_type": "kernel",
41
+ "precision": "very_close",
42
+ "split": "all",
43
+ "final": true,
44
+ "correctness": {
45
+ "passed": true,
46
+ "failed_checks": [],
47
+ "flags": [],
48
+ "metrics": {
49
+ "cases_passed": 6,
50
+ "cases": 6,
51
+ "max_abs_error": 0.0625,
52
+ "max_rel_error": 189.40449438202248,
53
+ "min_cosine": 0.9999999987530607,
54
+ "max_mismatch_frac": 0.0,
55
+ "nonfinite": 0,
56
+ "tier": "very_close",
57
+ "bar": "rtol 0.01, atol 0.01\u00d7rms (very close)",
58
+ "outputs": [
59
+ "image",
60
+ "noise_pred",
61
+ "prompt_embeds"
62
+ ]
63
+ },
64
+ "errors": []
65
+ },
66
+ "benchmark": {
67
+ "latency_ms": 35180.9,
68
+ "load_ms": 1126.4,
69
+ "peak_mem_mb": 5728.0,
70
+ "flags": []
71
+ }
72
+ }
73
+ },
74
+ "check": {
75
+ "kind": "check",
76
+ "model_type": "kernel",
77
+ "precision": "very_close",
78
+ "split": "all",
79
+ "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3",
80
+ "port": {
81
+ "dir": "/data/local/tmp/nnopt/port",
82
+ "port_json": {
83
+ "contract": 1,
84
+ "model_type": "kernel",
85
+ "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)",
86
+ "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",
87
+ "external_files": [
88
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin",
89
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.idx",
90
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin",
91
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx",
92
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin",
93
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx"
94
+ ],
95
+ "measure": {
96
+ "unit": "call",
97
+ "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"
98
+ }
99
+ },
100
+ "tree_sha256": "9af2993c42cd482ccffba308b53a24e7819164771d455f0f2f68f8faac724c85",
101
+ "external_sha256": {
102
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4",
103
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.idx": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b",
104
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1",
105
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a",
106
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5",
107
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07"
108
+ }
109
+ },
110
+ "executor": {
111
+ "executor": "adb",
112
+ "os": "android"
113
+ },
114
+ "thresholds": {
115
+ "fp32_rtol": 0.0001,
116
+ "fp32_atol_scale": 0.0001,
117
+ "fp16_rtol": 0.01,
118
+ "fp16_atol_scale": 0.01,
119
+ "int8_max_abs_diff": 1,
120
+ "int_max_abs_diff": 0,
121
+ "max_mismatch_frac": 0.0
122
+ },
123
+ "checks": [
124
+ {
125
+ "name": "cases_completed",
126
+ "value": 1.0,
127
+ "op": ">=",
128
+ "threshold": 1.0,
129
+ "passed": true,
130
+ "detail": "6/6 cases produced valid output"
131
+ },
132
+ {
133
+ "name": "outputs_match",
134
+ "value": 1.0,
135
+ "op": ">=",
136
+ "threshold": 1.0,
137
+ "passed": true,
138
+ "detail": "6/6 cases within tolerance: rtol 0.01, atol 0.01\u00d7rms (very close)",
139
+ "display": "6/6 cases"
140
+ },
141
+ {
142
+ "name": "max_abs_error",
143
+ "value": 0.0625,
144
+ "op": "<=",
145
+ "threshold": null,
146
+ "passed": null,
147
+ "skipped": true,
148
+ "detail": "worst |port - ref| over all outputs"
149
+ },
150
+ {
151
+ "name": "max_rel_error",
152
+ "value": 189.40449438202248,
153
+ "op": "<=",
154
+ "threshold": null,
155
+ "passed": null,
156
+ "skipped": true,
157
+ "detail": "worst |port - ref| / |ref| (ref != 0)"
158
+ },
159
+ {
160
+ "name": "min_cosine",
161
+ "value": 0.9999999987530607,
162
+ "op": ">=",
163
+ "threshold": null,
164
+ "passed": null,
165
+ "skipped": true,
166
+ "detail": "lowest cosine similarity of an output"
167
+ }
168
+ ],
169
+ "metrics": {
170
+ "cases_passed": 6,
171
+ "cases": 6,
172
+ "max_abs_error": 0.0625,
173
+ "max_rel_error": 189.40449438202248,
174
+ "min_cosine": 0.9999999987530607,
175
+ "max_mismatch_frac": 0.0,
176
+ "nonfinite": 0,
177
+ "tier": "very_close",
178
+ "bar": "rtol 0.01, atol 0.01\u00d7rms (very close)",
179
+ "outputs": [
180
+ "image",
181
+ "noise_pred",
182
+ "prompt_embeds"
183
+ ]
184
+ },
185
+ "cases": [
186
+ {
187
+ "id": "p000",
188
+ "split": "public",
189
+ "origin": "builtin",
190
+ "compute": {
191
+ "rc": 0,
192
+ "wall_ms": 21230.0,
193
+ "peak_rss_mb": 5204.0
194
+ },
195
+ "passed": true,
196
+ "max_abs_error": 0.03125,
197
+ "max_rel_error": 113.375,
198
+ "cosine": 0.9999999990347779,
199
+ "mismatch_frac": 0.0,
200
+ "nonfinite": 0,
201
+ "outputs": [
202
+ {
203
+ "name": "image",
204
+ "dtype": "float16",
205
+ "shape": [
206
+ 1,
207
+ 3,
208
+ 512,
209
+ 512
210
+ ],
211
+ "max_abs_error": 0.00048828125,
212
+ "max_rel_error": 0.0009689922480620155,
213
+ "cosine": 0.9999999999105549,
214
+ "mismatch_frac": 0.0,
215
+ "nonfinite": 0,
216
+ "passed": true
217
+ },
218
+ {
219
+ "name": "noise_pred",
220
+ "dtype": "float16",
221
+ "shape": [
222
+ 1,
223
+ 1024,
224
+ 128
225
+ ],
226
+ "max_abs_error": 0.001953125,
227
+ "max_rel_error": 4.7272727272727275,
228
+ "cosine": 0.9999999990347779,
229
+ "mismatch_frac": 0.0,
230
+ "nonfinite": 0,
231
+ "passed": true
232
+ },
233
+ {
234
+ "name": "prompt_embeds",
235
+ "dtype": "float16",
236
+ "shape": [
237
+ 1,
238
+ 512,
239
+ 7680
240
+ ],
241
+ "max_abs_error": 0.03125,
242
+ "max_rel_error": 113.375,
243
+ "cosine": 0.9999999999703847,
244
+ "mismatch_frac": 0.0,
245
+ "nonfinite": 0,
246
+ "passed": true
247
+ }
248
+ ]
249
+ },
250
+ {
251
+ "id": "p001",
252
+ "split": "public",
253
+ "origin": "builtin",
254
+ "compute": {
255
+ "rc": 0,
256
+ "wall_ms": 23460.0,
257
+ "peak_rss_mb": 5558.0
258
+ },
259
+ "passed": true,
260
+ "max_abs_error": 0.03125,
261
+ "max_rel_error": 37.25,
262
+ "cosine": 0.999999999197379,
263
+ "mismatch_frac": 0.0,
264
+ "nonfinite": 0,
265
+ "outputs": [
266
+ {
267
+ "name": "image",
268
+ "dtype": "float16",
269
+ "shape": [
270
+ 1,
271
+ 3,
272
+ 512,
273
+ 512
274
+ ],
275
+ "max_abs_error": 0.00048828125,
276
+ "max_rel_error": 0.000975609756097561,
277
+ "cosine": 0.9999999999110489,
278
+ "mismatch_frac": 0.0,
279
+ "nonfinite": 0,
280
+ "passed": true
281
+ },
282
+ {
283
+ "name": "noise_pred",
284
+ "dtype": "float16",
285
+ "shape": [
286
+ 1,
287
+ 1024,
288
+ 128
289
+ ],
290
+ "max_abs_error": 0.001953125,
291
+ "max_rel_error": 0.12,
292
+ "cosine": 0.999999999197379,
293
+ "mismatch_frac": 0.0,
294
+ "nonfinite": 0,
295
+ "passed": true
296
+ },
297
+ {
298
+ "name": "prompt_embeds",
299
+ "dtype": "float16",
300
+ "shape": [
301
+ 1,
302
+ 512,
303
+ 7680
304
+ ],
305
+ "max_abs_error": 0.03125,
306
+ "max_rel_error": 37.25,
307
+ "cosine": 0.9999999999472156,
308
+ "mismatch_frac": 0.0,
309
+ "nonfinite": 0,
310
+ "passed": true
311
+ }
312
+ ]
313
+ },
314
+ {
315
+ "id": "h000",
316
+ "split": "hidden",
317
+ "origin": "generated",
318
+ "compute": {
319
+ "rc": 0,
320
+ "wall_ms": 23320.0,
321
+ "peak_rss_mb": 5506.0
322
+ },
323
+ "passed": true,
324
+ "max_abs_error": 0.0625,
325
+ "max_rel_error": 31.4375,
326
+ "cosine": 0.9999999989172967,
327
+ "mismatch_frac": 0.0,
328
+ "nonfinite": 0,
329
+ "outputs": [
330
+ {
331
+ "name": "image",
332
+ "dtype": "float16",
333
+ "shape": [
334
+ 1,
335
+ 3,
336
+ 512,
337
+ 512
338
+ ],
339
+ "max_abs_error": 0.00048828125,
340
+ "max_rel_error": 0.0009746588693957114,
341
+ "cosine": 0.999999999913716,
342
+ "mismatch_frac": 0.0,
343
+ "nonfinite": 0,
344
+ "passed": true
345
+ },
346
+ {
347
+ "name": "noise_pred",
348
+ "dtype": "float16",
349
+ "shape": [
350
+ 1,
351
+ 1024,
352
+ 128
353
+ ],
354
+ "max_abs_error": 0.001953125,
355
+ "max_rel_error": 0.9811320754716981,
356
+ "cosine": 0.9999999989172967,
357
+ "mismatch_frac": 0.0,
358
+ "nonfinite": 0,
359
+ "passed": true
360
+ },
361
+ {
362
+ "name": "prompt_embeds",
363
+ "dtype": "float16",
364
+ "shape": [
365
+ 1,
366
+ 512,
367
+ 7680
368
+ ],
369
+ "max_abs_error": 0.0625,
370
+ "max_rel_error": 31.4375,
371
+ "cosine": 0.9999999999522909,
372
+ "mismatch_frac": 0.0,
373
+ "nonfinite": 0,
374
+ "passed": true
375
+ }
376
+ ]
377
+ },
378
+ {
379
+ "id": "h001",
380
+ "split": "hidden",
381
+ "origin": "generated",
382
+ "compute": {
383
+ "rc": 0,
384
+ "wall_ms": 23410.0,
385
+ "peak_rss_mb": 5375.0
386
+ },
387
+ "passed": true,
388
+ "max_abs_error": 0.03125,
389
+ "max_rel_error": 38.0,
390
+ "cosine": 0.9999999991483752,
391
+ "mismatch_frac": 0.0,
392
+ "nonfinite": 0,
393
+ "outputs": [
394
+ {
395
+ "name": "image",
396
+ "dtype": "float16",
397
+ "shape": [
398
+ 1,
399
+ 3,
400
+ 512,
401
+ 512
402
+ ],
403
+ "max_abs_error": 0.00048828125,
404
+ "max_rel_error": 0.0009737098344693282,
405
+ "cosine": 0.9999999999137019,
406
+ "mismatch_frac": 0.0,
407
+ "nonfinite": 0,
408
+ "passed": true
409
+ },
410
+ {
411
+ "name": "noise_pred",
412
+ "dtype": "float16",
413
+ "shape": [
414
+ 1,
415
+ 1024,
416
+ 128
417
+ ],
418
+ "max_abs_error": 0.001953125,
419
+ "max_rel_error": 0.1419753086419753,
420
+ "cosine": 0.9999999991483752,
421
+ "mismatch_frac": 0.0,
422
+ "nonfinite": 0,
423
+ "passed": true
424
+ },
425
+ {
426
+ "name": "prompt_embeds",
427
+ "dtype": "float16",
428
+ "shape": [
429
+ 1,
430
+ 512,
431
+ 7680
432
+ ],
433
+ "max_abs_error": 0.03125,
434
+ "max_rel_error": 38.0,
435
+ "cosine": 0.9999999999651432,
436
+ "mismatch_frac": 0.0,
437
+ "nonfinite": 0,
438
+ "passed": true
439
+ }
440
+ ]
441
+ },
442
+ {
443
+ "id": "h002",
444
+ "split": "hidden",
445
+ "origin": "generated",
446
+ "compute": {
447
+ "rc": 0,
448
+ "wall_ms": 24750.0,
449
+ "peak_rss_mb": 5466.0
450
+ },
451
+ "passed": true,
452
+ "max_abs_error": 0.0625,
453
+ "max_rel_error": 189.40449438202248,
454
+ "cosine": 0.9999999990230362,
455
+ "mismatch_frac": 0.0,
456
+ "nonfinite": 0,
457
+ "outputs": [
458
+ {
459
+ "name": "image",
460
+ "dtype": "float16",
461
+ "shape": [
462
+ 1,
463
+ 3,
464
+ 512,
465
+ 512
466
+ ],
467
+ "max_abs_error": 0.00048828125,
468
+ "max_rel_error": 0.0009765625,
469
+ "cosine": 0.9999999999234104,
470
+ "mismatch_frac": 0.0,
471
+ "nonfinite": 0,
472
+ "passed": true
473
+ },
474
+ {
475
+ "name": "noise_pred",
476
+ "dtype": "float16",
477
+ "shape": [
478
+ 1,
479
+ 1024,
480
+ 128
481
+ ],
482
+ "max_abs_error": 0.001953125,
483
+ "max_rel_error": 1.540983606557377,
484
+ "cosine": 0.9999999990230362,
485
+ "mismatch_frac": 0.0,
486
+ "nonfinite": 0,
487
+ "passed": true
488
+ },
489
+ {
490
+ "name": "prompt_embeds",
491
+ "dtype": "float16",
492
+ "shape": [
493
+ 1,
494
+ 512,
495
+ 7680
496
+ ],
497
+ "max_abs_error": 0.0625,
498
+ "max_rel_error": 189.40449438202248,
499
+ "cosine": 0.9999999999087043,
500
+ "mismatch_frac": 0.0,
501
+ "nonfinite": 0,
502
+ "passed": true
503
+ }
504
+ ]
505
+ },
506
+ {
507
+ "id": "h003",
508
+ "split": "hidden",
509
+ "origin": "generated",
510
+ "compute": {
511
+ "rc": 0,
512
+ "wall_ms": 25630.0,
513
+ "peak_rss_mb": 5458.0
514
+ },
515
+ "passed": true,
516
+ "max_abs_error": 0.03125,
517
+ "max_rel_error": 54.333333333333336,
518
+ "cosine": 0.9999999987530607,
519
+ "mismatch_frac": 0.0,
520
+ "nonfinite": 0,
521
+ "outputs": [
522
+ {
523
+ "name": "image",
524
+ "dtype": "float16",
525
+ "shape": [
526
+ 1,
527
+ 3,
528
+ 512,
529
+ 512
530
+ ],
531
+ "max_abs_error": 0.00048828125,
532
+ "max_rel_error": 0.0009718172983479105,
533
+ "cosine": 0.9999999999205494,
534
+ "mismatch_frac": 0.0,
535
+ "nonfinite": 0,
536
+ "passed": true
537
+ },
538
+ {
539
+ "name": "noise_pred",
540
+ "dtype": "float16",
541
+ "shape": [
542
+ 1,
543
+ 1024,
544
+ 128
545
+ ],
546
+ "max_abs_error": 0.001953125,
547
+ "max_rel_error": 0.4587628865979381,
548
+ "cosine": 0.9999999987530607,
549
+ "mismatch_frac": 0.0,
550
+ "nonfinite": 0,
551
+ "passed": true
552
+ },
553
+ {
554
+ "name": "prompt_embeds",
555
+ "dtype": "float16",
556
+ "shape": [
557
+ 1,
558
+ 512,
559
+ 7680
560
+ ],
561
+ "max_abs_error": 0.03125,
562
+ "max_rel_error": 54.333333333333336,
563
+ "cosine": 0.999999999949425,
564
+ "mismatch_frac": 0.0,
565
+ "nonfinite": 0,
566
+ "passed": true
567
+ }
568
+ ]
569
+ }
570
+ ],
571
+ "flags": [],
572
+ "errors": [],
573
+ "passed": true,
574
+ "started_at": "2026-11-29T04:01:06Z",
575
+ "reference_check": {
576
+ "verdict": "ok",
577
+ "ok": true,
578
+ "cases_checked": 6,
579
+ "bad": 0,
580
+ "message": null,
581
+ "bad_cases": []
582
+ },
583
+ "processor": {
584
+ "lock": "gpu",
585
+ "checked": true,
586
+ "used": [
587
+ "cpu",
588
+ "gpu"
589
+ ],
590
+ "seen": {
591
+ "gpu": [
592
+ "/dev/kgsl-3d0@bonsai_image",
593
+ "libOpenCL.so@bonsai_image",
594
+ "libOpenCL_adreno.so@bonsai_image"
595
+ ],
596
+ "npu": []
597
+ },
598
+ "gpu_busy_max_pct": 100,
599
+ "violation": null
600
+ },
601
+ "seconds": 166.09,
602
+ "speed": {
603
+ "metric": "latency_ms",
604
+ "value": 21879.0,
605
+ "unit": "ms",
606
+ "cases": 6,
607
+ "total_ms": 20000.0,
608
+ "load_ms": 1000.0,
609
+ "per": "call",
610
+ "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",
611
+ "phases_ms": {
612
+ "text_encoder": 4000.0,
613
+ "transformer": 10000.0,
614
+ "vae_decoder": 4000.0
615
+ }
616
+ },
617
+ "samples": "/out/samples/samples.json"
618
+ },
619
+ "bench": {
620
+ "kind": "bench",
621
+ "model_type": "kernel",
622
+ "bundle_digest": "a9435c0dbbdc329e5cfe2a5781abda9b6b72ab593f6e45d436e38b13e2e23ae3",
623
+ "case": "p000",
624
+ "port": {
625
+ "dir": "/data/local/tmp/nnopt/port",
626
+ "port_json": {
627
+ "contract": 1,
628
+ "model_type": "kernel",
629
+ "runtime": "hand-written OpenCL C++ runtime (dlopen libOpenCL.so, no other engine)",
630
+ "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",
631
+ "external_files": [
632
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin",
633
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.idx",
634
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin",
635
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx",
636
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin",
637
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx"
638
+ ],
639
+ "measure": {
640
+ "unit": "call",
641
+ "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"
642
+ }
643
+ },
644
+ "tree_sha256": "9af2993c42cd482ccffba308b53a24e7819164771d455f0f2f68f8faac724c85",
645
+ "external_sha256": {
646
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.bin": "b384a6e93c705076c2a9dd3418e5e47be82ba9948cd8c2b0b3cc2c4adf79bfa4",
647
+ "/data/local/tmp/nnopt/bonsai_image_weights/te.idx": "eb7466449abfd0c7dc427dfd09b8c49167d8c8f716f0f02ab2ae13a5ba6ac32b",
648
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.bin": "f30d70cee51edb96b2f278c390c4560923c68e0c9c0977f9481e0468be8ac2b1",
649
+ "/data/local/tmp/nnopt/bonsai_image_weights/dit.idx": "4ca7c3c7ef4165e9f6fd50b833f62cca21715a47f4536164521746327e2fbb7a",
650
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.bin": "54ac1a1045def03fecaa091e13663989639779185ad05efc107b353152b6e5e5",
651
+ "/data/local/tmp/nnopt/bonsai_image_weights/vae.idx": "d52f0646dd0c9b533b6025833e102295eea57b48c20da969f2203c4cdcc9cb07"
652
+ }
653
+ },
654
+ "executor": {
655
+ "executor": "adb",
656
+ "os": "android"
657
+ },
658
+ "environment": {
659
+ "os": "Android",
660
+ "gpu": "Adreno 840",
661
+ "soc": "Snapdragon 8 Elite Gen 5",
662
+ "brand": "Samsung",
663
+ "device": "Samsung Galaxy S26+",
664
+ "ram_gb": 12,
665
+ "android": "16",
666
+ "gpu_apis": [
667
+ "OpenCL",
668
+ "Vulkan"
669
+ ],
670
+ "released": "2026-02",
671
+ "roofline": {
672
+ "npu": {
673
+ "job": "NN-174CC0",
674
+ "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",
675
+ "measured": true,
676
+ "measured_at": "2026-10-31",
677
+ "measured_by": "probe",
678
+ "peak_int8_tops": 29.023,
679
+ "peak_fp16_tflops": 18.325,
680
+ "mem_bandwidth_gbps": 69.93,
681
+ "mem_bandwidth_int8_gbps": 70.46
682
+ },
683
+ "spec": {
684
+ "source": "spec-sheet estimate, not yet measured: LPDDR5X-10667 64-bit; Adreno 840 compute is a rough estimate",
685
+ "peak_int8_tops": 6.0,
686
+ "peak_fp16_tflops": 6.0,
687
+ "mem_bandwidth_gbps": 85.3
688
+ },
689
+ "source": "measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)",
690
+ "measured": true,
691
+ "device_best": {
692
+ "cpu_job": "NN-DA0137",
693
+ "gpu_job": "NN-DA0137",
694
+ "cpu_read_gbps": 74.03,
695
+ "gpu_read_gbps": 73.18,
696
+ "cpu_measured_at": "2026-10-23T04:46:29+00:00",
697
+ "gpu_measured_at": "2026-10-23T04:46:29+00:00"
698
+ },
699
+ "measured_at": "2026-11-06",
700
+ "measured_by": "device",
701
+ "device_probe": {
702
+ "job": "NN-10306A",
703
+ "measured_at": "2026-11-06T19:04:04+00:00",
704
+ "cpu_read_gbps": 62.33,
705
+ "gpu_read_gbps": 73.06
706
+ },
707
+ "peak_int8_tops": 6.0,
708
+ "peak_fp16_tflops": 6.0,
709
+ "mem_bandwidth_gbps": 73.06
710
+ },
711
+ "model_id": "m2q",
712
+ "version_id": "36",
713
+ "name": "Samsung Galaxy S26+",
714
+ "processor": "gpu"
715
+ },
716
+ "model_facts": {
717
+ "params": 3959590948,
718
+ "source": "nnopt scoping"
719
+ },
720
+ "config": {
721
+ "warmup": 2,
722
+ "runs": 5,
723
+ "repeat": 3,
724
+ "max_new_tokens": 128,
725
+ "external_check": true,
726
+ "sustained_s": 0.0,
727
+ "sustained_repeat": 10,
728
+ "sample_interval_s": 2.0,
729
+ "mem_interval_ms": 200,
730
+ "timeout_s": 1800.0,
731
+ "case": null,
732
+ "prompt_tokens": null,
733
+ "batch": 1,
734
+ "external_min_s": 2.0,
735
+ "external_max_repeat": 500,
736
+ "resolution": null,
737
+ "seconds": 10.0,
738
+ "time_budget_s": 9734.4,
739
+ "adapt": true,
740
+ "cool_wait_s": 600.0,
741
+ "rest_s": 3.0
742
+ },
743
+ "precision": "very_close",
744
+ "flags": [],
745
+ "errors": [],
746
+ "method": {
747
+ "warmup": 2,
748
+ "runs": 5,
749
+ "repeat": 3,
750
+ "adapted": false,
751
+ "first_run_s": 19.5,
752
+ "time_budget_s": 9734,
753
+ "estimate_s": 708
754
+ },
755
+ "started_at": "2026-11-29T04:03:52Z",
756
+ "inputs": {
757
+ "tensors": [
758
+ {
759
+ "name": "prompt_ids",
760
+ "shape": [
761
+ 1,
762
+ 16
763
+ ],
764
+ "dtype": "int32"
765
+ },
766
+ {
767
+ "name": "latents",
768
+ "shape": [
769
+ 1,
770
+ 1024,
771
+ 128
772
+ ],
773
+ "dtype": "float32"
774
+ },
775
+ {
776
+ "name": "timestep",
777
+ "shape": [
778
+ 1
779
+ ],
780
+ "dtype": "float32"
781
+ },
782
+ {
783
+ "name": "encoder_hidden_states",
784
+ "shape": [
785
+ 1,
786
+ 512,
787
+ 7680
788
+ ],
789
+ "dtype": "float32"
790
+ },
791
+ {
792
+ "name": "vae_latents",
793
+ "shape": [
794
+ 1,
795
+ 1024,
796
+ 128
797
+ ],
798
+ "dtype": "float32"
799
+ }
800
+ ]
801
+ },
802
+ "cooldown": {
803
+ "waited_s": 224.0,
804
+ "start": {
805
+ "temp_c": 54.8,
806
+ "capped": [
807
+ "policy0 3187/3628 MHz",
808
+ "policy6 3398/4742 MHz"
809
+ ],
810
+ "limits": {
811
+ "policy0": 3187200,
812
+ "policy6": 3398400
813
+ },
814
+ "status": 2
815
+ },
816
+ "end": {
817
+ "temp_c": 42.6,
818
+ "capped": [
819
+ "policy0 3187/3628 MHz",
820
+ "policy6 3398/4742 MHz"
821
+ ],
822
+ "limits": {
823
+ "policy0": 3187200,
824
+ "policy6": 3398400
825
+ },
826
+ "status": 0
827
+ },
828
+ "why": "plateau"
829
+ },
830
+ "repeat_used": 3,
831
+ "timed_telemetry": {
832
+ "samples": 879,
833
+ "seconds": 984.0,
834
+ "max_temp_c": {
835
+ "min": 105.0,
836
+ "max": 105.0,
837
+ "mean": 105.0
838
+ },
839
+ "gpu_temp_c": {
840
+ "min": 41.8,
841
+ "max": 75.6,
842
+ "mean": 57.53
843
+ },
844
+ "cpu_temp_c": {
845
+ "min": 105.0,
846
+ "max": 105.0,
847
+ "mean": 105.0
848
+ },
849
+ "gpu_mhz": null,
850
+ "cpu_mhz_max": {
851
+ "min": 883.2,
852
+ "max": 3398.0,
853
+ "mean": 1658.0
854
+ },
855
+ "gpu_busy_pct": {
856
+ "min": 0.0,
857
+ "max": 100.0,
858
+ "mean": 77.61
859
+ },
860
+ "power_w": null,
861
+ "power_source": null,
862
+ "ram_used_mb": null
863
+ },
864
+ "cpu_caps": {
865
+ "runs": 5,
866
+ "capped": 0,
867
+ "waited_s": 132.3,
868
+ "caps": []
869
+ },
870
+ "runs": [
871
+ {
872
+ "wall_ms": 91246.5,
873
+ "load_ms": 1126.4,
874
+ "peak_rss_mb": 5611.0,
875
+ "peak_hwm_mb": 5628.0,
876
+ "self_peak_mem_mb": 5626.0,
877
+ "requests": [
878
+ {
879
+ "total_ms": 26784.8,
880
+ "latency_ms": 26784.8
881
+ },
882
+ {
883
+ "total_ms": 29772.4,
884
+ "latency_ms": 29772.4
885
+ },
886
+ {
887
+ "total_ms": 33179.4,
888
+ "latency_ms": 33179.4
889
+ }
890
+ ],
891
+ "cpu": {
892
+ "temp_c": 50.8,
893
+ "capped": [],
894
+ "status": 2,
895
+ "waited_s": 0.0
896
+ }
897
+ },
898
+ {
899
+ "wall_ms": 99900.7,
900
+ "load_ms": 1096.4,
901
+ "peak_rss_mb": 5658.0,
902
+ "peak_hwm_mb": 5728.0,
903
+ "self_peak_mem_mb": 5726.0,
904
+ "requests": [
905
+ {
906
+ "total_ms": 27237.6,
907
+ "latency_ms": 27237.6
908
+ },
909
+ {
910
+ "total_ms": 34554.6,
911
+ "latency_ms": 34554.6
912
+ },
913
+ {
914
+ "total_ms": 36635.8,
915
+ "latency_ms": 36635.8
916
+ }
917
+ ],
918
+ "cpu": {
919
+ "temp_c": 46.9,
920
+ "capped": [],
921
+ "status": 2,
922
+ "waited_s": 24.3
923
+ }
924
+ },
925
+ {
926
+ "wall_ms": 103537.0,
927
+ "load_ms": 1149.3,
928
+ "peak_rss_mb": 5660.0,
929
+ "peak_hwm_mb": 5697.0,
930
+ "self_peak_mem_mb": 5695.0,
931
+ "requests": [
932
+ {
933
+ "total_ms": 26975.5,
934
+ "latency_ms": 26975.5
935
+ },
936
+ {
937
+ "total_ms": 35348.4,
938
+ "latency_ms": 35348.4
939
+ },
940
+ {
941
+ "total_ms": 39676.0,
942
+ "latency_ms": 39676.0
943
+ }
944
+ ],
945
+ "cpu": {
946
+ "temp_c": 47.1,
947
+ "capped": [],
948
+ "status": 2,
949
+ "waited_s": 29.8
950
+ }
951
+ },
952
+ {
953
+ "wall_ms": 102172.0,
954
+ "load_ms": 1161.7,
955
+ "peak_rss_mb": 5671.0,
956
+ "peak_hwm_mb": 5702.0,
957
+ "self_peak_mem_mb": 5700.0,
958
+ "requests": [
959
+ {
960
+ "total_ms": 27935.9,
961
+ "latency_ms": 27935.9
962
+ },
963
+ {
964
+ "total_ms": 35009.2,
965
+ "latency_ms": 35009.2
966
+ },
967
+ {
968
+ "total_ms": 37649.6,
969
+ "latency_ms": 37649.6
970
+ }
971
+ ],
972
+ "cpu": {
973
+ "temp_c": 47.3,
974
+ "capped": [],
975
+ "status": 2,
976
+ "waited_s": 41.8
977
+ }
978
+ },
979
+ {
980
+ "wall_ms": 103337.0,
981
+ "load_ms": 1044.0,
982
+ "peak_rss_mb": 5672.0,
983
+ "peak_hwm_mb": 5676.0,
984
+ "self_peak_mem_mb": 5674.0,
985
+ "requests": [
986
+ {
987
+ "total_ms": 28732.7,
988
+ "latency_ms": 28732.7
989
+ },
990
+ {
991
+ "total_ms": 35013.4,
992
+ "latency_ms": 35013.4
993
+ },
994
+ {
995
+ "total_ms": 38172.9,
996
+ "latency_ms": 38172.9
997
+ }
998
+ ],
999
+ "cpu": {
1000
+ "temp_c": 47.3,
1001
+ "capped": [],
1002
+ "status": 2,
1003
+ "waited_s": 36.4
1004
+ }
1005
+ }
1006
+ ],
1007
+ "summary": {
1008
+ "latency_ms": {
1009
+ "n": 10,
1010
+ "median": 35180.9,
1011
+ "mean": 35501.2,
1012
+ "min": 29772.4,
1013
+ "max": 39676.0,
1014
+ "p10": 32838.7,
1015
+ "p90": 38323.2
1016
+ },
1017
+ "cold_latency_ms": {
1018
+ "n": 5,
1019
+ "median": 27237.6,
1020
+ "mean": 27533.3,
1021
+ "min": 26784.8,
1022
+ "max": 28732.7,
1023
+ "p10": 26861.1,
1024
+ "p90": 28414.0
1025
+ },
1026
+ "load_ms": {
1027
+ "n": 5,
1028
+ "median": 1126.4,
1029
+ "mean": 1115.56,
1030
+ "min": 1044.0,
1031
+ "max": 1161.7,
1032
+ "p10": 1064.96,
1033
+ "p90": 1156.74
1034
+ },
1035
+ "wall_ms": {
1036
+ "n": 5,
1037
+ "median": 102172.0,
1038
+ "mean": 100039.0,
1039
+ "min": 91246.5,
1040
+ "max": 103537.0,
1041
+ "p10": 94708.2,
1042
+ "p90": 103457.0
1043
+ },
1044
+ "peak_rss_mb": 5672.0,
1045
+ "peak_hwm_mb": 5728.0,
1046
+ "self_reported_peak_mem_mb": 5726.0
1047
+ },
1048
+ "external": {
1049
+ "available": true,
1050
+ "method": "paired --repeat 3 vs 1",
1051
+ "pairs": 5,
1052
+ "latency_ms": 30670.0
1053
+ },
1054
+ "graded": {
1055
+ "latency_ms": 35180.9,
1056
+ "cold_latency_ms": 27237.6,
1057
+ "load_ms": 1126.4,
1058
+ "wall_ms": 102172.0,
1059
+ "peak_mem_mb": 5728.0
1060
+ },
1061
+ "roofline": {
1062
+ "mem_bandwidth_gbps": 73.06,
1063
+ "peak_gflops": 6000.0,
1064
+ "figures": {
1065
+ "processor": "gpu",
1066
+ "figures": "gpu",
1067
+ "source": "measured on the device by NN-10306A on 2026-11-06: GPU read 73.06 GB/s (OpenCL read_img)"
1068
+ }
1069
+ },
1070
+ "processor": {
1071
+ "lock": "gpu",
1072
+ "checked": true,
1073
+ "used": [
1074
+ "cpu",
1075
+ "gpu"
1076
+ ],
1077
+ "seen": {
1078
+ "gpu": [
1079
+ "/dev/kgsl-3d0@bonsai_image",
1080
+ "libOpenCL.so@bonsai_image",
1081
+ "libOpenCL_adreno.so@bonsai_image"
1082
+ ],
1083
+ "npu": []
1084
+ },
1085
+ "gpu_busy_max_pct": 100,
1086
+ "violation": null
1087
+ },
1088
+ "seconds": 1222.14
1089
+ },
1090
+ "reference": {
1091
+ "format": "nnopt-reference-bundle",
1092
+ "version": 1,
1093
+ "job_id": "NN-C9116E",
1094
+ "model_type": "kernel",
1095
+ "precision_policy": "very_close",
1096
+ "model": {
1097
+ "kind": "contract",
1098
+ "program": "/work/reference_runner"
1099
+ },
1100
+ "runner": {
1101
+ "kind": "contract",
1102
+ "program": "/work/reference_runner"
1103
+ },
1104
+ "params": {
1105
+ "inputs": [
1106
+ {
1107
+ "name": "prompt_ids",
1108
+ "shape": [
1109
+ 1,
1110
+ 16
1111
+ ],
1112
+ "dtype": "int32",
1113
+ "range": [
1114
+ 0,
1115
+ 151642
1116
+ ]
1117
+ },
1118
+ {
1119
+ "name": "latents",
1120
+ "shape": [
1121
+ 1,
1122
+ 1024,
1123
+ 128
1124
+ ],
1125
+ "dtype": "float32"
1126
+ },
1127
+ {
1128
+ "name": "timestep",
1129
+ "shape": [
1130
+ 1
1131
+ ],
1132
+ "dtype": "float32",
1133
+ "range": [
1134
+ 0.0,
1135
+ 1.0
1136
+ ]
1137
+ },
1138
+ {
1139
+ "name": "encoder_hidden_states",
1140
+ "shape": [
1141
+ 1,
1142
+ 512,
1143
+ 7680
1144
+ ],
1145
+ "dtype": "float32"
1146
+ },
1147
+ {
1148
+ "name": "vae_latents",
1149
+ "shape": [
1150
+ 1,
1151
+ 1024,
1152
+ 128
1153
+ ],
1154
+ "dtype": "float32"
1155
+ }
1156
+ ],
1157
+ "format": "NumPy .npy 1.0, C order, little-endian",
1158
+ "public_seeds": [
1159
+ 201,
1160
+ 202
1161
+ ],
1162
+ "outputs": [
1163
+ {
1164
+ "name": "image",
1165
+ "shape": [
1166
+ 1,
1167
+ 3,
1168
+ 512,
1169
+ 512
1170
+ ],
1171
+ "dtype": "float16"
1172
+ },
1173
+ {
1174
+ "name": "noise_pred",
1175
+ "shape": [
1176
+ 1,
1177
+ 1024,
1178
+ 128
1179
+ ],
1180
+ "dtype": "float16"
1181
+ },
1182
+ {
1183
+ "name": "prompt_embeds",
1184
+ "shape": [
1185
+ 1,
1186
+ 512,
1187
+ 7680
1188
+ ],
1189
+ "dtype": "float16"
1190
+ }
1191
+ ]
1192
+ },
1193
+ "tools": {
1194
+ "python": "3.12.3",
1195
+ "numpy": "2.5.4",
1196
+ "nnopt_verify": "0.1.0",
1197
+ "platform": "Linux-7.0.0-1014-gcp-x86_64-with-glibc2.39"
1198
+ },
1199
+ "created_at": "2026-11-29T01:48:31Z",
1200
+ "cases": [
1201
+ {
1202
+ "id": "p000",
1203
+ "split": "public",
1204
+ "origin": "builtin",
1205
+ "files": {
1206
+ "input:prompt_ids": "inputs/p000/prompt_ids.npy",
1207
+ "input:latents": "inputs/p000/latents.npy",
1208
+ "input:timestep": "inputs/p000/timestep.npy",
1209
+ "input:encoder_hidden_states": "inputs/p000/encoder_hidden_states.npy",
1210
+ "input:vae_latents": "inputs/p000/vae_latents.npy",
1211
+ "output:image": "outputs/p000/image.npy",
1212
+ "output:noise_pred": "outputs/p000/noise_pred.npy",
1213
+ "output:prompt_embeds": "outputs/p000/prompt_embeds.npy",
1214
+ "output": "outputs/p000.json"
1215
+ },
1216
+ "meta": {}
1217
+ },
1218
+ {
1219
+ "id": "p001",
1220
+ "split": "public",
1221
+ "origin": "builtin",
1222
+ "files": {
1223
+ "input:prompt_ids": "inputs/p001/prompt_ids.npy",
1224
+ "input:latents": "inputs/p001/latents.npy",
1225
+ "input:timestep": "inputs/p001/timestep.npy",
1226
+ "input:encoder_hidden_states": "inputs/p001/encoder_hidden_states.npy",
1227
+ "input:vae_latents": "inputs/p001/vae_latents.npy",
1228
+ "output:image": "outputs/p001/image.npy",
1229
+ "output:noise_pred": "outputs/p001/noise_pred.npy",
1230
+ "output:prompt_embeds": "outputs/p001/prompt_embeds.npy",
1231
+ "output": "outputs/p001.json"
1232
+ },
1233
+ "meta": {}
1234
+ },
1235
+ {
1236
+ "id": "h000",
1237
+ "split": "hidden",
1238
+ "origin": "generated",
1239
+ "files": {
1240
+ "input:prompt_ids": "inputs/h000/prompt_ids.npy",
1241
+ "input:latents": "inputs/h000/latents.npy",
1242
+ "input:timestep": "inputs/h000/timestep.npy",
1243
+ "input:encoder_hidden_states": "inputs/h000/encoder_hidden_states.npy",
1244
+ "input:vae_latents": "inputs/h000/vae_latents.npy",
1245
+ "output:image": "outputs/h000/image.npy",
1246
+ "output:noise_pred": "outputs/h000/noise_pred.npy",
1247
+ "output:prompt_embeds": "outputs/h000/prompt_embeds.npy",
1248
+ "output": "outputs/h000.json"
1249
+ },
1250
+ "meta": {}
1251
+ },
1252
+ {
1253
+ "id": "h001",
1254
+ "split": "hidden",
1255
+ "origin": "generated",
1256
+ "files": {
1257
+ "input:prompt_ids": "inputs/h001/prompt_ids.npy",
1258
+ "input:latents": "inputs/h001/latents.npy",
1259
+ "input:timestep": "inputs/h001/timestep.npy",
1260
+ "input:encoder_hidden_states": "inputs/h001/encoder_hidden_states.npy",
1261
+ "input:vae_latents": "inputs/h001/vae_latents.npy",
1262
+ "output:image": "outputs/h001/image.npy",
1263
+ "output:noise_pred": "outputs/h001/noise_pred.npy",
1264
+ "output:prompt_embeds": "outputs/h001/prompt_embeds.npy",
1265
+ "output": "outputs/h001.json"
1266
+ },
1267
+ "meta": {}
1268
+ },
1269
+ {
1270
+ "id": "h002",
1271
+ "split": "hidden",
1272
+ "origin": "generated",
1273
+ "files": {
1274
+ "input:prompt_ids": "inputs/h002/prompt_ids.npy",
1275
+ "input:latents": "inputs/h002/latents.npy",
1276
+ "input:timestep": "inputs/h002/timestep.npy",
1277
+ "input:encoder_hidden_states": "inputs/h002/encoder_hidden_states.npy",
1278
+ "input:vae_latents": "inputs/h002/vae_latents.npy",
1279
+ "output:image": "outputs/h002/image.npy",
1280
+ "output:noise_pred": "outputs/h002/noise_pred.npy",
1281
+ "output:prompt_embeds": "outputs/h002/prompt_embeds.npy",
1282
+ "output": "outputs/h002.json"
1283
+ },
1284
+ "meta": {}
1285
+ },
1286
+ {
1287
+ "id": "h003",
1288
+ "split": "hidden",
1289
+ "origin": "generated",
1290
+ "files": {
1291
+ "input:prompt_ids": "inputs/h003/prompt_ids.npy",
1292
+ "input:latents": "inputs/h003/latents.npy",
1293
+ "input:timestep": "inputs/h003/timestep.npy",
1294
+ "input:encoder_hidden_states": "inputs/h003/encoder_hidden_states.npy",
1295
+ "input:vae_latents": "inputs/h003/vae_latents.npy",
1296
+ "output:image": "outputs/h003/image.npy",
1297
+ "output:noise_pred": "outputs/h003/noise_pred.npy",
1298
+ "output:prompt_embeds": "outputs/h003/prompt_embeds.npy",
1299
+ "output": "outputs/h003.json"
1300
+ },
1301
+ "meta": {}
1302
+ }
1303
+ ],
1304
+ "splits": {
1305
+ "public": [
1306
+ "p000",
1307
+ "p001"
1308
+ ],
1309
+ "hidden": [
1310
+ "h000",
1311
+ "h001",
1312
+ "h002",
1313
+ "h003"
1314
+ ]
1315
+ },
1316
+ "notes": [],
1317
+ "determinism": {
1318
+ "outputs_bit_identical": true
1319
+ },
1320
+ "oracle_check": {
1321
+ "verdict": "ok",
1322
+ "ok": true,
1323
+ "cases_checked": 6,
1324
+ "bad": 0,
1325
+ "message": null,
1326
+ "bad_cases": []
1327
+ },
1328
+ "frozen_at": "2026-11-29T01:55:56Z"
1329
+ }
1330
+ }
sm8850-gpu-ternary/repro/Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # The machine nnopt built this deliverable on from scratch (REPRO.md, Tools): a public image and these
2
+ # packages, nothing of nnopt. build.sh fetches everything else itself. Build and use it:
3
+ # docker build --platform linux/amd64 -t build-env repro
4
+ # 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.sh
5
+ FROM ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac
6
+ ENV DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 LC_ALL=C.UTF-8
7
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git curl python3 python3-venv build-essential unzip xz-utils \
8
+ && rm -rf /var/lib/apt/lists/*
sm8850-gpu-ternary/repro/bench.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reproduce nnopt's numbers on your own device: the speed with nnopt's exact settings and, with --check, the outputs
3
+ on the public cases. See ../REPRO.md.
4
+
5
+ Needs python3 (3.8 or newer, no packages), sh, and adb (Android phones) or ssh and scp (a Jetson or Mac over the
6
+ network). plan.json next to this file holds the settings nnopt measured with and nnopt's numbers to compare against.
7
+
8
+ python3 repro/bench.py # speed, nnopt's settings, compared with nnopt's numbers
9
+ python3 repro/bench.py --check # outputs on the public cases, compared with the expected outputs
10
+ python3 repro/bench.py --deploy # run deploy.sh into --dir first
11
+ python3 repro/bench.py --sustained 600 # then run back to back for 10 minutes (throttling)
12
+ python3 repro/bench.py --plan repro/galaxy-s24/plan.json # measured on several phones: your phone's numbers
13
+
14
+ Connection: --serial SERIAL (adb; or $ANDROID_SERIAL), --ssh USER@HOST (or $SSH_TARGET), --local (this machine).
15
+ --dir is where deploy.sh installed the program on the device (default: plan.json's device_dir).
16
+ Exit code: 0 everything within tolerance, 1 something outside it, 2 an error.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import ast
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import shlex
28
+ import shutil
29
+ import statistics
30
+ import struct
31
+ import subprocess
32
+ import sys
33
+ import tempfile
34
+ import time
35
+ from array import array
36
+ from pathlib import Path
37
+
38
+ HERE = Path(__file__).resolve().parent
39
+ ROOT = HERE.parent # the deliverable: build.sh, deploy.sh, REPRO.md
40
+ TOKEN_TYPES = ("text_to_text", "vision_language")
41
+ OUT_EXT = {"text_to_text": ".json", "speech_to_text": ".json", "text_to_speech": ".wav", "vision_detection": ".json",
42
+ "vision_language": ".json", "kernel": "", "audio_generation": ".wav"}
43
+
44
+
45
+ class Fail(Exception):
46
+ pass
47
+
48
+
49
+ # ---------------------------------------------------------------- the device
50
+
51
+ class Device:
52
+ def __init__(self, kind: str, serial: str | None = None, target: str | None = None):
53
+ self.kind, self.serial, self.target = kind, serial, target
54
+ tool = {"adb": "adb", "ssh": "ssh", "local": "sh"}[kind]
55
+ if shutil.which(tool) is None:
56
+ raise Fail(f"{tool} is not installed or not on PATH (REPRO.md, Tools)")
57
+ if kind == "ssh" and not target:
58
+ raise Fail("--ssh USER@HOST (or SSH_TARGET) is needed for this device")
59
+
60
+ def describe(self) -> str:
61
+ return {"adb": f"adb{' -s ' + self.serial if self.serial else ''}", "ssh": f"ssh {self.target}",
62
+ "local": "this machine"}[self.kind]
63
+
64
+ def _adb(self) -> list[str]:
65
+ return ["adb"] + (["-s", self.serial] if self.serial else [])
66
+
67
+ def sh(self, script: str, timeout: float = 600) -> tuple[int, str]:
68
+ argv = {"adb": self._adb() + ["shell", script], "ssh": ["ssh", "-o", "BatchMode=yes", self.target or "", script],
69
+ "local": ["sh", "-c", script]}[self.kind]
70
+ try:
71
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
72
+ except subprocess.TimeoutExpired:
73
+ return 124, f"timed out after {timeout:.0f} s"
74
+ return p.returncode, p.stdout + p.stderr
75
+
76
+ def push(self, local: Path, remote: str) -> None:
77
+ argv = {"adb": self._adb() + ["push", str(local), remote],
78
+ "ssh": ["scp", "-q", "-r", str(local), f"{self.target}:{remote}"],
79
+ "local": ["cp", "-R", str(local), remote]}[self.kind]
80
+ p = subprocess.run(argv, capture_output=True, text=True)
81
+ if p.returncode != 0:
82
+ raise Fail(f"could not copy {local.name} to the device: {(p.stdout + p.stderr).strip()[-300:]}")
83
+
84
+ def pull(self, remote: str, local: Path) -> bool:
85
+ argv = {"adb": self._adb() + ["pull", remote, str(local)],
86
+ "ssh": ["scp", "-q", "-r", f"{self.target}:{remote}", str(local)],
87
+ "local": ["cp", "-R", remote, str(local)]}[self.kind]
88
+ return subprocess.run(argv, capture_output=True, text=True).returncode == 0
89
+
90
+
91
+ # Runs one command on the device: times it with the device's own clock and samples the memory (RSS) of its process
92
+ # tree, as nnopt does. Prints "REPRO START_NS END_NS EXIT PEAK_RSS_KB".
93
+ WRAP = r"""
94
+ d={io}; t={tag}
95
+ 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; }}
96
+ if [ -d /system/bin ]; then o="PID,PPID,RSS"; else o="pid,ppid,rss"; fi
97
+ rm -f "$d/$t.rc" "$d/$t.end"
98
+ s=$(now)
99
+ ( cd {dir} && {env}sh ./run.sh {args} > "$d/$t.log" 2>&1; r=$?; now > "$d/$t.end"; echo $r > "$d/$t.rc" ) &
100
+ root=$!; peak=0
101
+ while [ ! -f "$d/$t.rc" ]; do
102
+ 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 }}')
103
+ [ "${{m:-0}}" -gt "$peak" ] 2>/dev/null && peak=$m
104
+ sleep 0.2
105
+ done
106
+ echo "REPRO $s $(cat "$d/$t.end") $(cat "$d/$t.rc") $peak"
107
+ """
108
+ _MARK = re.compile(r"^REPRO (\d+) (\d+) (-?\d+) (\d+)\s*$", re.M)
109
+
110
+
111
+ def q(s: str) -> str:
112
+ return shlex.quote(s)
113
+
114
+
115
+ class Session:
116
+ """The program deployed in `folder` on the device, inputs staged in `folder`-repro-io."""
117
+
118
+ def __init__(self, dev: Device, folder: str, model_type: str, tmp: Path):
119
+ self.dev, self.dir, self.mt, self.tmp = dev, folder.rstrip("/"), model_type, tmp
120
+ self.io = self.dir + "-repro-io"
121
+ self.n = 0
122
+ rc, out = dev.sh(f"test -f {q(self.dir)}/run.sh && mkdir -p {q(self.io)} && echo ok", 60)
123
+ if "ok" not in out:
124
+ raise Fail(f"no run.sh in {self.dir} on the device: deploy first (bash deploy.sh {self.dir}, or --deploy)")
125
+
126
+ def stage(self, local: Path) -> str:
127
+ remote = f"{self.io}/{local.name}"
128
+ self.dev.push(local, remote if local.is_file() else self.io + "/")
129
+ return remote
130
+
131
+ def run(self, args: dict, *, repeat: int = 1, fetch_out: bool = False, timeout: float = 3600,
132
+ env: dict | None = None) -> dict:
133
+ self.n += 1
134
+ tag = f"r{self.n}"
135
+ out = f"{self.io}/{tag}.out{OUT_EXT[self.mt]}"
136
+ met = f"{self.io}/{tag}.metrics.json"
137
+ line = command(self.mt, args, out=out, metrics=met, repeat=repeat)
138
+ exports = "".join(f"{k}={q(str(v))} " for k, v in (env or {}).items())
139
+ rc, text = self.dev.sh(WRAP.format(io=q(self.io), tag=tag, dir=q(self.dir), args=line, env=exports), timeout)
140
+ m = _MARK.search(text)
141
+ res = {"command": "sh ./run.sh " + line, "exit": int(m.group(3)) if m else rc, "wall_ms": None,
142
+ "peak_rss_mb": None, "metrics": None, "out": None}
143
+ if m:
144
+ res["wall_ms"] = (int(m.group(2)) - int(m.group(1))) / 1e6
145
+ res["peak_rss_mb"] = int(m.group(4)) / 1024 or None
146
+ mloc = self.tmp / f"{tag}.metrics.json"
147
+ if self.dev.pull(met, mloc) and mloc.is_file():
148
+ try:
149
+ res["metrics"] = json.loads(mloc.read_text())
150
+ except ValueError:
151
+ pass
152
+ if fetch_out:
153
+ oloc = self.tmp / Path(out).name
154
+ if self.dev.pull(out, oloc) and oloc.exists():
155
+ res["out"] = oloc
156
+ if res["exit"] != 0:
157
+ _, log = self.dev.sh(f"tail -c 2000 {q(self.io)}/{tag}.log", 60)
158
+ res["log"] = log
159
+ return res
160
+
161
+ def close(self) -> None:
162
+ self.dev.sh(f"rm -rf {q(self.io)}", 120)
163
+
164
+
165
+ def command(mt: str, a: dict, *, out: str, metrics: str, repeat: int = 1) -> str:
166
+ """run.sh's arguments for one request (CONTRACT.md)."""
167
+ mode = a.get("mode", "generate")
168
+ args: list[str] = []
169
+ if mt == "audio_generation":
170
+ args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0)),
171
+ "--seconds", f"{float(a.get('seconds') or 10):.6f}".rstrip("0").rstrip(".")]
172
+ elif mt == "vision_detection":
173
+ for im in a["images"]:
174
+ args += ["--image", q(im)]
175
+ elif mt in TOKEN_TYPES:
176
+ if mt == "vision_language":
177
+ args += ["--image", q(a["image"])]
178
+ args += ["--prompt-file", q(a["input"]), "--max-new-tokens", str(int(a["max_new_tokens"]))]
179
+ if a.get("ignore_eos"):
180
+ args.append("--ignore-eos")
181
+ elif mt == "speech_to_text":
182
+ args = ["--audio", q(a["input"])]
183
+ elif mt == "kernel":
184
+ args = ["--inputs", q(a["input"])]
185
+ else: # text_to_speech
186
+ args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0))]
187
+ args += ["--out", q(out), "--metrics", q(metrics)]
188
+ if repeat > 1:
189
+ args += ["--repeat", str(int(repeat))]
190
+ return " ".join(args)
191
+
192
+
193
+ # ---------------------------------------------------------------- numbers
194
+
195
+ def derive(mt: str, r: dict, audio_s: float | None, batch: int = 1) -> dict:
196
+ """One request's numbers from the port's metrics, as nnopt computes them."""
197
+ t = float(r.get("total_ms") or 0)
198
+ d: dict = {"total_ms": t}
199
+ if mt == "vision_detection":
200
+ d.update(latency_ms=t, per_image_ms=t / batch, fps=batch * 1000 / t if t > 0 else None)
201
+ elif mt in TOKEN_TYPES:
202
+ ttft, n, p = float(r.get("ttft_ms") or 0), int(r.get("new_tokens") or 0), int(r.get("prompt_tokens") or 0)
203
+ dec = t - ttft
204
+ d.update(ttft_ms=ttft, tokens_per_s=(n - 1) / (dec / 1000) if dec > 0 and n > 1 else None,
205
+ prefill_tokens_per_s=p / (ttft / 1000) if ttft > 0 else None,
206
+ e2e_tokens_per_s=n / (t / 1000) if t > 0 else None)
207
+ elif mt == "speech_to_text":
208
+ d.update(latency_ms=t, real_time_factor=t / 1000 / audio_s if audio_s else None)
209
+ elif mt == "kernel":
210
+ d["latency_ms"] = t
211
+ elif mt == "audio_generation":
212
+ n, first = int(r.get("frames") or 1), float(r.get("ttfa_ms") or 0)
213
+ per = (t - first) / (n - 1) if n > 1 else t
214
+ audio_ms = 1000 * audio_s / n if audio_s else None
215
+ d.update(time_to_first_audio_ms=first, latency_ms=t, ms_per_frame=per,
216
+ real_time_factor=per / audio_ms if audio_ms else None)
217
+ else: # text_to_speech
218
+ d.update(time_to_first_audio_ms=r.get("ttfa_ms"), latency_ms=t,
219
+ real_time_factor=t / 1000 / audio_s if audio_s else None)
220
+ return d
221
+
222
+
223
+ def pct(values: list[float], p: float) -> float:
224
+ v = sorted(values)
225
+ if len(v) == 1:
226
+ return v[0]
227
+ k = (len(v) - 1) * p / 100
228
+ f = math.floor(k)
229
+ return v[f] + (v[min(f + 1, len(v) - 1)] - v[f]) * (k - f)
230
+
231
+
232
+ def stats(values) -> dict | None:
233
+ v = [float(x) for x in values if x is not None and math.isfinite(float(x))]
234
+ if not v:
235
+ return None
236
+ return {"median": statistics.median(v), "p10": pct(v, 10), "p90": pct(v, 90), "n": len(v)}
237
+
238
+
239
+ def fmt(x) -> str:
240
+ if x is None:
241
+ return "–"
242
+ a = abs(x)
243
+ return f"{x:.0f}" if a >= 1000 else f"{x:.1f}" if a >= 10 else f"{x:.3g}"
244
+
245
+
246
+ def wav_info(path: Path) -> tuple[int, int, int, int, bytes]:
247
+ """(sample rate, channels, bits, format, data) of a RIFF WAV (PCM or float)."""
248
+ b = path.read_bytes()
249
+ if b[:4] != b"RIFF" or b[8:12] != b"WAVE":
250
+ raise Fail(f"{path.name} is not a WAV file")
251
+ i, rate, ch, bits, fmt_tag, data = 12, 0, 0, 0, 0, b""
252
+ while i + 8 <= len(b):
253
+ cid, size = b[i:i + 4], struct.unpack("<I", b[i + 4:i + 8])[0]
254
+ body = b[i + 8:i + 8 + size]
255
+ if cid == b"fmt ":
256
+ fmt_tag, ch, rate = struct.unpack("<HHI", body[:8])
257
+ bits = struct.unpack("<H", body[14:16])[0]
258
+ if fmt_tag == 0xFFFE and len(body) >= 26: # WAVE_FORMAT_EXTENSIBLE: the real format is in the GUID
259
+ fmt_tag = struct.unpack("<H", body[24:26])[0]
260
+ elif cid == b"data":
261
+ data = body
262
+ i += 8 + size + (size & 1)
263
+ if not rate or not ch or not bits:
264
+ raise Fail(f"{path.name}: no WAV format chunk")
265
+ return rate, ch, bits, fmt_tag, data
266
+
267
+
268
+ def wav_seconds(path: Path) -> float:
269
+ rate, ch, bits, _, data = wav_info(path)
270
+ return len(data) / (ch * bits // 8) / rate
271
+
272
+
273
+ def wav_rms(path: Path) -> float:
274
+ rate, ch, bits, tag, data = wav_info(path)
275
+ if tag == 3 and bits == 32:
276
+ a = array("f")
277
+ elif bits == 16:
278
+ a = array("h")
279
+ else:
280
+ return float("nan")
281
+ a.frombytes(data[: len(data) // a.itemsize * a.itemsize])
282
+ if sys.byteorder == "big":
283
+ a.byteswap()
284
+ scale = 1.0 if a.typecode == "f" else 32768.0
285
+ return math.sqrt(sum((x / scale) ** 2 for x in a) / len(a)) if len(a) else 0.0
286
+
287
+
288
+ # ---------------------------------------------------------------- speed
289
+
290
+ def speed(sess: Session, plan: dict, args: argparse.Namespace) -> dict | None:
291
+ if not plan.get("settings") or not plan.get("inputs"):
292
+ print("nnopt did not measure the speed of this deliverable (see REPRO.md)")
293
+ return None
294
+ mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"]
295
+ warmup = args.warmup if args.warmup is not None else int(st["warmup"])
296
+ runs = args.runs if args.runs is not None else int(st["runs"])
297
+ repeat = int(st["repeat"])
298
+ batch = int(st.get("batch") or 1)
299
+ req: dict = {"mode": plan.get("mode", "generate")}
300
+ for k in ("max_new_tokens", "ignore_eos", "seed", "seconds"):
301
+ if st.get(k) is not None:
302
+ req[k] = st[k]
303
+ staged = {k: sess.stage(HERE / v) for k, v in inp.items() if isinstance(v, str)}
304
+ if "images" in inp:
305
+ req["images"] = [sess.stage(HERE / v) for v in inp["images"]]
306
+ req.update({k: v for k, v in staged.items()})
307
+ audio_s = None
308
+ if mt == "speech_to_text":
309
+ audio_s = wav_seconds(HERE / inp["input"])
310
+ elif mt == "audio_generation":
311
+ audio_s = float(st.get("seconds") or 10)
312
+ rest = float(st.get("rest_s") or 0)
313
+ print(f"{warmup} warm-up run{'s' * (warmup != 1)}, {runs} timed run{'s' * (runs != 1)} of {repeat} "
314
+ f"request{'s' * (repeat != 1)} each{settings_text(mt, st)}")
315
+ for i in range(warmup):
316
+ r = sess.run(req, repeat=1, timeout=args.timeout)
317
+ _ok(r, f"warm-up {i + 1}")
318
+ print(f" warm-up {i + 1}/{warmup}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" warm-up {i + 1} done")
319
+ timed, pairs, peak = [], [], []
320
+ for i in range(runs):
321
+ if rest:
322
+ time.sleep(rest)
323
+ r = sess.run(req, repeat=repeat, fetch_out=(i == 0), timeout=args.timeout)
324
+ _ok(r, f"timed run {i + 1}")
325
+ met = r["metrics"] or {}
326
+ if not isinstance(met.get("runs"), list) or len(met["runs"]) != repeat:
327
+ raise Fail(f"timed run {i + 1}: the metrics file needs {repeat} entries in \"runs\" (--repeat {repeat})")
328
+ if i == 0 and mt == "text_to_speech" and r["out"]:
329
+ audio_s = wav_seconds(r["out"])
330
+ reqs = [derive(mt, x, audio_s, batch) for x in met["runs"]]
331
+ timed.append({"wall_ms": r["wall_ms"], "load_ms": met.get("load_ms"), "requests": reqs,
332
+ "self_peak_mem_mb": met.get("peak_mem_mb")})
333
+ if r["peak_rss_mb"]:
334
+ peak.append(r["peak_rss_mb"])
335
+ line = f" timed run {i + 1}/{runs}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" timed run {i + 1}"
336
+ if plan.get("external_check", True):
337
+ p_req, p_rep = paired(mt, req, repeat, plan)
338
+ pr = sess.run(p_req, repeat=p_rep, timeout=args.timeout)
339
+ if pr["exit"] == 0 and pr["wall_ms"] and r["wall_ms"]:
340
+ pairs.append(r["wall_ms"] - pr["wall_ms"])
341
+ print(line)
342
+ warm = [x for t in timed for x in (t["requests"][1:] if len(t["requests"]) > 1 else t["requests"])]
343
+ keys = sorted({k for x in warm for k, v in x.items() if v is not None})
344
+ summary = {k: stats(x.get(k) for x in warm) for k in keys}
345
+ summary["load_ms"] = stats(t["load_ms"] for t in timed)
346
+ graded = {k: s["median"] for k, s in summary.items() if s}
347
+ if peak:
348
+ graded["peak_mem_mb"] = max(peak)
349
+ ext = external(mt, pairs, st, repeat, batch, audio_s, plan)
350
+ if ext:
351
+ graded.update(ext_cap(mt, graded, ext))
352
+ return {"runs": timed, "summary": summary, "graded": graded, "external": ext}
353
+
354
+
355
+ def settings_text(mt: str, st: dict) -> str:
356
+ bits = []
357
+ if mt in TOKEN_TYPES:
358
+ bits.append(f"{st['max_new_tokens']} new tokens per request" + (" (--ignore-eos)" if st.get("ignore_eos") else ""))
359
+ if st.get("prompt_tokens"):
360
+ bits.append(f"a ~{st['prompt_tokens']}-token prompt")
361
+ if mt == "vision_detection" and int(st.get("batch") or 1) > 1:
362
+ bits.append(f"{st['batch']} images per request")
363
+ if st.get("resolution"):
364
+ bits.append(f"{st['resolution']} input")
365
+ if mt == "audio_generation":
366
+ bits.append(f"{st.get('seconds')} s of audio per request")
367
+ return (": " + ", ".join(bits)) if bits else ""
368
+
369
+
370
+ def paired(mt: str, req: dict, repeat: int, plan: dict) -> tuple[dict, int]:
371
+ """The same request with the least work (one new token; one audio frame), or at --repeat 1: the difference in
372
+ wall time is the device-clock speed, which keeps the port's own timings honest."""
373
+ if mt in TOKEN_TYPES:
374
+ return {**req, "max_new_tokens": 1}, repeat
375
+ if mt == "audio_generation" and plan.get("frame_seconds"):
376
+ return {**req, "seconds": plan["frame_seconds"]}, repeat
377
+ return req, 1
378
+
379
+
380
+ def external(mt, pairs, st, repeat, batch, audio_s, plan) -> dict | None:
381
+ if not pairs:
382
+ return None
383
+ d = statistics.median(pairs)
384
+ if d <= 0:
385
+ return None
386
+ if mt in TOKEN_TYPES:
387
+ return {"tokens_per_s": (int(st["max_new_tokens"]) - 1) * repeat / (d / 1000)}
388
+ if mt == "audio_generation":
389
+ fs = plan.get("frame_seconds")
390
+ n = (max(1, round(float(st.get("seconds") or 10) / fs)) - 1) * repeat if fs else 0
391
+ return {"ms_per_frame": d / n, "real_time_factor": d / n / (1000 * fs)} if n > 0 else None
392
+ if repeat < 2:
393
+ return None
394
+ per = d / (repeat - 1)
395
+ out = {"latency_ms": per}
396
+ if mt == "vision_detection":
397
+ out["fps"] = batch * 1000 / per
398
+ if audio_s:
399
+ out["real_time_factor"] = per / 1000 / audio_s
400
+ return out
401
+
402
+
403
+ def ext_cap(mt: str, g: dict, ext: dict, tol: float = 0.15) -> dict:
404
+ """nnopt's rule: a self-reported speed more than 15% better than the device-clock measurement is replaced by it."""
405
+ out = {}
406
+ if mt in TOKEN_TYPES and ext.get("tokens_per_s") and g.get("tokens_per_s"):
407
+ if g["tokens_per_s"] > ext["tokens_per_s"] * (1 + tol):
408
+ out["tokens_per_s"] = ext["tokens_per_s"]
409
+ elif mt == "audio_generation" and ext.get("ms_per_frame") and g.get("ms_per_frame"):
410
+ if ext["ms_per_frame"] > g["ms_per_frame"] * (1 + tol):
411
+ out.update(ms_per_frame=ext["ms_per_frame"], real_time_factor=ext.get("real_time_factor"))
412
+ elif ext.get("latency_ms") and g.get("latency_ms"):
413
+ ratio = ext["latency_ms"] / g["latency_ms"]
414
+ if ratio > 1 + tol:
415
+ for k in ("latency_ms", "real_time_factor", "time_to_first_audio_ms", "per_image_ms"):
416
+ if g.get(k) is not None:
417
+ out[k] = g[k] * ratio
418
+ if g.get("fps"):
419
+ out["fps"] = g["fps"] / ratio
420
+ return out
421
+
422
+
423
+ def compare(plan: dict, mine: dict) -> tuple[list[list[str]], bool]:
424
+ rows, ok = [], True
425
+ for c in plan.get("compare") or []:
426
+ got, ref, tol = mine["graded"].get(c["key"]), c.get("nnopt"), float(c.get("tolerance_pct") or 10)
427
+ if got is None or not ref:
428
+ rows.append([c["label"], fmt(got), fmt(ref), "–", "not measured"])
429
+ continue
430
+ diff = 100 * (got - ref) / ref
431
+ within = abs(diff) <= tol
432
+ ok &= within or c.get("informational", False)
433
+ rows.append([c["label"] + (f" ({c['unit']})" if c.get("unit") else ""), fmt(got), fmt(ref), f"{diff:+.1f}%",
434
+ ("yes" if within else "NO") + f" (±{tol:g}%)"])
435
+ return rows, ok
436
+
437
+
438
+ def table(head: list[str], rows: list[list[str]]) -> str:
439
+ w = [max(len(str(r[i])) for r in [head] + rows) for i in range(len(head))]
440
+ line = lambda r: " ".join(str(x).ljust(w[i]) for i, x in enumerate(r)) # noqa: E731
441
+ return "\n".join([line(head), line(["-" * n for n in w])] + [line(r) for r in rows])
442
+
443
+
444
+ def sustained(sess: Session, plan: dict, seconds: float, args: argparse.Namespace) -> dict:
445
+ mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"]
446
+ key = (plan.get("compare") or [{}])[0].get("key")
447
+ req = {"mode": plan.get("mode", "generate"), **{k: st[k] for k in ("max_new_tokens", "ignore_eos", "seed", "seconds")
448
+ if st.get(k) is not None}}
449
+ req.update({k: f"{sess.io}/{Path(v).name}" for k, v in inp.items() if isinstance(v, str)})
450
+ if "images" in inp:
451
+ req["images"] = [f"{sess.io}/{Path(v).name}" for v in inp["images"]]
452
+ audio_s = wav_seconds(HERE / inp["input"]) if mt == "speech_to_text" else (
453
+ float(st.get("seconds") or 10) if mt == "audio_generation" else None)
454
+ series, t0 = [], time.monotonic()
455
+ print(f"sustained run: {seconds:.0f} s back to back")
456
+ while time.monotonic() - t0 < seconds:
457
+ r = sess.run(req, repeat=int(st.get("sustained_repeat") or st["repeat"]), timeout=args.timeout)
458
+ _ok(r, "sustained run")
459
+ reqs = [derive(mt, x, audio_s, int(st.get("batch") or 1)) for x in (r["metrics"] or {}).get("runs") or []]
460
+ s = stats(x.get(key) for x in reqs[1:] or reqs)
461
+ if s:
462
+ series.append((time.monotonic() - t0, s["median"]))
463
+ print(f" {series[-1][0]:5.0f} s {fmt(s['median'])}")
464
+ if len(series) < 2:
465
+ return {"series": series}
466
+ first = statistics.median(v for t, v in series if t <= series[0][0] + 60)
467
+ last = statistics.median(v for t, v in series if t >= series[-1][0] - 60)
468
+ return {"series": series, "first_minute": first, "last_minute": last, "ratio": last / first if first else None}
469
+
470
+
471
+ # ---------------------------------------------------------------- outputs
472
+
473
+ def words(text: str) -> list[str]:
474
+ return re.sub(r"[^\w\s']", " ", text.lower()).split()
475
+
476
+
477
+ def edits(a: list, b: list) -> int:
478
+ prev = list(range(len(b) + 1))
479
+ for i, x in enumerate(a, 1):
480
+ cur = [i]
481
+ for j, y in enumerate(b, 1):
482
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)))
483
+ prev = cur
484
+ return prev[-1]
485
+
486
+
487
+ def iou(a: list, b: list) -> float:
488
+ ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
489
+ iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
490
+ inter = ix * iy
491
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
492
+ return inter / union if union > 0 else 0.0
493
+
494
+
495
+ NPY = {"f4": ("f", 4), "f8": ("d", 8), "i1": ("b", 1), "u1": ("B", 1), "i2": ("h", 2), "u2": ("H", 2),
496
+ "i4": ("i", 4), "u4": ("I", 4), "i8": ("q", 8), "u8": ("Q", 8), "b1": ("B", 1)}
497
+
498
+
499
+ def read_npy(path: Path) -> tuple[str, list[float]]:
500
+ """A NumPy .npy file (format 1.0/2.0, C order) as (dtype, flat values), with the standard library only."""
501
+ b = path.read_bytes()
502
+ if b[:6] != b"\x93NUMPY":
503
+ raise Fail(f"{path.name} is not a .npy file")
504
+ hl, off = (struct.unpack("<H", b[8:10])[0], 10) if b[6] == 1 else (struct.unpack("<I", b[8:12])[0], 12)
505
+ head = ast.literal_eval(b[off:off + hl].decode("latin1"))
506
+ descr, data = head["descr"], b[off + hl:]
507
+ if head.get("fortran_order"):
508
+ raise Fail(f"{path.name}: Fortran order is not supported")
509
+ kind = descr.lstrip("<>|=")
510
+ if kind == "f2":
511
+ n = len(data) // 2
512
+ return kind, list(struct.unpack(("<" if descr[0] != ">" else ">") + "e" * n, data[:2 * n]))
513
+ if kind not in NPY:
514
+ raise Fail(f"{path.name}: dtype {descr} is not supported here")
515
+ code, size = NPY[kind]
516
+ a = array(code)
517
+ if a.itemsize != size:
518
+ raise Fail(f"{path.name}: this Python has no {size}-byte {code} type")
519
+ a.frombytes(data[: len(data) // size * size])
520
+ if (descr[0] == ">") != (sys.byteorder == "big") and size > 1:
521
+ a.byteswap()
522
+ return kind, list(a)
523
+
524
+
525
+ def check(sess: Session, plan: dict, args: argparse.Namespace) -> bool:
526
+ c = plan.get("check") or {}
527
+ cases, rules, mt = c.get("cases") or [], c.get("rules") or {}, plan["model_type"]
528
+ if not cases:
529
+ print("no public cases to check outputs against")
530
+ return True
531
+ print(f"{len(cases)} public case{'s' * (len(cases) != 1)}: {c.get('what', 'expected outputs')}")
532
+ ok, rows = True, []
533
+ tot = {"edits": 0, "words": 0, "matched": 0, "ref": 0, "ours": 0, "prefix": [], "tok": 0}
534
+ for case in cases:
535
+ base = HERE / case["dir"]
536
+ req: dict = {"mode": "generate"}
537
+ for k in ("input", "image"):
538
+ if case.get(k):
539
+ req[k] = sess.stage(base / case[k])
540
+ if mt == "vision_detection":
541
+ req["images"] = [req.pop("input")]
542
+ exp_path = base / case["expected"] if case.get("expected") else None
543
+ exp = json.loads(exp_path.read_text()) if exp_path and exp_path.suffix == ".json" else None
544
+ if mt in TOKEN_TYPES:
545
+ req["max_new_tokens"] = max(1, len(exp["tokens"]))
546
+ if mt in ("text_to_speech", "audio_generation"):
547
+ req["seed"] = case.get("seed", 0)
548
+ if mt == "audio_generation":
549
+ req["seconds"] = case.get("seconds", 10)
550
+ r = sess.run(req, repeat=1, fetch_out=True, timeout=args.timeout)
551
+ if r["exit"] != 0 or not r["out"]:
552
+ ok = False
553
+ rows.append([case["id"], "run failed", (r.get("log") or "")[-120:].replace("\n", " ")])
554
+ continue
555
+ if mt in TOKEN_TYPES:
556
+ got = json.loads(Path(r["out"]).read_text())
557
+ same_prompt = got.get("prompt_tokens") == exp["prompt_tokens"]
558
+ n = 0
559
+ for a, b in zip(got.get("tokens") or [], exp["tokens"]):
560
+ if a != b:
561
+ break
562
+ n += 1
563
+ frac = n / max(1, len(exp["tokens"]))
564
+ tot["prefix"].append(frac)
565
+ tot["tok"] += same_prompt
566
+ rows.append([case["id"], "prompt tokens " + ("match" if same_prompt else "DIFFER"),
567
+ f"{n}/{len(exp['tokens'])} new tokens identical before the first difference"])
568
+ elif mt == "speech_to_text":
569
+ got = json.loads(Path(r["out"]).read_text()).get("text", "")
570
+ e = edits(words(got), words(exp["text"]))
571
+ tot["edits"] += e
572
+ tot["words"] += len(words(exp["text"]))
573
+ rows.append([case["id"], f"{e} word edit{'s' * (e != 1)}", got[:60]])
574
+ elif mt == "text_to_speech":
575
+ mine, ref = wav_seconds(Path(r["out"])), float(case["expected_seconds"])
576
+ within = abs(mine / ref - 1) <= float(rules.get("duration_ratio_tolerance", 0.05))
577
+ ok &= within
578
+ rows.append([case["id"], f"{mine:.2f} s of audio (expected {ref:.2f} s)", "ok" if within else "DIFFERS"])
579
+ elif mt == "vision_detection":
580
+ got = json.loads(Path(r["out"]).read_text())
581
+ thr, margin, need = float(rules.get("score_threshold", 0.3)), float(rules.get("score_margin", 0.05)), float(
582
+ rules.get("iou_match", 0.5))
583
+ ref = [(b, cl) for b, s, cl in zip(exp["boxes"], exp["scores"], exp["classes"]) if s >= thr]
584
+ ours = [(b, cl) for b, s, cl in zip(got.get("boxes", []), got.get("scores", []), got.get("classes", []))
585
+ if s >= thr - margin]
586
+ used, m = set(), 0
587
+ for b, cl in ref:
588
+ best = max(((iou(b, ob), j) for j, (ob, oc) in enumerate(ours) if oc == cl and j not in used),
589
+ default=(0.0, -1))
590
+ if best[0] >= need:
591
+ used.add(best[1])
592
+ m += 1
593
+ tot["matched"] += m
594
+ tot["ref"] += len(ref)
595
+ tot["ours"] += len([1 for b, s in zip(got.get("boxes", []), got.get("scores", [])) if s >= thr])
596
+ rows.append([case["id"], f"{m}/{len(ref)} expected objects found", f"{len(ours)} detected"])
597
+ elif mt == "kernel":
598
+ bad, total, worst = 0, 0, 0.0
599
+ for t in case["outputs"]:
600
+ pulled = Path(r["out"]) / f"{t['name']}.npy"
601
+ if not pulled.is_file():
602
+ ok = False
603
+ rows.append([case["id"], f"no {t['name']}.npy written", ""])
604
+ continue
605
+ kind, mine = read_npy(pulled)
606
+ _, ref = read_npy(base / t["expected"])
607
+ if len(mine) != len(ref):
608
+ ok = False
609
+ rows.append([case["id"], f"{t['name']}: {len(mine)} values, expected {len(ref)}", ""])
610
+ continue
611
+ if kind.startswith("f"):
612
+ rt, at = (float(rules.get("fp16_rtol", 1e-2)), float(rules.get("fp16_atol_scale", 1e-2))) \
613
+ if kind == "f2" or t.get("dtype") == "float16" else \
614
+ (float(rules.get("fp32_rtol", 1e-4)), float(rules.get("fp32_atol_scale", 1e-4)))
615
+ rms = math.sqrt(sum(x * x for x in ref) / len(ref)) if ref else 0.0
616
+ for a, b in zip(mine, ref):
617
+ d = abs(a - b)
618
+ worst = max(worst, d)
619
+ bad += not (d <= at * rms + rt * abs(b))
620
+ else:
621
+ lim = float(rules.get("int8_max_abs_diff", 1) if kind in ("i1", "u1") else rules.get("int_max_abs_diff", 0))
622
+ for a, b in zip(mine, ref):
623
+ worst = max(worst, abs(a - b))
624
+ bad += abs(a - b) > lim
625
+ total += len(ref)
626
+ frac = bad / total if total else 0.0
627
+ within = frac <= float(rules.get("max_mismatch_frac", 0.0))
628
+ ok &= within
629
+ rows.append([case["id"], f"{bad} of {total} values outside tolerance", f"largest difference {worst:.3g}"])
630
+ else: # audio_generation: free-running audio is random; length and level are what can be checked
631
+ dur, rms = wav_seconds(Path(r["out"])), wav_rms(Path(r["out"]))
632
+ want = float(case.get("seconds", 10))
633
+ within = abs(dur - want) <= 0.05 * want + 0.1 and (math.isnan(rms) or rms >= float(rules.get("free_run_min_rms", 0.001)))
634
+ ok &= within
635
+ rows.append([case["id"], f"{dur:.2f} s of audio, RMS {rms:.3g}", "ok" if within else "DIFFERS"])
636
+ print(table(["case", "result", ""], rows))
637
+ if mt in TOKEN_TYPES and tot["prefix"]:
638
+ mean, need = statistics.mean(tot["prefix"]), float(rules.get("greedy_prefix_min", 0.75))
639
+ tok_ok = tot["tok"] == len(tot["prefix"])
640
+ ok &= tok_ok and mean >= need
641
+ print(f"prompt tokens identical on {tot['tok']}/{len(tot['prefix'])} cases (needed: all); greedy prefix "
642
+ f"{mean:.2f} (needed: {need:g} or more)")
643
+ if mt == "speech_to_text" and tot["words"]:
644
+ wer, need = tot["edits"] / tot["words"], float(rules.get("wer_vs_reference_max", 0.02))
645
+ ok &= wer <= need
646
+ print(f"word error rate against the expected transcripts {wer:.3f} (needed: {need:g} or less)")
647
+ if mt == "vision_detection" and tot["ref"]:
648
+ rec, prec = tot["matched"] / tot["ref"], tot["matched"] / max(1, tot["ours"])
649
+ need_r, need_p = float(rules.get("recall_min", 0.97)), float(rules.get("precision_min", 0.97))
650
+ ok &= rec >= need_r and prec >= need_p
651
+ print(f"recall {rec:.3f} (needed {need_r:g}), precision {prec:.3f} (needed {need_p:g})")
652
+ print("outputs: " + ("REPRODUCED" if ok else "NOT reproduced"))
653
+ return ok
654
+
655
+
656
+ def _ok(r: dict, what: str) -> None:
657
+ if r["exit"] != 0:
658
+ raise Fail(f"{what} failed (exit {r['exit']}): {(r.get('log') or '').strip()[-800:]}\ncommand: {r['command']}")
659
+
660
+
661
+ # ---------------------------------------------------------------- main
662
+
663
+ def main(argv: list[str] | None = None) -> int:
664
+ ap = argparse.ArgumentParser(description="Reproduce nnopt's numbers on your own device (REPRO.md).")
665
+ ap.add_argument("--plan", default=str(HERE / "plan.json"))
666
+ ap.add_argument("--serial", help="the phone's serial (adb devices); default $ANDROID_SERIAL")
667
+ ap.add_argument("--ssh", help="USER@HOST of a Jetson or Mac; default $SSH_TARGET")
668
+ ap.add_argument("--local", action="store_true", help="the program runs on this machine")
669
+ ap.add_argument("--dir", help="where deploy.sh installed the program on the device")
670
+ ap.add_argument("--deploy", action="store_true", help="run bash deploy.sh DIR first")
671
+ ap.add_argument("--check", action="store_true", help="check the outputs on the public cases instead of the speed")
672
+ ap.add_argument("--warmup", type=int)
673
+ ap.add_argument("--runs", type=int)
674
+ ap.add_argument("--sustained", type=float, default=0.0, help="seconds of back-to-back runs after the timed runs")
675
+ ap.add_argument("--timeout", type=float, default=3600.0, help="seconds per run")
676
+ ap.add_argument("--json", help="also write the results to this file")
677
+ a = ap.parse_args(argv)
678
+ if not Path(a.plan).is_file(): # measured on several phones: each has its own plan (repro/<phone>/plan.json)
679
+ mine = sorted(p.parent.name for p in HERE.glob("*/plan.json"))
680
+ print(f"error: no {a.plan}" + (f"; nnopt measured this on several phones: pass --plan repro/<phone>/plan.json "
681
+ f"for yours, <phone> one of: {', '.join(mine)}" if mine else ""), file=sys.stderr)
682
+ return 2
683
+ plan = json.loads(Path(a.plan).read_text())
684
+ kind = "local" if a.local else "ssh" if a.ssh else "adb" if a.serial else plan.get("connection", "adb")
685
+ serial = a.serial or (os.environ.get("ANDROID_SERIAL") if kind == "adb" else None)
686
+ target = a.ssh or (os.environ.get("SSH_TARGET") if kind == "ssh" else None)
687
+ folder = a.dir or plan["device_dir"]
688
+ try:
689
+ dev = Device(kind, serial=serial, target=target)
690
+ if a.deploy:
691
+ print(f"deploy: bash deploy.sh {folder}")
692
+ env = {**os.environ, "NNOPT_PORT_DIR": folder, **({"ANDROID_SERIAL": serial} if serial else {})}
693
+ if subprocess.run(["bash", "deploy.sh", folder], cwd=ROOT, env=env).returncode != 0:
694
+ raise Fail("deploy.sh failed")
695
+ print(f"{plan.get('title', 'nnopt reproduction')} · {dev.describe()} · {folder}")
696
+ with tempfile.TemporaryDirectory(prefix="nnopt-repro-") as tmp:
697
+ sess = Session(dev, folder, plan["model_type"], Path(tmp))
698
+ try:
699
+ if a.check:
700
+ ok = check(sess, plan, a)
701
+ result = {"check": ok}
702
+ elif (mine := speed(sess, plan, a)) is None:
703
+ ok, result = True, {"speed": None}
704
+ else:
705
+ rows, ok = compare(plan, mine)
706
+ print()
707
+ print(table(["metric", "yours", "nnopt", "diff", "within"], rows))
708
+ if mine["graded"].get("peak_mem_mb"):
709
+ print(f"peak memory (process tree RSS): {fmt(mine['graded']['peak_mem_mb'])} MB")
710
+ result = {"speed": mine, "compared": rows, "within": ok}
711
+ if a.sustained > 0:
712
+ result["sustained"] = s = sustained(sess, plan, a.sustained, a)
713
+ if s.get("ratio"):
714
+ print(f"sustained: last minute / first minute = {s['ratio']:.2f}")
715
+ print("speed: " + ("REPRODUCED" if ok else "NOT reproduced (see REPRO.md, Expected results)"))
716
+ finally:
717
+ sess.close()
718
+ out = Path(a.json) if a.json else HERE / "results" / time.strftime("run-%Y%m%d-%H%M%S.json")
719
+ out.parent.mkdir(parents=True, exist_ok=True)
720
+ out.write_text(json.dumps(result, indent=1, default=str) + "\n")
721
+ print(f"results: {out}")
722
+ return 0 if ok else 1
723
+ except Fail as e:
724
+ print(f"error: {e}", file=sys.stderr)
725
+ return 2
726
+
727
+
728
+ if __name__ == "__main__":
729
+ sys.exit(main())
sm8850-gpu-ternary/repro/inputs/tensors/encoder_hidden_states.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9560806c6ebef457554c2ef6924ec2e833a6d29a8684fb5883f05d4acabbcd85
3
+ size 15728768
sm8850-gpu-ternary/repro/inputs/tensors/latents.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2a77ead969fe3b28d9310112ff6b6ae3c133ab571b78065283a18a080fd2137
3
+ size 524416
sm8850-gpu-ternary/repro/inputs/tensors/prompt_ids.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4bc73b0afd77afeabea56b8f0b2877cb2a5aad11423c4ce7604c12417d99aa9
3
+ size 192
sm8850-gpu-ternary/repro/inputs/tensors/timestep.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4ae3c6d214471a218324d43af536acfd499898d4120967cf343402080b8b6ec
3
+ size 132
sm8850-gpu-ternary/repro/inputs/tensors/vae_latents.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f2c0ae257bb0a8e8bdc09414d22e4a9d3f280d1b1408c79ebd60fef0a721a78
3
+ size 524416
sm8850-gpu-ternary/repro/plan.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "nnopt-repro",
3
+ "version": 1,
4
+ "title": "prism-ml/bonsai-image-ternary-4B-unpacked on Samsung Galaxy S26+",
5
+ "kind": "port",
6
+ "model_type": "kernel",
7
+ "mode": "compute",
8
+ "connection": "adb",
9
+ "device_dir": "/data/local/tmp/nnopt/port",
10
+ "settings": {
11
+ "warmup": 2,
12
+ "runs": 5,
13
+ "repeat": 3,
14
+ "rest_s": 3.0,
15
+ "sustained_repeat": 10
16
+ },
17
+ "inputs": {
18
+ "input": "inputs/tensors"
19
+ },
20
+ "external_check": true,
21
+ "compare": [
22
+ {
23
+ "key": "latency_ms",
24
+ "label": "Time per request",
25
+ "unit": "ms",
26
+ "nnopt": 35180.9,
27
+ "p10": 32838.7,
28
+ "p90": 38323.2,
29
+ "tolerance_pct": 10
30
+ }
31
+ ],
32
+ "check": {
33
+ "cases": [
34
+ {
35
+ "id": "p000",
36
+ "dir": "expected/p000",
37
+ "input": "inputs",
38
+ "outputs": [
39
+ {
40
+ "name": "image",
41
+ "dtype": "float16",
42
+ "expected": "expected/image.npy"
43
+ },
44
+ {
45
+ "name": "noise_pred",
46
+ "dtype": "float16",
47
+ "expected": "expected/noise_pred.npy"
48
+ },
49
+ {
50
+ "name": "prompt_embeds",
51
+ "dtype": "float16",
52
+ "expected": "expected/prompt_embeds.npy"
53
+ }
54
+ ]
55
+ }
56
+ ],
57
+ "rules": {
58
+ "fp32_rtol": 0.0001,
59
+ "fp32_atol_scale": 0.0001,
60
+ "fp16_rtol": 0.01,
61
+ "fp16_atol_scale": 0.01,
62
+ "int8_max_abs_diff": 1,
63
+ "int_max_abs_diff": 0,
64
+ "max_mismatch_frac": 0.0
65
+ },
66
+ "what": "the reference outputs of your reference code"
67
+ }
68
+ }
sm8850-gpu-ternary/run.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Entry point on the phone: sh ./run.sh --inputs IN_DIR [--repeat R] --out OUT_DIR --metrics M.json
2
+ cd "$(dirname "$0")"
3
+ export LD_LIBRARY_PATH=/vendor/lib64:${LD_LIBRARY_PATH:-}
4
+ CACHE=/data/local/tmp/nnopt/bonsai_image_cache
5
+ mkdir -p "$CACHE" 2>/dev/null || CACHE=${TMPDIR:-/data/local/tmp}/bonsai_image_cache
6
+ exec ./bin/bonsai_image --weights /data/local/tmp/nnopt/bonsai_image_weights --cache "$CACHE" "$@"
sm8850-gpu-ternary/src/cl_loader.cpp ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Resolves the OpenCL API from the vendor libOpenCL.so at run time (no ICD loader needed at build time).
2
+ #define CL_TARGET_OPENCL_VERSION 300
3
+ #include <CL/cl.h>
4
+ #include <dlfcn.h>
5
+ #include <cstdio>
6
+ #include <cstdlib>
7
+
8
+ static void* cl_lib() {
9
+ static void* h = nullptr;
10
+ if (!h) {
11
+ const char* names[] = {"libOpenCL.so", "/vendor/lib64/libOpenCL.so", "/system/vendor/lib64/libOpenCL.so",
12
+ "libOpenCL_adreno.so", "/vendor/lib64/libOpenCL_adreno.so"};
13
+ for (const char* n : names) { h = dlopen(n, RTLD_NOW | RTLD_LOCAL); if (h) break; }
14
+ if (!h) { fprintf(stderr, "cannot dlopen libOpenCL.so: %s\n", dlerror()); exit(3); }
15
+ }
16
+ return h;
17
+ }
18
+ static void* cl_sym(const char* name) {
19
+ void* p = dlsym(cl_lib(), name);
20
+ if (!p) { fprintf(stderr, "OpenCL symbol missing: %s\n", name); exit(3); }
21
+ return p;
22
+ }
23
+
24
+ #define FWD(ret, name, params, args) \
25
+ extern "C" ret CL_API_CALL name params { \
26
+ typedef ret(CL_API_CALL * fn_t) params; \
27
+ static fn_t fn = (fn_t)cl_sym(#name); \
28
+ return fn args; \
29
+ }
30
+
31
+ FWD(cl_int, clGetPlatformIDs, (cl_uint a, cl_platform_id* b, cl_uint* c), (a, b, c))
32
+ 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))
33
+ 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))
34
+ FWD(cl_context, clCreateContext, (const cl_context_properties* a, cl_uint b, const cl_device_id* c,
35
+ void(CL_CALLBACK* d)(const char*, const void*, size_t, void*), void* e, cl_int* f), (a, b, c, d, e, f))
36
+ FWD(cl_command_queue, clCreateCommandQueueWithProperties, (cl_context a, cl_device_id b, const cl_queue_properties* c, cl_int* d), (a, b, c, d))
37
+ FWD(cl_mem, clCreateBuffer, (cl_context a, cl_mem_flags b, size_t c, void* d, cl_int* e), (a, b, c, d, e))
38
+ FWD(cl_int, clReleaseMemObject, (cl_mem a), (a))
39
+ 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))
40
+ FWD(cl_program, clCreateProgramWithBinary, (cl_context a, cl_uint b, const cl_device_id* c, const size_t* d,
41
+ const unsigned char** e, cl_int* f, cl_int* g), (a, b, c, d, e, f, g))
42
+ FWD(cl_int, clBuildProgram, (cl_program a, cl_uint b, const cl_device_id* c, const char* d,
43
+ void(CL_CALLBACK* e)(cl_program, void*), void* f), (a, b, c, d, e, f))
44
+ 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))
45
+ FWD(cl_int, clGetProgramInfo, (cl_program a, cl_program_info b, size_t c, void* d, size_t* e), (a, b, c, d, e))
46
+ FWD(cl_kernel, clCreateKernel, (cl_program a, const char* b, cl_int* c), (a, b, c))
47
+ FWD(cl_int, clSetKernelArg, (cl_kernel a, cl_uint b, size_t c, const void* d), (a, b, c, d))
48
+ 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))
49
+ FWD(cl_int, clEnqueueNDRangeKernel, (cl_command_queue a, cl_kernel b, cl_uint c, const size_t* d, const size_t* e,
50
+ const size_t* f, cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))
51
+ FWD(cl_int, clEnqueueWriteBuffer, (cl_command_queue a, cl_mem b, cl_bool c, size_t d, size_t e, const void* f,
52
+ cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))
53
+ FWD(cl_int, clEnqueueReadBuffer, (cl_command_queue a, cl_mem b, cl_bool c, size_t d, size_t e, void* f,
54
+ cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))
55
+ FWD(cl_int, clEnqueueCopyBuffer, (cl_command_queue a, cl_mem b, cl_mem c, size_t d, size_t e, size_t f,
56
+ cl_uint g, const cl_event* h, cl_event* i), (a, b, c, d, e, f, g, h, i))
57
+ FWD(void*, clEnqueueMapBuffer, (cl_command_queue a, cl_mem b, cl_bool c, cl_map_flags d, size_t e, size_t f,
58
+ cl_uint g, const cl_event* h, cl_event* i, cl_int* j), (a, b, c, d, e, f, g, h, i, j))
59
+ 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))
60
+ FWD(cl_mem, clCreateImage, (cl_context a, cl_mem_flags b, const cl_image_format* c, const cl_image_desc* d, void* e,
61
+ cl_int* f), (a, b, c, d, e, f))
62
+ FWD(cl_int, clFinish, (cl_command_queue a), (a))
63
+ FWD(cl_int, clFlush, (cl_command_queue a), (a))
64
+ FWD(cl_int, clWaitForEvents, (cl_uint a, const cl_event* b), (a, b))
65
+ FWD(cl_int, clGetEventProfilingInfo, (cl_event a, cl_profiling_info b, size_t c, void* d, size_t* e), (a, b, c, d, e))
66
+ FWD(cl_int, clReleaseEvent, (cl_event a), (a))
67
+ FWD(cl_int, clReleaseKernel, (cl_kernel a), (a))
68
+ FWD(cl_int, clReleaseProgram, (cl_program a), (a))
69
+ FWD(cl_int, clReleaseCommandQueue, (cl_command_queue a), (a))
70
+ FWD(cl_int, clReleaseContext, (cl_context a), (a))
sm8850-gpu-ternary/src/clrt.cpp ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "clrt.h"
2
+ #include <time.h>
3
+ #include <sys/stat.h>
4
+ #include <fstream>
5
+ #include <sstream>
6
+ #include <algorithm>
7
+
8
+ double now_ms() {
9
+ timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
10
+ return t.tv_sec * 1e3 + t.tv_nsec * 1e-6;
11
+ }
12
+
13
+ static std::string read_file(const std::string& p) {
14
+ std::ifstream f(p, std::ios::binary);
15
+ if (!f) { fprintf(stderr, "cannot read %s\n", p.c_str()); exit(2); }
16
+ std::stringstream ss; ss << f.rdbuf(); return ss.str();
17
+ }
18
+
19
+ static uint64_t fnv1a(const std::string& s, uint64_t h = 1469598103934665603ULL) {
20
+ for (unsigned char c : s) { h ^= c; h *= 1099511628211ULL; }
21
+ return h;
22
+ }
23
+
24
+ void ClRt::init(const std::string& kdir, const std::string& cdir) {
25
+ kernel_dir = kdir; cache_dir = cdir;
26
+ cl_uint np = 0;
27
+ CLCHK(clGetPlatformIDs(1, &plat, &np));
28
+ CLCHK(clGetDeviceIDs(plat, CL_DEVICE_TYPE_GPU, 1, &dev, nullptr));
29
+ char buf[512];
30
+ CLCHK(clGetDeviceInfo(dev, CL_DEVICE_NAME, sizeof buf, buf, nullptr)); dev_name = buf;
31
+ CLCHK(clGetDeviceInfo(dev, CL_DRIVER_VERSION, sizeof buf, buf, nullptr)); drv_ver = buf;
32
+ cl_ulong ma = 0; CLCHK(clGetDeviceInfo(dev, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof ma, &ma, nullptr)); max_alloc = ma;
33
+ cl_int e;
34
+ ctx = clCreateContext(nullptr, 1, &dev, nullptr, nullptr, &e); CLCHK(e);
35
+ profile = getenv("NNOPT_PROFILE") != nullptr;
36
+ sync_each = getenv("NNOPT_SYNC") != nullptr;
37
+ cl_queue_properties props[] = {CL_QUEUE_PROPERTIES, profile ? (cl_queue_properties)CL_QUEUE_PROFILING_ENABLE : 0, 0};
38
+ q = clCreateCommandQueueWithProperties(ctx, dev, props, &e); CLCHK(e);
39
+ qup = clCreateCommandQueueWithProperties(ctx, dev, nullptr, &e); CLCHK(e);
40
+ fprintf(stderr, "[cl] %s | %s | max_alloc %zu MB\n", dev_name.c_str(), drv_ver.c_str(), max_alloc >> 20);
41
+ mkdir(cache_dir.c_str(), 0755);
42
+ }
43
+
44
+ cl_program ClRt::build(const std::string& file, const std::string& opts) {
45
+ std::string src = read_file(kernel_dir + "/" + file);
46
+ uint64_t h = fnv1a(src); h = fnv1a(opts, h); h = fnv1a(dev_name, h); h = fnv1a(drv_ver, h);
47
+ char name[64]; snprintf(name, sizeof name, "/%016llx.bin", (unsigned long long)h);
48
+ std::string cpath = cache_dir + name;
49
+ cl_int e, be;
50
+ cl_program p = nullptr;
51
+ {
52
+ std::ifstream f(cpath, std::ios::binary);
53
+ if (f) {
54
+ std::stringstream ss; ss << f.rdbuf(); std::string bin = ss.str();
55
+ size_t len = bin.size(); const unsigned char* bp = (const unsigned char*)bin.data();
56
+ p = clCreateProgramWithBinary(ctx, 1, &dev, &len, &bp, &be, &e);
57
+ if (e != CL_SUCCESS || be != CL_SUCCESS || clBuildProgram(p, 1, &dev, opts.c_str(), nullptr, nullptr) != CL_SUCCESS) {
58
+ if (p) clReleaseProgram(p);
59
+ p = nullptr;
60
+ }
61
+ }
62
+ }
63
+ if (p) return p;
64
+ double t0 = now_ms();
65
+ const char* s = src.c_str(); size_t sl = src.size();
66
+ p = clCreateProgramWithSource(ctx, 1, &s, &sl, &e); CLCHK(e);
67
+ e = clBuildProgram(p, 1, &dev, opts.c_str(), nullptr, nullptr);
68
+ if (e != CL_SUCCESS) {
69
+ size_t ll = 0; clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &ll);
70
+ std::string log(ll, 0); clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, ll, &log[0], nullptr);
71
+ fprintf(stderr, "build of %s [%s] failed (%d):\n%s\n", file.c_str(), opts.c_str(), e, log.c_str());
72
+ exit(5);
73
+ }
74
+ size_t bl = 0; CLCHK(clGetProgramInfo(p, CL_PROGRAM_BINARY_SIZES, sizeof bl, &bl, nullptr));
75
+ std::vector<unsigned char> bin(bl); unsigned char* bp = bin.data();
76
+ CLCHK(clGetProgramInfo(p, CL_PROGRAM_BINARIES, sizeof bp, &bp, nullptr));
77
+ std::string tmp = cpath + ".tmp";
78
+ { std::ofstream f(tmp, std::ios::binary); f.write((const char*)bin.data(), bl); }
79
+ rename(tmp.c_str(), cpath.c_str());
80
+ fprintf(stderr, "[cl] built %s [%s] in %.0f ms\n", file.c_str(), opts.c_str(), now_ms() - t0);
81
+ return p;
82
+ }
83
+
84
+ cl_kernel ClRt::kernel(cl_program p, const char* name) {
85
+ cl_int e; cl_kernel k = clCreateKernel(p, name, &e);
86
+ if (e != CL_SUCCESS) { fprintf(stderr, "clCreateKernel %s failed %d\n", name, e); exit(5); }
87
+ if (getenv("NNOPT_KINFO")) {
88
+ cl_ulong pm = 0; size_t wg = 0;
89
+ clGetKernelWorkGroupInfo(k, dev, CL_KERNEL_PRIVATE_MEM_SIZE, sizeof pm, &pm, nullptr);
90
+ clGetKernelWorkGroupInfo(k, dev, CL_KERNEL_WORK_GROUP_SIZE, sizeof wg, &wg, nullptr);
91
+ fprintf(stderr, "[kinfo] %s private %llu B, max wg %zu\n", name, (unsigned long long)pm, wg);
92
+ }
93
+ return k;
94
+ }
95
+
96
+ cl_mem ClRt::buf(size_t bytes, cl_mem_flags flags) {
97
+ if (bytes == 0) bytes = 16;
98
+ if (bytes > max_alloc) { fprintf(stderr, "buffer of %zu bytes exceeds max alloc %zu\n", bytes, max_alloc); exit(4); }
99
+ cl_int e; cl_mem m = clCreateBuffer(ctx, flags, bytes, nullptr, &e);
100
+ if (e != CL_SUCCESS) { fprintf(stderr, "clCreateBuffer(%zu) failed %d (allocated so far %zu MB)\n", bytes, e, bytes_alloc >> 20); exit(4); }
101
+ bytes_alloc += bytes;
102
+ return m;
103
+ }
104
+ void ClRt::release(cl_mem m) { if (m) clReleaseMemObject(m); }
105
+
106
+ void ClRt::write(cl_mem m, const void* src, size_t bytes, size_t off, bool blocking) {
107
+ CLCHK(clEnqueueWriteBuffer(q, m, blocking ? CL_TRUE : CL_FALSE, off, bytes, src, 0, nullptr, nullptr));
108
+ }
109
+ void ClRt::upload(cl_mem m, const void* src, size_t bytes) {
110
+ CLCHK(clEnqueueWriteBuffer(qup, m, CL_TRUE, 0, bytes, src, 0, nullptr, nullptr));
111
+ }
112
+ void ClRt::read(cl_mem m, void* dst, size_t bytes, size_t off) {
113
+ CLCHK(clEnqueueReadBuffer(q, m, CL_TRUE, off, bytes, dst, 0, nullptr, nullptr));
114
+ }
115
+
116
+ void ClRt::launch(cl_kernel k, const char* name, int dims, const size_t* gws, const size_t* lws, double flops) {
117
+ cl_event ev = nullptr;
118
+ cl_int e = clEnqueueNDRangeKernel(q, k, dims, nullptr, gws, lws, 0, nullptr, profile ? &ev : nullptr);
119
+ if (e != CL_SUCCESS) {
120
+ fprintf(stderr, "launch %s failed %d (gws %zu,%zu,%zu lws %zu,%zu,%zu)\n", name, e, gws[0], dims > 1 ? gws[1] : 1,
121
+ dims > 2 ? gws[2] : 1, lws ? lws[0] : 0, lws && dims > 1 ? lws[1] : 0, lws && dims > 2 ? lws[2] : 0);
122
+ exit(4);
123
+ }
124
+ if (profile) { pending.push_back({name, ev}); prof[name].flops += flops; if (pending.size() > 2000) flush_prof(); }
125
+ if (sync_each) {
126
+ e = clFinish(q);
127
+ if (e != CL_SUCCESS) { fprintf(stderr, "kernel %s failed at finish: %d\n", name, e); exit(4); }
128
+ }
129
+ }
130
+
131
+ void ClRt::flush_prof() {
132
+ if (pending.empty()) return;
133
+ clFinish(q);
134
+ for (auto& pe : pending) {
135
+ cl_ulong s = 0, en = 0;
136
+ clGetEventProfilingInfo(pe.second, CL_PROFILING_COMMAND_START, sizeof s, &s, nullptr);
137
+ clGetEventProfilingInfo(pe.second, CL_PROFILING_COMMAND_END, sizeof en, &en, nullptr);
138
+ auto& p = prof[pe.first]; p.ms += (en - s) * 1e-6; p.calls++;
139
+ clReleaseEvent(pe.second);
140
+ }
141
+ pending.clear();
142
+ }
143
+
144
+ void ClRt::print_prof() {
145
+ if (!profile) return;
146
+ flush_prof();
147
+ std::vector<std::pair<std::string, Prof>> v(prof.begin(), prof.end());
148
+ std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second.ms > b.second.ms; });
149
+ double tot = 0; for (auto& x : v) tot += x.second.ms;
150
+ fprintf(stderr, "%-28s %7s %10s %9s %6s %8s\n", "kernel", "calls", "total_ms", "mean_us", "share", "GFLOP/s");
151
+ for (auto& x : v)
152
+ fprintf(stderr, "%-28s %7d %10.2f %9.1f %5.1f%% %8.1f\n", x.first.c_str(), x.second.calls, x.second.ms,
153
+ 1e3 * x.second.ms / std::max(1, x.second.calls), 100 * x.second.ms / tot,
154
+ x.second.ms > 0 ? x.second.flops / (x.second.ms * 1e6) : 0);
155
+ fprintf(stderr, "total kernel time %.1f ms\n", tot);
156
+ prof.clear();
157
+ }
sm8850-gpu-ternary/src/clrt.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Minimal OpenCL runtime helpers: context/queue, program build with a binary cache, buffers, launches.
2
+ #pragma once
3
+ #define CL_TARGET_OPENCL_VERSION 300
4
+ #include <CL/cl.h>
5
+ #include <cstdio>
6
+ #include <cstdlib>
7
+ #include <cstdint>
8
+ #include <string>
9
+ #include <vector>
10
+ #include <map>
11
+
12
+ #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)
13
+
14
+ double now_ms();
15
+
16
+ struct ClRt {
17
+ cl_platform_id plat = nullptr;
18
+ cl_device_id dev = nullptr;
19
+ cl_context ctx = nullptr;
20
+ cl_command_queue q = nullptr;
21
+ cl_command_queue qup = nullptr; // second queue: weight uploads that overlap the kernels on q
22
+ std::string dev_name, drv_ver, cache_dir, kernel_dir;
23
+ size_t max_alloc = 0;
24
+ bool profile = false;
25
+ bool sync_each = false; // debugging: clFinish after every launch
26
+ struct Prof { double ms = 0; int calls = 0; double flops = 0; };
27
+ std::map<std::string, Prof> prof;
28
+ std::vector<std::pair<std::string, cl_event>> pending;
29
+ std::vector<cl_mem> owned;
30
+ size_t bytes_alloc = 0;
31
+
32
+ void init(const std::string& kernel_dir, const std::string& cache_dir);
33
+ cl_program build(const std::string& file, const std::string& opts);
34
+ cl_kernel kernel(cl_program p, const char* name);
35
+ cl_mem buf(size_t bytes, cl_mem_flags flags = CL_MEM_READ_WRITE);
36
+ void release(cl_mem m);
37
+ void write(cl_mem m, const void* src, size_t bytes, size_t off = 0, bool blocking = true);
38
+ void read(cl_mem m, void* dst, size_t bytes, size_t off = 0);
39
+ // blocking write on the upload queue; the caller makes sure no kernel still uses m
40
+ void upload(cl_mem m, const void* src, size_t bytes);
41
+ void finish() { CLCHK(clFinish(q)); }
42
+ void launch(cl_kernel k, const char* name, int dims, const size_t* gws, const size_t* lws, double flops = 0);
43
+ void flush_prof();
44
+ void print_prof();
45
+ };
46
+
47
+ // set kernel args from a parameter pack
48
+ inline void set_args_i(cl_kernel, int) {}
49
+ template <typename T, typename... R>
50
+ inline void set_args_i(cl_kernel k, int i, const T& a, const R&... r) {
51
+ CLCHK(clSetKernelArg(k, i, sizeof(T), &a));
52
+ set_args_i(k, i + 1, r...);
53
+ }
54
+ template <typename... A>
55
+ inline void set_args(cl_kernel k, const A&... a) { set_args_i(k, 0, a...); }