Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable user-facing changes to MTPLX. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
[Semantic Versioning](https://semver.org/).

## [Unreleased]

### Added

- **8-bit verify matmuls of 12 to 32 rows reach MLX's tensor-unit (NAX) tile, behind `MTPLX_Q8_NAX_PAD=1` (off by default).** Stock MLX runs an 8-bit matmul of 7 to 12 rows on `qmv_wide` and, for narrow outputs (N = 5120 on Qwen3.8-27B: the GDN out-projection and the MLP down-projection of the 8-bit layers), 13 to 32 rows on the split-K tile, neither of which uses the tensor units; those two shapes then take 2.6 to 2.7 times their weight-read time. The lane appends zero rows (to 13 rows for wide outputs, 33 for narrow ones) so MLX picks `qmm_t_nax`, and slices the real rows back; shapes that already reach the NAX tile are left alone. Measured on an M5 Pro with Qwen3.8-27B Optimized-Speed: a verify forward of 12 to 25 rows is 4.6 to 5.4% faster at 32K context (6.4 to 7.5 ms) and 2.3 to 3.8% at 100K (5.0 to 7.2 ms); 4 to 10 rows are untouched. Results differ from stock by accumulation order only (per layer at most 7e-3 relative); on 26 real context-copy windows the expected accepted tokens per window are equal (4.825 against 4.825). `MTPLX_Q8_NAX_PAD_MIN_ROWS` moves the floor; the kernel self-check probes the lane.

## [2.12.2] - 2026-10-03

### Fixed
Expand Down
30 changes: 30 additions & 0 deletions mtplx/kernel_selfcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,27 @@ def _check_qmm_lane(mx, fn, m: int, bits: int, group_size: int, dtype) -> float:
return _max_abs_diff(mx, y, ref)


def _check_q8_nax_pad(mx, dtype) -> float:
"""The padded 8-bit lane at 13 rows (padded to 33) against stock at 13 rows.

N = 8192 is the narrowest width at K = 1024 where 13 rows stay on the split-K
tile and 33 rows reach the NAX tile, the case the lane exists for.
"""
from . import nax_verify

m, n, group_size = 13, 8192, 64
rows = nax_verify.q8_nax_pad_rows(m, _K, n, group_size)
if rows is None:
return float("inf")
w_q, scales, biases = _quantized_fixture(mx, _K, n, 8, group_size, dtype)
x = (mx.random.normal((m, _K), dtype=mx.float32) * 0.5).astype(dtype)
y = nax_verify.nax_qmm_q8_padded(x, w_q, scales, biases, rows=rows, group_size=group_size)
ref = _qmm_reference(mx, x, w_q, scales, biases, bits=8, group_size=group_size)
if tuple(y.shape) != tuple(ref.shape):
return float("inf")
return _max_abs_diff(mx, y, ref)


def _check_qwen_row_owned_router(mx, dtype) -> float:
"""Require bitwise stock routing for every installed M1-M16 row count."""

Expand Down Expand Up @@ -889,6 +910,15 @@ def _record(lane: str, tolerance: float, probe) -> None:
for lane in ("qmm_m4", "qmm_m4_wide", "qmm_m6", "qmm_m6_wide", "qmm_m16_nax"):
lanes[lane] = _STATUS_SKIPPED

if nax_on and nax_verify.q8_nax_pad_enabled():
# Opt-in padded 8-bit lane (MTPLX_Q8_NAX_PAD=1), probed whatever the
# model's main bit width: mixed models (Qwen3.8-27B Optimized-Speed)
# keep their GDN out-projections, last MLPs and lm_head at 8 bits.
if nax_verify.nax_available():
_record("qmm_q8_nax_pad", _QMM_TOLERANCE, lambda: _check_q8_nax_pad(mx, dtype))
else:
lanes["qmm_q8_nax_pad"] = _STATUS_SKIPPED

# lm_head_topk kernels exist but are not routed on the serve path.
lanes["lm_head_topk"] = _STATUS_SKIPPED

Expand Down
135 changes: 133 additions & 2 deletions mtplx/nax_verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
K % 32 == 0, N % 4 == 0.

MTPLX additions: M-padding dispatch (verify rows 2..16 pad to the 16-row NAX
tile; weight streaming dominates so padded rows are nearly free), env gating,
and availability probes. Exactness vs stock mx.quantized_matmul is enforced by
tile; weight streaming dominates so padded rows are nearly free), the same
padding for 8-bit verify rows onto MLX's own NAX tile (``MTPLX_Q8_NAX_PAD``,
default off, see ``q8_nax_pad_rows``), env gating, and availability probes.
Exactness vs stock mx.quantized_matmul is enforced by
the capture-commit/R1b gates before any product use.
"""

Expand Down Expand Up @@ -718,6 +720,111 @@ def nax_qmm_m16(
return y


def q8_nax_pad_enabled() -> bool:
"""Opt in to the padded 8-bit NAX lane (default off, read per call)."""
return str(os.environ.get("MTPLX_Q8_NAX_PAD", "")).strip().lower() in {
"1",
"true",
"on",
"yes",
}


# Rows from which the padded 8-bit lane engages by default. In the Qwen3.8-27B
# verify forward (M5 Pro) 9- and 10-row windows got 0.4 to 2.9% slower although
# the matmuls alone are faster, 12 rows and up 2 to 6% faster. From
# _Q8_NAX_PAD_TWO_TILE_MIN_ROWS a narrow shape pads to 33 rows (two 32-row tiles);
# see q8_nax_pad_rows.
_Q8_NAX_PAD_MIN_ROWS = 12
_Q8_NAX_PAD_TWO_TILE_MIN_ROWS = 9


def _q8_nax_pad_min_rows() -> int:
try:
return max(7, int(os.environ.get("MTPLX_Q8_NAX_PAD_MIN_ROWS", _Q8_NAX_PAD_MIN_ROWS)))
except ValueError:
return _Q8_NAX_PAD_MIN_ROWS


def _mlx_qmv_batch_limit(K: int, N: int) -> int:
"""MLX's ``get_qmv_batch_limit`` for a generation-17 GPU (not the ``d`` class)."""
if K <= 2048 and N <= 2048:
return 33
if K <= 4096 and N <= 4096:
return 25
return 13


def mlx_qmm_takes_nax(M: int, K: int, N: int, group_size: int) -> bool:
"""Whether MLX runs a transposed affine quantized matmul of M rows on its NAX tile.

Mirrors ``QuantizedMatmul::eval_gpu`` in MLX 0.32.2 to 0.32.4 for a 2-D weight on a
generation-17 GPU: below the qmv batch limit it takes ``qmv``/``qmv_wide``; from
there ``qmm_splitk``, which splits K whenever the 32x32 tile grid has 256 or fewer
threadgroups and only otherwise falls through to ``qmm``, which takes ``qmm_t_nax``
when K is a multiple of 64.
"""
if M < _mlx_qmv_batch_limit(K, N) or K % 64 != 0:
return False
tiles = ((N + 31) // 32) * ((M + 31) // 32)
split_k = max(1, 512 // tiles)
k_align = max(int(group_size), 32)
split_k = min(split_k, K // k_align)
while split_k > 1 and K % (split_k * k_align) != 0:
split_k -= 1
return split_k <= 1


def q8_nax_pad_rows(M: int, K: int, N: int, group_size: int) -> int | None:
"""Rows to pad an M-row 8-bit verify matmul to so MLX takes ``qmm_t_nax``, or None.

Between 7 and 32 rows stock MLX runs these shapes on ``qmv_wide`` (below 13 rows)
or on the split-K tile ``qmm_t_splitk`` (narrow N, such as the 5120-wide GDN
out-projection and MLP down of Qwen3.8-27B), neither of which uses the tensor
units; at 13 to 32 rows those two shapes take 2.6 to 2.7 times their weight-read
time. Zero rows appended to the input reach the NAX tile and read no more weight
bytes. Wide shapes pad to the qmv limit (13 rows, one 32-row tile); a narrow
shape needs 33 rows (two tiles), which costs more than ``qmv_wide`` below 9 rows
(M5 Pro, Qwen3.8-27B shapes: GDN out-projection 0.185 against 0.201 ms at 7 rows,
0.220 against 0.201 ms at 9). None where stock already takes the NAX tile (the
wide shapes from 13 rows) or where padding does not pay.
"""
if not 7 <= M <= 32:
return None
if mlx_qmm_takes_nax(M, K, N, group_size):
return None
rows = max(M, _mlx_qmv_batch_limit(K, N))
if rows <= 32 and mlx_qmm_takes_nax(rows, K, N, group_size):
return rows
if M >= _Q8_NAX_PAD_TWO_TILE_MIN_ROWS and mlx_qmm_takes_nax(33, K, N, group_size):
return 33
return None


def nax_qmm_q8_padded(
x2: mx.array,
w_q: mx.array,
scales: mx.array,
biases: mx.array,
*,
rows: int,
group_size: int = 64,
) -> mx.array:
"""Run an 8-bit verify matmul with x2 (M, K) padded to ``rows`` zero-filled rows."""
M = int(x2.shape[0])
pad = mx.zeros((int(rows) - M, int(x2.shape[1])), dtype=x2.dtype)
y = mx.quantized_matmul(
mx.concatenate([x2, pad], axis=0),
w_q,
scales=scales,
biases=biases,
transpose=True,
group_size=group_size,
bits=8,
)
return y[:M]


_QLINEAR_PATCH: dict[str, object] = {"installed": False, "original": None}

# F23b (2026-08-16): verify-shaped QuantizedLinear calls that entered the
Expand Down Expand Up @@ -832,6 +939,30 @@ def patched(self, x: mx.array) -> mx.array: # type: ignore[no-untyped-def]
y = y + self["bias"]
return y
_count_qlinear_fallback(bits, m)
elif (
_q8_nax_pad_min_rows() <= m <= 32
and q8_nax_pad_enabled()
and not lane_disabled("qmm_q8_nax_pad")
and x.dtype in (mx.bfloat16, mx.float16)
and getattr(self, "mode", "affine") == "affine"
and nax_available()
):
# Wide verify windows (context-copy blocks), opt-in
# (MTPLX_Q8_NAX_PAD=1): zero rows take stock MLX to its NAX
# tile where it would run qmv_wide or the split-K tile.
w_q = self["weight"]
k = int(x.shape[-1])
n = int(w_q.shape[0])
rows = q8_nax_pad_rows(m, k, n, group_size)
if rows is not None:
y = nax_qmm_q8_padded(
x.reshape(m, k), w_q, self["scales"], self["biases"],
rows=rows, group_size=group_size,
)
y = y.reshape(*x.shape[:-1], n)
if "bias" in self:
y = y + self["bias"]
return y
if bits == 6 and x.ndim >= 2 and current_attention_phase() != "prefill":
# 6-bit affine (9B tier), added 2026-07-07: split-K hexpack
# kernels, exactness-gated vs stock across {bf16,fp16} x
Expand Down
26 changes: 26 additions & 0 deletions tests/test_kernel_selfcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,29 @@ def test_health_payload_before_any_run_is_safe() -> None:
payload = report_for_health()
assert payload == {"ran": False}
json.dumps(payload)


def test_q8_nax_pad_lane_is_probed_for_any_model_bits(monkeypatch) -> None:
"""MTPLX_Q8_NAX_PAD adds its own probe, also for a 4-bit model (mixed
models keep 8-bit layers); a corrupted lane falls back and stops routing."""
monkeypatch.setenv("MTPLX_NAX_VERIFY", "1")
monkeypatch.delenv("MTPLX_Q8_NAX_PAD", raising=False)
report = run_kernel_selfcheck(mx.bfloat16, 4, 64)
assert "qmm_q8_nax_pad" not in report["lanes"]

monkeypatch.setenv("MTPLX_Q8_NAX_PAD", "1")
report = run_kernel_selfcheck(mx.bfloat16, 4, 64)
expect = "ok" if nax_verify.nax_available() else "skipped"
assert report["lanes"]["qmm_q8_nax_pad"] == expect
if not nax_verify.nax_available():
return
original = nax_verify.nax_qmm_q8_padded

def corrupted(*a, **k):
return original(*a, **k) + 1000.0

monkeypatch.setattr(nax_verify, "nax_qmm_q8_padded", corrupted)
report = run_kernel_selfcheck(mx.bfloat16, 4, 64)
assert report["lanes"]["qmm_q8_nax_pad"] == "fallback"
assert lane_disabled("qmm_q8_nax_pad")
assert report_for_health()["qmm_q8_nax_pad"] == "fallback"
115 changes: 115 additions & 0 deletions tests/test_nax_verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,118 @@ def test_m5_falls_through_to_stock_by_default(monkeypatch) -> None:
assert mx.array_equal(y, ref), "M=5 default must be the stock result"
finally:
uninstall_nax_qlinear_patch()


def test_q8_nax_pad_rows_follow_the_mlx_dispatch() -> None:
"""The padded 8-bit lane pads only where stock MLX misses its NAX tile
(Qwen3.8-27B 8-bit shapes, group size 64)."""
from mtplx.nax_verify import mlx_qmm_takes_nax, q8_nax_pad_rows

gdn_out, mlp_down, gate_up, lm_head = (6144, 5120), (17408, 5120), (5120, 17408), (5120, 248320)
# Narrow N: split-K tile from 13 rows; 33 rows (two 32-row tile rows) reach NAX.
for k, n in (gdn_out, mlp_down):
for m in (13, 17, 25, 32):
assert not mlx_qmm_takes_nax(m, k, n, 64)
assert q8_nax_pad_rows(m, k, n, 64) == 33
assert mlx_qmm_takes_nax(33, k, n, 64)
# Two tiles cost more than qmv_wide below 9 rows: stock there.
assert q8_nax_pad_rows(9, k, n, 64) == 33
assert q8_nax_pad_rows(8, k, n, 64) is None
# Wide N: stock already takes NAX from 13 rows, qmv_wide below.
for k, n in (gate_up, lm_head):
for m in (13, 17, 25, 32):
assert mlx_qmm_takes_nax(m, k, n, 64)
assert q8_nax_pad_rows(m, k, n, 64) is None
for m in (7, 9, 12):
assert q8_nax_pad_rows(m, k, n, 64) == 13
# Outside 7..32 rows and K not a multiple of 64: never padded.
for m in (4, 6, 33, 64):
assert q8_nax_pad_rows(m, *gdn_out, 64) is None
assert q8_nax_pad_rows(13, 6144 + 32, 5120, 32) is None


def _q8_layer(K: int, N: int):
mx.random.seed(5)
layer = nn.QuantizedLinear(K, N, bias=False, group_size=64, bits=8)
layer.weight, layer.scales, layer.biases = mx.quantize(
(mx.random.normal((N, K), dtype=mx.float32) * 0.02).astype(mx.bfloat16), group_size=64, bits=8
)
mx.eval(layer.parameters())
return layer


def _q8_stock(layer, x):
return mx.quantized_matmul(
x, layer["weight"], scales=layer["scales"], biases=layer["biases"],
transpose=True, group_size=64, bits=8,
)


def test_q8_nax_pad_is_off_by_default(monkeypatch) -> None:
from mtplx import nax_verify
from mtplx.attention_context import attention_phase

monkeypatch.delenv("MTPLX_Q8_NAX_PAD", raising=False)
calls = {"n": 0}
original = nax_verify.nax_qmm_q8_padded

def counting(*a, **k):
calls["n"] += 1
return original(*a, **k)

monkeypatch.setattr(nax_verify, "nax_qmm_q8_padded", counting)
report = install_nax_qlinear_patch()
assert report["installed"] is True
try:
layer = _q8_layer(1024, 8192)
x = (mx.random.normal((13, 1024), dtype=mx.float32) * 0.5).astype(mx.bfloat16)
with attention_phase("decode_verify"):
y = layer(x)
assert calls["n"] == 0
assert mx.array_equal(y, _q8_stock(layer, x)), "switch off must give the stock result"
finally:
uninstall_nax_qlinear_patch()


@pytest.mark.skipif(not nax_available(), reason="requires Apple G17 + macOS >= 26.2")
def test_q8_nax_pad_routes_wide_verify_rows_only(monkeypatch) -> None:
"""With the switch on, 13 verify rows of a split-K shape take the padded
lane and stay within the qmm tolerance of stock; prefill, rows below the
floor and shapes that already reach NAX stay stock bit for bit."""
from mtplx import nax_verify
from mtplx.attention_context import attention_phase

monkeypatch.setenv("MTPLX_Q8_NAX_PAD", "1")
calls = {"n": 0}
original = nax_verify.nax_qmm_q8_padded

def counting(*a, **k):
calls["n"] += 1
return original(*a, **k)

monkeypatch.setattr(nax_verify, "nax_qmm_q8_padded", counting)
report = install_nax_qlinear_patch()
assert report["installed"] is True
try:
layer = _q8_layer(1024, 8192)
x = (mx.random.normal((1, 13, 1024), dtype=mx.float32) * 0.5).astype(mx.bfloat16)
ref = _q8_stock(layer, x)
with attention_phase("decode_verify"):
y = layer(x)
assert calls["n"] == 1
assert y.shape == (1, 13, 8192)
diff = float(mx.abs(y.astype(mx.float32) - ref.astype(mx.float32)).max())
assert diff < 0.1, f"padded 8-bit lane drift too large: {diff}"
with attention_phase("prefill"):
assert mx.array_equal(layer(x), ref)
assert calls["n"] == 1, "prefill took the padded lane"
wide = _q8_layer(1024, 16384) # 13 rows already reach NAX here
with attention_phase("decode_verify"):
assert mx.array_equal(wide(x), _q8_stock(wide, x))
assert calls["n"] == 1
monkeypatch.setenv("MTPLX_Q8_NAX_PAD_MIN_ROWS", "14")
with attention_phase("decode_verify"):
assert mx.array_equal(layer(x), ref)
assert calls["n"] == 1, "rows below MTPLX_Q8_NAX_PAD_MIN_ROWS took the padded lane"
finally:
uninstall_nax_qlinear_patch()
Loading