binade 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- binade-0.1.0/LICENSE +202 -0
- binade-0.1.0/PKG-INFO +162 -0
- binade-0.1.0/README.md +124 -0
- binade-0.1.0/binade/__init__.py +3 -0
- binade-0.1.0/binade/baselines.py +58 -0
- binade-0.1.0/binade/bf16.py +61 -0
- binade-0.1.0/binade/classify.py +75 -0
- binade-0.1.0/binade/cli.py +15 -0
- binade-0.1.0/binade/format.py +132 -0
- binade-0.1.0/binade/info.py +39 -0
- binade-0.1.0/binade/lossy.py +68 -0
- binade-0.1.0/binade/mlx/__init__.py +0 -0
- binade-0.1.0/binade/mlx/cublas_plan.py +192 -0
- binade-0.1.0/binade/mlx/cuda_kernels.py +995 -0
- binade-0.1.0/binade/mlx/kernel.py +886 -0
- binade-0.1.0/binade/mlx/loader.py +247 -0
- binade-0.1.0/binade/mlx/moe.py +115 -0
- binade-0.1.0/binade/mlx/r4.py +379 -0
- binade-0.1.0/binade/mlx/rice_kernel.py +98 -0
- binade-0.1.0/binade/mlx/slow_linear.py +172 -0
- binade-0.1.0/binade/pack.py +173 -0
- binade-0.1.0/binade/policies.py +157 -0
- binade-0.1.0/binade/rice.py +182 -0
- binade-0.1.0/binade/scan.py +229 -0
- binade-0.1.0/binade/st.py +226 -0
- binade-0.1.0/binade/tile.py +49 -0
- binade-0.1.0/binade/unpack.py +135 -0
- binade-0.1.0/binade.egg-info/PKG-INFO +162 -0
- binade-0.1.0/binade.egg-info/SOURCES.txt +46 -0
- binade-0.1.0/binade.egg-info/dependency_links.txt +1 -0
- binade-0.1.0/binade.egg-info/entry_points.txt +2 -0
- binade-0.1.0/binade.egg-info/requires.txt +17 -0
- binade-0.1.0/binade.egg-info/top_level.txt +1 -0
- binade-0.1.0/pyproject.toml +55 -0
- binade-0.1.0/setup.cfg +4 -0
- binade-0.1.0/tests/test_bf16.py +61 -0
- binade-0.1.0/tests/test_classify_lossy_baselines.py +110 -0
- binade-0.1.0/tests/test_cuda_gemm.py +63 -0
- binade-0.1.0/tests/test_format.py +99 -0
- binade-0.1.0/tests/test_info.py +34 -0
- binade-0.1.0/tests/test_kernel.py +109 -0
- binade-0.1.0/tests/test_pack.py +83 -0
- binade-0.1.0/tests/test_policies.py +198 -0
- binade-0.1.0/tests/test_r4.py +83 -0
- binade-0.1.0/tests/test_r4_moe.py +373 -0
- binade-0.1.0/tests/test_rice.py +134 -0
- binade-0.1.0/tests/test_runtime.py +90 -0
- binade-0.1.0/tests/test_st.py +54 -0
binade-0.1.0/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.
|
binade-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: binade
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lossless compression of BF16 LLM weights whose outputs stay bit-identical to the original, for MLX on Apple Silicon and NVIDIA GPUs
|
|
5
|
+
Author: Guy Shafir
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/GuyShafir/binade
|
|
8
|
+
Project-URL: Repository, https://github.com/GuyShafir/binade
|
|
9
|
+
Project-URL: Paper, https://github.com/GuyShafir/binade/blob/main/paper/binade.pdf
|
|
10
|
+
Project-URL: Models, https://huggingface.co/Binade
|
|
11
|
+
Keywords: llm,compression,lossless,bf16,mlx,apple-silicon,cuda,inference
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: MacOS
|
|
16
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=2.0
|
|
25
|
+
Requires-Dist: safetensors>=0.4
|
|
26
|
+
Requires-Dist: huggingface-hub>=1.0
|
|
27
|
+
Requires-Dist: mlx==0.32.2
|
|
28
|
+
Requires-Dist: mlx-lm==0.31.3
|
|
29
|
+
Provides-Extra: cuda
|
|
30
|
+
Requires-Dist: mlx[cuda]==0.32.2; extra == "cuda"
|
|
31
|
+
Provides-Extra: eval
|
|
32
|
+
Requires-Dist: pyarrow>=15; extra == "eval"
|
|
33
|
+
Provides-Extra: figures
|
|
34
|
+
Requires-Dist: matplotlib>=3.8; extra == "figures"
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# Binade
|
|
40
|
+
|
|
41
|
+
Bit-exact compression of BF16 LLM weights for Apple Silicon (MLX), and for NVIDIA GPUs through MLX's CUDA backend.
|
|
42
|
+
|
|
43
|
+
A BF16 weight keeps its sign and mantissa as one raw byte. Its 8-bit exponent (the weight's binade) is replaced by its frequency rank in a per-tensor table, stored on disk in Rice codes at about 10.75 bits per weight instead of 16. At load, the ranks become a 4-bit runtime layout that Metal kernels read directly during inference.
|
|
44
|
+
|
|
45
|
+
The outputs are bit-identical to the original model, not merely close. The kernels reproduce the summation order of MLX's own BF16 kernels, so prompt logits and generated tokens match the uncompressed model exactly.
|
|
46
|
+
|
|
47
|
+
## Results
|
|
48
|
+
|
|
49
|
+
Apple M4 Max, 48 GB, MLX 0.32.2. Every number comes from a script in `scripts/`; its output is in `results/`.
|
|
50
|
+
|
|
51
|
+
| | BF16 | Binade | |
|
|
52
|
+
|---|---|---|---|
|
|
53
|
+
| Gemma 4 12B checkpoint | 23.92 GB | 16.10 GB | 10.746 bits per packed weight, bit-exact round trip ([roundtrip_v2](results/gemma-4-12B-it/roundtrip_v2.md)) |
|
|
54
|
+
| Gemma 4 12B greedy decode | 19.15 tok/s | 24.66 tok/s | **1.29x**, identical tokens ([decode_speed](results/gemma-4-12B-it/decode_speed.md)) |
|
|
55
|
+
| Gemma 4 12B exactness | | | prompt logits over the full vocabulary and 256 greedy tokens identical ([generate_check](results/gemma-4-12B-it/generate_check_r4_v2_binade_first.md)) |
|
|
56
|
+
| Gemma 4 26B-A4B checkpoint | 51.61 GB | 35.05 GB | BF16 does not load on a 48 GB Mac ([roundtrip_v2](results/gemma-4-26B-A4B-it/roundtrip_v2.md)) |
|
|
57
|
+
| Gemma 4 26B-A4B decode | n/a | 58.8 tok/s | 40-token prompt in 0.32 s, logits and 64 tokens identical to BF16 ([decode_speed](results/gemma-4-26B-A4B-it/decode_speed.md), [generate_check](results/gemma-4-26B-A4B-it/generate_check_r4_v2_streamed_binade_first.md)) |
|
|
58
|
+
|
|
59
|
+
The 26B exactness check compares against a BF16 reference that reads one layer at a time from disk, since BF16 does not fit in memory.
|
|
60
|
+
|
|
61
|
+
- **Matvec kernel.** Batch-1 matvec on the 12B's shapes runs at 100% of BF16's bandwidth efficiency, 1.33x BF16 per token ([kernel test](results/kernel/gemma-4-12B-it.md)).
|
|
62
|
+
- **Prompt processing (12B matmuls).** 1.30x BF16 at 16 prompt rows, 0.77 to 0.90x at 32 to 128, and 0.95x at 2048 ([prefill_bench](results/gemma-4-12B-it/prefill_bench.md)).
|
|
63
|
+
|
|
64
|
+
## NVIDIA GPUs
|
|
65
|
+
|
|
66
|
+
MLX 0.32.2's CUDA backend. Exactness: logits at all 16,352 WikiText-2 positions per model identical to BF16; for Gemma 4 12B and 26B-A4B on every GPU listed, also with the fused prompt kernels forced onto every prompt length.
|
|
67
|
+
|
|
68
|
+
| GPU | model | BF16 | Binade | first token after 40 tokens |
|
|
69
|
+
|---|---|---|---|---|
|
|
70
|
+
| RTX PRO 6000 (96 GB) | Llama 3.1 8B, Qwen3.5 9B, Gemma 4 12B, 26B-A4B, 31B | runs | identical, 32 of 32 generations too; decode 1.01 to 1.10x BF16 ([summary](results/cuda/summary.md)) | 12B 0.059 s (BF16 0.045), 26B 0.053 s (BF16 0.041) |
|
|
71
|
+
| L4 (24 GB) | Gemma 4 12B | out of memory | 20.0 GB peak, 11.1 tok/s, identical to BF16 streamed from disk ([results/cuda-l4](results/cuda-l4/gemma-4-12B-it)) | 0.257 s (8-bit: 0.148 s) |
|
|
72
|
+
| A100 (40 GB) | Gemma 4 26B-A4B | out of memory | 40.0 GB peak, 46.5 tok/s, identical to BF16 streamed from disk ([results/cuda-a100](results/cuda-a100/gemma-4-26B-A4B-it)) | 0.101 s (8-bit: 0.084 s; Binade is faster from 128 tokens on) |
|
|
73
|
+
|
|
74
|
+
Multi-row products in MLX's CUDA backend go to cuBLAS, which is closed. Its BF16 GEMM order can still be reproduced: each output is a sequence of tensor-core MMA steps along K, split-K partitions follow a fixed rule, and cuBLASLt reports which algorithm and split it chose. The algorithms differ by GPU (one of them, on the A100 and L4, sums K in two slices), so the fused prompt kernels run only for algorithms verified on that GPU (`binade/mlx/cublas_plan.py`, `tests/test_cuda_gemm.py`); anything else rebuilds BF16 weights for cuBLAS, which is exact by construction.
|
|
75
|
+
|
|
76
|
+
## How it works
|
|
77
|
+
|
|
78
|
+
- **No exponent locality.** Neighbouring weights do not share exponents: per-tile palettes gain only 0.011 to 0.027 bits per weight over a shuffled tensor on four models ([comparison](results/comparison.md)). Binade therefore codes frequency ranks from one table per tensor.
|
|
79
|
+
- **Two file formats.** Format 1 uses fixed width per 128-weight tile with escapes (11.27 bits per weight). Format 2, the default, uses Rice codes (10.75 bits per weight).
|
|
80
|
+
- **Runtime layout.** At load a GPU kernel turns either format into R4: every rank in 4 bits, with rare escapes. R4 takes 12.07 bits per weight in memory, and its matvec streams at full bandwidth.
|
|
81
|
+
- **Exactness.** The matvec, the MoE expert gather and the GEMM mirror MLX's own kernels step for step. Where they cannot, the runtime rebuilds the BF16 weight and calls MLX, which is exact by construction.
|
|
82
|
+
|
|
83
|
+
[DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
|
|
84
|
+
|
|
85
|
+
## Install
|
|
86
|
+
|
|
87
|
+
Python 3.11 or newer on Apple Silicon (or Linux with CUDA 12). Exactness depends on MLX's own kernels, so MLX and mlx-lm are pinned (0.32.2 and 0.31.3).
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
pip install binade # Apple Silicon
|
|
91
|
+
pip install "binade[cuda]" # Linux + CUDA 12
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
To run the tests or reproduce the results, install from a clone with the extras (`requirements.lock` has the exact versions the results used):
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
git clone https://github.com/GuyShafir/binade && cd binade
|
|
98
|
+
pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[dev,eval,figures,cuda]"
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Use
|
|
102
|
+
|
|
103
|
+
Load a published Binade model straight from the Hugging Face Hub (the [Binade](https://huggingface.co/Binade) organization), or pack one yourself from the Hugging Face cache or a local directory:
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
hf download google/gemma-4-12B-it
|
|
107
|
+
binade pack google/gemma-4-12B-it --out models/gemma-4-12B-it-binade
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Run it with mlx-lm:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from mlx_lm import generate
|
|
114
|
+
from binade.mlx.r4 import load
|
|
115
|
+
|
|
116
|
+
model, tokenizer, _ = load("Binade/gemma-4-12B-it") # or a local packed directory
|
|
117
|
+
messages = [{"role": "user", "content": "Why is the sky blue?"}]
|
|
118
|
+
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
|
|
119
|
+
print(generate(model, tokenizer, prompt, max_tokens=200))
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`binade unpack <packed-dir or Hub repo id> --out DIR` rebuilds the original BF16 checkpoint, bit for bit.
|
|
123
|
+
|
|
124
|
+
## Verify and reproduce
|
|
125
|
+
|
|
126
|
+
- `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
|
|
127
|
+
- `scripts/generate_check.py`: greedy decoding against the BF16 model (`--reference streamed` for models that do not fit).
|
|
128
|
+
- `scripts/exactness_scale.py`: logits at 16,352 positions and 32 generations against BF16 (resident or streamed), optionally with the fused kernels forced.
|
|
129
|
+
- `scripts/decode_speed.py`, `scripts/matvec_bench.py`, `scripts/prefill_bench.py`, `scripts/prompt_speed.py`, `scripts/cuda_gemm_bench.py`: speed.
|
|
130
|
+
- `scripts/fit_probe.py`: which variants load on a GPU; `scripts/reference_check.py`: MLX against the reference implementation.
|
|
131
|
+
- `scripts/histogram.py`, `scripts/mutual_info.py`, `scripts/iid_model.py`, `scripts/compare.py`, `scripts/exponent_patch.py`: the exponent statistics.
|
|
132
|
+
- `pytest`: unit and kernel tests, including order-sensitive data that exposes any change in summation order.
|
|
133
|
+
|
|
134
|
+
Result files record the commit of the development repository that produced them; that history is not published. Early result files use the project's working name, `xp`.
|
|
135
|
+
|
|
136
|
+
## Limitations
|
|
137
|
+
|
|
138
|
+
- **Tied to MLX's internals.** Exactness relies on MLX 0.32.2's kernels and dispatch rules. A different MLX version or GPU generation can change the summation order, and the tests would catch it. The fused GEMM is enabled only on M3 and M4 GPUs.
|
|
139
|
+
- **Validated models.** Gemma 4 12B, E4B and 26B-A4B, Llama 3.1 8B and Qwen3.5 9B: bit-identical to BF16 at every one of 16,352 WikiText-2 positions per model, and in greedy generation (`results/*/exactness_scale.md`).
|
|
140
|
+
- **E-models.** Gemma 4 E-models keep their per-layer embedding tables in BF16.
|
|
141
|
+
- **Prompt processing.** Prefill at 32 to 128 prompt rows runs at 0.77 to 0.90x BF16. On long prompts, a model without memory headroom for rebuilding weights runs the fused GEMM at 0.75x the speed of MLX's.
|
|
142
|
+
- **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
|
|
143
|
+
- **CUDA.** Decoding runs at 1.01 to 1.10x BF16; prompts take longer (1.3x BF16's time to the first token after 40 tokens on the RTX PRO 6000). The fused prompt kernels cover dense products up to 128 rows and every expert product, on the RTX PRO 6000, L4 and A100; longer dense prompts, and dense prompts on other GPUs, rebuild BF16 weights for cuBLAS.
|
|
144
|
+
|
|
145
|
+
## Related work
|
|
146
|
+
|
|
147
|
+
Binade codes the same exponent redundancy as:
|
|
148
|
+
- DFloat11 (Huffman, arXiv 2504.11651);
|
|
149
|
+
- ZipServ (fixed-width exponent windows fused into GEMM, arXiv 2603.17435);
|
|
150
|
+
- Unweight (per-tensor palettes, Cloudflare);
|
|
151
|
+
- ENEC (frequency ranks, arXiv 2604.03298);
|
|
152
|
+
- NeuZip (arXiv 2410.20650) and ZipNN (arXiv 2411.05239).
|
|
153
|
+
|
|
154
|
+
We found no public implementation of lossless compressed inference on Metal.
|
|
155
|
+
|
|
156
|
+
## Paper
|
|
157
|
+
|
|
158
|
+
[paper/binade.pdf](paper/binade.pdf): the exponent statistics behind the format, the exactness argument, and the evaluation on Apple Silicon and NVIDIA GPUs. The LaTeX source is in `paper/latex`; `paper/latex/make_assets.py` generates its tables and figures from `results/`.
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
Apache-2.0 ([LICENSE](LICENSE)). Model weights keep their own licenses.
|
binade-0.1.0/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Binade
|
|
2
|
+
|
|
3
|
+
Bit-exact compression of BF16 LLM weights for Apple Silicon (MLX), and for NVIDIA GPUs through MLX's CUDA backend.
|
|
4
|
+
|
|
5
|
+
A BF16 weight keeps its sign and mantissa as one raw byte. Its 8-bit exponent (the weight's binade) is replaced by its frequency rank in a per-tensor table, stored on disk in Rice codes at about 10.75 bits per weight instead of 16. At load, the ranks become a 4-bit runtime layout that Metal kernels read directly during inference.
|
|
6
|
+
|
|
7
|
+
The outputs are bit-identical to the original model, not merely close. The kernels reproduce the summation order of MLX's own BF16 kernels, so prompt logits and generated tokens match the uncompressed model exactly.
|
|
8
|
+
|
|
9
|
+
## Results
|
|
10
|
+
|
|
11
|
+
Apple M4 Max, 48 GB, MLX 0.32.2. Every number comes from a script in `scripts/`; its output is in `results/`.
|
|
12
|
+
|
|
13
|
+
| | BF16 | Binade | |
|
|
14
|
+
|---|---|---|---|
|
|
15
|
+
| Gemma 4 12B checkpoint | 23.92 GB | 16.10 GB | 10.746 bits per packed weight, bit-exact round trip ([roundtrip_v2](results/gemma-4-12B-it/roundtrip_v2.md)) |
|
|
16
|
+
| Gemma 4 12B greedy decode | 19.15 tok/s | 24.66 tok/s | **1.29x**, identical tokens ([decode_speed](results/gemma-4-12B-it/decode_speed.md)) |
|
|
17
|
+
| Gemma 4 12B exactness | | | prompt logits over the full vocabulary and 256 greedy tokens identical ([generate_check](results/gemma-4-12B-it/generate_check_r4_v2_binade_first.md)) |
|
|
18
|
+
| Gemma 4 26B-A4B checkpoint | 51.61 GB | 35.05 GB | BF16 does not load on a 48 GB Mac ([roundtrip_v2](results/gemma-4-26B-A4B-it/roundtrip_v2.md)) |
|
|
19
|
+
| Gemma 4 26B-A4B decode | n/a | 58.8 tok/s | 40-token prompt in 0.32 s, logits and 64 tokens identical to BF16 ([decode_speed](results/gemma-4-26B-A4B-it/decode_speed.md), [generate_check](results/gemma-4-26B-A4B-it/generate_check_r4_v2_streamed_binade_first.md)) |
|
|
20
|
+
|
|
21
|
+
The 26B exactness check compares against a BF16 reference that reads one layer at a time from disk, since BF16 does not fit in memory.
|
|
22
|
+
|
|
23
|
+
- **Matvec kernel.** Batch-1 matvec on the 12B's shapes runs at 100% of BF16's bandwidth efficiency, 1.33x BF16 per token ([kernel test](results/kernel/gemma-4-12B-it.md)).
|
|
24
|
+
- **Prompt processing (12B matmuls).** 1.30x BF16 at 16 prompt rows, 0.77 to 0.90x at 32 to 128, and 0.95x at 2048 ([prefill_bench](results/gemma-4-12B-it/prefill_bench.md)).
|
|
25
|
+
|
|
26
|
+
## NVIDIA GPUs
|
|
27
|
+
|
|
28
|
+
MLX 0.32.2's CUDA backend. Exactness: logits at all 16,352 WikiText-2 positions per model identical to BF16; for Gemma 4 12B and 26B-A4B on every GPU listed, also with the fused prompt kernels forced onto every prompt length.
|
|
29
|
+
|
|
30
|
+
| GPU | model | BF16 | Binade | first token after 40 tokens |
|
|
31
|
+
|---|---|---|---|---|
|
|
32
|
+
| RTX PRO 6000 (96 GB) | Llama 3.1 8B, Qwen3.5 9B, Gemma 4 12B, 26B-A4B, 31B | runs | identical, 32 of 32 generations too; decode 1.01 to 1.10x BF16 ([summary](results/cuda/summary.md)) | 12B 0.059 s (BF16 0.045), 26B 0.053 s (BF16 0.041) |
|
|
33
|
+
| L4 (24 GB) | Gemma 4 12B | out of memory | 20.0 GB peak, 11.1 tok/s, identical to BF16 streamed from disk ([results/cuda-l4](results/cuda-l4/gemma-4-12B-it)) | 0.257 s (8-bit: 0.148 s) |
|
|
34
|
+
| A100 (40 GB) | Gemma 4 26B-A4B | out of memory | 40.0 GB peak, 46.5 tok/s, identical to BF16 streamed from disk ([results/cuda-a100](results/cuda-a100/gemma-4-26B-A4B-it)) | 0.101 s (8-bit: 0.084 s; Binade is faster from 128 tokens on) |
|
|
35
|
+
|
|
36
|
+
Multi-row products in MLX's CUDA backend go to cuBLAS, which is closed. Its BF16 GEMM order can still be reproduced: each output is a sequence of tensor-core MMA steps along K, split-K partitions follow a fixed rule, and cuBLASLt reports which algorithm and split it chose. The algorithms differ by GPU (one of them, on the A100 and L4, sums K in two slices), so the fused prompt kernels run only for algorithms verified on that GPU (`binade/mlx/cublas_plan.py`, `tests/test_cuda_gemm.py`); anything else rebuilds BF16 weights for cuBLAS, which is exact by construction.
|
|
37
|
+
|
|
38
|
+
## How it works
|
|
39
|
+
|
|
40
|
+
- **No exponent locality.** Neighbouring weights do not share exponents: per-tile palettes gain only 0.011 to 0.027 bits per weight over a shuffled tensor on four models ([comparison](results/comparison.md)). Binade therefore codes frequency ranks from one table per tensor.
|
|
41
|
+
- **Two file formats.** Format 1 uses fixed width per 128-weight tile with escapes (11.27 bits per weight). Format 2, the default, uses Rice codes (10.75 bits per weight).
|
|
42
|
+
- **Runtime layout.** At load a GPU kernel turns either format into R4: every rank in 4 bits, with rare escapes. R4 takes 12.07 bits per weight in memory, and its matvec streams at full bandwidth.
|
|
43
|
+
- **Exactness.** The matvec, the MoE expert gather and the GEMM mirror MLX's own kernels step for step. Where they cannot, the runtime rebuilds the BF16 weight and calls MLX, which is exact by construction.
|
|
44
|
+
|
|
45
|
+
[DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
Python 3.11 or newer on Apple Silicon (or Linux with CUDA 12). Exactness depends on MLX's own kernels, so MLX and mlx-lm are pinned (0.32.2 and 0.31.3).
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
pip install binade # Apple Silicon
|
|
53
|
+
pip install "binade[cuda]" # Linux + CUDA 12
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
To run the tests or reproduce the results, install from a clone with the extras (`requirements.lock` has the exact versions the results used):
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
git clone https://github.com/GuyShafir/binade && cd binade
|
|
60
|
+
pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[dev,eval,figures,cuda]"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Use
|
|
64
|
+
|
|
65
|
+
Load a published Binade model straight from the Hugging Face Hub (the [Binade](https://huggingface.co/Binade) organization), or pack one yourself from the Hugging Face cache or a local directory:
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
hf download google/gemma-4-12B-it
|
|
69
|
+
binade pack google/gemma-4-12B-it --out models/gemma-4-12B-it-binade
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Run it with mlx-lm:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from mlx_lm import generate
|
|
76
|
+
from binade.mlx.r4 import load
|
|
77
|
+
|
|
78
|
+
model, tokenizer, _ = load("Binade/gemma-4-12B-it") # or a local packed directory
|
|
79
|
+
messages = [{"role": "user", "content": "Why is the sky blue?"}]
|
|
80
|
+
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
|
|
81
|
+
print(generate(model, tokenizer, prompt, max_tokens=200))
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`binade unpack <packed-dir or Hub repo id> --out DIR` rebuilds the original BF16 checkpoint, bit for bit.
|
|
85
|
+
|
|
86
|
+
## Verify and reproduce
|
|
87
|
+
|
|
88
|
+
- `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
|
|
89
|
+
- `scripts/generate_check.py`: greedy decoding against the BF16 model (`--reference streamed` for models that do not fit).
|
|
90
|
+
- `scripts/exactness_scale.py`: logits at 16,352 positions and 32 generations against BF16 (resident or streamed), optionally with the fused kernels forced.
|
|
91
|
+
- `scripts/decode_speed.py`, `scripts/matvec_bench.py`, `scripts/prefill_bench.py`, `scripts/prompt_speed.py`, `scripts/cuda_gemm_bench.py`: speed.
|
|
92
|
+
- `scripts/fit_probe.py`: which variants load on a GPU; `scripts/reference_check.py`: MLX against the reference implementation.
|
|
93
|
+
- `scripts/histogram.py`, `scripts/mutual_info.py`, `scripts/iid_model.py`, `scripts/compare.py`, `scripts/exponent_patch.py`: the exponent statistics.
|
|
94
|
+
- `pytest`: unit and kernel tests, including order-sensitive data that exposes any change in summation order.
|
|
95
|
+
|
|
96
|
+
Result files record the commit of the development repository that produced them; that history is not published. Early result files use the project's working name, `xp`.
|
|
97
|
+
|
|
98
|
+
## Limitations
|
|
99
|
+
|
|
100
|
+
- **Tied to MLX's internals.** Exactness relies on MLX 0.32.2's kernels and dispatch rules. A different MLX version or GPU generation can change the summation order, and the tests would catch it. The fused GEMM is enabled only on M3 and M4 GPUs.
|
|
101
|
+
- **Validated models.** Gemma 4 12B, E4B and 26B-A4B, Llama 3.1 8B and Qwen3.5 9B: bit-identical to BF16 at every one of 16,352 WikiText-2 positions per model, and in greedy generation (`results/*/exactness_scale.md`).
|
|
102
|
+
- **E-models.** Gemma 4 E-models keep their per-layer embedding tables in BF16.
|
|
103
|
+
- **Prompt processing.** Prefill at 32 to 128 prompt rows runs at 0.77 to 0.90x BF16. On long prompts, a model without memory headroom for rebuilding weights runs the fused GEMM at 0.75x the speed of MLX's.
|
|
104
|
+
- **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
|
|
105
|
+
- **CUDA.** Decoding runs at 1.01 to 1.10x BF16; prompts take longer (1.3x BF16's time to the first token after 40 tokens on the RTX PRO 6000). The fused prompt kernels cover dense products up to 128 rows and every expert product, on the RTX PRO 6000, L4 and A100; longer dense prompts, and dense prompts on other GPUs, rebuild BF16 weights for cuBLAS.
|
|
106
|
+
|
|
107
|
+
## Related work
|
|
108
|
+
|
|
109
|
+
Binade codes the same exponent redundancy as:
|
|
110
|
+
- DFloat11 (Huffman, arXiv 2504.11651);
|
|
111
|
+
- ZipServ (fixed-width exponent windows fused into GEMM, arXiv 2603.17435);
|
|
112
|
+
- Unweight (per-tensor palettes, Cloudflare);
|
|
113
|
+
- ENEC (frequency ranks, arXiv 2604.03298);
|
|
114
|
+
- NeuZip (arXiv 2410.20650) and ZipNN (arXiv 2411.05239).
|
|
115
|
+
|
|
116
|
+
We found no public implementation of lossless compressed inference on Metal.
|
|
117
|
+
|
|
118
|
+
## Paper
|
|
119
|
+
|
|
120
|
+
[paper/binade.pdf](paper/binade.pdf): the exponent statistics behind the format, the exactness argument, and the evaluation on Apple Silicon and NVIDIA GPUs. The LaTeX source is in `paper/latex`; `paper/latex/make_assets.py` generates its tables and figures from `results/`.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
Apache-2.0 ([LICENSE](LICENSE)). Model weights keep their own licenses.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Reference exponent codes to compare against (DESIGN.md 4). All return bits per exponent."""
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def entropy(hist: np.ndarray) -> float:
|
|
9
|
+
"""Shannon entropy (bits) of a histogram."""
|
|
10
|
+
p = hist[hist > 0] / hist.sum()
|
|
11
|
+
return float(-(p * np.log2(p)).sum())
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def huffman_lengths(hist: np.ndarray) -> np.ndarray:
|
|
15
|
+
"""Huffman code length per symbol (0 for absent symbols; 1 if only one symbol)."""
|
|
16
|
+
lengths = np.zeros(len(hist), np.int64)
|
|
17
|
+
syms = [int(s) for s in np.flatnonzero(hist)]
|
|
18
|
+
if len(syms) == 1:
|
|
19
|
+
lengths[syms[0]] = 1
|
|
20
|
+
return lengths
|
|
21
|
+
heap = [(int(hist[s]), s, [s]) for s in syms]
|
|
22
|
+
heapq.heapify(heap)
|
|
23
|
+
while len(heap) > 1:
|
|
24
|
+
c1, t1, s1 = heapq.heappop(heap)
|
|
25
|
+
c2, t2, s2 = heapq.heappop(heap)
|
|
26
|
+
for s in s1 + s2:
|
|
27
|
+
lengths[s] += 1
|
|
28
|
+
heapq.heappush(heap, (c1 + c2, min(t1, t2), s1 + s2))
|
|
29
|
+
return lengths
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def huffman_bits(hist: np.ndarray, lengths: np.ndarray | None = None) -> int:
|
|
33
|
+
"""Total bits to code `hist` with a static Huffman code (its own unless `lengths` given)."""
|
|
34
|
+
if lengths is None:
|
|
35
|
+
lengths = huffman_lengths(hist)
|
|
36
|
+
return int((hist.astype(np.int64) * lengths).sum())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def tensor_palette_bits(hist: np.ndarray) -> int:
|
|
40
|
+
"""One palette per tensor, b = ceil(log2(distinct)); palette entries at 8 bits each."""
|
|
41
|
+
d = int((hist > 0).sum())
|
|
42
|
+
b = int(np.ceil(np.log2(d))) if d > 1 else 0
|
|
43
|
+
return int(hist.sum()) * b + 8 * d
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def palette16_segment_bits(in_weights: int, numel: int, segments: int) -> int:
|
|
47
|
+
"""Unweight-class: per-tensor palette of the 16 most frequent exponents, 4-bit index.
|
|
48
|
+
A 64-weight row segment holding any other exponent keeps its 8-bit exponents.
|
|
49
|
+
Charges the 16-byte palette and one flag bit per segment."""
|
|
50
|
+
return 4 * in_weights + 8 * (numel - in_weights) + segments + 16 * 8
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def window7_bits(hist: np.ndarray) -> int:
|
|
54
|
+
"""ZipServ-class: 7 contiguous exponents per tensor at a fixed 3-bit code (code 000 is
|
|
55
|
+
the outlier escape); an outlier is also stored as a full 16-bit BF16 value."""
|
|
56
|
+
covered = max(int(hist[b : b + 7].sum()) for b in range(0, 250))
|
|
57
|
+
n = int(hist.sum())
|
|
58
|
+
return 3 * n + 16 * (n - covered)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""BF16 bit helpers (DESIGN.md 1). Every function accepts numpy or mlx arrays.
|
|
2
|
+
|
|
3
|
+
BF16 layout: bit 15 sign, bits 14..7 exponent, bits 6..0 mantissa.
|
|
4
|
+
`raw` packs sign into bit 7 and mantissa into bits 6..0; it is stored verbatim.
|
|
5
|
+
Only the exponent byte is compressed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _ns(a):
|
|
12
|
+
"""(module, uint8, uint16) matching the array type of `a`."""
|
|
13
|
+
if isinstance(a, np.ndarray):
|
|
14
|
+
return np, np.uint8, np.uint16
|
|
15
|
+
import mlx.core as mx
|
|
16
|
+
|
|
17
|
+
return mx, mx.uint8, mx.uint16
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def exponent(w):
|
|
21
|
+
"""uint16 BF16 bit patterns -> uint8 exponent field."""
|
|
22
|
+
_, u8, _ = _ns(w)
|
|
23
|
+
return ((w >> 7) & 0xFF).astype(u8)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def raw(w):
|
|
27
|
+
"""uint16 BF16 bit patterns -> uint8 sign (bit 7) | mantissa (bits 6..0)."""
|
|
28
|
+
_, u8, _ = _ns(w)
|
|
29
|
+
return (((w >> 8) & 0x80) | (w & 0x7F)).astype(u8)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def split(w):
|
|
33
|
+
return raw(w), exponent(w)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def join(r, e):
|
|
37
|
+
"""Inverse of split: (raw, exp) uint8 -> uint16 BF16 bit patterns."""
|
|
38
|
+
_, _, u16 = _ns(r)
|
|
39
|
+
r = r.astype(u16)
|
|
40
|
+
e = e.astype(u16)
|
|
41
|
+
return ((r & 0x80) << 8) | (e << 7) | (r & 0x7F)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def round_mantissa(w, m):
|
|
45
|
+
"""Keep the top m of 7 mantissa bits, round half to even, exponent field unchanged.
|
|
46
|
+
|
|
47
|
+
A round-up that would carry into the exponent saturates at the largest m-bit
|
|
48
|
+
mantissa instead, so the exponent stream stays lossless (DESIGN.md 11).
|
|
49
|
+
Inf and NaN (exponent 255) pass through untouched.
|
|
50
|
+
"""
|
|
51
|
+
if not 1 <= m <= 7:
|
|
52
|
+
raise ValueError(f"m must be in 1..7, got {m}")
|
|
53
|
+
if m == 7:
|
|
54
|
+
return w
|
|
55
|
+
ns, _, _ = _ns(w)
|
|
56
|
+
s = 7 - m
|
|
57
|
+
mant = w & 0x7F
|
|
58
|
+
q = (mant + ((1 << (s - 1)) - 1) + ((mant >> s) & 1)) >> s
|
|
59
|
+
q = ns.minimum(q, (1 << m) - 1)
|
|
60
|
+
out = (w & 0xFF80) | (q << s)
|
|
61
|
+
return ns.where(((w >> 7) & 0xFF) == 0xFF, w, out)
|