Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -1566,8 +1566,7 @@ def __call__(self, x):
and self.n_group == 1
):
# One token: the reference logits come from the one-row fp32
# gemv, which the fused router reproduces (multi-row calls use
# a different matmul and keep the reference path).
# gemv, which the fused router reproduces.
routed = _decode_kernels.moe_router(
x.reshape(1, -1),
self.weight,
Expand All @@ -1586,9 +1585,10 @@ def __call__(self, x):
and 2 <= x.shape[1] <= _DECODE_BLOCK
and self.n_group == 1
):
# Verify block: the reference logits come from MLX's NAX split-K
# GEMM, which moe_router_rows reproduces op for op.
routed = _decode_kernels.moe_router_rows(
# Verify rows use the one-token fp32 GEMV arithmetic, so each
# row gets the routing its decode step computes. The stock
# block GEMM uses TF32 on NAX and can give different routes.
routed = _decode_kernels.moe_router(
x.reshape(x.shape[1], -1),
self.weight,
self.e_score_correction_bias,
Expand Down
156 changes: 156 additions & 0 deletions tests/test_glm53_verify_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# SPDX-License-Identifier: Apache-2.0
"""GLM-5.3 MTP verify blocks route each row like its one-token decode step."""

from __future__ import annotations

from types import SimpleNamespace

import mlx.core as mx
import pytest

from omlx.custom_kernels.nax import is_nax_available
from omlx.patches import mlx_vlm_glm5_next_compat as compat
from omlx.patches.mlx_vlm_glm5_next_compat import decode_kernels as dk


@pytest.fixture(autouse=True)
def _apply_glm5_next_compat():
compat.apply_mlx_vlm_glm5_next_compat_patch()


# One-row routing tests require the GLM NAX GPU kernels.
@pytest.fixture
def glm5_fused_decode():
"""Require NAX kernels for verification-to-one-token routing parity."""
if not is_nax_available():
pytest.skip("the fused GLM-5.3 decode kernels run on M5 (NAX) GPUs")
compat.apply_mlx_vlm_glm5_next_compat_patch()
from mlx_vlm.models.glm5_next import language

assert language._DECODE_FUSION
return language


def _language():
from mlx_vlm.models.glm5_next import language

return language


def _bits(a: mx.array) -> mx.array:
view = {2: mx.uint16, 4: mx.uint32}[a.dtype.size]
return a.view(view)


def _mismatches(a: mx.array, b: mx.array) -> int:
assert a.shape == b.shape and a.dtype == b.dtype
return int(mx.sum(_bits(a) != _bits(b)).item())


def _router(experts=288, hidden=4096, seed=0):
language = _language()
mx.random.seed(seed)
cfg = SimpleNamespace(
num_experts_per_tok=8,
norm_topk_prob=True,
n_group=1,
topk_group=1,
routed_scaling_factor=2.5,
n_routed_experts=experts,
hidden_size=hidden,
)
gate = language.Glm5NextMoEGate(cfg)
gate.weight = mx.random.normal((experts, hidden)) * 0.02
gate.e_score_correction_bias = mx.random.normal((experts,)) * 0.01
return gate


@pytest.mark.usefixtures("glm5_fused_decode")
@pytest.mark.parametrize("rows", [2, 3, 4, 8])
def test_verify_rows_route_like_their_decode_step(rows):
gate = _router(seed=rows)
for trial in range(3):
x = (mx.random.normal((1, rows, 4096)) * (0.3 + trial)).astype(mx.bfloat16)
before = dk.STATS["router"]
indices, scores = gate(x)
assert dk.STATS["router"] == before + 1
assert indices.shape == (1, rows, 8) and scores.shape == (1, rows, 8)
for r in range(rows):
one_idx, one_scores = gate(x[:, r : r + 1])
assert mx.array_equal(indices[:, r : r + 1], one_idx).item(), (trial, r)
assert _mismatches(scores[:, r : r + 1], one_scores) == 0, (trial, r)


@pytest.mark.usefixtures("glm5_fused_decode")
def test_verify_rows_select_the_reference_experts(monkeypatch):
"""Same selected set as the composed router on the same fp32 logits."""
language = compat_language()
gate = _router(seed=11)
x = (mx.random.normal((1, 4, 4096)) * 0.7).astype(mx.bfloat16)
indices, scores = gate(x)
rows = [gate(x[:, r : r + 1]) for r in range(4)]
monkeypatch.setattr(language, "_DECODE_FUSION", False)
for r in range(4):
ref_idx, ref_scores = gate(x[:, r : r + 1])
assert mx.array_equal(rows[r][0], ref_idx).item()
assert _mismatches(rows[r][1], ref_scores) == 0
assert sorted(indices[0, r].tolist()) == sorted(ref_idx[0, 0].tolist())


@pytest.mark.usefixtures("glm5_fused_decode")
@pytest.mark.parametrize("batch,rows,groups", [(2, 4, 1), (1, 9, 1), (1, 4, 2)])
def test_ineligible_blocks_keep_the_reference(batch, rows, groups, monkeypatch):
language = compat_language()
gate = _router(experts=128, hidden=1024, seed=5)
gate.n_group = groups
x = (mx.random.normal((batch, rows, 1024)) * 0.7).astype(mx.bfloat16)
before = dk.STATS["router"]
indices, scores = gate(x)
assert dk.STATS["router"] == before
monkeypatch.setattr(language, "_DECODE_FUSION", False)
ref_idx, ref_scores = gate(x)
assert mx.array_equal(indices, ref_idx).item()
assert _mismatches(scores, ref_scores) == 0


@pytest.mark.usefixtures("glm5_fused_decode")
def test_disabled_fusion_keeps_the_block_reference(monkeypatch):
language = compat_language()
monkeypatch.setattr(language, "_DECODE_FUSION", False)
gate = _router(seed=6)
x = mx.random.normal((1, 4, 4096)).astype(mx.bfloat16)
before = dk.STATS["router"]
indices, scores = gate(x)
ref_idx, ref_scores = language.group_expert_select(
x.astype(mx.float32) @ gate.weight.astype(mx.float32).T,
gate.e_score_correction_bias,
gate.top_k,
gate.n_group,
gate.topk_group,
gate.routed_scaling_factor,
gate.norm_topk_prob,
)
assert dk.STATS["router"] == before
assert mx.array_equal(indices, ref_idx).item()
assert _mismatches(scores, ref_scores) == 0


@pytest.mark.usefixtures("glm5_fused_decode")
def test_declined_kernel_keeps_the_block_reference(monkeypatch):
language = compat_language()
# K >= 16 * E selects an unsupported split-K GEMV configuration.
gate = _router(experts=16, hidden=1024, seed=7)
x = mx.random.normal((1, 4, 1024)).astype(mx.bfloat16)
before = dk.STATS["router"]
indices, scores = gate(x)
assert dk.STATS["router"] == before
monkeypatch.setattr(language, "_DECODE_FUSION", False)
ref_idx, ref_scores = gate(x)
assert mx.array_equal(indices, ref_idx).item()
assert _mismatches(scores, ref_scores) == 0


def compat_language():
from mlx_vlm.models.glm5_next import language

return language
21 changes: 21 additions & 0 deletions tests/test_glm5_next_mtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,7 @@ def test_fused_verify_cycles_are_bitwise_reference_with_nax_tf32():
code = (
"import sys; sys.path[:0] = [%r, %r]\n"
"import test_glm5_next_mtp as t\n"
"t.dk.moe_router = t._kernel_parity_router(t.dk.moe_router)\n"
"from omlx.patches.mlx_vlm_glm5_next_compat import decode_kernels as dk\n"
"used = []\n"
"for seed, ctx in ((5, 300), (11, 2101)):\n"
Expand Down Expand Up @@ -1695,3 +1696,23 @@ def test_batched_rollback_rejects_a_fused_capture():
capture = language.KdaStepCapture(None, mx.zeros((2, 4, 8)), None, None)
with pytest.raises(ValueError):
rollback_rows(language, [cache], [capture], [0, 1], 4)


def _kernel_parity_router(one_row):
"""Pin block-reference routes when comparing downstream fusion kernels.

The default router is covered by test_glm53_verify_router.py. These
tests compare the remaining kernels with identical expert decisions.
"""

def routed(x, *args, **kwargs):
if 2 <= x.shape[0] <= 8:
return dk.moe_router_rows(x, *args, **kwargs)
return one_row(x, *args, **kwargs)

return routed


@pytest.fixture(autouse=True)
def _verify_router_block_replay(monkeypatch):
monkeypatch.setattr(dk, "moe_router", _kernel_parity_router(dk.moe_router))
52 changes: 45 additions & 7 deletions tests/test_mlx_vlm_glm5_next_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3175,7 +3175,8 @@ def _run_with_tf32(snippet: str) -> str:
"import sys; sys.path[:0] = [%r, %r]\n"
"from omlx.patches import mlx_vlm_glm5_next_compat as compat\n"
"compat.apply_mlx_vlm_glm5_next_compat_patch()\n"
"import test_mlx_vlm_glm5_next_compat as t\n" % (str(here), str(here.parent))
"import test_mlx_vlm_glm5_next_compat as t\n"
"t.dk.moe_router = t._kernel_parity_router(t.dk.moe_router)\n" % (str(here), str(here.parent))
) + snippet
env = dict(os.environ, MLX_ENABLE_TF32="1")
done = subprocess.run(
Expand Down Expand Up @@ -4225,22 +4226,31 @@ def test_router_declines_other_gemv_configurations():


def _check_router_rows(experts=288, hidden=4096):
"""Verify-block routers (2..8 rows), bitwise; returns engaged calls."""
"""The block-GEMM replay kernel, independently of default gate dispatch."""
language = _language()
gate = _router(experts, hidden, seed=7)
engaged = 0
for trial, rows in enumerate([2, 3, 4, 5, 8, 4]):
x = (mx.random.normal((1, rows, hidden)) * (0.3 + trial)).astype(mx.bfloat16)
before = _stats()["router_rows"]
indices, scores = gate(x)
routed = dk.moe_router_rows(
x.reshape(rows, hidden),
gate.weight,
gate.e_score_correction_bias,
gate.top_k,
gate.routed_scaling_factor,
gate.norm_topk_prob,
)
engaged += _stats()["router_rows"] - before
language._DECODE_FUSION = False
try:
ref_indices, ref_scores = gate(x)
finally:
language._DECODE_FUSION = True
assert mx.array_equal(indices, ref_indices).item(), rows
assert _mismatches(scores, ref_scores) == 0, rows
if routed is not None:
indices, scores = (a.reshape(1, rows, -1) for a in routed)
assert mx.array_equal(indices, ref_indices).item(), rows
assert _mismatches(scores, ref_scores) == 0, rows
return engaged


Expand Down Expand Up @@ -4468,9 +4478,17 @@ def test_router_rows_first_use_check_inside_compile_uses_reference():
" language = t._language()\n"
" gate = t._router(64, 512, seed=6)\n"
" x = mx.random.normal((1, 4, 512)).astype(mx.bfloat16)\n"
" traced = mx.compile(lambda v: gate(v))(x)\n"
" def call(v):\n"
" out = dk.moe_router_rows(v.reshape(4, 512), gate.weight,\n"
" gate.e_score_correction_bias, 8, 2.5, True)\n"
" if out is None:\n"
" return language.group_expert_select(\n"
" v.astype(mx.float32) @ gate.weight.astype(mx.float32).T,\n"
" gate.e_score_correction_bias, 8, 1, 1, 2.5, True)\n"
" return tuple(a.reshape(1, 4, -1) for a in out)\n"
" traced = mx.compile(call)(x)\n"
" assert dk._ROUTER_ROWS_CHECKED == {} # no check inside compile\n"
" eager = gate(x)\n"
" eager = call(x)\n"
" assert list(dk._ROUTER_ROWS_CHECKED.values()) == [True]\n"
" mx.eval(traced)\n"
" language._DECODE_FUSION = False\n"
Expand Down Expand Up @@ -4691,3 +4709,23 @@ def test_compiled_ffn_block_releases_the_layer_weights():
leak = _leaked_bytes(lambda layer: mx.compile(layer._ffn_block))
# A pinned weight would leave 8 MB+; only tiny trace constants may remain.
assert leak < (64 << 10), f"{leak} bytes still active after the layer was dropped"


def _kernel_parity_router(one_row):
"""Pin block-reference routes when comparing downstream fusion kernels.

The default router is covered by test_glm53_verify_router.py. These
tests compare the remaining kernels with identical expert decisions.
"""

def routed(x, *args, **kwargs):
if 2 <= x.shape[0] <= 8:
return dk.moe_router_rows(x, *args, **kwargs)
return one_row(x, *args, **kwargs)

return routed


@pytest.fixture(autouse=True)
def _verify_router_block_replay(monkeypatch):
monkeypatch.setattr(dk, "moe_router", _kernel_parity_router(dk.moe_router))
Loading