mlx-kquant
Bring K-quant precision to MLX on Apple Silicon: a C++/Metal
extension for a stock mlx wheel that adds the K-quant superblock and per-block integer codecs
as native MLX ops, plus a toolchain that quantizes a model into a K-quant MLX safetensors
checkpoint and runs, LoRA-trains, and fuses it.
Two layers:
- Ops (C++/Metal) - a
kq.* namespace (dequantize, quantized_matmul, gather_qmm,
quantize) backed by Metal kernels compiled to a .metallib at build time (no runtime JIT). All
ten K-quant/legacy codecs: q2_k, q3_k, q4_k, q5_k, q6_k and q4_0, q4_1, q5_0, q5_1, q8_0, plus
nine IQ codecs
(iq4_nl, iq4_xs, iq3_s, iq3_xxs, iq2_xxs, iq2_xs, iq2_s, iq1_s, iq1_m), plus the QAT
structured-sparse ternary codec stq1_0 and the two PrismML Ternary Bonsai codecs pq2_0, ptq1_0
(ggml types 142 and 143, private to the PrismML llama.cpp fork, so the ids may change), plus the
four-level 2-bit codec q2_0 - all
twenty-three decode, matmul (incl. tensor-core prefill), and encode (IQ, stq1_0, Prism and q2_0
encode is CPU-only) - plus the native-fp wire
codecs mxfp4, nvfp4 (decode, CPU NEON + Metal matmul incl. tensor-core prefill, and the fused
MoE family incl. biased gpt-oss experts; no encoder - GGUFs ship these tensors pre-quantized) -
plus mxfp8, a
gather-only codec for lookup tables (CPU and Metal dequantize of gathered rows, no matmul; see
GGML type 43). On top of these four core
ops the namespace also carries fused decode/prefill kernels (MoE GLU and router, attention, norm
fusions) and a set of DeepSeek/GLM sparse-attention kernels - see
docs/kernels.md.
- Tooling (Python) -
mlx-kquant quantize / run / chat / lora / fuse (plus verify, inspect,
calibrate-imatrix) and a loader that create and run K-quant checkpoints in MLX-native
safetensors format.
Why
K-quants have roughly half the divergence vs. affine quants at the same bitrate (as measured by KLD).
| Model |
Budget |
MLX affine |
K-quant |
Divergence cut |
| Qwen3.6-27B |
4-bit |
0.0577 @ 4.69 bpw |
Q4_K_M 0.0208 @ 4.88 bpw |
2.8× |
| Qwen3.6-27B |
5-bit |
0.0214 @ 5.68 bpw |
Q5_K_M 0.0096 @ 5.73 bpw |
2.2× |
| gemma-4-E2B |
4-bit |
1.2254 @ 5.76 bpw |
Q4_K_M 0.6657 @ 5.77 bpw |
1.8× |
| gemma-4-E2B |
5-bit |
0.4979 @ 6.67 bpw |
Q5_K_XL 0.2316 @ 6.67 bpw |
2.2× |
mlx-kquant brings them to the MLX ecosystem with tuned Metal kernels. Quantize an MLX safetensors model
to a uniform- or mixed-precision K-quant checkpoint, then load, generate, LoRA-train, and fuse it
on a stock mlx wheel.
Install
macOS 26.2 (Tahoe) or later on Apple Silicon. Prebuilt wheels (CPython 3.11-3.14):
pip install mlx-kquant # the K-quant ops + precompiled metallib
pip install "mlx-kquant[tools]" # the CLI (quantize / run / chat / lora / fuse)
Either pulls the ABI-matched mlx==0.32.3 automatically.
From source (or to develop) needs the Metal toolchain (xcrun metal); the metallib compiles at
install time, no runtime JIT:
git clone https://github.com/asher/mlx-kquant && cd mlx-kquant
pip install "mlx==0.32.3" # pinned, ABI-matched stock wheel (pulls the Metal backend)
pip install -e ".[tools]" # builds _ext + mlx_kquant.metallib; adds mlx-lm for the CLI
Linux (CPU-only) also builds, with no Metal toolchain. The ops run on their portable eval_cpu
paths and no metallib is produced. (The tuned matmul/gather are Apple-Silicon-targeted: arm64 Linux
picks up the NEON int8 GEMV when the CPU has dot-product, but the Accelerate GEMM is Apple-only, and
x86_64 stays on the scalar/threaded path.) The base mlx wheel ships no backend on Linux, so
install the CPU one explicitly:
pip install "mlx[cpu]==0.32.3" # base frontend + libmlx CPU backend
pip install -e . --no-build-isolation
CPU is for portability and CI, not throughput. Running a full model forward on Linux also needs
MLX_DISABLE_COMPILE=1, see Limitations.
Smoke-test the toolchain:
import mlx_kquant as kq
kq.codecs() # -> ['q2_k', 'q3_k', ..., 'q8_0']
kq.metallib_loads() # -> True (the bundled metallib opened on the Metal device)
The extension links libmlx and its kernels #include MLX's steel-GEMM headers, so it is bound to
an exact MLX ABI and header API. The pin is intentionally ==, never >=; moving to a newer
mlx may require updating the bundled headers and recompiling. See Version pinning.
Quickstart
Quantize a checkpoint and run it, load it through mlx-lm, fine-tune it with LoRA, or build directly on
the kq.* ops.
Create and run a checkpoint
The CLI (the [tools] extra adds mlx-lm) quantizes an HF / mlx-lm model into a K-quant MLX
safetensors checkpoint and runs it:
pip install "mlx-kquant[tools]"
mlx-kquant quantize --model Qwen/Qwen3-0.6B --preset q4_k_m --mlx-path qwen3-q4
mlx-kquant run --model qwen3-q4 --prompt "Explain entropy in one sentence."
mlx-kquant chat --model qwen3-q4 --temp 0.7 # interactive REPL (mlx-lm chat)
run takes the usual sampling knobs (--temp, --top-p, --top-k, --min-p, --seed,
--repetition-penalty, --presence-penalty, --frequency-penalty) and chat-template controls
(--system-prompt, --no-chat-template, --chat-template-config for template kwargs such as
'{"enable_thinking": false}'). The chat REPL has a line-editable prompt with persistent
history (--no-history or in-chat /history off|on|clear to control it) and in-chat sampling
control (/temp, /top-p, /top-k, /min-p, /max-tokens, and the three penalties;
/sampling shows current values); /load <file> prefills the next prompt from a text file for
editing; /clear resets the conversation and wipes the screen; Tab completes /commands and
paths; Ctrl-C cancels the in-flight reply (at an idle
prompt it exits, as does Ctrl-D). --max-kv-size bounds the KV cache for long sessions (a rotating
window, set at start).
The result is a standard MLX checkpoint (config.json + sharded safetensors, weights as K-quant wire
bytes). Load it in code with the bundled loader:
import mlx.core as mx
from mlx_kquant.loader import load
model, config = load("qwen3-q4") # KQuant* layers swapped in, on a stock mlx-lm model
mx.eval(model(mx.array([[1, 2, 3]])))
mlx-kquant lora (train an adapter) and mlx-kquant fuse (merge it back) round out the toolchain -
see LoRA fine-tuning. Run mlx-kquant --help for every subcommand.
Using with mlx-lm
In-process, a kquant checkpoint also loads through stock mlx-lm: one idempotent call installs the
load shim, and from then on mlx_lm.load / mlx_lm.generate (and anything built on
mlx_lm.utils.load_model, e.g. an eval harness or your own serving loop) open a kquant checkpoint
transparently:
from mlx_kquant.mlx_lm_patch import patch_mlx_lm_load
patch_mlx_lm_load() # process-wide, idempotent; call once before mlx_lm.load
from mlx_lm import load, generate
model, tokenizer = load("qwen3-q4")
print(generate(model, tokenizer, "Explain entropy.", max_tokens=64))
This is the load-only shim for inference / eval / serving; patch_mlx_lm_lora()
(below) adds the train/merge shims on top. The bundled mlx_kquant.loader.load
(above) is the standalone path when you don't need the rest of mlx-lm.
LoRA fine-tuning
A kquant checkpoint is a frozen base you can adapt with LoRA. Attach an adapter for inference, train
one (the matmul/gather ops define a gradient-through-the-base vjp, so the adapter is differentiable
while the quantized weights stay frozen), and merge it back with mlx-kquant fuse (re-encode to
kquant, or --dequantize to float). One call wires it into stock mlx-lm:
from mlx_kquant.mlx_lm_patch import patch_mlx_lm_lora
patch_mlx_lm_lora() # before building LoRA layers / loading adapters; idempotent
See docs/lora.md for attach / train / merge workflows. (DoRA on a kquant base is
not supported - use LoRA.)
Using K-quant ops directly
Under the toolchain, the four kq.* ops operate on raw K-quant wire bytes. K-quant scales live
inside the packed bytes, so the scales argument is a vestigial placeholder (the API keeps it for
shape symmetry with MLX's affine quant); kq.quantize returns one for you.
import mlx.core as mx
import mlx_kquant as kq
N, K = 256, 512 # q4_k: K must be a multiple of 256
w = mx.random.normal((N, K))
# encode float -> K-quant wire bytes (CPU or Metal); optional imatrix steers the encoder
wq, scales = kq.quantize(w, "q4_k") # wq: uint8 [N, bytes_per_row]
# dequantize back to float
deq = kq.dequantize(wq, scales, "q4_k") # float16 [N, K]
# quantized matmul: x @ dequant(w).T (transpose=True => w is [N, K])
x = mx.random.normal((8, K))
y = kq.quantized_matmul(x, wq, scales, "q4_k", transpose=True) # [8, N]
Mixture-of-experts (gathered) matmul:
E, N, K = 128, 704, 2816
we = mx.random.normal((E, N, K))
weq, sc = kq.quantize(we, "q4_k") # per-expert wire bytes
x = mx.random.normal((1, 8, K)) # (tokens, top_k, K)
idx = mx.array([[0, 5, 9, 17, 33, 41, 88, 120]], dtype=mx.uint32)
out = kq.gather_qmm(x, weq, sc, "q4_k", rhs_indices=idx, transpose=True)
Ready-made modules that store the wire bytes and dispatch the matching kq.* op ship in
mlx_kquant.nn:
from mlx_kquant.nn import KQuantLinear, KQuantEmbedding, KQuantSwitchLinear
x = mx.random.normal((8, 512)) # a (tokens, in_dims) activation batch
lin = KQuantLinear(in_dims=512, out_dims=256, bias=False, codec="q4_k")
lin.weight = wq # the uint8 wire bytes from kq.quantize, above
lin.scales = scales # [1] placeholder (scales live in the bytes)
y = lin(x) # kq.quantized_matmul under the hood
KQuantEmbedding (with a tied-as_linear), the gather_qmm-backed KQuantSwitchLinear for MoE
experts, and KQuantMultiLinear