binade 0.1.2__tar.gz → 0.1.4__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.4/PKG-INFO +247 -0
- binade-0.1.4/README.md +206 -0
- {binade-0.1.2 → binade-0.1.4}/binade/__init__.py +1 -1
- {binade-0.1.2 → binade-0.1.4}/binade/classify.py +10 -7
- {binade-0.1.2 → binade-0.1.4}/binade/cli.py +4 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/cuda_kernels.py +213 -28
- binade-0.1.4/binade/mlx/draft.py +134 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/kernel.py +95 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/r4.py +43 -4
- binade-0.1.4/binade/mlx/serve.py +73 -0
- {binade-0.1.2 → binade-0.1.4}/binade/pack.py +117 -46
- {binade-0.1.2 → binade-0.1.4}/binade/st.py +34 -9
- binade-0.1.4/binade/torch/__init__.py +231 -0
- binade-0.1.4/binade/unpack.py +450 -0
- binade-0.1.4/binade.egg-info/PKG-INFO +247 -0
- {binade-0.1.2 → binade-0.1.4}/binade.egg-info/SOURCES.txt +5 -1
- {binade-0.1.2 → binade-0.1.4}/binade.egg-info/requires.txt +4 -0
- {binade-0.1.2 → binade-0.1.4}/pyproject.toml +2 -1
- {binade-0.1.2 → binade-0.1.4}/tests/test_classify_lossy_baselines.py +13 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_cuda_gemm.py +48 -0
- binade-0.1.4/tests/test_draft.py +85 -0
- binade-0.1.4/tests/test_pack.py +273 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_r4_moe.py +63 -4
- {binade-0.1.2 → binade-0.1.4}/tests/test_serve.py +27 -2
- binade-0.1.4/tests/test_torch.py +99 -0
- binade-0.1.2/PKG-INFO +0 -176
- binade-0.1.2/README.md +0 -138
- binade-0.1.2/binade/mlx/serve.py +0 -39
- binade-0.1.2/binade/unpack.py +0 -135
- binade-0.1.2/binade.egg-info/PKG-INFO +0 -176
- binade-0.1.2/tests/test_pack.py +0 -89
- {binade-0.1.2 → binade-0.1.4}/LICENSE +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/baselines.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/bf16.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/format.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/info.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/lossy.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/__init__.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/cublas_plan.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/loader.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/moe.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/rice_kernel.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/mlx/slow_linear.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/policies.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/rice.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/scan.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade/tile.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade.egg-info/dependency_links.txt +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade.egg-info/entry_points.txt +0 -0
- {binade-0.1.2 → binade-0.1.4}/binade.egg-info/top_level.txt +0 -0
- {binade-0.1.2 → binade-0.1.4}/setup.cfg +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_bf16.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_format.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_info.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_kernel.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_ple.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_policies.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_r4.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_rice.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_runtime.py +0 -0
- {binade-0.1.2 → binade-0.1.4}/tests/test_st.py +0 -0
binade-0.1.4/PKG-INFO
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: binade
|
|
3
|
+
Version: 0.1.4
|
|
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: torch
|
|
32
|
+
Requires-Dist: torch>=2.1; extra == "torch"
|
|
33
|
+
Requires-Dist: accelerate>=1.0; extra == "torch"
|
|
34
|
+
Provides-Extra: eval
|
|
35
|
+
Requires-Dist: pyarrow>=15; extra == "eval"
|
|
36
|
+
Provides-Extra: figures
|
|
37
|
+
Requires-Dist: matplotlib>=3.8; extra == "figures"
|
|
38
|
+
Provides-Extra: dev
|
|
39
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
<p align="center"><img src="https://raw.githubusercontent.com/GuyShafir/binade/main/docs/social-preview.png" width="100%" alt="binade: lossless LLM weights, outputs bit-identical. Below the words, a band of exponent ranks from real Gemma 4 12B weights, one square per weight."></p>
|
|
43
|
+
|
|
44
|
+
# Binade
|
|
45
|
+
|
|
46
|
+
Bit-exact compression of BF16 LLM weights that runs compressed: on NVIDIA GPUs (through MLX's CUDA backend) and on Apple Silicon (MLX).
|
|
47
|
+
|
|
48
|
+
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 CUDA and Metal kernels read directly during inference.
|
|
49
|
+
|
|
50
|
+
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.
|
|
51
|
+
|
|
52
|
+
## Results on NVIDIA GPUs
|
|
53
|
+
|
|
54
|
+
RTX PRO 6000 (96 GB), MLX 0.32.2's CUDA backend, greedy decoding at batch 1, median of three fresh processes. Every number comes from a script in `scripts/`; its output is in `results/`.
|
|
55
|
+
|
|
56
|
+
| | BF16 | Binade | |
|
|
57
|
+
|---|---|---|---|
|
|
58
|
+
| Llama 3.1 8B | 89.6 tok/s, 16.2 GB | 101.5 tok/s, 12.6 GB | **1.13x** ([decode_speed](results/cuda/Llama-3.1-8B-Instruct/decode_speed.md)) |
|
|
59
|
+
| Qwen3.5 9B | 82.2 tok/s, 18.4 GB | 97.6 tok/s, 14.4 GB | **1.19x** ([decode_speed](results/cuda/Qwen3.5-9B/decode_speed.md)) |
|
|
60
|
+
| Gemma 4 12B | 55.5 tok/s, 24.1 GB | 63.4 tok/s, 18.8 GB | **1.14x** ([decode_speed](results/cuda/gemma-4-12B-it/decode_speed.md)) |
|
|
61
|
+
| Gemma 4 31B | 22.9 tok/s, 62.1 GB | 27.4 tok/s, 47.5 GB | **1.20x** ([decode_speed](results/cuda/gemma-4-31B-it/decode_speed.md)) |
|
|
62
|
+
| Gemma 4 26B-A4B (MoE) | 132.3 tok/s, 51.9 GB | 133.8 tok/s, 39.1 GB | **1.01x** ([decode_speed](results/cuda/gemma-4-26B-A4B-it/decode_speed.md)) |
|
|
63
|
+
|
|
64
|
+
Exactness: logits at all 16,352 WikiText-2 positions per model identical to BF16, and 32 of 32 greedy generations ([summary](results/cuda/summary.md)); for Gemma 4 12B and 26B-A4B on every GPU listed below, also with the fused prompt kernels forced onto every prompt length.
|
|
65
|
+
|
|
66
|
+
**Against the other lossless runtime.** Llama 3.1 8B on the same GPU and prompt: DFloat11 decodes 25.8 tok/s in 12.0 GB, Binade 101.5 tok/s in 12.6 GB, 3.9 times as fast at batch 1. Each is bit-identical to its own framework's BF16: DFloat11 runs at 0.38x PyTorch's (68.3 tok/s), Binade at 1.13x MLX's (89.6 tok/s). DFloat11 rebuilds BF16 weights before each forward pass, a cost it amortizes over larger batches; Binade computes from the compressed layout. Batched serving is not in this comparison ([pytorch](results/cuda/pytorch.md)).
|
|
67
|
+
|
|
68
|
+
Where BF16 does not fit:
|
|
69
|
+
|
|
70
|
+
| GPU | model | BF16 | Binade | first token after 40 tokens |
|
|
71
|
+
|---|---|---|---|---|
|
|
72
|
+
| 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) |
|
|
73
|
+
| 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) |
|
|
74
|
+
|
|
75
|
+
On the RTX PRO 6000 the first token after a 40-token prompt takes 0.059 s for the 12B (BF16 0.045) and 0.053 s for the 26B (BF16 0.041).
|
|
76
|
+
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
## A checkpoint too large to run here: Amazon Ergo, 1.1 trillion parameters
|
|
80
|
+
|
|
81
|
+
[Amazon-FMR/Ergo-bf16](https://huggingface.co/Amazon-FMR/Ergo-bf16) (a mixture of experts, 256 experts per layer, 65 weight files) is 2,215.7 GB in BF16. Packed it is **1,515.8 GB (68.4%)**: 700 GB less to download and keep, at 10.92 bits per weight. `binade unpack` writes the 65 files back byte for byte, each with the SHA-256 Amazon's repository lists for it, so whatever serves the original serves the restored directory.
|
|
82
|
+
|
|
83
|
+
| check | result |
|
|
84
|
+
|---|---|
|
|
85
|
+
| each of the 65 shards decoded again right after packing (numpy decoder) and hashed | 65 / 65 equal the SHA-256 the Hub lists |
|
|
86
|
+
| the finished pack decoded on 4 x T4, 8 processes (`binade unpack --check`) | 65 / 65; 2,215.7 GB in 31.0 min (1.19 GB/s) |
|
|
87
|
+
| 8 shards restored to local SSD on 4 x T4, then hashed with `sha256sum` | 8 / 8 equal the Hub's; 279.6 GB in 342 s (817 MB/s) |
|
|
88
|
+
|
|
89
|
+
Here the pack is a storage format: the runtime above runs on one GPU and does not serve a model this size. The pack was made without ever holding the checkpoint: `scripts/stream_pack.py` downloads, packs, checks and deletes one shard at a time (4.0 hours on one 112-vCPU Spot VM, 44 shards in flight). The first expert layer codes worst (12.17 and 12.48 bits per weight for its two expert stacks); layers 21 to 50 code at 10.71 to 10.82, the layers before and after them in between. Per file and per tensor kind: [results/Ergo-bf16/pack.md](results/Ergo-bf16/pack.md).
|
|
90
|
+
|
|
91
|
+
## Results on Apple Silicon
|
|
92
|
+
|
|
93
|
+
Apple M4 Max, 48 GB, MLX 0.32.2.
|
|
94
|
+
|
|
95
|
+
| | BF16 | Binade | |
|
|
96
|
+
|---|---|---|---|
|
|
97
|
+
| 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)) |
|
|
98
|
+
| 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)) |
|
|
99
|
+
| 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)) |
|
|
100
|
+
| Gemma 4 12B decode with its self-draft | 18.74 tok/s | 32.19 tok/s | **1.72x**: the pack verifies a 4-bit draft of itself, 3 tokens per step; 25.0 GB resident; tokens identical to BF16 run with the same draft ([self_draft](results/gemma-4-12B-it/self_draft.md)) |
|
|
101
|
+
| 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)) |
|
|
102
|
+
| Gemma 4 E4B checkpoint | 15.99 GB | 10.70 GB | every tensor packed: the 2.8B-weight per-layer embedding table and the vision and audio towers too; Google's 4-bit QAT checkpoint (w4a16, that table left in 16-bit) is 11.51 GB ([roundtrip_v2](results/gemma-4-E4B-it/roundtrip_v2.md)) |
|
|
103
|
+
| Gemma 4 E4B resident after load | 14.93 GB | 10.79 GB | the per-layer table stays in its Rice coding in memory; logits at all 16,352 positions and 32 of 32 generations identical ([fit_probe](results/gemma-4-E4B-it/fit_probe.md), [exactness_scale](results/gemma-4-E4B-it/exactness_scale.md)) |
|
|
104
|
+
| Gemma 4 E2B checkpoint | 10.25 GB | 6.84 GB | 6.59 GB resident, decode 1.18x, identical at 16,352 positions and 32 of 32 generations ([roundtrip_v2](results/gemma-4-E2B-it/roundtrip_v2.md), [exactness_scale](results/gemma-4-E2B-it/exactness_scale.md), [decode_speed](results/gemma-4-E2B-it/decode_speed.md)) |
|
|
105
|
+
| Llama 3.1 8B decode with its self-draft | 30.4 tok/s | 59.6 tok/s | **1.96x**, 17.3 GB resident (BF16 with the same draft: 54.0 tok/s in 20.8 GB), identical tokens in every mode ([self_draft](results/Llama-3.1-8B-Instruct/self_draft.md)) |
|
|
106
|
+
| Llama 3.2 3B decode with its self-draft | 67.2 tok/s | 118.0 tok/s | **1.76x**, 7.2 GB resident, identical tokens in every mode ([self_draft](results/Llama-3.2-3B-Instruct/self_draft.md)) |
|
|
107
|
+
| Qwen3.5 4B checkpoint | 9.32 GB | 6.27 GB | 6.35 GB resident, decode 1.27x, identical at 16,352 positions and 32 of 32 generations ([roundtrip_v2](results/Qwen3.5-4B/roundtrip_v2.md), [exactness_scale](results/Qwen3.5-4B/exactness_scale.md), [decode_speed](results/Qwen3.5-4B/decode_speed.md)) |
|
|
108
|
+
| 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)) |
|
|
109
|
+
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
- **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)).
|
|
113
|
+
- **Distance to the floor.** The file is 0.21 to 0.30 bits per weight (2 to 3%) above the entropy of the whole BF16 pattern on four models, and a first-order context model of the exponents could save at most 0.004 bits more ([entropy_floor](results/entropy_floor.md)).
|
|
114
|
+
- **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)).
|
|
115
|
+
|
|
116
|
+
## How it works
|
|
117
|
+
|
|
118
|
+
- **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.
|
|
119
|
+
- **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).
|
|
120
|
+
- **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. A table that only ever feeds lookups (Gemma 4 E-models' per-layer embedding table) stays in its Rice coding in memory, and the Rice kernel decodes the rows each lookup asks for.
|
|
121
|
+
- **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.
|
|
122
|
+
|
|
123
|
+
[DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
|
|
124
|
+
|
|
125
|
+
## Install
|
|
126
|
+
|
|
127
|
+
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).
|
|
128
|
+
|
|
129
|
+
```
|
|
130
|
+
pip install binade # Apple Silicon
|
|
131
|
+
pip install "binade[cuda]" # Linux + CUDA 12
|
|
132
|
+
pip install "binade[torch]" # adds PyTorch, for binade.torch.load
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
To run the tests or reproduce the results, install from a clone with the extras (`requirements.lock` has the exact versions the results used):
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
git clone https://github.com/GuyShafir/binade && cd binade
|
|
139
|
+
pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[dev,eval,figures,cuda]"
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Use
|
|
143
|
+
|
|
144
|
+
Load a published Binade model straight from the Hugging Face Hub: the [Binade](https://huggingface.co/Binade) organization has Gemma 4 E2B, E4B, 12B, 26B-A4B and 31B, Qwen3.5 4B and 9B, and Llama 3.1 8B and 3.2 3B Instruct. Or pack one yourself from the Hugging Face cache or a local directory:
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
hf download google/gemma-4-12B-it
|
|
148
|
+
binade pack google/gemma-4-12B-it --out models/gemma-4-12B-it-binade
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Run it with mlx-lm:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from mlx_lm import generate
|
|
155
|
+
from binade.mlx.r4 import load
|
|
156
|
+
|
|
157
|
+
model, tokenizer, _ = load("Binade/gemma-4-12B-it") # or a local packed directory
|
|
158
|
+
messages = [{"role": "user", "content": "Why is the sky blue?"}]
|
|
159
|
+
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
|
|
160
|
+
print(generate(model, tokenizer, prompt, max_tokens=200))
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`binade unpack <packed-dir or Hub repo id> --out DIR` writes the original checkpoint back. A pack holds each source file's header and SHA-256, so the weight files come back byte for byte, with the `sha256sum` of the files the publisher uploaded, and unpack refuses a file whose hash differs (`--check` verifies a pack that way without writing it; packs made before 0.1.4 hold no source header and come back tensor for tensor). `--jobs N` decodes N files at a time, by default one process per NVIDIA GPU; `--cpu` uses the numpy decoder, one process per core; `--stream` fetches a Hub pack one shard at a time and deletes each shard once restored, so the disk holds one copy. A rerun goes on where the last one stopped: restored files are left alone, and a `--check` continues from its `--report` file.
|
|
164
|
+
|
|
165
|
+
### In PyTorch: the pack as the original weights
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from binade.torch import load # pip install "binade[torch]"
|
|
169
|
+
|
|
170
|
+
model, tokenizer = load("Binade/Llama-3.1-8B-Instruct", device="cuda") # the stock transformers model, in BF16
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The pack is decoded at load into the tensors the source checkpoint held, bit for bit, and given to the checkpoint's own transformers class. Everything computed afterwards is PyTorch's own arithmetic on the original weights, so the outputs are the original model's in PyTorch. This saves the download and the disk (a third of BF16), not GPU memory: the loaded model is BF16. Computing from the compressed layout, which is what saves memory, is the MLX runtime above; why that runtime is not in PyTorch yet is measured in [results/cuda/torch_order.md](results/cuda/torch_order.md). `binade.torch.state_dict(path)` gives the tensors without transformers. Checked against `from_pretrained` on the source checkpoint ([torch_load](results/torch_load.md)): every tensor identical and the same greedy generation on Llama 3.2 3B, Llama 3.1 8B, Gemma 4 E2B and Qwen3.5 4B.
|
|
174
|
+
|
|
175
|
+
A model that needs several GPUs loads the way `from_pretrained` loads it: `load("Binade/Llama-3.1-8B-Instruct", device_map="auto")`, with `max_memory` if wanted. The map is computed by transformers' own code, each tensor is decoded onto the device its module was given, and the model is dispatched as `from_pretrained` dispatches it. On two L4s, for four `device_map` / `max_memory` settings: the same map, every one of 291 parameters on the same device with the same bits, and the same greedy generation as `from_pretrained` ([torch_multi_gpu](results/cuda-l4x2/Llama-3.1-8B-Instruct/torch_multi_gpu.md)). The loader also ends as `from_pretrained` ends: the checkpoint's generation config, and the Hub kernels transformers 5.25 turns on by default.
|
|
176
|
+
|
|
177
|
+
Or serve it over mlx-lm's OpenAI-compatible HTTP API, for any chat client:
|
|
178
|
+
|
|
179
|
+
```
|
|
180
|
+
binade serve --model Binade/gemma-4-12B-it --port 8080
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
`binade serve` takes every `mlx_lm.server` option; a stock (unpacked) model name loads as mlx-lm would, so one server can switch between the two.
|
|
184
|
+
|
|
185
|
+
### Faster on a Mac: the pack verifies a draft of itself
|
|
186
|
+
|
|
187
|
+
Speculative decoding needs a fast draft model with the same tokenizer. The pack supplies one from its own weights, quantized to 4-bit at load, so nothing else is downloaded; the exact model then checks the draft's tokens a few at a time in one pass over its weights. Greedy output is the exact model's output; the draft only sets the pace.
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from binade.mlx.draft import load
|
|
191
|
+
from mlx_lm import generate
|
|
192
|
+
|
|
193
|
+
model, draft, tokenizer = load("Binade/gemma-4-12B-it")
|
|
194
|
+
print(generate(model, tokenizer, prompt, max_tokens=200, draft_model=draft, num_draft_tokens=4))
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
```
|
|
198
|
+
binade serve --model Binade/gemma-4-12B-it --draft-model self --num-draft-tokens 4
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Up to four draft tokens keep every verify pass on the wide kernel (`results/*/self_draft.md`). Resident memory grows by about 4.5 bits per weight for the draft, still below BF16's 16. mlx-lm's speculative loop needs a trimmable cache, so models with linear-attention layers (Qwen3.5's `ArraysCache`) decode without a draft; MoE experts are not drafted yet.
|
|
202
|
+
|
|
203
|
+
## Verify and reproduce
|
|
204
|
+
|
|
205
|
+
- `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
|
|
206
|
+
- `scripts/generate_check.py`: greedy decoding against the BF16 model (`--reference streamed` for models that do not fit).
|
|
207
|
+
- `scripts/exactness_scale.py`: logits at 16,352 positions and 32 generations against BF16 (resident or streamed), optionally with the fused kernels forced.
|
|
208
|
+
- `scripts/decode_speed.py`, `scripts/torch_bench.py` (PyTorch BF16 and DFloat11 on the same prompt), `scripts/self_draft_bench.py`, `scripts/matvec_bench.py`, `scripts/prefill_bench.py`, `scripts/prompt_speed.py`, `scripts/cuda_gemm_bench.py`: speed.
|
|
209
|
+
- `scripts/cuda_exact_finite.py`: the CUDA runtime against MLX's BF16 product on data where every output shows the order of the sum; `scripts/torch_order_*.py`, `scripts/linear_chain_time.py`: which order PyTorch's BF16 linear layer sums in and how fast ([results/cuda/torch_order.md](results/cuda/torch_order.md)).
|
|
210
|
+
- `scripts/torch_load_bench.py`: `binade.torch.load` against `from_pretrained` on the source checkpoint (tensors, generation, load time).
|
|
211
|
+
- `scripts/torch_multi_gpu.py`: `binade.torch.load(device_map=...)` against `from_pretrained(device_map=...)` on several GPUs (the map, every parameter's device and bits, generation).
|
|
212
|
+
- `scripts/stream_pack.py`: pack a Hub checkpoint too large to hold twice, one shard at a time, each decoded again and compared with the SHA-256 the Hub lists for the source file; `scripts/restore_check.py`: restore shards on this machine's GPUs and compare `sha256sum` with the Hub's; `scripts/storage_summary.py`: the results page of such a pack from its own records.
|
|
213
|
+
- `scripts/fit_probe.py`: which variants load on a GPU; `scripts/reference_check.py`: MLX against the reference implementation.
|
|
214
|
+
- `scripts/histogram.py`, `scripts/mutual_info.py`, `scripts/iid_model.py`, `scripts/entropy_floor.py`, `scripts/compare.py`, `scripts/exponent_patch.py`: the exponent statistics and how far the file sits from the entropy floor.
|
|
215
|
+
- `pytest`: unit and kernel tests, including order-sensitive data that exposes any change in summation order.
|
|
216
|
+
|
|
217
|
+
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`.
|
|
218
|
+
|
|
219
|
+
## Limitations
|
|
220
|
+
|
|
221
|
+
- **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.
|
|
222
|
+
- **Validated models.** Gemma 4 12B, E2B, E4B and 26B-A4B, Llama 3.1 8B, Llama 3.2 3B, Qwen3.5 4B and 9B: bit-identical to BF16 at every one of 16,352 WikiText-2 positions per model, and in greedy generation (`results/*/exactness_scale.md`). Gemma 4 31B the same on NVIDIA (`results/cuda/gemma-4-31B-it/exactness_scale.md`).
|
|
223
|
+
- **Vision and audio.** Their weights are packed in the file (and restored by `binade unpack`), but the runtime loads the text model through mlx-lm, so it serves text.
|
|
224
|
+
- **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.
|
|
225
|
+
- **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
|
|
226
|
+
- **Speculative decoding and ties.** With a draft, the exact model checks several tokens in one multi-row pass, and MLX sums a multi-row product in a different order than a single-row one. Both are exact BF16 arithmetic, but a near-tie between two tokens can resolve differently, so speculative greedy output can differ from sequential greedy output at a few positions. The pack behaves exactly as BF16 does in both modes: `results/*/self_draft.md` compares the pack against BF16 with the same draft, token for token, and reports speculative against sequential separately.
|
|
227
|
+
- **CUDA.** Decoding runs at 1.01 to 1.20x BF16 (the MoE model, bound by the CPU, at 1.01x); 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. The runtime is MLX's CUDA backend, not PyTorch: PyTorch's BF16 linear layer sums in a different order ([pytorch](results/cuda/pytorch.md)), so a PyTorch runtime needs its own exact path.
|
|
228
|
+
- **CUDA: no speculative decoding yet.** MLX's CUDA backend pays a setup cost on a multi-row pass each time the cache length is new, so the self-draft loses to sequential decoding there (0.76x BF16 in fresh processes, [self_draft](results/cuda/Llama-3.1-8B-Instruct/self_draft.md)); it is a Mac feature for now. Greedy decoding on that backend is also not reproducible run to run, for BF16 as for the pack, so exactness there is checked on logits for the same inputs (`scripts/exactness_scale.py`).
|
|
229
|
+
|
|
230
|
+
## Related work
|
|
231
|
+
|
|
232
|
+
Binade codes the same exponent redundancy as:
|
|
233
|
+
- DFloat11 (Huffman, arXiv 2504.11651; measured side by side in [results/cuda/pytorch.md](results/cuda/pytorch.md));
|
|
234
|
+
- ZipServ (fixed-width exponent windows fused into GEMM, arXiv 2603.17435);
|
|
235
|
+
- Unweight (per-tensor palettes, Cloudflare);
|
|
236
|
+
- ENEC (frequency ranks, arXiv 2604.03298);
|
|
237
|
+
- NeuZip (arXiv 2410.20650) and ZipNN (arXiv 2411.05239).
|
|
238
|
+
|
|
239
|
+
We found no public implementation of lossless compressed inference on Metal.
|
|
240
|
+
|
|
241
|
+
## Paper
|
|
242
|
+
|
|
243
|
+
[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/`.
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
Apache-2.0 ([LICENSE](LICENSE)). Model weights keep their own licenses.
|
binade-0.1.4/README.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
<p align="center"><img src="https://raw.githubusercontent.com/GuyShafir/binade/main/docs/social-preview.png" width="100%" alt="binade: lossless LLM weights, outputs bit-identical. Below the words, a band of exponent ranks from real Gemma 4 12B weights, one square per weight."></p>
|
|
2
|
+
|
|
3
|
+
# Binade
|
|
4
|
+
|
|
5
|
+
Bit-exact compression of BF16 LLM weights that runs compressed: on NVIDIA GPUs (through MLX's CUDA backend) and on Apple Silicon (MLX).
|
|
6
|
+
|
|
7
|
+
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 CUDA and Metal kernels read directly during inference.
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
|
|
11
|
+
## Results on NVIDIA GPUs
|
|
12
|
+
|
|
13
|
+
RTX PRO 6000 (96 GB), MLX 0.32.2's CUDA backend, greedy decoding at batch 1, median of three fresh processes. Every number comes from a script in `scripts/`; its output is in `results/`.
|
|
14
|
+
|
|
15
|
+
| | BF16 | Binade | |
|
|
16
|
+
|---|---|---|---|
|
|
17
|
+
| Llama 3.1 8B | 89.6 tok/s, 16.2 GB | 101.5 tok/s, 12.6 GB | **1.13x** ([decode_speed](results/cuda/Llama-3.1-8B-Instruct/decode_speed.md)) |
|
|
18
|
+
| Qwen3.5 9B | 82.2 tok/s, 18.4 GB | 97.6 tok/s, 14.4 GB | **1.19x** ([decode_speed](results/cuda/Qwen3.5-9B/decode_speed.md)) |
|
|
19
|
+
| Gemma 4 12B | 55.5 tok/s, 24.1 GB | 63.4 tok/s, 18.8 GB | **1.14x** ([decode_speed](results/cuda/gemma-4-12B-it/decode_speed.md)) |
|
|
20
|
+
| Gemma 4 31B | 22.9 tok/s, 62.1 GB | 27.4 tok/s, 47.5 GB | **1.20x** ([decode_speed](results/cuda/gemma-4-31B-it/decode_speed.md)) |
|
|
21
|
+
| Gemma 4 26B-A4B (MoE) | 132.3 tok/s, 51.9 GB | 133.8 tok/s, 39.1 GB | **1.01x** ([decode_speed](results/cuda/gemma-4-26B-A4B-it/decode_speed.md)) |
|
|
22
|
+
|
|
23
|
+
Exactness: logits at all 16,352 WikiText-2 positions per model identical to BF16, and 32 of 32 greedy generations ([summary](results/cuda/summary.md)); for Gemma 4 12B and 26B-A4B on every GPU listed below, also with the fused prompt kernels forced onto every prompt length.
|
|
24
|
+
|
|
25
|
+
**Against the other lossless runtime.** Llama 3.1 8B on the same GPU and prompt: DFloat11 decodes 25.8 tok/s in 12.0 GB, Binade 101.5 tok/s in 12.6 GB, 3.9 times as fast at batch 1. Each is bit-identical to its own framework's BF16: DFloat11 runs at 0.38x PyTorch's (68.3 tok/s), Binade at 1.13x MLX's (89.6 tok/s). DFloat11 rebuilds BF16 weights before each forward pass, a cost it amortizes over larger batches; Binade computes from the compressed layout. Batched serving is not in this comparison ([pytorch](results/cuda/pytorch.md)).
|
|
26
|
+
|
|
27
|
+
Where BF16 does not fit:
|
|
28
|
+
|
|
29
|
+
| GPU | model | BF16 | Binade | first token after 40 tokens |
|
|
30
|
+
|---|---|---|---|---|
|
|
31
|
+
| 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) |
|
|
32
|
+
| 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) |
|
|
33
|
+
|
|
34
|
+
On the RTX PRO 6000 the first token after a 40-token prompt takes 0.059 s for the 12B (BF16 0.045) and 0.053 s for the 26B (BF16 0.041).
|
|
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
|
+
## A checkpoint too large to run here: Amazon Ergo, 1.1 trillion parameters
|
|
39
|
+
|
|
40
|
+
[Amazon-FMR/Ergo-bf16](https://huggingface.co/Amazon-FMR/Ergo-bf16) (a mixture of experts, 256 experts per layer, 65 weight files) is 2,215.7 GB in BF16. Packed it is **1,515.8 GB (68.4%)**: 700 GB less to download and keep, at 10.92 bits per weight. `binade unpack` writes the 65 files back byte for byte, each with the SHA-256 Amazon's repository lists for it, so whatever serves the original serves the restored directory.
|
|
41
|
+
|
|
42
|
+
| check | result |
|
|
43
|
+
|---|---|
|
|
44
|
+
| each of the 65 shards decoded again right after packing (numpy decoder) and hashed | 65 / 65 equal the SHA-256 the Hub lists |
|
|
45
|
+
| the finished pack decoded on 4 x T4, 8 processes (`binade unpack --check`) | 65 / 65; 2,215.7 GB in 31.0 min (1.19 GB/s) |
|
|
46
|
+
| 8 shards restored to local SSD on 4 x T4, then hashed with `sha256sum` | 8 / 8 equal the Hub's; 279.6 GB in 342 s (817 MB/s) |
|
|
47
|
+
|
|
48
|
+
Here the pack is a storage format: the runtime above runs on one GPU and does not serve a model this size. The pack was made without ever holding the checkpoint: `scripts/stream_pack.py` downloads, packs, checks and deletes one shard at a time (4.0 hours on one 112-vCPU Spot VM, 44 shards in flight). The first expert layer codes worst (12.17 and 12.48 bits per weight for its two expert stacks); layers 21 to 50 code at 10.71 to 10.82, the layers before and after them in between. Per file and per tensor kind: [results/Ergo-bf16/pack.md](results/Ergo-bf16/pack.md).
|
|
49
|
+
|
|
50
|
+
## Results on Apple Silicon
|
|
51
|
+
|
|
52
|
+
Apple M4 Max, 48 GB, MLX 0.32.2.
|
|
53
|
+
|
|
54
|
+
| | BF16 | Binade | |
|
|
55
|
+
|---|---|---|---|
|
|
56
|
+
| 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)) |
|
|
57
|
+
| 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)) |
|
|
58
|
+
| 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)) |
|
|
59
|
+
| Gemma 4 12B decode with its self-draft | 18.74 tok/s | 32.19 tok/s | **1.72x**: the pack verifies a 4-bit draft of itself, 3 tokens per step; 25.0 GB resident; tokens identical to BF16 run with the same draft ([self_draft](results/gemma-4-12B-it/self_draft.md)) |
|
|
60
|
+
| 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)) |
|
|
61
|
+
| Gemma 4 E4B checkpoint | 15.99 GB | 10.70 GB | every tensor packed: the 2.8B-weight per-layer embedding table and the vision and audio towers too; Google's 4-bit QAT checkpoint (w4a16, that table left in 16-bit) is 11.51 GB ([roundtrip_v2](results/gemma-4-E4B-it/roundtrip_v2.md)) |
|
|
62
|
+
| Gemma 4 E4B resident after load | 14.93 GB | 10.79 GB | the per-layer table stays in its Rice coding in memory; logits at all 16,352 positions and 32 of 32 generations identical ([fit_probe](results/gemma-4-E4B-it/fit_probe.md), [exactness_scale](results/gemma-4-E4B-it/exactness_scale.md)) |
|
|
63
|
+
| Gemma 4 E2B checkpoint | 10.25 GB | 6.84 GB | 6.59 GB resident, decode 1.18x, identical at 16,352 positions and 32 of 32 generations ([roundtrip_v2](results/gemma-4-E2B-it/roundtrip_v2.md), [exactness_scale](results/gemma-4-E2B-it/exactness_scale.md), [decode_speed](results/gemma-4-E2B-it/decode_speed.md)) |
|
|
64
|
+
| Llama 3.1 8B decode with its self-draft | 30.4 tok/s | 59.6 tok/s | **1.96x**, 17.3 GB resident (BF16 with the same draft: 54.0 tok/s in 20.8 GB), identical tokens in every mode ([self_draft](results/Llama-3.1-8B-Instruct/self_draft.md)) |
|
|
65
|
+
| Llama 3.2 3B decode with its self-draft | 67.2 tok/s | 118.0 tok/s | **1.76x**, 7.2 GB resident, identical tokens in every mode ([self_draft](results/Llama-3.2-3B-Instruct/self_draft.md)) |
|
|
66
|
+
| Qwen3.5 4B checkpoint | 9.32 GB | 6.27 GB | 6.35 GB resident, decode 1.27x, identical at 16,352 positions and 32 of 32 generations ([roundtrip_v2](results/Qwen3.5-4B/roundtrip_v2.md), [exactness_scale](results/Qwen3.5-4B/exactness_scale.md), [decode_speed](results/Qwen3.5-4B/decode_speed.md)) |
|
|
67
|
+
| 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)) |
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
- **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)).
|
|
72
|
+
- **Distance to the floor.** The file is 0.21 to 0.30 bits per weight (2 to 3%) above the entropy of the whole BF16 pattern on four models, and a first-order context model of the exponents could save at most 0.004 bits more ([entropy_floor](results/entropy_floor.md)).
|
|
73
|
+
- **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)).
|
|
74
|
+
|
|
75
|
+
## How it works
|
|
76
|
+
|
|
77
|
+
- **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.
|
|
78
|
+
- **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).
|
|
79
|
+
- **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. A table that only ever feeds lookups (Gemma 4 E-models' per-layer embedding table) stays in its Rice coding in memory, and the Rice kernel decodes the rows each lookup asks for.
|
|
80
|
+
- **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.
|
|
81
|
+
|
|
82
|
+
[DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
|
|
83
|
+
|
|
84
|
+
## Install
|
|
85
|
+
|
|
86
|
+
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).
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
pip install binade # Apple Silicon
|
|
90
|
+
pip install "binade[cuda]" # Linux + CUDA 12
|
|
91
|
+
pip install "binade[torch]" # adds PyTorch, for binade.torch.load
|
|
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 has Gemma 4 E2B, E4B, 12B, 26B-A4B and 31B, Qwen3.5 4B and 9B, and Llama 3.1 8B and 3.2 3B Instruct. 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` writes the original checkpoint back. A pack holds each source file's header and SHA-256, so the weight files come back byte for byte, with the `sha256sum` of the files the publisher uploaded, and unpack refuses a file whose hash differs (`--check` verifies a pack that way without writing it; packs made before 0.1.4 hold no source header and come back tensor for tensor). `--jobs N` decodes N files at a time, by default one process per NVIDIA GPU; `--cpu` uses the numpy decoder, one process per core; `--stream` fetches a Hub pack one shard at a time and deletes each shard once restored, so the disk holds one copy. A rerun goes on where the last one stopped: restored files are left alone, and a `--check` continues from its `--report` file.
|
|
123
|
+
|
|
124
|
+
### In PyTorch: the pack as the original weights
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from binade.torch import load # pip install "binade[torch]"
|
|
128
|
+
|
|
129
|
+
model, tokenizer = load("Binade/Llama-3.1-8B-Instruct", device="cuda") # the stock transformers model, in BF16
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The pack is decoded at load into the tensors the source checkpoint held, bit for bit, and given to the checkpoint's own transformers class. Everything computed afterwards is PyTorch's own arithmetic on the original weights, so the outputs are the original model's in PyTorch. This saves the download and the disk (a third of BF16), not GPU memory: the loaded model is BF16. Computing from the compressed layout, which is what saves memory, is the MLX runtime above; why that runtime is not in PyTorch yet is measured in [results/cuda/torch_order.md](results/cuda/torch_order.md). `binade.torch.state_dict(path)` gives the tensors without transformers. Checked against `from_pretrained` on the source checkpoint ([torch_load](results/torch_load.md)): every tensor identical and the same greedy generation on Llama 3.2 3B, Llama 3.1 8B, Gemma 4 E2B and Qwen3.5 4B.
|
|
133
|
+
|
|
134
|
+
A model that needs several GPUs loads the way `from_pretrained` loads it: `load("Binade/Llama-3.1-8B-Instruct", device_map="auto")`, with `max_memory` if wanted. The map is computed by transformers' own code, each tensor is decoded onto the device its module was given, and the model is dispatched as `from_pretrained` dispatches it. On two L4s, for four `device_map` / `max_memory` settings: the same map, every one of 291 parameters on the same device with the same bits, and the same greedy generation as `from_pretrained` ([torch_multi_gpu](results/cuda-l4x2/Llama-3.1-8B-Instruct/torch_multi_gpu.md)). The loader also ends as `from_pretrained` ends: the checkpoint's generation config, and the Hub kernels transformers 5.25 turns on by default.
|
|
135
|
+
|
|
136
|
+
Or serve it over mlx-lm's OpenAI-compatible HTTP API, for any chat client:
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
binade serve --model Binade/gemma-4-12B-it --port 8080
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`binade serve` takes every `mlx_lm.server` option; a stock (unpacked) model name loads as mlx-lm would, so one server can switch between the two.
|
|
143
|
+
|
|
144
|
+
### Faster on a Mac: the pack verifies a draft of itself
|
|
145
|
+
|
|
146
|
+
Speculative decoding needs a fast draft model with the same tokenizer. The pack supplies one from its own weights, quantized to 4-bit at load, so nothing else is downloaded; the exact model then checks the draft's tokens a few at a time in one pass over its weights. Greedy output is the exact model's output; the draft only sets the pace.
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
from binade.mlx.draft import load
|
|
150
|
+
from mlx_lm import generate
|
|
151
|
+
|
|
152
|
+
model, draft, tokenizer = load("Binade/gemma-4-12B-it")
|
|
153
|
+
print(generate(model, tokenizer, prompt, max_tokens=200, draft_model=draft, num_draft_tokens=4))
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
```
|
|
157
|
+
binade serve --model Binade/gemma-4-12B-it --draft-model self --num-draft-tokens 4
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Up to four draft tokens keep every verify pass on the wide kernel (`results/*/self_draft.md`). Resident memory grows by about 4.5 bits per weight for the draft, still below BF16's 16. mlx-lm's speculative loop needs a trimmable cache, so models with linear-attention layers (Qwen3.5's `ArraysCache`) decode without a draft; MoE experts are not drafted yet.
|
|
161
|
+
|
|
162
|
+
## Verify and reproduce
|
|
163
|
+
|
|
164
|
+
- `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
|
|
165
|
+
- `scripts/generate_check.py`: greedy decoding against the BF16 model (`--reference streamed` for models that do not fit).
|
|
166
|
+
- `scripts/exactness_scale.py`: logits at 16,352 positions and 32 generations against BF16 (resident or streamed), optionally with the fused kernels forced.
|
|
167
|
+
- `scripts/decode_speed.py`, `scripts/torch_bench.py` (PyTorch BF16 and DFloat11 on the same prompt), `scripts/self_draft_bench.py`, `scripts/matvec_bench.py`, `scripts/prefill_bench.py`, `scripts/prompt_speed.py`, `scripts/cuda_gemm_bench.py`: speed.
|
|
168
|
+
- `scripts/cuda_exact_finite.py`: the CUDA runtime against MLX's BF16 product on data where every output shows the order of the sum; `scripts/torch_order_*.py`, `scripts/linear_chain_time.py`: which order PyTorch's BF16 linear layer sums in and how fast ([results/cuda/torch_order.md](results/cuda/torch_order.md)).
|
|
169
|
+
- `scripts/torch_load_bench.py`: `binade.torch.load` against `from_pretrained` on the source checkpoint (tensors, generation, load time).
|
|
170
|
+
- `scripts/torch_multi_gpu.py`: `binade.torch.load(device_map=...)` against `from_pretrained(device_map=...)` on several GPUs (the map, every parameter's device and bits, generation).
|
|
171
|
+
- `scripts/stream_pack.py`: pack a Hub checkpoint too large to hold twice, one shard at a time, each decoded again and compared with the SHA-256 the Hub lists for the source file; `scripts/restore_check.py`: restore shards on this machine's GPUs and compare `sha256sum` with the Hub's; `scripts/storage_summary.py`: the results page of such a pack from its own records.
|
|
172
|
+
- `scripts/fit_probe.py`: which variants load on a GPU; `scripts/reference_check.py`: MLX against the reference implementation.
|
|
173
|
+
- `scripts/histogram.py`, `scripts/mutual_info.py`, `scripts/iid_model.py`, `scripts/entropy_floor.py`, `scripts/compare.py`, `scripts/exponent_patch.py`: the exponent statistics and how far the file sits from the entropy floor.
|
|
174
|
+
- `pytest`: unit and kernel tests, including order-sensitive data that exposes any change in summation order.
|
|
175
|
+
|
|
176
|
+
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`.
|
|
177
|
+
|
|
178
|
+
## Limitations
|
|
179
|
+
|
|
180
|
+
- **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.
|
|
181
|
+
- **Validated models.** Gemma 4 12B, E2B, E4B and 26B-A4B, Llama 3.1 8B, Llama 3.2 3B, Qwen3.5 4B and 9B: bit-identical to BF16 at every one of 16,352 WikiText-2 positions per model, and in greedy generation (`results/*/exactness_scale.md`). Gemma 4 31B the same on NVIDIA (`results/cuda/gemma-4-31B-it/exactness_scale.md`).
|
|
182
|
+
- **Vision and audio.** Their weights are packed in the file (and restored by `binade unpack`), but the runtime loads the text model through mlx-lm, so it serves text.
|
|
183
|
+
- **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.
|
|
184
|
+
- **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
|
|
185
|
+
- **Speculative decoding and ties.** With a draft, the exact model checks several tokens in one multi-row pass, and MLX sums a multi-row product in a different order than a single-row one. Both are exact BF16 arithmetic, but a near-tie between two tokens can resolve differently, so speculative greedy output can differ from sequential greedy output at a few positions. The pack behaves exactly as BF16 does in both modes: `results/*/self_draft.md` compares the pack against BF16 with the same draft, token for token, and reports speculative against sequential separately.
|
|
186
|
+
- **CUDA.** Decoding runs at 1.01 to 1.20x BF16 (the MoE model, bound by the CPU, at 1.01x); 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. The runtime is MLX's CUDA backend, not PyTorch: PyTorch's BF16 linear layer sums in a different order ([pytorch](results/cuda/pytorch.md)), so a PyTorch runtime needs its own exact path.
|
|
187
|
+
- **CUDA: no speculative decoding yet.** MLX's CUDA backend pays a setup cost on a multi-row pass each time the cache length is new, so the self-draft loses to sequential decoding there (0.76x BF16 in fresh processes, [self_draft](results/cuda/Llama-3.1-8B-Instruct/self_draft.md)); it is a Mac feature for now. Greedy decoding on that backend is also not reproducible run to run, for BF16 as for the pack, so exactness there is checked on logits for the same inputs (`scripts/exactness_scale.py`).
|
|
188
|
+
|
|
189
|
+
## Related work
|
|
190
|
+
|
|
191
|
+
Binade codes the same exponent redundancy as:
|
|
192
|
+
- DFloat11 (Huffman, arXiv 2504.11651; measured side by side in [results/cuda/pytorch.md](results/cuda/pytorch.md));
|
|
193
|
+
- ZipServ (fixed-width exponent windows fused into GEMM, arXiv 2603.17435);
|
|
194
|
+
- Unweight (per-tensor palettes, Cloudflare);
|
|
195
|
+
- ENEC (frequency ranks, arXiv 2604.03298);
|
|
196
|
+
- NeuZip (arXiv 2410.20650) and ZipNN (arXiv 2411.05239).
|
|
197
|
+
|
|
198
|
+
We found no public implementation of lossless compressed inference on Metal.
|
|
199
|
+
|
|
200
|
+
## Paper
|
|
201
|
+
|
|
202
|
+
[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/`.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
Apache-2.0 ([LICENSE](LICENSE)). Model weights keep their own licenses.
|
|
@@ -24,9 +24,12 @@ MM_MARKERS = (
|
|
|
24
24
|
"mm_projector",
|
|
25
25
|
".visual.",
|
|
26
26
|
)
|
|
27
|
-
ATTN = {"q_proj", "k_proj", "v_proj", "o_proj", "qkv_proj", "out_proj"}
|
|
27
|
+
ATTN = {"q_proj", "k_proj", "v_proj", "o_proj", "qkv_proj", "out_proj", "wqkv", "wo"}
|
|
28
28
|
LINATTN = {"linear_attn"}
|
|
29
|
-
MLP = {"gate_proj", "up_proj", "down_proj", "gate_up_proj", "w1", "w2", "w3"}
|
|
29
|
+
MLP = {"gate_proj", "up_proj", "down_proj", "gate_up_proj", "w1", "w2", "w3", "up", "down", "shared_up_proj", "shared_down_proj"}
|
|
30
|
+
# weights some checkpoints store under the bare parameter name, without a `.weight` suffix (Amazon
|
|
31
|
+
# Ergo: layers.N.feed_forward.up_proj is the [experts, out, in] stack, shared_up_proj the shared expert)
|
|
32
|
+
BARE = {"gate_proj", "up_proj", "down_proj", "gate_up_proj", "shared_up_proj", "shared_down_proj"}
|
|
30
33
|
PLE_PROJ = {"per_layer_input_gate", "per_layer_projection", "per_layer_model_projection"}
|
|
31
34
|
MIN_DIM = 256
|
|
32
35
|
_BLOCK = re.compile(r"^(.*?\blayers\.(\d+))\.")
|
|
@@ -49,17 +52,17 @@ def classify(name: str, shape: tuple[int, ...], dtype: str) -> Klass:
|
|
|
49
52
|
return Klass("mm", "mm", layer, block)
|
|
50
53
|
if "embed_tokens_per_layer" in parts:
|
|
51
54
|
return Klass("ple", "ple", None)
|
|
52
|
-
if name.endswith("embed_tokens.weight"):
|
|
55
|
+
if name.endswith("embed_tokens.weight") or name == "tok_embeddings.weight":
|
|
53
56
|
return Klass("embed", "embed_tokens", None)
|
|
54
|
-
if name.endswith("lm_head.weight"):
|
|
57
|
+
if name.endswith("lm_head.weight") or name == "output.weight":
|
|
55
58
|
return Klass("embed", "lm_head", None)
|
|
56
59
|
matrix = dtype == "BF16" and len(shape) in (2, 3) and min(shape[-2:]) >= MIN_DIM
|
|
57
|
-
# a weight is
|
|
58
|
-
is_weight = parts[-1] == "weight" or (len(shape) == 3 and "experts" in parts)
|
|
60
|
+
# a weight is `<module>.weight`, a fused expert stack without the suffix, or a bare parameter name
|
|
61
|
+
is_weight = parts[-1] == "weight" or (len(shape) == 3 and "experts" in parts) or parts[-1] in BARE
|
|
59
62
|
if matrix and is_weight:
|
|
60
63
|
comps = set(parts)
|
|
61
64
|
sub = None
|
|
62
|
-
if "experts" in comps:
|
|
65
|
+
if "experts" in comps or (len(shape) == 3 and parts[-1] in BARE):
|
|
63
66
|
sub = "experts"
|
|
64
67
|
elif comps & LINATTN:
|
|
65
68
|
sub = "linattn"
|