Repository navigation
Add 1-bit affine quantization support (Metal) - #3161
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adds 1-bit affine quantization support to MLX, extending the existing quantization framework from {2, 3, 4, 5, 6, 8} bits to include 1-bit. The implementation provides efficient packing and inference for 1-bit quantized weights on Apple Silicon (Metal) and CPU backends.
Changes:
- Added 1-bit support to affine quantization with formula:
scale = w_max - w_min,bias = w_minwhere bit 0 → w_min, bit 1 → w_max - Implemented full Metal kernel support for 1-bit in both NAX and non-NAX paths across all quantized operations (quantize, dequantize, qmm, qmv)
- Extended CPU backend with 1-bit quantization, dequantization, and quantized matmul dispatch
- Added comprehensive test coverage for 1-bit symmetric/asymmetric weights, zero handling, and quantized matmul correctness
- Updated Python bindings documentation and validation to accept bits=1
- Added 1-bit benchmark entries for performance comparison across different group sizes
- Excluded CUDA backend from 1-bit support (added to cuda_skip.py)
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
python/tests/test_quantized.py |
Added 1-bit to existing parameterized tests and new dedicated test_1bit_quantize_dequantize with symmetric/asymmetric weights, zero handling, and qmm/qmv correctness tests |
python/tests/cuda_skip.py |
Added 1-bit test to CUDA skip list since CUDA backend doesn't support 1-bit |
python/src/ops.cpp |
Updated quantization mode documentation table to include 1-bit in supported bits |
mlx/ops.cpp |
Modified validation to accept bits >= 1 and added 1-bit quantization formula (scale = w_max - w_min, bias = w_min) |
mlx/backend/metal/kernels/quantized_nax.metal |
Added 1-bit kernel instantiation macro for NAX path |
mlx/backend/metal/kernels/quantized_nax.h |
Implemented 1-bit versions of load_vector, load_vector_safe, qdot, qdot_safe, qouter, and dequantize for NAX optimized kernels |
mlx/backend/metal/kernels/quantized.metal |
Added 1-bit kernel instantiation macro and quantize/dequantize logic for non-NAX path |
mlx/backend/metal/kernels/quantized.h |
Implemented 1-bit versions of all quantization primitives for non-NAX kernels |
mlx/backend/cpu/quantized.cpp |
Added 1-bit case to qmm dispatch and quantization logic matching Metal implementation |
benchmarks/python/comparative/compare.py |
Added compare_mlx_quant function and 1-bit benchmark entries for qmv and qmm paths |
benchmarks/python/comparative/bench_mlx.py |
Added 1-bit entries to quant_matmul dictionary for all group sizes and transpose modes, plus auto-quantization logic |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Hi @khosravipasha that is pretty cool. I am not sure we want to support 1-bit quants natively in MLX, even 2 bits are not really used out there. The options I see are:
|
|
@angeloskath Thanks for the comment, we actually do have a native 1-bit modelx just released today, so would be amazing to have it in the official mlx repo. Sorry for delayed response, we were waiting to come out of stealth before resending the PR. Checkout our launch: https://huggingface.co/prism-ml I made a few changes I will send a the fresh code in a bit, we also have changes on mlx-swift for iPhones. |
3155f5c to
644a8cd
Compare
angeloskath
left a comment
There was a problem hiding this comment.
Did a first pass and left some comments.
The main one is on the change in qmv_fast and why it is needed it isn't clear from the PR.
There is also linter errors and so on. But let's fix these and get it merged.
|
Thanks for the feedback, addressed the easy ones, the main one is to figure out a good way to handle qmv_fast changes (4B model has shapes that are not divisible by 2028 nor 1024, that causes block_size for loops to have some left overs; see detail in the comment) Had a question about NAX vs non-NAX, is there something special need to do, not too familiar what their difference is, I mainly tested in Mac M4 Pro. Want to make sure works well on older Mac (M1-M3). |
NAX refers to the neural accelerators for M5. I can run some benchmarks. There isn't anything overly special per se, just the matmuls are faster so we need to make sure we can keep feeding the NAX quickly enough so dequantizing should be efficient. There could be a lot of room for tuning this but let's get something working that isn't too far from bf16 for a largeish matrix and we should be good to go. |
I see thanks, yeah more neural chips on M5 chips seems exciting from what I have read, have not had a chance to try them yet myself. For now mostly care about correctness, and not being very slow. Definetly can be tuned, I saw Ivan ran speed benchmarks with M5 Max already, looks very fast |
Point at PrismML-Eng/mlx@prism which adds 1-bit affine quantization Metal kernels, enabling Bonsai-8B-mlx-1bit (1.2 GB Qwen3-8B) to run locally on Apple Silicon. Temporary pin until ml-explore/mlx#3161 merges upstream. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Based on upstream mlx-lm HEAD (Gemma 4, BatchGenerator refactor). Points mlx dep at PrismML-Eng/mlx@prism for 1-bit affine quantization Metal kernels. Enables Bonsai-8B-mlx-1bit locally. Temporary pin until ml-explore/mlx#3161 merges upstream. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
@angeloskath did you got a chance to do another pass. Was not sure which path for the extra epilogue is good to do. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
nice what made it faster? above comment is the only thing I see (other comments might still be in draft?) fixed the merge conflict in the last push and merged with a more recent main (skip_cuda was removed and is now inline so made the change for 1-bit to skip cuda unit tests) |
|
Tested on M1 (8GB, macOS 26.5), source build from this branch. CPU backend looks good — 29/29 tests pass and I cross-checked quantize/dequantize/quantized_matmul against an independent numpy reference implementation, all match exactly (max|Δ|=0) across gs={32,64,128} with various weight distributions. On Metal I found an issue with 1-bit + gs=32. The PR tests don't catch this because they use binary-valued weights that happen to work at gs=32. It shows up with continuous (e.g. gaussian) weights. Root cause is in constexpr int packs_per_thread = bits == 2 ? 1 : 2;For bits=1: Changing it to This is related to the block size discussion above — with Reproducer (before fix): import mlx.core as mx, numpy as np
w = mx.array(np.random.default_rng(42).standard_normal((128, 512)).astype(np.float32) * 0.1)
x = mx.random.normal(shape=(1, 512))
wq, s, b = mx.quantize(w, group_size=32, bits=1)
y_q = mx.quantized_matmul(x, wq, s, b, True, 32, 1)
y_ref = x @ mx.dequantize(wq, s, b, 32, 1).T
mx.eval(y_q, y_ref)
print(float(mx.abs(y_q - y_ref).max().item())) # ~14.8, should be ~1e-6 |
|
@seongyun1104 |
|
Yes, just the one line: - constexpr int packs_per_thread = bits == 2 ? 1 : 2;
+ constexpr int packs_per_thread = bits <= 2 ? 1 : 2;For end-to-end check, a Happy to verify on M1 if useful. |
affine qmv_fast set packs_per_thread=2 for all bits except 2-bit, so 1-bit got values_per_thread=64 (x_thread[64], ~256B/thread) -> low occupancy -> 1-bit decode saturates only ~75% of M5 DRAM BW vs ~90/96% for 2/4-bit. Use 1 pack/thread for bits<=2 (values_per_thread=32), matching 2-bit's register footprint. Measured on M5 Pro (distinct-weight DRAM-bound, 2-bit as drift control): 1-bit 24.0 -> 21.9 us/matvec (~9%, 75->82% BW), 2-bit control 33.2->32.9 (0.8% drift); correct, rel_err 2.7e-4. Also makes scale_step_per_thread (=group_size/values_per_thread) well-defined for group_size=32 at 1-bit.
|
@seongyun1104 thanks for the pointer, pushed the fix into this PR branch, also seems to get some speed up for some cases. @angeloskath |
|
@khosravipasha Thanks for picking it up — nice surprise that it nets a speedup in some cases too. |
Adds a weekly GitHub Actions workflow that tracks the upstream work needed before the PrismML mlx-swift fork can be dropped (ml-explore/mlx#3161 and the downstream mlx-swift / mlx-swift-lm releases). It maintains a single tracking issue with a per-gate checklist and @mentions the repo owner the first time the core PR is merged. Runs on a Monday cron and on manual workflow_dispatch. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H6LPADC2GJKEDPZivAx4Hb
zcbenz
left a comment
There was a problem hiding this comment.
Thanks for keeping the PR updated!
btw in future please consider creating PRs from personal accounts, it is not possible for us to push to or rebase branch in org account even when you enable the option on GitHub.
| y_q = mx.quantized_matmul(x, w_q, scales, biases, True, gs, 1) | ||
| y_hat = x @ w_hat.T | ||
| self.assertEqual(y_q.shape, y_hat.shape) | ||
| self.assertLess((y_q - y_hat).abs().max(), 1e-5) |
There was a problem hiding this comment.
This fails on Windows CPU build with array(0.00, dtype=float32) not less than 1e-05, seems to be bug of MLX, maybe try:
| self.assertLess((y_q - y_hat).abs().max(), 1e-5) | |
| self.assertLess((y_q - y_hat).abs().max().item(), 1e-5) |
|
@zcbenz Thanks for the review, we will take a look.
Oh did not know that, this was my personal account when I initially submitted the PR, but I guess the fork needs to be in a personal account too |
|
@zcbenz Thanks for the review! We merged the latest Metal quantization tests and the affected Mac CPU tests pass. Windows/CUDA still need CI rerun to confirm its all good. Quick M5 Max benchmarks, measured before the upstream merge: 512 prompt tokens, 128 generated tokens, three runs after warmup.
|
| y_q = mx.quantized_matmul(x, w_q, scales, biases, True, gs, 1) | ||
| y_hat = x @ w_hat.T | ||
| self.assertEqual(y_q.shape, y_hat.shape) | ||
| self.assertLess((y_q - y_hat).abs().max().item(), 1e-5) |
There was a problem hiding this comment.
Can you try setting error to 2e-5 for Windows?
FAIL: test_1bit_quantize_dequantize (test_quantized.TestQuantized.test_1bit_quantize_dequantize) (gs=32, case='quantized_matmul_asymmetric')
Test 1-bit affine quantization.
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\a\mlx\mlx\python\tests\test_quantized.py", line 320, in test_1bit_quantize_dequantize
self.assertLess((y_q - y_hat).abs().max().item(), 1e-5)
AssertionError: 1.1444091796875e-05 not less than 1e-05
There was a problem hiding this comment.
hmm curious why this happens only on Window, added these two lines
tol = 2e-5 if platform.system() == "Windows" else 1e-5
self.assertLess((y_q - y_hat).abs().max().item(), tol)
There was a problem hiding this comment.
Some CPU ops are probably having precision issues on Windows.

Add 1-bit affine quantization support (Metal)
Proposed changes
This PR adds 1-bit support to MLX's affine quantization mode, extending the supported bit-widths from
{2, 3, 4, 5, 6, 8}to{1, 2, 3, 4, 5, 6, 8}.MLX already supports affine quantization at 2, 3, 4, 5, 6, and 8 bits via
w_hat = scale * w_q + bias. This PR extends that same framework to 1-bit, adding full kernel support for 1-bit affine dequantization and quantized matmul across CPU and Metal backends.This assumes the model has already been quantized externally (e.g. during training) — the contribution here is efficient packing and inference on Apple Silicon. It supports packing for both affine and symmetric 1-bit weights:
Affine 1-bit — weights have arbitrary per-group min/max:
Symmetric 1-bit — weights are
{-d, +d}per group, automatically handled by the affine formula above sincew_min = -d, w_max = +d:A dedicated symmetric 1-bit mode (scale only, no bias) could save memory and skip the bias addition in the matmul kernels, but for now both cases run through the same affine path.
What's included
qmmdispatch)quantized.h) and NAX (quantized_nax.h,quantized_nax.metal) paths, plus quantize/dequantize kernelsmx.quantize(w, bits=1),mx.dequantize(...), andmx.quantized_matmul(...)documentationtest_quantize_dequantize,test_qmm, and a dedicatedtest_1bit_quantize_dequantizecovering round-trip accuracy, zero handling, and quantized matmul correctness. Full test suite passes (672 tests, 0 failures).dispatch_bitsdoes not include acase 1:path. The new 1-bit test is added tocuda_skip.py.Expected model-level performance (hypothetical, 8B parameter model, Apple M4 Pro 48 GB)
Based on the kernel-level benchmarks below, a hypothetical 8B parameter model at 1-bit would see roughly (varying by group size due to scale/bias metadata overhead):
We verified one scenario (group size 128, all weights quantized) and observed throughput in the ballpark of the estimates above. The primary purpose of this table is to give a sense of the runtime speed that 1-bit quantization enables. These are back-of-the-envelope numbers — actual end-to-end performance will vary depending on which layers are quantized, group size, attention overhead, and other non-quantized computation.
Kernel Corretness validation (KL divergence, 8B parameter model, WikiText-2)
To validate matmul kernel correctness, we compared two runs of the same 1-bit quantized model: one using the quantized matmul kernels (weights stay packed in 1-bit), and the other with the 1-bit weights dequantized to FP16 first and run through standard FP16 matmul. This is not a comparison between an FP16 model and its quantized version — both sides use identical weight values, so any divergence would indicate a kernel bug. Both the prompt processing (qmm) and token generation (qmv) paths were tested.
Prompt processing (qmm path) — 20 WikiText-2 chunks:
Token generation (qmv path) — 113 autoregressive steps (single-token qmv) across 5 prompts:
Both forward and reverse KL are near-zero, confirming the quantized kernels produce results consistent with the dequantized FP16 reference in both qmm and qmv code paths.
Changes
mlx/backend/cpu/quantized.cpp- 1-bit quantization logic andqmmdispatchmlx/backend/metal/kernels/quantized.h- Metal 1-bitload_vector,qdot,qdot_safe,qouter,dequantizemlx/backend/metal/kernels/quantized_nax.h- Same for NAX kernelsmlx/ops.cpp- Validation to acceptbits=1python/src/ops.cpp- Updated docstring tablepython/tests/test_quantized.py- Added 1-bit to existing tests + dedicated 1-bit testpython/tests/cuda_skip.py- Skip 1-bit test on CUDAbenchmarks/python/comparative/bench_mlx.py- Added 1-bit entries toquant_matmuldict; auto-quantizes weight from--sizeargsbenchmarks/python/comparative/compare.py- Addedquant_matmulbenchmark entries comparing 1/2/4/8-bit across qmv and qmm pathsNotes
The Metal
qmv_quad_implkernel has a minor edge case with 1-bit when the inner dimension is < 128. In practice this should never come up — virtually all models have dimensions well above 128.If all weights in a group are exactly 0, the affine 1-bit quantization computes
scale = eps(floored) andbias = 0, which dequantizes all values to near-zero (correct behavior).Kernel-level
quantized_matmulbenchmarks (Apple M4 Pro 48 GB, GPU, NAX path,group_size=128, 1000 calls, weight shape in parentheses):qmv path (M=1, single-token generation, memory-bandwidth bound):
qmm path (M=32, prompt processing, more compute-bound):
1-bit entries have been added to
benchmarks/python/comparative/bench_mlx.pyandcompare.py. To reproduce (from repo root):Questions for reviewers
NAX vs non-NAX testing: All benchmarks and the full test suite were run on macOS 26.2 (M4 Pro 48 GB), where NAX is active. The non-NAX path was partially validated by rebuilding with
-DCMAKE_CXX_FLAGS=-DMLX_METAL_NO_NAX— unit tests pass, but full benchmarking was only done on the NAX path. We only have access to an M4. Is the-DMLX_METAL_NO_NAXbuild flag sufficient to validate the non-NAX path, or would you recommend testing on actual older hardware (M1/M2/M3)?Test coverage: The full test suite passes (672 tests, 0 failures), including dedicated 1-bit tests for both symmetric and asymmetric weight round-trip accuracy, zero handling, and quantized matmul correctness across both qmm and qmv paths. Is there any additional testing you'd like to see before merging?
Future work
Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes