strata-engine commited on
Commit
04ecd36
·
verified ·
1 Parent(s): 9fa0ff2

Inkling-2-Mini-DFlash2 for Strata: Q8 attention + SF4 feed-forward mix (strata-dflash2-q1), 551,600,700 bytes

Browse files
Files changed (5) hide show
  1. Inkling-2-Mini-DFlash2-mix.safetensors +3 -0
  2. LICENSE +202 -0
  3. NOTICE +46 -0
  4. README.md +41 -0
  5. make_mix_from_original.py +168 -0
Inkling-2-Mini-DFlash2-mix.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387
3
+ size 551600700
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 [yyyy] [name of copyright owner]
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.
NOTICE ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Inkling-2-Mini-DFlash2 (mix), a modified copy for the Strata engine
2
+ ====================================================================
3
+
4
+ This repository file, Inkling-2-Mini-DFlash2-mix.safetensors, is derived from the model
5
+ "Inkling-2-Mini-DFlash2" (https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) by Inco AI / z-lab,
6
+ a DFlash 2 block-diffusion draft model for thinkingmachines/Inkling-2-Mini
7
+ (https://inco.ai/blog/dflash2/, https://github.com/z-lab/dflash), which is licensed under the
8
+ Apache License, Version 2.0. The licence text is in the file LICENSE next to this one.
9
+
10
+ Original work
11
+ Repository: incoai/Inkling-2-Mini-DFlash2
12
+ Revision: 4f9088ea66c21f2b99ed657d1941c306b03e84d2
13
+ File: model.safetensors, 989,975,616 bytes,
14
+ SHA-256 217980ab00d116693fa5946df7bbfd967caf5fac1f529afd541fbd470ddb54ee
15
+ Copyright and credit for the weights belong to their authors, Inco AI and z-lab. This file
16
+ keeps that attribution. Strata did not train these weights.
17
+
18
+ Changes made (Apache License 2.0, section 4(b): the modified file carries this statement)
19
+ Date: 2026-11-26
20
+ By: Strata (https://github.com/Niko1221/Strata), with the Strata 0.2.23 engine
21
+ (strata-inkling, the 0.1.69 engine line), run with STRATA_INK_DFLASH2_DUMP. The script
22
+ make_mix_from_original.py in this repository repeats the same arithmetic with numpy and
23
+ produces a byte-identical file from the original.
24
+ What: 1. The file format. The tensors are stored in the format "strata-dflash2-q1", a safetensors
25
+ file that the Strata engine reads directly (the header's __metadata__ says
26
+ {"format": "strata-dflash2-q1", "variant": "mix"}). Other programs cannot load it.
27
+ 2. Quantization of the large matrices of the 5 transformer layers, the part of the weights
28
+ that is a standard matrix multiplication:
29
+ attention (q_proj, o_proj): 8-bit integers with one float32 scale per row;
30
+ feed-forward (gate_proj, up_proj, down_proj): 4-bit SF4 (E2M1 values, a UE4M3 scale
31
+ per 16 values, one float32 scale per matrix).
32
+ 3. The norm weights and convolution base kernels are stored as float32 (they were
33
+ bfloat16; the values are the same). All other tensors (fc, the K/V and convolution
34
+ projections, the candidate selector and its two codebooks) are unchanged bfloat16
35
+ values. The unused rows of the two codebooks beyond the
36
+ 200,058 vocabulary entries are left out.
37
+ Everything else (architecture, the values of the unchanged tensors) is as in the original.
38
+ Result: 551,600,700 bytes, SHA-256 cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387.
39
+
40
+ The quantization loses a little precision against the original. Measured with the Strata engine
41
+ on an RTX 5090 and an RTX 5060 Ti, the drafter's acceptance stays within about 2 percent of the
42
+ original's (see the README). A draft only proposes tokens: the main model checks every one of them,
43
+ and its own answer is what is returned.
44
+
45
+ This modified file is provided under the same licence as the original (Apache License 2.0), "AS IS",
46
+ without warranties or conditions of any kind. No endorsement by Inco AI or z-lab is implied.
README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: incoai/Inkling-2-Mini-DFlash2
4
+ base_model_relation: quantized
5
+ tags:
6
+ - strata
7
+ - speculative-decoding
8
+ - dflash
9
+ - inkling-2-mini
10
+ ---
11
+
12
+ # Inkling-2-Mini-DFlash2 for Strata
13
+
14
+ The DFlash 2 draft model of [incoai/Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Inco AI and z-lab, Apache-2.0), quantized for the
15
+ [Strata](https://github.com/Niko1221/Strata) engine. It is the only drafter Strata uses for Inkling 2 Mini. Only the Strata engine reads this file.
16
+
17
+ | | original | this file |
18
+ |---|---|---|
19
+ | file | `model.safetensors` | `Inkling-2-Mini-DFlash2-mix.safetensors` |
20
+ | size | 989,975,616 bytes | 551,600,700 bytes |
21
+ | SHA-256 | `217980ab00d116693fa5946df7bbfd967caf5fac1f529afd541fbd470ddb54ee` | `cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387` |
22
+ | large matrices | 16-bit | attention 8-bit (one scale per row), feed-forward 4-bit SF4 |
23
+ | format | safetensors | safetensors, `strata-dflash2-q1`, variant `mix` |
24
+
25
+ The 5 layers' q/o and gate/up/down matrices are quantized; fc, K/V and convolution projections, the selector with its two codebooks and the norms keep their values. Changes are listed in `NOTICE`.
26
+
27
+ ## Measured (Strata 0.2.23 engine, Inkling-2-Mini-SQ-20, greedy, DFlash 2 against no drafter)
28
+
29
+ - Acceptance of the drafted tokens: within about 2 points of the original file on an RTX 5090 and an RTX 5060 Ti; exact-mode output identical to the original's on both cards (6 prompts).
30
+ - RTX 5090 (32 GB), end-to-end tokens/s, fast mode: 4 users +10.5%, 8 +22%, 16 +20%, 32 +8.6%; above 32 users the engine decodes without the drafter (64 users -1%).
31
+ - RTX 5060 Ti (16 GB), 1 user, decode tokens/s with / without the drafter: prose 82.9 / 83.8, json 159.3 / 83.8, code 241.5 / 83.9. 16 users +11%, 32 users +29%, 64 users +47%.
32
+ - Drafter load time 0.25 s; drafter weights 331 MiB (the original as BF16: 748 MiB). Download: 552 MB against 990 MB.
33
+
34
+ ## Use
35
+
36
+ Strata's setup and update download it next to the model and check the SHA-256. By hand: save it as `dflash2.safetensors` in the model's folder; without it Inkling 2 Mini runs without a drafter.
37
+ `make_mix_from_original.py` (numpy only) rebuilds this file from the original byte for byte.
38
+
39
+ ## Licence and credit
40
+
41
+ Weights: Inco AI and z-lab, Apache License 2.0 (`LICENSE`, `NOTICE`); this is a modified copy under the same licence, made on 2026-11-26. The DFlash 2 support in Strata that runs this drafter is based on the DFlash 2 port by **tjm8874**.
make_mix_from_original.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Makes Strata's pre-quantized DFlash 2 file (format "strata-dflash2-q1", variant "mix") from the original incoai/Inkling-2-Mini-DFlash2 model.safetensors with numpy only.
3
+
4
+ python -I make_mix_from_original.py model.safetensors Inkling-2-Mini-DFlash2-mix.safetensors
5
+
6
+ The Strata engine writes the same file itself (STRATA_INK_DFLASH2_DUMP, on the GPU); this script repeats its arithmetic in float32 so that the file can be checked or remade without a GPU. The
7
+ result must have SHA-256 cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387 and 551,600,700 bytes.
8
+
9
+ mix = attention matrices (q_proj, o_proj) as int8 with one float32 scale per row (scale = rowmax / 127; q = round-half-even(x / scale), clamped to +-127);
10
+ feed-forward matrices (gate_proj, up_proj, down_proj) as SF4: E2M1 values packed two to a byte (first value in the low nibble), a UE4M3 scale per 16 values
11
+ (block max / (6 * w_outer), rounded to E4M3), one float32 w_outer = tensor max / (6 * 448); everything else as in the original (norms and convolution base kernels widened to float32).
12
+ """
13
+ import json
14
+ import struct
15
+ import sys
16
+
17
+ import numpy as np
18
+
19
+ HID, FF, QD, KVD, DYN, RANK, LAYERS, HD = 2304, 6912, 4096, 1024, 576, 256, 5, 128
20
+ VOCAB = 200058 # the engine's vocabulary; the checkpoint's codebooks have more rows, the unused ones are left out
21
+
22
+
23
+ def read_safetensors(path):
24
+ f = open(path, "rb")
25
+ n = struct.unpack("<Q", f.read(8))[0]
26
+ hdr = json.loads(f.read(n))
27
+ base = 8 + n
28
+
29
+ def get(name):
30
+ t = hdr[name]
31
+ a, b = t["data_offsets"]
32
+ f.seek(base + a)
33
+ raw = np.frombuffer(f.read(b - a), dtype=np.uint16 if t["dtype"] == "BF16" else np.float32)
34
+ return raw.reshape(t["shape"]), t["dtype"]
35
+ return get
36
+
37
+
38
+ def bf16_to_f32(u16):
39
+ return (u16.astype(np.uint32) << 16).view(np.float32)
40
+
41
+
42
+ def f32_of(get, name):
43
+ a, dt = get(name)
44
+ return bf16_to_f32(a) if dt == "BF16" else a.astype(np.float32)
45
+
46
+
47
+ def q8_rows(w_bf16):
48
+ w = bf16_to_f32(w_bf16)
49
+ am = np.max(np.abs(w), axis=1)
50
+ sc = np.where(am > 0, am * np.float32(1.0 / 127.0), np.float32(0)).astype(np.float32)
51
+ inv = np.where(sc > 0, np.float32(1.0) / np.where(sc > 0, sc, 1), np.float32(0)).astype(np.float32)
52
+ q = np.clip(np.rint(w * inv[:, None]), -127, 127).astype(np.int8)
53
+ return q.reshape(-1), sc
54
+
55
+
56
+ def e4m3_byte(x):
57
+ """x >= 0 (float32, at most 448) -> the E4M3 (finite, bias 7) code that round-to-nearest-even gives, and its value as float32."""
58
+ x = x.astype(np.float64)
59
+ m, e = np.frexp(x) # x = m * 2^e, m in [0.5, 1)
60
+ e = np.maximum(e - 1, -6) # exponent of the leading bit, subnormals share 2^-6
61
+ step = np.ldexp(1.0, e - 3)
62
+ q = np.rint(x / step) * step # exact: division by a power of two
63
+ q = np.minimum(q, 448.0)
64
+ m2, e2 = np.frexp(q)
65
+ e2 = e2 - 1
66
+ sub = q < 2.0 ** -6
67
+ code = np.where(sub, np.rint(q / 2.0 ** -9), ((e2 + 7) << 3) + np.rint((q / np.ldexp(1.0, e2) - 1.0) * 8.0))
68
+ code = np.where(q == 0, 0, code).astype(np.uint8)
69
+ return code, q.astype(np.float32)
70
+
71
+
72
+ def e2m1_code(x):
73
+ """float32 -> 4-bit E2M1 code, round to nearest even (a tie goes to the even code), saturating at 6, the sign bit kept (also on -0)."""
74
+ a = np.abs(x)
75
+ mid = np.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], dtype=np.float32) # midpoints of 0 0.5 1 1.5 2 3 4 6
76
+ even_at_tie = np.array([0, 2, 2, 4, 4, 6, 6])
77
+ lo = np.searchsorted(mid, a, side="left") # midpoints strictly below a = the code of a that is not a tie
78
+ hi = np.searchsorted(mid, a, side="right") # midpoints at or below a; hi > lo means a is exactly a midpoint
79
+ code = np.where(hi > lo, even_at_tie[np.minimum(lo, 6)], lo)
80
+ return code.astype(np.uint8) | np.where(np.signbit(x), 8, 0).astype(np.uint8)
81
+
82
+
83
+ def sf4(w_bf16):
84
+ """-> packed (N, K/2) uint8, block scales (N, K/16) uint8, w_outer float32."""
85
+ N, K = w_bf16.shape
86
+ w = bf16_to_f32(w_bf16)
87
+ amax = np.max(np.abs(w))
88
+ w_outer = np.float32(max(np.float32(amax) / np.float32(6.0 * 448.0), np.float32(1e-12)))
89
+ blocks = w.reshape(N, K // 16, 16)
90
+ am = np.max(np.abs(blocks), axis=2)
91
+ sc_f = np.minimum(am / (w_outer * np.float32(6.0)), np.float32(448.0)).astype(np.float32)
92
+ sc_byte, sc_val = e4m3_byte(sc_f)
93
+ sc_byte = np.where(am > 0, sc_byte, 0).astype(np.uint8)
94
+ sc_val = np.where(am > 0, sc_val, 0).astype(np.float32)
95
+ denom = (w_outer * sc_val).astype(np.float32)
96
+ inv = np.where(denom > 0, np.float32(1.0) / np.where(denom > 0, denom, 1), np.float32(0)).astype(np.float32)
97
+ v = (blocks * inv[:, :, None]).astype(np.float32).reshape(N, K)
98
+ code = e2m1_code(v)
99
+ packed = (code[:, 0::2] | (code[:, 1::2] << 4)).astype(np.uint8)
100
+ return packed, sc_byte, w_outer
101
+
102
+
103
+ def main(src, dst):
104
+ get = read_safetensors(src)
105
+ items = [] # (name, dtype, shape, bytes)
106
+
107
+ def add(name, dtype, shape, arr):
108
+ items.append((name, dtype, list(shape), np.ascontiguousarray(arr).tobytes()))
109
+
110
+ def bf(name, shape):
111
+ a, dt = get(name)
112
+ assert dt == "BF16" and list(a.shape) == list(shape), (name, dt, a.shape)
113
+ add(name, "BF16", shape, a)
114
+
115
+ def f32(name, shape):
116
+ add(name, "F32", shape, f32_of(get, name))
117
+
118
+ bf("fc.weight", (HID, 4 * HID))
119
+ f32("hidden_norm.weight", (HID,))
120
+ f32("norm.weight", (HID,))
121
+ bf("candidate_selector.hidden_projection.weight", (RANK, HID))
122
+ for nm in ("candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook"):
123
+ a, dt = get(nm)
124
+ assert dt == "BF16" and a.shape[1] == RANK and a.shape[0] >= VOCAB
125
+ add(nm, "BF16", (VOCAB, RANK), a[:VOCAB])
126
+ for l in range(LAYERS):
127
+ p = "layers.%d." % l
128
+ bf(p + "self_attn.k_proj.weight", (KVD, HID))
129
+ bf(p + "self_attn.v_proj.weight", (KVD, HID))
130
+ bf(p + "attention_conv.kernel_projection.weight", (DYN, HID))
131
+ bf(p + "mlp_conv.kernel_projection.weight", (DYN, HID))
132
+ f32(p + "attention_conv.base_kernel", (2, 2, HID))
133
+ f32(p + "mlp_conv.base_kernel", (2, 2, HID))
134
+ f32(p + "input_layernorm.weight", (HID,))
135
+ f32(p + "post_attention_layernorm.weight", (HID,))
136
+ f32(p + "self_attn.q_norm.weight", (HD,))
137
+ f32(p + "self_attn.k_norm.weight", (HD,))
138
+ for nm, N, K, kind in (("self_attn.q_proj.weight", QD, HID, "q8"), ("self_attn.o_proj.weight", HID, QD, "q8"),
139
+ ("mlp.gate_proj.weight", FF, HID, "sf4"), ("mlp.up_proj.weight", FF, HID, "sf4"), ("mlp.down_proj.weight", HID, FF, "sf4")):
140
+ a, dt = get(p + nm)
141
+ assert dt == "BF16" and list(a.shape) == [N, K], (nm, a.shape)
142
+ if kind == "q8":
143
+ q, sc = q8_rows(a)
144
+ add(p + nm + ".q", "I8", (N * K,), q)
145
+ add(p + nm + ".s", "F32", (N,), sc)
146
+ else:
147
+ pk, sb, wo = sf4(a)
148
+ add(p + nm + ".q", "U8", (N * K // 2,), pk)
149
+ add(p + nm + ".s", "U8", (N * K // 16,), sb)
150
+ add(p + nm + ".o", "F32", (1,), np.array([wo], dtype=np.float32))
151
+ print("layer", l, "done", file=sys.stderr)
152
+ js = '{"__metadata__":{"format":"strata-dflash2-q1","variant":"mix"}'
153
+ off = 0
154
+ for name, dtype, shape, raw in items:
155
+ js += ',"%s":{"dtype":"%s","shape":[%s],"data_offsets":[%d,%d]}' % (name, dtype, ",".join(str(s) for s in shape), off, off + len(raw))
156
+ off += len(raw)
157
+ js += "}"
158
+ js += " " * ((-len(js)) % 8)
159
+ with open(dst, "wb") as o:
160
+ o.write(struct.pack("<Q", len(js)))
161
+ o.write(js.encode("ascii"))
162
+ for _, _, _, raw in items:
163
+ o.write(raw)
164
+ print("wrote", dst, 8 + len(js) + off, "bytes")
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main(sys.argv[1], sys.argv[2])