binade 0.1.0__tar.gz → 0.1.2__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.
Files changed (51) hide show
  1. {binade-0.1.0 → binade-0.1.2}/PKG-INFO +19 -5
  2. {binade-0.1.0 → binade-0.1.2}/README.md +18 -4
  3. {binade-0.1.0 → binade-0.1.2}/binade/__init__.py +1 -1
  4. {binade-0.1.0 → binade-0.1.2}/binade/cli.py +5 -3
  5. {binade-0.1.0 → binade-0.1.2}/binade/mlx/loader.py +7 -7
  6. {binade-0.1.0 → binade-0.1.2}/binade/mlx/r4.py +54 -3
  7. binade-0.1.2/binade/mlx/serve.py +39 -0
  8. {binade-0.1.0 → binade-0.1.2}/binade/mlx/slow_linear.py +5 -2
  9. {binade-0.1.0 → binade-0.1.2}/binade/pack.py +29 -9
  10. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/PKG-INFO +19 -5
  11. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/SOURCES.txt +3 -0
  12. {binade-0.1.0 → binade-0.1.2}/pyproject.toml +1 -1
  13. {binade-0.1.0 → binade-0.1.2}/tests/test_pack.py +9 -3
  14. binade-0.1.2/tests/test_ple.py +102 -0
  15. binade-0.1.2/tests/test_serve.py +56 -0
  16. {binade-0.1.0 → binade-0.1.2}/LICENSE +0 -0
  17. {binade-0.1.0 → binade-0.1.2}/binade/baselines.py +0 -0
  18. {binade-0.1.0 → binade-0.1.2}/binade/bf16.py +0 -0
  19. {binade-0.1.0 → binade-0.1.2}/binade/classify.py +0 -0
  20. {binade-0.1.0 → binade-0.1.2}/binade/format.py +0 -0
  21. {binade-0.1.0 → binade-0.1.2}/binade/info.py +0 -0
  22. {binade-0.1.0 → binade-0.1.2}/binade/lossy.py +0 -0
  23. {binade-0.1.0 → binade-0.1.2}/binade/mlx/__init__.py +0 -0
  24. {binade-0.1.0 → binade-0.1.2}/binade/mlx/cublas_plan.py +0 -0
  25. {binade-0.1.0 → binade-0.1.2}/binade/mlx/cuda_kernels.py +0 -0
  26. {binade-0.1.0 → binade-0.1.2}/binade/mlx/kernel.py +0 -0
  27. {binade-0.1.0 → binade-0.1.2}/binade/mlx/moe.py +0 -0
  28. {binade-0.1.0 → binade-0.1.2}/binade/mlx/rice_kernel.py +0 -0
  29. {binade-0.1.0 → binade-0.1.2}/binade/policies.py +0 -0
  30. {binade-0.1.0 → binade-0.1.2}/binade/rice.py +0 -0
  31. {binade-0.1.0 → binade-0.1.2}/binade/scan.py +0 -0
  32. {binade-0.1.0 → binade-0.1.2}/binade/st.py +0 -0
  33. {binade-0.1.0 → binade-0.1.2}/binade/tile.py +0 -0
  34. {binade-0.1.0 → binade-0.1.2}/binade/unpack.py +0 -0
  35. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/dependency_links.txt +0 -0
  36. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/entry_points.txt +0 -0
  37. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/requires.txt +0 -0
  38. {binade-0.1.0 → binade-0.1.2}/binade.egg-info/top_level.txt +0 -0
  39. {binade-0.1.0 → binade-0.1.2}/setup.cfg +0 -0
  40. {binade-0.1.0 → binade-0.1.2}/tests/test_bf16.py +0 -0
  41. {binade-0.1.0 → binade-0.1.2}/tests/test_classify_lossy_baselines.py +0 -0
  42. {binade-0.1.0 → binade-0.1.2}/tests/test_cuda_gemm.py +0 -0
  43. {binade-0.1.0 → binade-0.1.2}/tests/test_format.py +0 -0
  44. {binade-0.1.0 → binade-0.1.2}/tests/test_info.py +0 -0
  45. {binade-0.1.0 → binade-0.1.2}/tests/test_kernel.py +0 -0
  46. {binade-0.1.0 → binade-0.1.2}/tests/test_policies.py +0 -0
  47. {binade-0.1.0 → binade-0.1.2}/tests/test_r4.py +0 -0
  48. {binade-0.1.0 → binade-0.1.2}/tests/test_r4_moe.py +0 -0
  49. {binade-0.1.0 → binade-0.1.2}/tests/test_rice.py +0 -0
  50. {binade-0.1.0 → binade-0.1.2}/tests/test_runtime.py +0 -0
  51. {binade-0.1.0 → binade-0.1.2}/tests/test_st.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: binade
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
5
  Author: Guy Shafir
6
6
  License-Expression: Apache-2.0
@@ -36,6 +36,8 @@ Provides-Extra: dev
36
36
  Requires-Dist: pytest>=8; extra == "dev"
37
37
  Dynamic: license-file
38
38
 
39
+ <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>
40
+
39
41
  # Binade
40
42
 
41
43
  Bit-exact compression of BF16 LLM weights for Apple Silicon (MLX), and for NVIDIA GPUs through MLX's CUDA backend.
@@ -54,6 +56,10 @@ Apple M4 Max, 48 GB, MLX 0.32.2. Every number comes from a script in `scripts/`;
54
56
  | 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
57
  | 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
58
  | 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)) |
59
+ | 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)) |
60
+ | 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)) |
61
+ | 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)) |
62
+ | 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)) |
57
63
  | 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
64
 
59
65
  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.
@@ -77,7 +83,7 @@ Multi-row products in MLX's CUDA backend go to cuBLAS, which is closed. Its BF16
77
83
 
78
84
  - **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
85
  - **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.
86
+ - **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.
81
87
  - **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
88
 
83
89
  [DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
@@ -100,7 +106,7 @@ pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[de
100
106
 
101
107
  ## Use
102
108
 
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:
109
+ 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
110
 
105
111
  ```
106
112
  hf download google/gemma-4-12B-it
@@ -121,6 +127,14 @@ print(generate(model, tokenizer, prompt, max_tokens=200))
121
127
 
122
128
  `binade unpack <packed-dir or Hub repo id> --out DIR` rebuilds the original BF16 checkpoint, bit for bit.
123
129
 
130
+ Or serve it over mlx-lm's OpenAI-compatible HTTP API, for any chat client:
131
+
132
+ ```
133
+ binade serve --model Binade/gemma-4-12B-it --port 8080
134
+ ```
135
+
136
+ `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.
137
+
124
138
  ## Verify and reproduce
125
139
 
126
140
  - `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
@@ -136,8 +150,8 @@ Result files record the commit of the development repository that produced them;
136
150
  ## Limitations
137
151
 
138
152
  - **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.
153
+ - **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`).
154
+ - **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.
141
155
  - **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
156
  - **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
143
157
  - **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.
@@ -1,3 +1,5 @@
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
+
1
3
  # Binade
2
4
 
3
5
  Bit-exact compression of BF16 LLM weights for Apple Silicon (MLX), and for NVIDIA GPUs through MLX's CUDA backend.
@@ -16,6 +18,10 @@ Apple M4 Max, 48 GB, MLX 0.32.2. Every number comes from a script in `scripts/`;
16
18
  | 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
19
  | 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
20
  | 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)) |
21
+ | 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)) |
22
+ | 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)) |
23
+ | 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)) |
24
+ | 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)) |
19
25
  | 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
26
 
21
27
  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.
@@ -39,7 +45,7 @@ Multi-row products in MLX's CUDA backend go to cuBLAS, which is closed. Its BF16
39
45
 
40
46
  - **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
47
  - **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.
48
+ - **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.
43
49
  - **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
50
 
45
51
  [DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
@@ -62,7 +68,7 @@ pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[de
62
68
 
63
69
  ## Use
64
70
 
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:
71
+ 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:
66
72
 
67
73
  ```
68
74
  hf download google/gemma-4-12B-it
@@ -83,6 +89,14 @@ print(generate(model, tokenizer, prompt, max_tokens=200))
83
89
 
84
90
  `binade unpack <packed-dir or Hub repo id> --out DIR` rebuilds the original BF16 checkpoint, bit for bit.
85
91
 
92
+ Or serve it over mlx-lm's OpenAI-compatible HTTP API, for any chat client:
93
+
94
+ ```
95
+ binade serve --model Binade/gemma-4-12B-it --port 8080
96
+ ```
97
+
98
+ `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.
99
+
86
100
  ## Verify and reproduce
87
101
 
88
102
  - `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
@@ -98,8 +112,8 @@ Result files record the commit of the development repository that produced them;
98
112
  ## Limitations
99
113
 
100
114
  - **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.
115
+ - **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`).
116
+ - **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.
103
117
  - **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
118
  - **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
105
119
  - **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.
@@ -1,3 +1,3 @@
1
1
  """Binade: bit-exact BF16 weight compression for Apple Silicon."""
2
2
 
3
- __version__ = "0.0.1"
3
+ __version__ = "0.1.2"
@@ -1,15 +1,17 @@
1
- """Command line: `binade pack ...` and `binade unpack ...`."""
1
+ """Command line: `binade pack ...`, `binade unpack ...` and `binade serve ...`."""
2
2
 
3
3
  import sys
4
4
 
5
5
 
6
6
  def main():
7
- if len(sys.argv) < 2 or sys.argv[1] not in ("pack", "unpack"):
8
- sys.exit("usage: binade {pack,unpack} ... (binade pack --help for options)")
7
+ if len(sys.argv) < 2 or sys.argv[1] not in ("pack", "unpack", "serve"):
8
+ sys.exit("usage: binade {pack,unpack,serve} ... (binade pack --help for options)")
9
9
  cmd = sys.argv.pop(1)
10
10
  sys.argv[0] = f"binade {cmd}"
11
11
  if cmd == "pack":
12
12
  from .pack import main as run
13
+ elif cmd == "serve":
14
+ from .mlx.serve import main as run
13
15
  else:
14
16
  from .unpack import main as run
15
17
  run()
@@ -27,7 +27,8 @@ from mlx.utils import tree_flatten, tree_unflatten
27
27
  from mlx_lm.utils import _get_classes, load_model, load_tokenizer
28
28
 
29
29
  from .. import st
30
- from ..pack import PARTS
30
+ from ..classify import classify
31
+ from ..pack import PARTS, pack_meta
31
32
  from .moe import BinadeSwitchGLU
32
33
  from .slow_linear import BinadeEmbedding, BinadeLinear
33
34
 
@@ -101,7 +102,7 @@ def swap_modules(model: nn.Module, specs: dict, sanitize=lambda w: w) -> list[st
101
102
  unused.append(name)
102
103
  continue
103
104
  if isinstance(old, nn.Embedding):
104
- new = BinadeEmbedding(specs[name])
105
+ new = BinadeEmbedding(specs[name], gather_only=classify(name, tuple(specs[name]["raw"][0]), "BF16").cls == "ple")
105
106
  elif isinstance(old, nn.Linear):
106
107
  new = BinadeLinear(specs[name], bias="bias" in old)
107
108
  else:
@@ -146,9 +147,8 @@ def model_classes(specs: dict | None = None, dropped: list | None = None):
146
147
  def load_packed_model(path, lazy: bool = True):
147
148
  """(model, config) for a Binade-packed model directory."""
148
149
  path = Path(path)
149
- config = json.loads((path / "config.json").read_text())
150
- q = config.get("quantization_config", {})
151
- if q.get("quant_method") != "binade" or str(q.get("version")) not in PARTS:
150
+ q = pack_meta(path) or {}
151
+ if str(q.get("version")) not in PARTS:
152
152
  raise ValueError(f"{path}: not a Binade model ({q})")
153
153
  dropped = []
154
154
  model, config = load_model(path, lazy=lazy, strict=True, get_model_classes=model_classes(packed_specs(path), dropped))
@@ -156,7 +156,7 @@ def load_packed_model(path, lazy: bool = True):
156
156
  return model, config
157
157
 
158
158
 
159
- def load(path, lazy: bool = True, cache_limit_gb: float | None = 8):
159
+ def load(path, lazy: bool = True, cache_limit_gb: float | None = 8, tokenizer_config: dict | None = None):
160
160
  """(model, tokenizer, dropped checkpoint tensors) for a Binade-packed model: a directory, a
161
161
  cached HF repo id, or an HF repo id to download (st.fetch).
162
162
 
@@ -168,7 +168,7 @@ def load(path, lazy: bool = True, cache_limit_gb: float | None = 8):
168
168
  mx.set_cache_limit(int(cache_limit_gb * (1 << 30)))
169
169
  path = st.fetch(str(path))
170
170
  model, config = load_packed_model(path, lazy)
171
- tok = load_tokenizer(Path(path), eos_token_ids=config.get("eos_token_id", None))
171
+ tok = load_tokenizer(Path(path), tokenizer_config, eos_token_ids=config.get("eos_token_id", None))
172
172
  return model, tok, config["binade_dropped"]
173
173
 
174
174
 
@@ -11,6 +11,11 @@ raw bytes plus about 4.06 bits per weight.
11
11
  Single-row inputs (batch-1 decode) run the R4 kernel, whose outputs are bit-identical to
12
12
  MLX's BF16 matvec. Multi-row inputs (prompt processing) rebuild the BF16 weight with the
13
13
  R4 decode kernel and call MLX's matmul, bit-identical by construction.
14
+
15
+ A gather-only table (Gemma 4 E-models' per-layer embedding tables, `embed_tokens_per_layer`,
16
+ the model's largest tensor) never enters a matmul, so it needs no R4 layout: a format 2 table
17
+ stays in its Rice coding in memory (RiceEmbedding) and the Rice kernel decodes the rows a
18
+ lookup asks for.
14
19
  """
15
20
 
16
21
  import re
@@ -320,13 +325,56 @@ class R4Embedding(nn.Module, _R4):
320
325
  return self._rows(x)
321
326
 
322
327
 
328
+ class RiceEmbedding(nn.Module):
329
+ """Gather-only table kept in Binade format 2 (Rice) in memory, about 10.7 bits per weight
330
+ resident instead of R4's 12.07. A lookup gathers the rows' tiles and word offsets and runs
331
+ the Rice decode kernel on just those rows, lazily (no host sync), then joins exponents with
332
+ the raw bytes. No as_linear: the table never enters a matmul."""
333
+
334
+ def __init__(self, w: dict):
335
+ super().__init__()
336
+ raw = w["raw"]
337
+ self.K = raw.shape[-1]
338
+ self.N = raw.size // self.K
339
+ self.T = -(-self.K // TILE)
340
+ if w["meta"].size != self.N * self.T or w["roff"].size != self.N:
341
+ raise ValueError(f"{w['meta'].size} tiles and {w['roff'].size} row offsets for {self.N} x {self.K}")
342
+ self._a = {
343
+ "raw": raw.reshape(self.N, self.K),
344
+ "table": w["table"],
345
+ "meta": w["meta"].reshape(self.N, self.T),
346
+ "bits": w["bits"] if w["bits"].size else mx.zeros((1,), dtype=mx.uint32),
347
+ "roff": w["roff"],
348
+ "shape": tuple(raw.shape),
349
+ }
350
+
351
+ def __call__(self, ids: mx.array) -> mx.array:
352
+ a = self._a
353
+ flat = ids.reshape(-1).astype(mx.uint32)
354
+ rank, _ = rice_ranks(a["meta"][flat].reshape(-1), a["bits"], a["roff"][flat], self.K)
355
+ e = a["table"][rank[:, : self.K]].astype(mx.uint16)
356
+ r = a["raw"][flat].astype(mx.uint16)
357
+ out = (((r & 0x80) << 8) | (e << 7) | (r & 0x7F)).view(mx.bfloat16)
358
+ return out.reshape(*ids.shape, self.K)
359
+
360
+ def dense(self) -> mx.array:
361
+ """The BF16 table, decoded in row chunks."""
362
+ step = max(1, CHUNK // self.K)
363
+ rows = []
364
+ for r0 in range(0, self.N, step):
365
+ rows.append(self(mx.arange(r0, min(self.N, r0 + step), dtype=mx.uint32)))
366
+ mx.eval(rows[-1])
367
+ return (rows[0] if len(rows) == 1 else mx.concatenate(rows)).reshape(self._a["shape"])
368
+
369
+
323
370
  def _evaluated(a: dict) -> dict:
324
371
  mx.eval(a["raw"], a["codes"], a["flags"], a["esc"], a["row_esc"])
325
372
  return a
326
373
 
327
374
 
328
375
  def convert(model: nn.Module, log=None) -> int:
329
- """Swap every v1 module for its R4 counterpart in place; returns how many were converted.
376
+ """Swap every file-array module for its runtime counterpart in place (R4, or RiceEmbedding
377
+ for a gather-only format 2 table); returns how many were converted.
330
378
  Holds only paths between swaps, so each v1 module is freed as soon as it is replaced."""
331
379
  paths = [path for path, m in model.named_modules() if isinstance(m, (BinadeLinear, BinadeEmbedding, BinadeSwitchGLU))]
332
380
 
@@ -344,6 +392,9 @@ def convert(model: nn.Module, log=None) -> int:
344
392
  gu, dn = (R4Linear(_evaluated(transcode(h))) for h in holders(m))
345
393
  new = R4SwitchGLU(gu, dn, m._activation)
346
394
  del gu, dn
395
+ elif isinstance(m, BinadeEmbedding) and m.gather_only and "bits" in m.weight:
396
+ new = RiceEmbedding(m.weight)
397
+ mx.eval(*new._a.values())
347
398
  else:
348
399
  a = _evaluated(transcode(m))
349
400
  new = R4Embedding(a) if isinstance(m, BinadeEmbedding) else R4Linear(a)
@@ -359,7 +410,7 @@ def convert(model: nn.Module, log=None) -> int:
359
410
  return len(paths)
360
411
 
361
412
 
362
- def load(path, log=None, cache_limit_gb: float = 2, wire: bool = True):
413
+ def load(path, log=None, cache_limit_gb: float = 2, wire: bool = True, tokenizer_config: dict | None = None):
363
414
  """(model, tokenizer, dropped) for a Binade model, converted to the R4 runtime.
364
415
 
365
416
  Caps MLX's buffer cache (global) at cache_limit_gb: decoding needs only small buffers,
@@ -373,7 +424,7 @@ def load(path, log=None, cache_limit_gb: float = 2, wire: bool = True):
373
424
  if wire and not CUDA and mx.metal.is_available():
374
425
  mx.set_wired_limit(int(mx.device_info()["max_recommended_working_set_size"]))
375
426
 
376
- model, tokenizer, dropped = load_v1(path, cache_limit_gb=cache_limit_gb)
427
+ model, tokenizer, dropped = load_v1(path, cache_limit_gb=cache_limit_gb, tokenizer_config=tokenizer_config)
377
428
  convert(model, log)
378
429
  mx.clear_cache()
379
430
  return model, tokenizer, dropped
@@ -0,0 +1,39 @@
1
+ """binade serve: mlx-lm's OpenAI-compatible HTTP server (mlx_lm.server) with Binade models on
2
+ the R4 runtime.
3
+
4
+ binade serve --model Binade/gemma-4-12B-it [--port 8080] [any mlx_lm.server option]
5
+
6
+ A model path that is a Binade pack (a local directory or a Hub repo id, downloaded if needed)
7
+ loads through binade.mlx.r4.load; any other model loads as mlx-lm would, so one server can
8
+ switch between packed and stock models by name. Adapters and draft models are mlx-lm's:
9
+ they apply to stock models, and a Binade model given an adapter is refused (its modules are
10
+ not nn.Linear).
11
+ """
12
+
13
+ from mlx_lm.utils import load as load_stock
14
+
15
+ from .. import st
16
+ from ..pack import pack_meta
17
+
18
+
19
+ def load(model_path, tokenizer_config=None, adapter_path=None, **kwargs):
20
+ """mlx_lm.utils.load's signature: (model, tokenizer), Binade packs on the R4 runtime."""
21
+ try:
22
+ path = st.fetch(str(model_path))
23
+ except FileNotFoundError:
24
+ path = None
25
+ if path is None or pack_meta(path) is None:
26
+ return load_stock(model_path, tokenizer_config=tokenizer_config, adapter_path=adapter_path, **kwargs)
27
+ if adapter_path is not None:
28
+ raise ValueError(f"{model_path} is a Binade model; adapters are not supported on the R4 runtime")
29
+ from .r4 import load as load_r4
30
+
31
+ model, tokenizer, _ = load_r4(path, tokenizer_config=tokenizer_config)
32
+ return model, tokenizer
33
+
34
+
35
+ def main():
36
+ import mlx_lm.server as server
37
+
38
+ server.load = load
39
+ server.main()
@@ -148,11 +148,14 @@ class BinadeLinear(nn.Module):
148
148
 
149
149
  class BinadeEmbedding(nn.Module):
150
150
  """Drop-in for nn.Embedding: lookups decode only the chunks holding the requested rows;
151
- the tied output projection (as_linear) decodes the whole table."""
151
+ the tied output projection (as_linear) decodes the whole table. gather_only marks a table
152
+ that never enters a matmul (Gemma's per-layer embedding tables, the `ple` class), which
153
+ the R4 runtime then keeps in its file coding (r4.RiceEmbedding)."""
152
154
 
153
- def __init__(self, spec: dict):
155
+ def __init__(self, spec: dict, gather_only: bool = False):
154
156
  super().__init__()
155
157
  self.weight = _placeholders(spec)
158
+ self.gather_only = gather_only
156
159
  self._plan = None
157
160
 
158
161
  def __call__(self, ids: mx.array) -> mx.array:
@@ -1,6 +1,6 @@
1
1
  """Binade packer: BF16 safetensors model -> Binade model (DESIGN.md 10, 6, 7).
2
2
 
3
- binade pack <model-dir | cached-hf-repo-id> --out DIR [--format 2|1] [--revision REV] [--classes linear,embed]
3
+ binade pack <model-dir | cached-hf-repo-id> --out DIR [--format 2|1] [--revision REV] [--classes linear,embed,ple,mm]
4
4
 
5
5
  Streams one tensor at a time. A packed weight `name` becomes name.raw (sign + mantissa,
6
6
  original shape), name.table and the exponent coding: format 1 (binade/format.py)
@@ -19,11 +19,12 @@ from pathlib import Path
19
19
  import numpy as np
20
20
 
21
21
  from . import bf16, st
22
- from .classify import classify
22
+ from .classify import MIN_DIM, classify
23
23
  from . import rice
24
24
  from .format import TILE, encode, rank_table
25
25
 
26
26
  VERSION = "2" # default format: Rice (smaller, faster to load); "1" for the slow runtime
27
+ CLASSES = ("linear", "embed", "ple", "mm") # packed by default: the text decode path and the vision/audio towers (binade/classify.py); the runtime serves text, so mm tensors are only ever unpacked
27
28
  CHUNK = 1 << 24 # weights per read
28
29
  PARTS = {"1": ("raw", "table", "meta", "idx", "esc"), "2": ("raw", "table", "meta", "bits", "roff")}
29
30
  SUFFIXES = PARTS[VERSION]
@@ -35,12 +36,32 @@ def quant(version: str = VERSION) -> dict:
35
36
 
36
37
 
37
38
  QUANT = quant()
39
+
40
+
41
+ def pack_meta(path) -> dict | None:
42
+ """The Binade marker of a packed directory ({"quant_method": "binade", "version", "tile"}): the
43
+ "binade" entry of binade_pack.json, else the quantization_config that packs before binade 0.1.1
44
+ wrote into config.json; None for a directory that is not a Binade pack."""
45
+ path = Path(path)
46
+ report = path / "binade_pack.json"
47
+ if report.exists():
48
+ meta = json.loads(report.read_text()).get("binade")
49
+ if meta and meta.get("quant_method") == "binade":
50
+ return meta
51
+ config = path / "config.json"
52
+ q = json.loads(config.read_text()).get("quantization_config", {}) if config.exists() else {}
53
+ return q if q.get("quant_method") == "binade" else None
38
54
  REPO = Path(__file__).resolve().parents[1]
39
55
 
40
56
 
41
57
  def packable(info: st.TensorInfo, classes) -> bool:
58
+ """BF16, 2-D or 3-D, in a requested class. Vision/audio tensors (mm) are packed only at
59
+ linear-weight sizes: a depthwise 1-D convolution such as [1024, 1, 5] codes at over 16 bits
60
+ per weight (a table and a tile header per 5-weight row)."""
42
61
  k = classify(info.name, info.shape, info.dtype)
43
- return info.dtype == "BF16" and len(info.shape) in (2, 3) and k.cls in classes
62
+ if info.dtype != "BF16" or len(info.shape) not in (2, 3) or k.cls not in classes:
63
+ return False
64
+ return k.cls != "mm" or min(info.shape[-2:]) >= MIN_DIM
44
65
 
45
66
 
46
67
  def spans(info: st.TensorInfo, chunk: int = CHUNK):
@@ -98,7 +119,7 @@ def _reserve(infos, classes, metadata) -> int:
98
119
  return n + len(json.dumps(metadata)) + 4096
99
120
 
100
121
 
101
- def pack_model(src: Path, out: Path, classes=("linear", "embed"), chunk: int = CHUNK, log=print, version: str = VERSION) -> dict:
122
+ def pack_model(src: Path, out: Path, classes=CLASSES, chunk: int = CHUNK, log=print, version: str = VERSION) -> dict:
102
123
  if version not in PARTS:
103
124
  raise ValueError(f"unknown Binade format {version!r}")
104
125
  t0 = time.perf_counter()
@@ -126,11 +147,10 @@ def pack_model(src: Path, out: Path, classes=("linear", "embed"), chunk: int = C
126
147
  weight_map.update({n: shard.name for n in names})
127
148
  w.close()
128
149
 
129
- config = json.loads((src / "config.json").read_text())
130
- config["quantization_config"] = quant(version)
131
- (out / "config.json").write_text(json.dumps(config, indent=2) + "\n")
150
+ # config.json stays the original model's: the Binade marker lives in binade_pack.json (pack_meta),
151
+ # so the Hugging Face Hub does not take a Binade checkpoint for a quantization of its base model
132
152
  for f in src.iterdir():
133
- if f.is_file() and not f.name.endswith(".safetensors") and f.name not in ("config.json", "model.safetensors.index.json"):
153
+ if f.is_file() and not f.name.endswith(".safetensors") and f.name != "model.safetensors.index.json":
134
154
  shutil.copy(f, out / f.name)
135
155
  files = sorted(set(weight_map.values()))
136
156
  total = sum((out / f).stat().st_size for f in files)
@@ -158,7 +178,7 @@ def main():
158
178
  ap.add_argument("model")
159
179
  ap.add_argument("--out", type=Path, required=True)
160
180
  ap.add_argument("--revision")
161
- ap.add_argument("--classes", default="linear,embed")
181
+ ap.add_argument("--classes", default=",".join(CLASSES))
162
182
  ap.add_argument("--format", default=VERSION, choices=sorted(PARTS), help="1: fixed width with escapes; 2: Rice (smaller, decoded to R4 at load)")
163
183
  args = ap.parse_args()
164
184
  r = pack_model(st.resolve(args.model, args.revision), args.out, tuple(args.classes.split(",")), version=args.format)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: binade
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
5
  Author: Guy Shafir
6
6
  License-Expression: Apache-2.0
@@ -36,6 +36,8 @@ Provides-Extra: dev
36
36
  Requires-Dist: pytest>=8; extra == "dev"
37
37
  Dynamic: license-file
38
38
 
39
+ <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>
40
+
39
41
  # Binade
40
42
 
41
43
  Bit-exact compression of BF16 LLM weights for Apple Silicon (MLX), and for NVIDIA GPUs through MLX's CUDA backend.
@@ -54,6 +56,10 @@ Apple M4 Max, 48 GB, MLX 0.32.2. Every number comes from a script in `scripts/`;
54
56
  | 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
57
  | 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
58
  | 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)) |
59
+ | 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)) |
60
+ | 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)) |
61
+ | 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)) |
62
+ | 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)) |
57
63
  | 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
64
 
59
65
  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.
@@ -77,7 +83,7 @@ Multi-row products in MLX's CUDA backend go to cuBLAS, which is closed. Its BF16
77
83
 
78
84
  - **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
85
  - **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.
86
+ - **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.
81
87
  - **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
88
 
83
89
  [DESIGN.md](DESIGN.md) has the formats, the runtime layout and the exactness argument.
@@ -100,7 +106,7 @@ pip install -e ".[dev,eval,figures]" # add cuda on Linux: ".[de
100
106
 
101
107
  ## Use
102
108
 
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:
109
+ 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
110
 
105
111
  ```
106
112
  hf download google/gemma-4-12B-it
@@ -121,6 +127,14 @@ print(generate(model, tokenizer, prompt, max_tokens=200))
121
127
 
122
128
  `binade unpack <packed-dir or Hub repo id> --out DIR` rebuilds the original BF16 checkpoint, bit for bit.
123
129
 
130
+ Or serve it over mlx-lm's OpenAI-compatible HTTP API, for any chat client:
131
+
132
+ ```
133
+ binade serve --model Binade/gemma-4-12B-it --port 8080
134
+ ```
135
+
136
+ `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.
137
+
124
138
  ## Verify and reproduce
125
139
 
126
140
  - `scripts/roundtrip_test.py`: every tensor of a packed model against the original, bit for bit.
@@ -136,8 +150,8 @@ Result files record the commit of the development repository that produced them;
136
150
  ## Limitations
137
151
 
138
152
  - **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.
153
+ - **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`).
154
+ - **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.
141
155
  - **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
156
  - **Quantization is faster.** Lossy 8-bit quantization is faster and smaller; Binade's case is exactness.
143
157
  - **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.
@@ -30,6 +30,7 @@ binade/mlx/loader.py
30
30
  binade/mlx/moe.py
31
31
  binade/mlx/r4.py
32
32
  binade/mlx/rice_kernel.py
33
+ binade/mlx/serve.py
33
34
  binade/mlx/slow_linear.py
34
35
  tests/test_bf16.py
35
36
  tests/test_classify_lossy_baselines.py
@@ -38,9 +39,11 @@ tests/test_format.py
38
39
  tests/test_info.py
39
40
  tests/test_kernel.py
40
41
  tests/test_pack.py
42
+ tests/test_ple.py
41
43
  tests/test_policies.py
42
44
  tests/test_r4.py
43
45
  tests/test_r4_moe.py
44
46
  tests/test_rice.py
45
47
  tests/test_runtime.py
48
+ tests/test_serve.py
46
49
  tests/test_st.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "binade"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "Lossless compression of BF16 LLM weights whose outputs stay bit-identical to the original, for MLX on Apple Silicon and NVIDIA GPUs"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -8,7 +8,7 @@ import pytest
8
8
  from safetensors import safe_open
9
9
 
10
10
  from binade import st
11
- from binade.pack import pack_model
11
+ from binade.pack import pack_meta, pack_model, quant
12
12
  from binade.unpack import PackedModel
13
13
 
14
14
 
@@ -61,8 +61,14 @@ def test_pack_roundtrip_bit_exact(tmp_path, version, gpu):
61
61
  assert f"model.layers.0.experts.gate_up_proj.{'idx' if version == '1' else 'bits'}" in keys
62
62
  loaded = mx.load(str(out / "model.safetensors"))
63
63
  assert loaded["model.layers.0.experts.gate_up_proj.raw"].shape == (4, 256, 256)
64
- config = json.loads((out / "config.json").read_text())
65
- assert config["quantization_config"]["quant_method"] == "binade" and config["quantization_config"]["version"] == version
64
+ # config.json is the original's; the marker is in binade_pack.json, and older packs that carry it
65
+ # in config.json's quantization_config are still recognized
66
+ assert (out / "config.json").read_bytes() == (src / "config.json").read_bytes()
67
+ assert pack_meta(out) == quant(version)
68
+ old = tmp_path / "old_style"
69
+ old.mkdir()
70
+ (old / "config.json").write_text(json.dumps({**json.loads((src / "config.json").read_text()), "quantization_config": quant(version)}))
71
+ assert pack_meta(old) == quant(version) and pack_meta(src) is None
66
72
  index = json.loads((out / "model.safetensors.index.json").read_text())
67
73
  assert set(index["weight_map"]) == keys
68
74
  assert (out / "tokenizer.json").exists() and (out / "binade_pack.json").exists()
@@ -0,0 +1,102 @@
1
+ """Gemma per-layer embedding tables (the `ple` class, gather only): packed by default, served
2
+ from their Rice coding in memory by the R4 runtime, lookups and model outputs bit-identical."""
3
+
4
+ import json
5
+
6
+ import mlx.core as mx
7
+ import numpy as np
8
+ import pytest
9
+ from mlx.utils import tree_flatten
10
+ from mlx_lm.models import gemma4_text
11
+ from mlx_lm.models.cache import make_prompt_cache
12
+ from mlx_lm.utils import load_model
13
+
14
+ from binade import st
15
+ from binade.mlx.loader import load_packed_model, packed_specs
16
+ from binade.mlx.r4 import RiceEmbedding, convert
17
+ from binade.pack import pack_model
18
+
19
+
20
+ def _tiny_gemma(tmp_path, per_layer: int = 64):
21
+ config = {
22
+ "model_type": "gemma4_text",
23
+ "hidden_size": 256,
24
+ "num_hidden_layers": 2,
25
+ "intermediate_size": 640,
26
+ "num_attention_heads": 4,
27
+ "num_key_value_heads": 1,
28
+ "head_dim": 32,
29
+ "global_head_dim": 64,
30
+ "num_kv_shared_layers": 0,
31
+ "vocab_size": 512,
32
+ "vocab_size_per_layer_input": 512,
33
+ "hidden_size_per_layer_input": per_layer,
34
+ "sliding_window": 64,
35
+ "rms_norm_eps": 1e-6,
36
+ "tie_word_embeddings": True,
37
+ }
38
+ mx.random.seed(0)
39
+ model = gemma4_text.Model(gemma4_text.ModelArgs.from_dict(config))
40
+ weights = {k: (v * 40).astype(mx.bfloat16) for k, v in tree_flatten(model.parameters())}
41
+ src = tmp_path / f"src_{per_layer}"
42
+ src.mkdir()
43
+ mx.save_safetensors(str(src / "model.safetensors"), weights)
44
+ (src / "config.json").write_text(json.dumps(config))
45
+ return src
46
+
47
+
48
+ def _bits(a: mx.array) -> np.ndarray:
49
+ return np.array(a.view(mx.uint16))
50
+
51
+
52
+ @pytest.mark.parametrize("per_layer", [64, 72]) # K = 128 (one full tile) and 144 (a partial last tile)
53
+ def test_rice_embedding_lookups(tmp_path, per_layer):
54
+ src = _tiny_gemma(tmp_path, per_layer)
55
+ out = tmp_path / "packed"
56
+ report = pack_model(src, out, log=lambda *_: None)
57
+ name = next(n for n in report["tensors"] if "embed_tokens_per_layer" in n)
58
+ orig = {i.name: i for i in st.list_tensors(src)}[name]
59
+ arrays = mx.load(str(out / "model.safetensors"))
60
+ emb = RiceEmbedding({p: arrays[f"{name}.{p}"] for p in packed_specs(out)[name]})
61
+ assert emb.K == 2 * per_layer and emb.N == 512
62
+ assert np.array_equal(_bits(emb.dense()), st.read(orig))
63
+ ids = mx.array([[3, 511, 0, 3], [77, 300, 42, 9]])
64
+ got = emb(ids)
65
+ assert got.shape == (2, 4, emb.K)
66
+ assert np.array_equal(_bits(got), st.read(orig)[np.array(ids)])
67
+
68
+
69
+ @pytest.mark.parametrize("version", ["1", "2"])
70
+ def test_model_with_ple_matches_bf16(tmp_path, version):
71
+ """Prompt pass and a decode step through the per-layer inputs are bit-identical; format 2
72
+ serves the table from RiceEmbedding, format 1 (no Rice stream) from R4Embedding."""
73
+ src = _tiny_gemma(tmp_path)
74
+ out = tmp_path / "packed"
75
+ report = pack_model(src, out, log=lambda *_: None, version=version)
76
+ assert any("embed_tokens_per_layer" in n for n in report["tensors"]) and "ple" in report["classes"]
77
+ ref, _ = load_model(src)
78
+ model, _ = load_packed_model(out)
79
+ convert(model)
80
+ kinds = [type(m).__name__ for _, m in model.named_modules()]
81
+ assert kinds.count("RiceEmbedding") == (1 if version == "2" else 0)
82
+ assert kinds.count("R4Embedding") == (1 if version == "2" else 2)
83
+
84
+ prompt = mx.array([[1, 5, 77, 300, 42, 511, 0, 9]])
85
+ ca, cb = make_prompt_cache(ref), make_prompt_cache(model)
86
+ a, b = ref(prompt, cache=ca), model(prompt, cache=cb)
87
+ mx.eval(a, b)
88
+ assert np.array_equal(_bits(a), _bits(b))
89
+ step = mx.array([[271]])
90
+ a, b = ref(step, cache=ca), model(step, cache=cb)
91
+ mx.eval(a, b)
92
+ assert np.array_equal(_bits(a), _bits(b))
93
+
94
+
95
+ def test_ple_left_out_when_not_requested(tmp_path):
96
+ src = _tiny_gemma(tmp_path)
97
+ out = tmp_path / "packed"
98
+ report = pack_model(src, out, classes=("linear", "embed"), log=lambda *_: None)
99
+ assert not any("embed_tokens_per_layer" in n for n in report["tensors"])
100
+ model, _ = load_packed_model(out)
101
+ convert(model)
102
+ assert "RiceEmbedding" not in [type(m).__name__ for _, m in model.named_modules()]
@@ -0,0 +1,56 @@
1
+ """binade serve: mlx_lm.server's model provider loads Binade packs onto the R4 runtime and stock
2
+ models as mlx-lm does."""
3
+
4
+ from argparse import Namespace
5
+
6
+ import mlx.core as mx
7
+ import numpy as np
8
+ from mlx_lm.generate import generate_step
9
+
10
+ from binade.mlx import serve
11
+ from binade.pack import pack_model
12
+ from test_runtime import _tiny_llama
13
+
14
+
15
+ def _with_tokenizer(src):
16
+ """A word-level tokenizer over the tiny model's 512-token vocabulary, so mlx-lm's loaders find one."""
17
+ from tokenizers import Tokenizer, models
18
+
19
+ Tokenizer(models.WordLevel(vocab={f"t{i}": i for i in range(512)}, unk_token="t0")).save(str(src / "tokenizer.json"))
20
+ (src / "tokenizer_config.json").write_text('{"eos_token": "t1", "model_max_length": 512}')
21
+ return src
22
+
23
+
24
+ def _provider(model):
25
+ import mlx_lm.server as server
26
+
27
+ server.load = serve.load
28
+ args = Namespace(model=str(model), adapter_path=None, draft_model=None, trust_remote_code=False, chat_template=None,
29
+ use_default_chat_template=False, pipeline=False)
30
+ return server.ModelProvider(args)
31
+
32
+
33
+ def test_provider_loads_pack_and_stock(tmp_path):
34
+ src = _with_tokenizer(_tiny_llama(tmp_path, True))
35
+ out = tmp_path / "packed"
36
+ pack_model(src, out, log=lambda *_: None)
37
+ p = _provider(out)
38
+ model, tok = p.load("default_model")
39
+ kinds = [type(m).__name__ for _, m in model.named_modules()]
40
+ assert "R4Linear" in kinds and "BinadeLinear" not in kinds
41
+ ref, _ = p.load(str(src)) # switching to the stock model by path
42
+ assert "R4Linear" not in [type(m).__name__ for _, m in ref.named_modules()]
43
+ prompt = mx.array([1, 5, 77, 300, 42, 511, 0, 9])
44
+ a = [int(t) for t, _ in generate_step(prompt, model, max_tokens=8)]
45
+ b = [int(t) for t, _ in generate_step(prompt, ref, max_tokens=8)]
46
+ assert a == b
47
+
48
+
49
+ def test_adapter_refused_on_pack(tmp_path):
50
+ import pytest
51
+
52
+ src = _tiny_llama(tmp_path, False)
53
+ out = tmp_path / "packed"
54
+ pack_model(src, out, log=lambda *_: None)
55
+ with pytest.raises(ValueError, match="adapters"):
56
+ serve.load(str(out), adapter_path=str(tmp_path))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes