maniac-11111 commited on
Commit
9d3ee31
·
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. BOARD.md +37 -0
  3. LICENSE +202 -0
  4. MANIFEST.json +25 -0
  5. README.md +58 -0
  6. RELEASE_NOTES.md +15 -0
  7. chat_template.jinja +154 -0
  8. config.json +119 -0
  9. decode.py +649 -0
  10. extras.safetensors +3 -0
  11. generation_config.json +12 -0
  12. goldens/L0_e0_fp32.safetensors +3 -0
  13. merges.txt +0 -0
  14. packed/experts/L00.safetensors +3 -0
  15. packed/experts/L01.safetensors +3 -0
  16. packed/experts/L02.safetensors +3 -0
  17. packed/experts/L03.safetensors +3 -0
  18. packed/experts/L04.safetensors +3 -0
  19. packed/experts/L05.safetensors +3 -0
  20. packed/experts/L06.safetensors +3 -0
  21. packed/experts/L07.safetensors +3 -0
  22. packed/experts/L08.safetensors +3 -0
  23. packed/experts/L09.safetensors +3 -0
  24. packed/experts/L10.safetensors +3 -0
  25. packed/experts/L11.safetensors +3 -0
  26. packed/experts/L12.safetensors +3 -0
  27. packed/experts/L13.safetensors +3 -0
  28. packed/experts/L14.safetensors +3 -0
  29. packed/experts/L15.safetensors +3 -0
  30. packed/experts/L16.safetensors +3 -0
  31. packed/experts/L17.safetensors +3 -0
  32. packed/experts/L18.safetensors +3 -0
  33. packed/experts/L19.safetensors +3 -0
  34. packed/experts/L20.safetensors +3 -0
  35. packed/experts/L21.safetensors +3 -0
  36. packed/experts/L22.safetensors +3 -0
  37. packed/experts/L23.safetensors +3 -0
  38. packed/experts/L24.safetensors +3 -0
  39. packed/experts/L25.safetensors +3 -0
  40. packed/experts/L26.safetensors +3 -0
  41. packed/experts/L27.safetensors +3 -0
  42. packed/experts/L28.safetensors +3 -0
  43. packed/experts/L29.safetensors +3 -0
  44. packed/experts/L30.safetensors +3 -0
  45. packed/experts/L31.safetensors +3 -0
  46. packed/experts/L32.safetensors +3 -0
  47. packed/experts/L33.safetensors +3 -0
  48. packed/experts/L34.safetensors +3 -0
  49. packed/experts/L35.safetensors +3 -0
  50. packed/experts/L36.safetensors +3 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
BOARD.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mach-1-Ternary-Additive-35B — benchmark board
2
+
3
+ Payload: integer L1-ball trellis expert codes + per-wavefront gamma scales +
4
+ continuous fp16 su/sv side-streams; 64-level integer-lattice spine; int5-g64
5
+ head; int4 embed — every weight matmul is add/subtract-only. Ship gate:
6
+ decode.py-primitive reconstruction == served checkpoint (bf16 rounding,
7
+ layers 0/20/39).
8
+
9
+ Protocol: same-harness EvalScope 1.9.1 + vLLM, PrismML App. B (thinking mode,
10
+ temp 1.0, top_p 0.95, top_k 20, PrismML token tiers, AIME mean-of-8, IFEval
11
+ prompt-strict, IFBench prompt-loose). Retention = 100 x score / BF16 teacher
12
+ (Qwen3.6-35B-A3B), same harness. tau2-bench = fixed external user-simulator
13
+ (Qwen3.6-35B BF16, greedy), single pass, identical for every model.
14
+
15
+ ## Flagship payload (12/12)
16
+
17
+ | benchmark | score | teacher | retention |
18
+ |---|---|---|---|
19
+ | AIME25 @8 | 87.50 | 88.33 | **99.1%** |
20
+ | AIME26 @8 | 89.58 | 90.00 | **99.5%** |
21
+ | MATH-500 | 98.00 | 98.60 | **99.4%** |
22
+ | GSM8K | 94.69 | 96.21 | 98.4% |
23
+ | MBPP+ | 94.44 | 96.03 | 98.3% |
24
+ | HumanEval+ | 92.68 | 95.12 | 97.4% |
25
+ | MMLU-Redux | 89.18 | 92.68 | 96.2% |
26
+ | IFEval | 83.75 (n=5) | 89.05 | 94.0% |
27
+ | MuSR | 61.77 | 66.66 | 92.7% |
28
+ | BFCL-v3 | 68.97 | 74.98 | 92.0% |
29
+ | tau2-bench | 71.58 | 79.51 | 90.0% |
30
+ | IFBench | 54.08 | 64.97 | 83.2% |
31
+ | **mean retention** | | | **95.0%** |
32
+
33
+ ## Read-quality notes
34
+ - Multi-read cells quote the mean over all reads with n; single reads are n=1.
35
+ - IFEval strict single-read spread measured ~2-3 pts; tau2 complete-read
36
+ spread up to ~6 on some artifacts — sub-point deltas are ties.
37
+ - Expert payload 6.207 GB.
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
MANIFEST.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "payload": "rdsl64j_s300",
3
+ "base": "Qwen/Qwen3.6-35B-A3B",
4
+ "categories": {
5
+ "experts_packed": 42,
6
+ "ne_packed": 41,
7
+ "head_packed": 8,
8
+ "embed_packed": 2,
9
+ "extras": 361,
10
+ "mtp_dropped": 17
11
+ },
12
+ "packed_GB": {
13
+ "experts": 6.2083,
14
+ "ne_spine": 0.7039,
15
+ "head": 0.3337,
16
+ "embed_int4": 0.2875,
17
+ "embed_lut4_alternative_container": 0.5086
18
+ },
19
+ "embed_note": "embed ships in two interchangeable containers (int4 codes; lossless lut4); deployed payload counts one (int4)",
20
+ "extras_GB": 0.0523,
21
+ "n_e2e_norm_overrides": 131,
22
+ "text_payload_GB": 7.5335,
23
+ "text_bpw": 1.6978,
24
+ "codec_reference": "packed/experts/codec.json"
25
+ }
README.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- Theme-aware embed. If your renderer ignores <picture>, use the plain
2
+ image line underneath instead and delete this block. -->
3
+
4
+ ![Screenshot 2026-08-03 at 10.32.36 AM](https://cdn-uploads.huggingface.co/production/uploads/680868b984cac4b136ea7900/0YxMKj31WMJT1NwbVAGjj.png)
5
+
6
+ <!-- Plain fallback:
7
+ ![Capability retention vs BF16 teacher](assets/benchmarks-light.png)
8
+ -->
9
+
10
+ ## Benchmarks
11
+
12
+
13
+
14
+ | | Mean retention, 12 benchmarks |
15
+ | --- | ---: |
16
+ | **Mach-1 Small** | **95.0%** |
17
+ | Ternary Bonsai 27B (PrismML) | 93.6% |
18
+ | Gemma 4 Q2_K_XL (Unsloth) | 85.6% |
19
+
20
+ ### Per-benchmark Retention
21
+
22
+ | Benchmark | Mach-1 Small | Ternary Bonsai 27B | Gemma 4 Q2_K_XL |
23
+ | --- | ---: | ---: | ---: |
24
+ | AIME26 | **99.5%** | 92.7% | 67.7% |
25
+ | MATH-500 | **99.4%** | 98.2% | 95.6% |
26
+ | AIME25 | **99.1%** | 91.7% | 67.2% |
27
+ | GSM8K | 98.4% | **100.2%** | 97.3% |
28
+ | MBPP+ | 98.3% | **98.4%** | 92.2% |
29
+ | HumanEval+ | 97.4% | **98.7%** | 94.1% |
30
+ | MMLU-Redux | 96.2% | 94.0% | **96.9%** |
31
+ | IFEval | 94.0% | 89.8% | **95.5%** |
32
+ | MuSR | **92.7%** | 91.6% | 91.1% |
33
+ | BFCL-v3 | 92.0% | **98.9%** | 95.7% |
34
+ | τ²-bench | 90.0% | **91.2%** | 73.1% |
35
+ | IFBench | **83.2%** | 77.7% | 61.3% |
36
+ | **Mean** | **95.0%** | **93.6%** | **85.6%** |
37
+
38
+ Mach-1 Small's own scores and teacher scores:
39
+
40
+ | Benchmark | Score | Teacher (Qwen3.6-35B-A3B BF16) | Retention |
41
+ | --- | ---: | ---: | ---: |
42
+ | AIME26 | 89.58 | 90.00 | 99.5% |
43
+ | MATH-500 | 98.00 | 98.60 | 99.4% |
44
+ | AIME25 | 87.50 | 88.33 | 99.1% |
45
+ | GSM8K | 94.69 | 96.21 | 98.4% |
46
+ | MBPP+ | 94.44 | 96.03 | 98.3% |
47
+ | HumanEval+ | 92.68 | 95.12 | 97.4% |
48
+ | MMLU-Redux | 89.18 | 92.68 | 96.2% |
49
+ | IFEval | 83.75 | 89.05 | 94.0% |
50
+ | MuSR | 61.77 | 66.66 | 92.7% |
51
+ | BFCL-v3 | 68.97 | 74.98 | 92.0% |
52
+ | τ²-bench | 71.58 | 79.51 | 90.0% |
53
+ | IFBench | 54.08 | 64.97 | 83.2% |
54
+
55
+ ### Speed
56
+
57
+ ![Screenshot 2026-08-03 at 11.55.47 AM](https://cdn-uploads.huggingface.co/production/uploads/680868b984cac4b136ea7900/lYFfUCU1QWrGjM23vbb66.png)
58
+
RELEASE_NOTES.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Release notes
2
+
3
+ Current payload:
4
+
5
+ - Experts: integer L1-ball trellis codes (K=1.5, V=8; book:
6
+ `packed/experts/codebook.safetensors`) + `wave_gamma` per-wavefront scales +
7
+ continuous fp16 `su`/`sv` side-streams. Expert files carry NO Wscale — `sv`
8
+ is the complete scale (decode with `wscale=None`); `wave_gamma` applies in
9
+ rotated space before the `su`/`sv` Hadamards.
10
+ - Spine: 64-level integer lattice in the K=4 trellis. Head: int5-g64.
11
+ Embedding: int4 + exact-overwrite exception list.
12
+ - Ship gate: decode.py-primitive reconstruction == the served checkpoint
13
+ (bf16 rounding, layers 0/20/39 x 4 experts x 3 projs).
14
+ - Full measured board and retention table: see BOARD.md. Expert payload
15
+ 6.207 GB.
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5MoeForConditionalGeneration"
4
+ ],
5
+ "image_token_id": 248056,
6
+ "model_type": "qwen3_5_moe",
7
+ "text_config": {
8
+ "attention_bias": false,
9
+ "attention_dropout": 0.0,
10
+ "attn_output_gate": true,
11
+ "bos_token_id": 248044,
12
+ "dtype": "bfloat16",
13
+ "eos_token_id": 248044,
14
+ "full_attention_interval": 4,
15
+ "head_dim": 256,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "layer_types": [
20
+ "linear_attention",
21
+ "linear_attention",
22
+ "linear_attention",
23
+ "full_attention",
24
+ "linear_attention",
25
+ "linear_attention",
26
+ "linear_attention",
27
+ "full_attention",
28
+ "linear_attention",
29
+ "linear_attention",
30
+ "linear_attention",
31
+ "full_attention",
32
+ "linear_attention",
33
+ "linear_attention",
34
+ "linear_attention",
35
+ "full_attention",
36
+ "linear_attention",
37
+ "linear_attention",
38
+ "linear_attention",
39
+ "full_attention",
40
+ "linear_attention",
41
+ "linear_attention",
42
+ "linear_attention",
43
+ "full_attention",
44
+ "linear_attention",
45
+ "linear_attention",
46
+ "linear_attention",
47
+ "full_attention",
48
+ "linear_attention",
49
+ "linear_attention",
50
+ "linear_attention",
51
+ "full_attention",
52
+ "linear_attention",
53
+ "linear_attention",
54
+ "linear_attention",
55
+ "full_attention",
56
+ "linear_attention",
57
+ "linear_attention",
58
+ "linear_attention",
59
+ "full_attention"
60
+ ],
61
+ "linear_conv_kernel_dim": 4,
62
+ "linear_key_head_dim": 128,
63
+ "linear_num_key_heads": 16,
64
+ "linear_num_value_heads": 32,
65
+ "linear_value_head_dim": 128,
66
+ "mamba_ssm_dtype": "float32",
67
+ "max_position_embeddings": 262144,
68
+ "model_type": "qwen3_5_moe_text",
69
+ "moe_intermediate_size": 512,
70
+ "mtp_num_hidden_layers": 0,
71
+ "mtp_use_dedicated_embeddings": false,
72
+ "num_attention_heads": 16,
73
+ "num_experts": 256,
74
+ "num_experts_per_tok": 8,
75
+ "num_hidden_layers": 40,
76
+ "num_key_value_heads": 2,
77
+ "output_router_logits": false,
78
+ "pad_token_id": null,
79
+ "partial_rotary_factor": 0.25,
80
+ "rms_norm_eps": 1e-06,
81
+ "rope_parameters": {
82
+ "mrope_interleaved": true,
83
+ "mrope_section": [
84
+ 11,
85
+ 11,
86
+ 10
87
+ ],
88
+ "partial_rotary_factor": 0.25,
89
+ "rope_theta": 10000000,
90
+ "rope_type": "default"
91
+ },
92
+ "router_aux_loss_coef": 0.001,
93
+ "shared_expert_intermediate_size": 512,
94
+ "tie_word_embeddings": false,
95
+ "use_cache": true,
96
+ "vocab_size": 248320
97
+ },
98
+ "tie_word_embeddings": false,
99
+ "transformers_version": "4.57.1",
100
+ "video_token_id": 248057,
101
+ "vision_config": {
102
+ "deepstack_visual_indexes": [],
103
+ "depth": 27,
104
+ "hidden_act": "gelu_pytorch_tanh",
105
+ "hidden_size": 1152,
106
+ "in_channels": 3,
107
+ "initializer_range": 0.02,
108
+ "intermediate_size": 4304,
109
+ "model_type": "qwen3_5_moe",
110
+ "num_heads": 16,
111
+ "num_position_embeddings": 2304,
112
+ "out_hidden_size": 2048,
113
+ "patch_size": 16,
114
+ "spatial_merge_size": 2,
115
+ "temporal_patch_size": 2
116
+ },
117
+ "vision_end_token_id": 248054,
118
+ "vision_start_token_id": 248053
119
+ }
decode.py ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone numpy decoder for the packed Mach-1 checkpoint.
3
+
4
+ Packed layout (HF repo):
5
+ packed/experts/L{LL}.safetensors -- per expert e, proj in gate/up/down:
6
+ e{e}.{proj}.trellis int16 [ntiles, 16*K] (trellis bitstream, ~K bpw)
7
+ e{e}.{proj}.su fp16 [n]
8
+ e{e}.{proj}.sv fp16 [m] (Wscale absorbed)
9
+ or (demoted K1 experts)
10
+ e{e}.{proj}.SU int8 [n]; e{e}.{proj}.SV int8 [m]; e{e}.{proj}.Wscale fp16 []
11
+ plus, when the manifest carries "basis" (shared cold-expert low-rank basis):
12
+ basis.{proj}.A fp16 [r, n]; basis.{proj}.B fp16 [m, r]
13
+ e{e}.{proj}.c fp16 [r] (demoted experts only)
14
+ metadata["manifest"]: {"cb2":..., "cb1":..., "demoted":[e,...], "geom":{proj:[m,n]},
15
+ optional "basis": {"r":r, "dtype":"fp16", "shared_A_gu":false}}
16
+ packed/experts/codebook.safetensors: tlut fp16 [512, 2] (shared by K2/K1; the tlut
17
+ depends only on (tlut_bits=9, V=2) -- K only changes trellis transitions).
18
+ packed/ne/L{LL}.safetensors (zero-padded LNN) -- codec
19
+ "canon_rht_bitshift_trellis_intlattice"; no manifest key. Per-file metadata:
20
+ cb_params {K:4,L:16,V:2,tlut_bits:9,quantlut_sym,td 16x16} + dims
21
+ {name: [m0, n0, m, n]}. Keys per tensor:
22
+ {name}|trellis int16, {name}|SU int8 [n], {name}|SV int8 [m], {name}|Wscale fp16
23
+ tier-shared codebook: packed/ne/tlut.safetensors tlut fp16 [512, 2]
24
+ packed/ne/{L{i}|head_c{c}of8}.safetensors (single-digit L{i}: older builds) --
25
+ transform-free tier:
26
+ {name}|packed uint8 [B, T*K/8], {name}|gscale fp16 [B, T/128], {name}|lut fp16 [4096]
27
+ metadata["manifest"]: {"codec":"lloyd_bitshift_trellis","L":12,"group":128,
28
+ "pattern":[K]*4,"tensors":{name:{shape:[m0,n0],transposed:bool}}}
29
+ packed/head/head_c{c}of8.safetensors -- codec "int5g64_packed":
30
+ LMHEADCHUNK:{r0}:{r1}|qp uint8 [rows, n/8*5], |gscale fp16 [rows, n/64]
31
+ (+ optional |prot_rows int32 / |prot_dense exact rows); metadata dims {name:[rows,n]}
32
+ packed/ne/embed_int4.safetensors (decode_embed(bits=4)) --
33
+ affine int4-g64: q_packed uint8 [rows, hid/2], mn/mx fp16 [rows, hid/64]
34
+ packed/ne/embed_packed.safetensors (8-bpw lossless Lloyd-LUT container;
35
+ decode_embed_packed) and embed_int3.safetensors (older int3):
36
+ q_packed uint8 [rows, hid*3/8], mn fp16 [rows, hid/64], mx fp16 [rows, hid/64]
37
+
38
+ Usage:
39
+ from decode import (decode_trellis, decode_expert_layer, decode_ne_shard,
40
+ decode_head, decode_embed_packed, decode_embed)
41
+ """
42
+ import json
43
+ import math
44
+ import os
45
+
46
+ import numpy as np
47
+
48
+ HIDDEN, INTER, NEXP, NLAYERS = 2048, 512, 256, 40
49
+ NHEADC = 8
50
+ CB2 = dict(K=2, L=16, V=2, tlut_bits=9, decode_mode="quantlut_sym", td_x=16, td_y=16)
51
+ CB1 = dict(K=1, L=16, V=2, tlut_bits=9, decode_mode="quantlut_sym", td_x=16, td_y=16)
52
+ CB4 = dict(K=4, L=16, V=2, tlut_bits=9, decode_mode="quantlut_sym", td_x=16, td_y=16)
53
+
54
+ def padto(d):
55
+ """Dim -> padded dim: identity for powers of two, else next power of two."""
56
+ if d > 0 and (d & (d - 1)) == 0:
57
+ return d
58
+ return 1 << math.ceil(math.log2(d))
59
+
60
+
61
+ # ============================================================================ #
62
+ # Expert tier. Format:
63
+ # * A weight matrix is padded to (m, n) = (padto(m0), padto(n0)) and cut into
64
+ # td_x x td_y tiles, row-major over the (m/td_x, n/td_y) grid.
65
+ # * Each tile is a length-T scalar sequence (T = td_x*td_y, row-major inside the
66
+ # tile) produced by an L-bit shift register: the register emits one V-vector
67
+ # per step (T/V steps), then shifts in K*V fresh bits. State recurrence:
68
+ # reg_i = ((reg_{i-1} << K*V) | fresh_i) & (2^L - 1)
69
+ # * Bitstream per tile: the L bits of reg_0 (MSB first), then the K*V fresh bits
70
+ # of each later step (MSB first) -- T*K bits total, packed into BIG-ENDIAN
71
+ # 16-bit words. The last L-K*V register bits are not stored: the sequence is
72
+ # tail-biting, they wrap around to the start of the stream.
73
+ # * A register state s maps to a V-vector through a hashed symmetric LUT
74
+ # ("quantlut_sym"): with p = s*(s+1) exact-integer,
75
+ # row(s) = (p >> (16 - tlut_bits - 1)) & (2^tlut_bits - 1)
76
+ # vec(s) = tlut[row(s)] with component 0 negated iff bit 15 of p is set
77
+ # * Un-rotation (two-sided RHT): with H_d the orthonormal Walsh-Hadamard matrix
78
+ # (Sylvester order, scaled 1/sqrt(d); symmetric),
79
+ # W = diag(sv) . H_m . Wunit . H_n . diag(su), restricted to [:m0, :n0]
80
+ # computed as: FWHT each row over n then scale columns by su, then FWHT each
81
+ # column over m and scale rows by sv. For K1 packs Wunit is first multiplied
82
+ # by the scalar `wscale`.
83
+ # The operation order above (and in _np_hadamard) is part of the format: fp32
84
+ # elementwise add/sub/mul/div are IEEE-exact, so following it reproduces the
85
+ # encoder's decode exactly.
86
+ # ============================================================================ #
87
+ _FULL_LUT_CACHE = {}
88
+
89
+
90
+ def _np_full_lut(tlut, L, tlut_bits):
91
+ """Expand the persisted [2^tlut_bits, V] codebook to the full [2^L, V] fp32
92
+ decoder table per the hashed-symmetric-LUT rule above."""
93
+ small = np.asarray(tlut, np.float32)
94
+ s = np.arange(1 << L, dtype=np.int64)
95
+ p = s * (s + 1) # exact in int64
96
+ row = (p >> (16 - tlut_bits - 1)) & ((1 << tlut_bits) - 1)
97
+ table = small[row].copy() # [2^L, V]
98
+ table[:, 0] *= (1 - ((p >> 15) & 1) * 2).astype(np.float32)
99
+ return table
100
+
101
+
102
+ def _np_full_lut_cached(tlut, L, tlut_bits):
103
+ key = (L, tlut_bits, np.asarray(tlut).tobytes())
104
+ if key not in _FULL_LUT_CACHE:
105
+ _FULL_LUT_CACHE[key] = _np_full_lut(tlut, L, tlut_bits)
106
+ return _FULL_LUT_CACHE[key]
107
+
108
+
109
+ def _np_rate_bits(T, K, V):
110
+ """(bits per shift step, bits per tile). K need not be an integer: the only
111
+ rate constraint is that K*V and K*T are whole numbers of bits."""
112
+ step, nbits = float(K) * V, float(K) * T
113
+ if step != int(step) or nbits != int(nbits):
114
+ raise ValueError(f"rate K={K} with V={V}, T={T} needs whole-bit steps "
115
+ f"(K*V={step}) and a whole-bit tile (K*T={nbits})")
116
+ return int(step), int(nbits)
117
+
118
+
119
+ def _np_unpack_trellis(stream, T, L, K, V):
120
+ """Packed bitstream [rows, T*K/16] (u)int16 -> register states [rows, T//V] int32."""
121
+ words = np.ascontiguousarray(stream)
122
+ if words.dtype != np.uint16:
123
+ words = words.view(np.uint16)
124
+ step, nbits = _np_rate_bits(T, K, V)
125
+ if step > L:
126
+ raise ValueError(f"K*V={step} exceeds register width L={L}")
127
+ rows, nstep = words.shape[0], T // V
128
+ bits = ((words[:, :, None].astype(np.int64) >> np.arange(15, -1, -1)) & 1)
129
+ bits = bits.reshape(rows, -1)[:, :nbits] # MSB-first big-endian words
130
+ bits = np.concatenate([bits, bits[:, :L - step]], axis=1) # tail-biting wrap
131
+ seed_w = 1 << np.arange(L - 1, -1, -1, dtype=np.int64)
132
+ step_w = 1 << np.arange(step - 1, -1, -1, dtype=np.int64)
133
+ fresh = bits[:, L:L + (nstep - 1) * step].reshape(rows, nstep - 1, step) @ step_w
134
+ states = np.empty((rows, nstep), np.int32)
135
+ reg = bits[:, :L] @ seed_w
136
+ states[:, 0] = reg
137
+ mask = (1 << L) - 1
138
+ for i in range(1, nstep):
139
+ reg = ((reg << step) & mask) | fresh[:, i - 1]
140
+ states[:, i] = reg
141
+ return states
142
+
143
+
144
+ def _np_recons(states, table, m, n, td_x, td_y):
145
+ """Register states [ntiles, T//V] + full LUT -> codebook-unit weights [m, n] fp32
146
+ (V scalars per state, row-major tiles, row-major tile grid)."""
147
+ vals = table[states] # [ntiles, T//V, V]
148
+ return np.ascontiguousarray(
149
+ vals.reshape(m // td_x, n // td_y, td_x, td_y).transpose(0, 2, 1, 3)
150
+ ).reshape(m, n)
151
+
152
+
153
+ def _np_hadamard(x):
154
+ """Orthonormal Walsh-Hadamard transform (Sylvester order) along the LAST axis:
155
+ y = FWHT(x) / sqrt(dim). Butterflies pair at stride 1, then 2, 4, ... in fp32,
156
+ with a single fp32 division by sqrt(dim) after the final pass."""
157
+ dim = x.shape[-1]
158
+ if dim & (dim - 1):
159
+ raise ValueError(f"pure-numpy RHT needs a power-of-2 dim, got {dim}")
160
+ cur = np.ascontiguousarray(x, dtype=np.float32).reshape(-1, dim)
161
+ span = 1
162
+ while span < dim:
163
+ blk = cur.reshape(-1, dim // (2 * span), 2, span)
164
+ nxt = np.empty_like(blk)
165
+ nxt[:, :, 0, :] = blk[:, :, 0, :] + blk[:, :, 1, :]
166
+ nxt[:, :, 1, :] = blk[:, :, 0, :] - blk[:, :, 1, :]
167
+ cur = nxt.reshape(-1, dim)
168
+ span *= 2
169
+ return (cur / np.float32(np.sqrt(np.float32(dim)))).reshape(x.shape)
170
+
171
+
172
+ def decode_trellis(trellis, su, sv, tlut, m0, n0, cb_params, wscale=None, cb=None,
173
+ device="cuda"):
174
+ """Trellis decode -> fp32 [m0, n0].
175
+
176
+ su [n] / sv [m] are the RHT vectors over the PADDED dims: int8 +/-1 signs for raw
177
+ PTQ tensors (then `wscale` must be given), or continuous fp16 vectors for the
178
+ K2 experts (Wscale absorbed into sv; pass wscale=None).
179
+ Reverses: unpack states -> tiles -> [m,n] -> *wscale -> *su-side FWHT -> *sv-side
180
+ FWHT -> unpad. `cb` may carry a prebuilt table (numpy [2^L, V] LUT);
181
+ anything else is ignored and rebuilt from tlut.
182
+ """
183
+ mode = cb_params.get("decode_mode", "quantlut_sym")
184
+ if mode != "quantlut_sym":
185
+ raise NotImplementedError(f"numpy decode implements quantlut_sym, got {mode}")
186
+ td_x, td_y = cb_params["td_x"], cb_params["td_y"]
187
+ L, K, V = cb_params["L"], cb_params["K"], cb_params["V"]
188
+ m, n = padto(m0), padto(n0)
189
+ table = cb if isinstance(cb, np.ndarray) else \
190
+ _np_full_lut_cached(tlut, L, cb_params["tlut_bits"])
191
+ states = _np_unpack_trellis(np.asarray(trellis), td_x * td_y, L, K, V)
192
+ unit = _np_recons(states, table, m, n, td_x, td_y)
193
+ # the unit tensor is defined at fp16 precision
194
+ unit = unit.astype(np.float16).astype(np.float32)
195
+ if wscale is not None:
196
+ unit = unit * np.float32(wscale)
197
+ rowside = _np_hadamard(unit) * np.asarray(su, np.float32) # over n, then *su
198
+ colside = _np_hadamard(rowside.T) * np.asarray(sv, np.float32) # over m, then *sv
199
+ return np.ascontiguousarray(colside.T[:m0, :n0])
200
+
201
+
202
+ # ============================================================================ #
203
+ # packed-dir glue: whole-layer / whole-shard reconstruction.
204
+ # ============================================================================ #
205
+ def _read_safetensors_np(path):
206
+ """Read a pack file. v3 files carry a zstd sidecar (`__zsc__` + metadata["zsc"])
207
+ holding every non-code-stream tensor byte-exactly; expand it transparently."""
208
+ from safetensors import safe_open
209
+ out = {}
210
+ with safe_open(path, framework="numpy") as fh:
211
+ meta = fh.metadata() or {}
212
+ for k in fh.keys():
213
+ out[k] = fh.get_tensor(k)
214
+ if "__zsc__" in out:
215
+ import zstandard
216
+ man = json.loads(meta["zsc"])
217
+ buf = zstandard.ZstdDecompressor().decompress(
218
+ out.pop("__zsc__").tobytes(), max_output_size=man["raw_len"])
219
+ for key, dt, shape, off, nb in man["entries"]:
220
+ out[key] = np.frombuffer(buf, dtype=np.dtype(dt),
221
+ count=nb // np.dtype(dt).itemsize,
222
+ offset=off).reshape(shape)
223
+ return out, meta
224
+
225
+
226
+ _ST_TORCH_DTYPES = {"BF16": "bfloat16", "F16": "float16", "F32": "float32",
227
+ "F64": "float64", "I8": "int8", "U8": "uint8", "I16": "int16",
228
+ "I32": "int32", "I64": "int64", "BOOL": "bool"}
229
+
230
+
231
+ def read_safetensors_torch(path):
232
+ """Torch-side v2/v3 reader for dtype-opaque files (bf16). v3 files hold ONLY
233
+ `__zsc__`; entries carry safetensors dtype tokens ("BF16", ...).
234
+ Returns ({name: torch.Tensor}, metadata)."""
235
+ import torch
236
+ from safetensors import safe_open
237
+ out = {}
238
+ with safe_open(path, framework="pt") as fh:
239
+ meta = fh.metadata() or {}
240
+ for k in fh.keys():
241
+ out[k] = fh.get_tensor(k)
242
+ if "__zsc__" in out:
243
+ import zstandard
244
+ man = json.loads(meta["zsc"])
245
+ buf = zstandard.ZstdDecompressor().decompress(
246
+ out.pop("__zsc__").numpy().tobytes(), max_output_size=man["raw_len"])
247
+ for key, dt, shape, off, nb in man["entries"]:
248
+ if dt in _ST_TORCH_DTYPES: # safetensors dtype token
249
+ t = torch.frombuffer(bytearray(buf[off:off + nb]),
250
+ dtype=getattr(torch, _ST_TORCH_DTYPES[dt]))
251
+ out[key] = t.reshape(shape)
252
+ else: # numpy dtype str
253
+ a = np.frombuffer(buf, dtype=np.dtype(dt),
254
+ count=nb // np.dtype(dt).itemsize, offset=off)
255
+ out[key] = torch.from_numpy(a.reshape(shape).copy())
256
+ return out, meta
257
+
258
+
259
+ def decode_expert_layer(packed_dir, layer, device="cuda"):
260
+ """Reassemble fused gate_up_proj [256,1024,2048] fp32 + down_proj [256,2048,512].
261
+ K2 experts decode with continuous su/sv (no wscale); demoted K1 experts decode
262
+ with int8 signs + Wscale, plus the shared low-rank basis residual (B*c)@A when
263
+ the manifest carries "basis"."""
264
+ path = os.path.join(packed_dir, "experts", f"L{layer:02d}.safetensors")
265
+ t, meta = _read_safetensors_np(path)
266
+ # chunked shards (metadata fields includes wave_gamma) route to
267
+ # decode_expert_layer_v3t
268
+ if "wave_gamma" in (meta.get("fields") or ""):
269
+ return decode_expert_layer_v3t(packed_dir, layer)
270
+ man = json.loads(meta["manifest"])
271
+ tlut, _ = _read_safetensors_np(os.path.join(packed_dir, "experts", "codebook.safetensors"))
272
+ tlut = tlut["tlut"]
273
+ # K only changes transitions, so the [2^L, V] LUT is shared
274
+ cb2 = cb1 = _np_full_lut_cached(tlut, man.get("cb2", CB2)["L"],
275
+ man.get("cb2", CB2)["tlut_bits"])
276
+ demoted = set(man["demoted"])
277
+ geom = {p: tuple(v) for p, v in man["geom"].items()} # proj -> (m, n)
278
+ basis = man.get("basis")
279
+ if basis is not None: # shared cold-expert low-rank basis
280
+ bA = {p: t[f"basis.{p}.A"].astype(np.float32) for p in geom}
281
+ bB = {p: t[f"basis.{p}.B"].astype(np.float32) for p in geom}
282
+ gate_up = np.empty((NEXP, 2 * INTER, HIDDEN), np.float32)
283
+ down = np.empty((NEXP, HIDDEN, INTER), np.float32)
284
+ for e in range(NEXP):
285
+ for proj, dst in (("gate", gate_up[e, :INTER]), ("up", gate_up[e, INTER:]),
286
+ ("down", down[e])):
287
+ m0, n0 = geom[proj]
288
+ if e in demoted:
289
+ ws = float(np.asarray(t[f"e{e}.{proj}.Wscale"]).ravel()[0])
290
+ w = decode_trellis(t[f"e{e}.{proj}.trellis"], t[f"e{e}.{proj}.SU"],
291
+ t[f"e{e}.{proj}.SV"], tlut, m0, n0, man.get("cb1", CB1),
292
+ wscale=ws, cb=cb1, device=device)
293
+ if basis is not None:
294
+ # rs[m,n] = sum_r B[m,r]*c[r]*A[r,n], fp32, added BEFORE any
295
+ # bf16 cast -- the op order is part of the format
296
+ c = t[f"e{e}.{proj}.c"].astype(np.float32)
297
+ w = w + (bB[proj] * c[None, :]) @ bA[proj]
298
+ else:
299
+ w = decode_trellis(t[f"e{e}.{proj}.trellis"], t[f"e{e}.{proj}.su"],
300
+ t[f"e{e}.{proj}.sv"], tlut, m0, n0, man.get("cb2", CB2),
301
+ wscale=None, cb=cb2, device=device)
302
+ dst[:] = w
303
+ return {"gate_up_proj": gate_up, "down_proj": down}
304
+
305
+
306
+ # ============================================================================ #
307
+ # NE transform-free tier: Lloyd bitshift trellis L=12, uniform K, group-128 fp16
308
+ # scales, per-matrix 4096-entry fp16 LUT.
309
+ # ============================================================================ #
310
+ NELL_L = 12
311
+
312
+
313
+ def _nell_bits_to_states(packed, T, k, L=NELL_L):
314
+ """Inverse of the encoder's states_to_bits: step t's k NEW trellis bits are stored
315
+ MSB-first, bytes are big-endian packbits. State recurrence (s_{-1} = 0):
316
+ s_t = ((s_{t-1} << k) | b_t) & (2^L - 1)."""
317
+ B = packed.shape[0]
318
+ bits = np.unpackbits(packed, axis=1, count=T * k).astype(np.int64)
319
+ mask = (1 << L) - 1
320
+ states = np.empty((B, T), np.int32)
321
+ s = np.zeros(B, np.int64)
322
+ pos = 0
323
+ for t in range(T):
324
+ b = np.zeros(B, np.int64)
325
+ for j in range(k):
326
+ b = (b << 1) | bits[:, pos]
327
+ pos += 1
328
+ s = ((s << k) | b) & mask
329
+ states[:, t] = s
330
+ return states
331
+
332
+
333
+ def decode_ne_ll_tensor(t, man, name):
334
+ """One transform-free NE matrix -> fp32 [m0, n0]: fp16 LUT gathered as fp32,
335
+ * per-group fp16 scale in fp32, transpose back."""
336
+ g, k = man["group"], man["pattern"][0]
337
+ geom = man["tensors"][name]
338
+ m0, n0 = geom["shape"]
339
+ B, T = (n0, m0) if geom["transposed"] else (m0, n0)
340
+ lut = t[f"{name}|lut"].astype(np.float32)
341
+ gs = t[f"{name}|gscale"].astype(np.float32)
342
+ states = _nell_bits_to_states(t[f"{name}|packed"], T, k)
343
+ W = lut[states] * np.repeat(gs, g, axis=1)
344
+ return np.ascontiguousarray(W.T) if geom["transposed"] else W
345
+
346
+
347
+ def decode_ne_shard_canon(t, meta, packed_dir, device="cuda", subdir="ne"):
348
+ """NE spine shard (codec canon_rht_bitshift_trellis_intlattice, zero-padded
349
+ L00-L39 files). No manifest key: per-file metadata holds cb_params and dims
350
+ (name -> [m0, n0, m, n]); keys are <tensor>|{trellis,SU,SV,Wscale} with int8
351
+ sign SU/SV + scalar Wscale; the tier-shared codebook is <subdir>/tlut.safetensors."""
352
+ cbp = json.loads(meta["cb_params"])
353
+ dims = json.loads(meta["dims"])
354
+ tlut, _ = _read_safetensors_np(os.path.join(packed_dir, subdir, "tlut.safetensors"))
355
+ tlut = tlut["tlut"]
356
+ cb = _np_full_lut_cached(tlut, cbp["L"], cbp["tlut_bits"])
357
+ out = {}
358
+ for name in sorted({key.rsplit("|", 1)[0] for key in t}):
359
+ m0, n0 = dims[name][0], dims[name][1]
360
+ out[name] = decode_trellis(t[f"{name}|trellis"], t[f"{name}|SU"], t[f"{name}|SV"],
361
+ tlut, m0, n0, cbp,
362
+ wscale=float(np.asarray(t[f"{name}|Wscale"]).ravel()[0]),
363
+ cb=cb, device=device)
364
+ return out
365
+
366
+
367
+ def decode_ne_shard(packed_dir, shard, device="cuda", subdir="ne"):
368
+ """Decode every NE tensor in one shard -> {name: fp32 [m0,n0]}. Dispatches on the
369
+ shard's own metadata. subdir picks the size variant: "ne" (default) or "ne-4bit"."""
370
+ path = os.path.join(packed_dir, subdir, f"{shard}.safetensors")
371
+ t, meta = _read_safetensors_np(path)
372
+ if "manifest" not in meta:
373
+ codec = meta.get("codec")
374
+ assert codec == "canon_rht_bitshift_trellis_intlattice", \
375
+ f"NE shard {shard}: no manifest and unknown codec {codec!r}"
376
+ return decode_ne_shard_canon(t, meta, packed_dir, device=device, subdir=subdir)
377
+ man = json.loads(meta["manifest"])
378
+ if man.get("codec") == "lloyd_bitshift_trellis":
379
+ return {name: decode_ne_ll_tensor(t, man, name) for name in man["tensors"]}
380
+ cb_params = man["cb"]
381
+ tlut, _ = _read_safetensors_np(os.path.join(packed_dir, "ne", "codebook.safetensors"))
382
+ tlut = tlut["tlut"]
383
+ cb = _np_full_lut_cached(tlut, cb_params["L"], cb_params["tlut_bits"])
384
+ out = {}
385
+ for name, geom in man["tensors"].items():
386
+ out[name] = decode_trellis(t[f"{name}|trellis"], t[f"{name}|SU"], t[f"{name}|SV"],
387
+ tlut, geom["m0"], geom["n0"], cb_params,
388
+ wscale=float(np.asarray(t[f"{name}|Wscale"]).ravel()[0]),
389
+ cb=cb, device=device)
390
+ return out
391
+
392
+
393
+ # ============================================================================ #
394
+ # Embedding: int{3,4} asymmetric group codes, and the lossless Lloyd-LUT container.
395
+ # ============================================================================ #
396
+ def pack_embed_q(q, bits=3):
397
+ """q uint8 [rows, hid] with values < 2**bits -> packed uint8 [rows, hid*bits/8]."""
398
+ rows, hid = q.shape
399
+ b = np.unpackbits(q[..., None], axis=-1, count=8)[..., 8 - bits:] # [rows,hid,bits] MSB-first
400
+ return np.packbits(b.reshape(rows, hid * bits), axis=1)
401
+
402
+
403
+ def unpack_embed_q(packed, hid, bits=3):
404
+ rows = packed.shape[0]
405
+ b = np.unpackbits(packed, axis=1, count=hid * bits).reshape(rows, hid, bits)
406
+ q = np.zeros((rows, hid), np.uint8)
407
+ for j in range(bits):
408
+ q = (q << 1) | b[..., j]
409
+ return q
410
+
411
+
412
+ def decode_embed(packed_dir, bits=3, group=None):
413
+ """embed_int{bits} codes -> fp32 [rows, hid]. mn/mx stored fp16, step computed
414
+ in fp32 exactly as at encode time. `group` is inferred from the stored shapes
415
+ when not given, so g64 and g128 packs decode identically.
416
+ Optional exception tensors: elements listed in exc_idx int32 (flat index) are
417
+ overwritten with the exact bf16 bit patterns in exc_bits uint16 (expanded to
418
+ fp32 here)."""
419
+ path = os.path.join(packed_dir, "ne", f"embed_int{bits}.safetensors")
420
+ t, meta = _read_safetensors_np(path)
421
+ mn = t["mn"].astype(np.float32)[..., None] # [rows, hid/g, 1]
422
+ mx = t["mx"].astype(np.float32)[..., None]
423
+ rows, ng = mn.shape[0], mn.shape[1]
424
+ if group is None:
425
+ group = (t["q_packed"].shape[1] * 8 // bits) // ng
426
+ hid = ng * group
427
+ q = unpack_embed_q(t["q_packed"], hid, bits=bits).astype(np.float32)
428
+ lv = float(2 ** bits - 1)
429
+ step = np.maximum(mx - mn, 1e-8) / lv
430
+ dec = (mn + q.reshape(rows, ng, group) * step).reshape(rows, hid)
431
+ if "exc_idx" in t:
432
+ vals = (np.asarray(t["exc_bits"]).astype(np.uint32) << 16).view(np.float32)
433
+ dec.reshape(-1)[np.asarray(t["exc_idx"], dtype=np.int64)] = vals
434
+ return dec
435
+
436
+
437
+ def decode_embed_packed(packed_dir, subdir="ne"):
438
+ """embed_packed.safetensors (per-group Lloyd LUT + 4-bit nibble codes, chunk keys
439
+ EMBEDCHUNK:{r0}:{r1}.{codes|lut}) -> fp32 [rows, hid]. Lossless: the lut stores
440
+ the source bf16 bit patterns. Low nibble = even column. Uses the torch-side
441
+ reader because the lut is bf16."""
442
+ path = os.path.join(packed_dir, subdir, "embed_packed.safetensors")
443
+ t, meta = read_safetensors_torch(path)
444
+ group = int(meta.get("group", 128))
445
+ chunks = sorted({k.rsplit(".", 1)[0] for k in t},
446
+ key=lambda c: int(c.split(":")[1]))
447
+ r_end, parts = 0, []
448
+ for c in chunks:
449
+ r0, r1 = int(c.split(":")[1]), int(c.split(":")[2])
450
+ assert r0 == r_end, f"non-contiguous embed chunks at {c}"
451
+ r_end = r1
452
+ codes = np.asarray(t[f"{c}.codes"]) # uint8 [rows, cols/2]
453
+ lut = t[f"{c}.lut"].float().numpy() # [G, 16] exact bf16 values
454
+ rows, half = codes.shape
455
+ cols = half * 2
456
+ q = np.empty((rows, cols), np.uint8)
457
+ q[:, 0::2] = codes & 0x0F
458
+ q[:, 1::2] = codes >> 4
459
+ w = np.take_along_axis(lut, q.reshape(-1, group).astype(np.int64), axis=1)
460
+ parts.append(w.reshape(rows, cols))
461
+ return np.concatenate(parts, axis=0)
462
+
463
+
464
+ if __name__ == "__main__":
465
+ import argparse
466
+ ap = argparse.ArgumentParser(description="spot-verify a packed dir against decoded refs")
467
+ ap.add_argument("--packed-dir", required=True)
468
+ ap.add_argument("--ref-experts", default=None)
469
+ ap.add_argument("--ref-ne", default=None)
470
+ ap.add_argument("--layers", default="0")
471
+ ap.add_argument("--ne-shards", default="L0")
472
+ ap.add_argument("--device", default="cuda")
473
+ a = ap.parse_args()
474
+
475
+ def _re(x, y):
476
+ x, y = np.asarray(x, np.float32).ravel(), np.asarray(y, np.float32).ravel()
477
+ return float(np.linalg.norm(x - y) / max(np.linalg.norm(y), 1e-30))
478
+
479
+ if a.ref_experts:
480
+ for L in [int(x) for x in a.layers.split(",") if x.strip()]:
481
+ dec = decode_expert_layer(a.packed_dir, L, device=a.device)
482
+ ref, _ = _read_safetensors_np(os.path.join(a.ref_experts, f"L{L:02d}.safetensors"))
483
+ for key in ("gate_up_proj", "down_proj"):
484
+ print(f"[experts L{L} {key}] relerr_vs_ref={_re(dec[key], ref[key]):.2e}")
485
+ if a.ref_ne:
486
+ for shard in [x for x in a.ne_shards.split(",") if x.strip()]:
487
+ dec = decode_ne_shard(a.packed_dir, shard, device=a.device)
488
+ refp = os.path.join(a.ref_ne, f"{shard}.safetensors")
489
+ ref, _ = _read_safetensors_np(refp) if os.path.exists(refp) else ({}, {})
490
+ for name, w in dec.items():
491
+ if name in ref:
492
+ print(f"[NE {shard} {name}] relerr_vs_ref={_re(w, ref[name]):.4f}")
493
+ else:
494
+ print(f"[NE {shard} {name}] shape={w.shape} (no ref)")
495
+
496
+
497
+ # ============================================================================ #
498
+ # int5-g64 head tier: symmetric int5 codes, one fp16 scale per 64 reduction-dim
499
+ # weights, RAW domain (no rotation). Storage: 8 codes packed into 5 little-endian
500
+ # bytes (code i occupies bits [5i, 5i+5) of the 40-bit block; stored value =
501
+ # q + 16, q in [-16, 15]).
502
+ # Optional protected rows: |prot_rows int32 + |prot_dense bf16 overwrite the
503
+ # listed rows with exact dense values.
504
+ # ============================================================================ #
505
+ def pack_int5(q):
506
+ """int8 [m, n] in [-16, 15] -> uint8 [m, n//8*5] little-endian 5-bit pack."""
507
+ m, n = q.shape
508
+ assert n % 8 == 0, n
509
+ u = (q.astype(np.int64) + 16).astype(np.uint64)
510
+ assert u.max() < 32 and u.min() >= 0, (int(u.min()), int(u.max()))
511
+ blocks = u.reshape(m, n // 8, 8)
512
+ word = np.zeros((m, n // 8), dtype=np.uint64)
513
+ for i in range(8):
514
+ word |= blocks[:, :, i] << np.uint64(5 * i)
515
+ by = word.astype("<u8").view(np.uint8).reshape(m, n // 8, 8)[:, :, :5]
516
+ return np.ascontiguousarray(by.reshape(m, n // 8 * 5))
517
+
518
+
519
+ def unpack_int5(qp, n):
520
+ """Inverse of pack_int5 -> int8 [m, n] in [-16, 15]."""
521
+ m = qp.shape[0]
522
+ assert qp.shape[1] == n // 8 * 5, (qp.shape, n)
523
+ by = qp.reshape(m, n // 8, 5)
524
+ full = np.zeros((m, n // 8, 8), dtype=np.uint8)
525
+ full[:, :, :5] = by
526
+ word = full.reshape(m, n // 8 * 8).view("<u8").reshape(m, n // 8)
527
+ out = np.zeros((m, n // 8, 8), dtype=np.int8)
528
+ for i in range(8):
529
+ out[:, :, i] = ((word >> np.uint64(5 * i)) & np.uint64(31)).astype(np.int8) - 16
530
+ return out.reshape(m, n)
531
+
532
+
533
+ def decode_int5g64(qp, gscale, m0, n0, group=64, prot_rows=None, prot_dense=None):
534
+ """int5-g64 head decode -> fp32 [m0, n0]: W[r, j] = q[r, j] * gscale[r, j // group];
535
+ protected rows are then overwritten with their exact dense values."""
536
+ q = unpack_int5(np.asarray(qp), n0).astype(np.float32)
537
+ s = np.asarray(gscale, dtype=np.float32)
538
+ W = q * np.repeat(s, group, axis=1)[:, :n0]
539
+ if prot_rows is not None and len(prot_rows):
540
+ W[np.asarray(prot_rows, dtype=np.int64)] = np.asarray(prot_dense,
541
+ dtype=np.float32)
542
+ return np.ascontiguousarray(W[:m0, :n0])
543
+
544
+
545
+ def decode_head(packed_dir, subdir="head"):
546
+ """int5-g64 lm_head (packed/{subdir}/head_c{c}of8.safetensors, codec
547
+ "int5g64_packed") -> fp32 [vocab, hid]. Chunk keys LMHEADCHUNK:{r0}:{r1}|{qp|gscale}
548
+ (+ optional |prot_rows / |prot_dense); each file's dims metadata gives the chunk's
549
+ [rows, n]; row chunks assemble in r0 order."""
550
+ d = os.path.join(packed_dir, subdir)
551
+ files = sorted(f for f in os.listdir(d)
552
+ if f.startswith("head_c") and f.endswith(".safetensors"))
553
+ assert files, f"no head chunk files under {d}"
554
+ pieces = []
555
+ for f in files:
556
+ t, meta = _read_safetensors_np(os.path.join(d, f))
557
+ group = int(meta.get("group", 64))
558
+ dims = json.loads(meta["dims"])
559
+ for name, (m0, n0) in dims.items():
560
+ r0 = int(name.split(":")[1])
561
+ w = decode_int5g64(t[f"{name}|qp"], t[f"{name}|gscale"], m0, n0,
562
+ group=group, prot_rows=t.get(f"{name}|prot_rows"),
563
+ prot_dense=t.get(f"{name}|prot_dense"))
564
+ pieces.append((r0, w))
565
+ pieces.sort(key=lambda x: x[0])
566
+ return np.concatenate([w for _, w in pieces], axis=0)
567
+
568
+
569
+ # ============================================================================ #
570
+ # Chunked-container expert decode with per-(expert, wavefront) gammas.
571
+ # Layout: 32-expert CHUNK-STACKED keys e{c0}.{proj}.{trellis|su|sv|wave_gamma}
572
+ # (c0 in 0,32,...,224), NO Wscale / int8 signs. su/sv are continuous fp16 over
573
+ # the PADDED dims with Wscale absorbed into sv; wave_gamma is fp16 [n_chunk,
574
+ # Mb+Nb] indexed by wave_index_map. Discriminator: file metadata carries
575
+ # fields="trellis|su|sv|wave_gamma".
576
+ # Op order (part of the format):
577
+ # states -> recons -> cast fp16 -> apply_wave_gamma (BEFORE both Hadamards)
578
+ # -> hadamard over n -> * su (between the Hadamards)
579
+ # -> transpose -> hadamard over m -> * sv -> transpose -> crop
580
+ # ============================================================================ #
581
+ def wave_index_map(Mb, Nb):
582
+ """Tile grid [Mb, Nb] -> the LAST wavefront index that wrote each tile
583
+ (the encoder's starts recurrence, including the schedule's duplicated
584
+ top-right-starting wave)."""
585
+ starts = ([(Mb - i - 1, Nb - 1) for i in range(Mb)]
586
+ + [(0, Nb - i - 1) for i in range(Nb)])
587
+ idx = np.zeros((Mb, Nb), dtype=np.int32)
588
+ for w, (jm, jn) in enumerate(starts):
589
+ while 0 <= jm < Mb and 0 <= jn < Nb:
590
+ idx[jm, jn] = w
591
+ jm += 1
592
+ jn -= 1
593
+ return idx
594
+
595
+
596
+ def apply_wave_gamma(Wr, gamma, td=16):
597
+ """Multiply each td x td tile of Wr [m, n] by gamma[wave(tile)]."""
598
+ m, n = Wr.shape
599
+ Mb, Nb = m // td, n // td
600
+ g = np.asarray(gamma, np.float32)[wave_index_map(Mb, Nb)]
601
+ return np.ascontiguousarray(
602
+ (Wr.reshape(Mb, td, Nb, td) * g[:, None, :, None]).reshape(m, n))
603
+
604
+
605
+ CB_V3T = dict(K=1.5, L=16, V=8, tlut_bits=15, decode_mode="quantlut_sym",
606
+ td_x=16, td_y=16)
607
+
608
+
609
+ def decode_expert_v3t(t, tlut, proj, e, m0, n0, cb_params=None, table=None):
610
+ """Decode ONE expert's projection from a chunked-container layer dict."""
611
+ cbp = cb_params or CB_V3T
612
+ c0, off = (e // 32) * 32, e % 32
613
+ if table is None:
614
+ table = _np_full_lut_cached(tlut, cbp["L"], cbp["tlut_bits"])
615
+ m, n = padto(m0), padto(n0)
616
+ tr = np.asarray(t[f"e{c0}.{proj}.trellis"][off])
617
+ su = np.asarray(t[f"e{c0}.{proj}.su"][off], np.float32)
618
+ sv = np.asarray(t[f"e{c0}.{proj}.sv"][off], np.float32)
619
+ states = _np_unpack_trellis(tr, cbp["td_x"] * cbp["td_y"],
620
+ cbp["L"], cbp["K"], cbp["V"])
621
+ unit = _np_recons(states, table, m, n, cbp["td_x"], cbp["td_y"])
622
+ unit = unit.astype(np.float16).astype(np.float32)
623
+ gk = f"e{c0}.{proj}.wave_gamma"
624
+ if gk in t:
625
+ unit = apply_wave_gamma(unit, np.asarray(t[gk][off], np.float32),
626
+ td=cbp["td_x"])
627
+ rowside = _np_hadamard(unit) * su
628
+ colside = _np_hadamard(rowside.T) * sv
629
+ return np.ascontiguousarray(colside.T[:m0, :n0])
630
+
631
+
632
+ def decode_expert_layer_v3t(packed_dir, layer):
633
+ """Whole-layer reassembly for the chunked container -> gate_up/down fp32."""
634
+ path = os.path.join(packed_dir, "experts", f"L{layer:02d}.safetensors")
635
+ t, meta = _read_safetensors_np(path)
636
+ assert "wave_gamma" in (meta.get("fields") or ""), "not a chunked-container shard (fields metadata lacks wave_gamma)"
637
+ tlut, _ = _read_safetensors_np(os.path.join(packed_dir, "experts",
638
+ "codebook.safetensors"))
639
+ tlut = tlut["tlut"]
640
+ table = _np_full_lut_cached(tlut, CB_V3T["L"], CB_V3T["tlut_bits"])
641
+ gate_up = np.empty((NEXP, 2 * INTER, HIDDEN), np.float32)
642
+ down = np.empty((NEXP, HIDDEN, INTER), np.float32)
643
+ for e in range(NEXP):
644
+ gate_up[e, :INTER] = decode_expert_v3t(t, tlut, "gate", e, INTER, HIDDEN,
645
+ table=table)
646
+ gate_up[e, INTER:] = decode_expert_v3t(t, tlut, "up", e, INTER, HIDDEN,
647
+ table=table)
648
+ down[e] = decode_expert_v3t(t, tlut, "down", e, HIDDEN, INTER, table=table)
649
+ return {"gate_up_proj": gate_up, "down_proj": down}
extras.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:013fe06943020ebffb1c3326a38e5dbe789eaef1d2c7f11975793ee91e2da7da
3
+ size 52335992
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 248044,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 248046,
6
+ 248044
7
+ ],
8
+ "pad_token_id": 248044,
9
+ "temperature": 1.0,
10
+ "top_k": 20,
11
+ "top_p": 0.95
12
+ }
goldens/L0_e0_fp32.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d740993d72430e46b44faba103ee2ae0b91d1271c515ad4b21ac4362e790a325
3
+ size 12583352
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
packed/experts/L00.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46ce93394c8c50deacc5447f022e13618de382cf04f7b0963c74e2beb4e9b1f2
3
+ size 155181208
packed/experts/L01.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0c42283c64130e30c63c2239b1e371dbc42973d7e0598707a7aba692b7bcf6e
3
+ size 155181208
packed/experts/L02.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36ce3634b9da230fba4a9272aa3c8e38ad6fefadfc3092e3e0e110bf2a31402c
3
+ size 155181208
packed/experts/L03.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5faed106e9eca8b533adad896d8d5096d399f5419655b83c88993113e3cc90c
3
+ size 155181208
packed/experts/L04.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25ed7547ce623868f5abe55fefd7e993f3d06627b869afbb5d2ac2e59ce27cd8
3
+ size 155181208
packed/experts/L05.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7263de6c512148a8428d69b8ee9e9863024668dd7c7387d0b172a946b7058bbc
3
+ size 155181208
packed/experts/L06.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f72aa6d5af5346bf0b481354b7bb25b2f0ed74633b0fdb57b3de04afe281a8c
3
+ size 155181208
packed/experts/L07.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6dc718b28d8d33f5d3582bdc96d681db4a7cae62593a2267dc2d84f85b312c5
3
+ size 155181208
packed/experts/L08.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44989b42d4c89c9182e3e0868fd8ca2cbcecc48dccb3e7c167698c9d0e413b00
3
+ size 155181208
packed/experts/L09.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b35db17e3ea832dbcd69b663250759cd8769e8a427ef1c0b670f6c897e11eb7b
3
+ size 155181208
packed/experts/L10.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:216d9e27b624d6b3ba18196ab82be7b4c7ad9f3c8c5593ff90d62c9d741b700b
3
+ size 155181208
packed/experts/L11.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0973ce67cb7eded3042b17a1ef4e9259ae036284090b9b4800f44e2bcfe03441
3
+ size 155181208
packed/experts/L12.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41c8d788406abe62201ce7b7a8826bc79126eac8f609eaa9a5a89f8dfd545331
3
+ size 155181208
packed/experts/L13.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd39c71803a28607e5dac60188bc084535cc651c519ac2dd023f681cd1544fd4
3
+ size 155181208
packed/experts/L14.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f43f300d69327861bba48a068e5fe2578340280b84d2868b0e7ceceafaa4b816
3
+ size 155181208
packed/experts/L15.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2cc4710dfb5d7926f5c1ccba606a187cf2dc5fd15b1d29cf32f5d092817786f
3
+ size 155181208
packed/experts/L16.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d70daff68a440a13107d6fc6f3ac5c58d79f845d0da46110ecbd8f1e811520d9
3
+ size 155181208
packed/experts/L17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27d382c46bf01a0e9d04f014b66b98dbfe2bfff10145e03552db0b679fc761f7
3
+ size 155181208
packed/experts/L18.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82705f3a85d149e695323592dc7a8df0e0fd856b83f7b3bad0a6cbb93999d446
3
+ size 155181208
packed/experts/L19.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3004bbdd61cd7491c66b64706925611b4af2202917f3c54e29ed1ec4c7675af2
3
+ size 155181208
packed/experts/L20.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a65552b5c5c97b1b306308c1d7eaa3b04a9327f5b3304af01296f0da89d14f6
3
+ size 155181208
packed/experts/L21.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7152fa5e1c856fd51d8986dc0c615eb8aaa1779e8361cf2db20de7eb544919c2
3
+ size 155181208
packed/experts/L22.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c2a4ef0896c2ef1fd768e0d6e42baf351e29740133e34e2651baa2790288ff9
3
+ size 155181208
packed/experts/L23.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e8218c7e6cb3a841bd69a33a3577ea9b2330cd183bc8051245af13d5db79526
3
+ size 155181208
packed/experts/L24.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85598864d8a0c95b52bddba92daf808cf0982ce04a93f04c96641b11724553c5
3
+ size 155181208
packed/experts/L25.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34a32d1cf323a5b6f0bec152ca30e1922806e6da87383ae6733730f43913503e
3
+ size 155181208
packed/experts/L26.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ac4e7cf8efcc94fa72848e337c86b1f6594cefe8e18006800c87dfd33334e30
3
+ size 155181208
packed/experts/L27.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ed5ed0e4231a394271f3b20700091ceaa422d661e685722dc0a047635fb129d
3
+ size 155181208
packed/experts/L28.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44d34c83d6384b00de68cd65b4e7416f8b899a63df6986d1d6ea1c6209f40ca1
3
+ size 155181208
packed/experts/L29.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f86acf7df3a4fb2188c55aecfc1f23c16e16df258e885af8b066175052c8510
3
+ size 155181208
packed/experts/L30.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22f204b0f6924402e48fd5553ffa88b225b659d723a4b0079dba1296731a09e0
3
+ size 155181208
packed/experts/L31.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04ce1c0913d0870e3f3ef3e713ff388481494ea790f1166613e8b3d340de84a5
3
+ size 155181208
packed/experts/L32.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:735ee4c7e4c578d0a0d78180220052eb7e5a6bc15b697adebd526881770c23f6
3
+ size 155181208
packed/experts/L33.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:269933ec55cde295936c06e4a657cd691b39b1d15a6cecbdceeaed2644e0a9c4
3
+ size 155181208
packed/experts/L34.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a87eb2a8df870c181047addf0d219dea5445c94b1dcd250550ed8cdaad0f8fd5
3
+ size 155181208
packed/experts/L35.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91bf39bcbc9dd7e060c7f9582b8a5498001d23f46a785adcea4862a71b7eac88
3
+ size 155181208
packed/experts/L36.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60b4103e563fb55053eaeafd9b45a6cb00afbbe966da2537f159d3d218c3699d
3
+ size 155181208