From 8f639ca543ed37f9792329c01dfd015f7d431632 Mon Sep 17 00:00:00 2001 From: Beata Kouchnir <12824699+beatakouchnir@users.noreply.github.com> Date: Sat, 26 Sep 2026 12:50:58 +1000 Subject: [PATCH] qwen4_exp: default the n-gram hash seed to 1234, and check the constants at load Re-applied onto da1148f9 by @sje397: eauchs/mlx-lm#1 no longer applies because da1148f9 reorganised the n-gram shard handling underneath it. The change is Beata's; only the anchors moved. The seed is not in config.json, so the default is load-bearing: a different seed rebuilds different multipliers and every PLE lookup lands on the wrong rows. `Model.sanitize` now compares the constants rebuilt from the config against the checkpoint's own copies and raises on mismatch, so a wrong seed fails loudly instead of silently reading the wrong rows. Verified against a real checkpoint, which the test alone cannot do (it constructs the model, so any self-consistent seed satisfies it): the community oQ4e conversion of this architecture at Jundot/Qwen3.8-Flash-Next-oQ4e-mtp carries layer_multipliers (3,), ngram_heads_vocab_sizes (16,) and ngram_heads_offsets (16,), and all three match the seed-1234 rebuild exactly at ple_layer_index 0. Candidates 0, 617 and 1235 do not match any layer index. So 1234 is not merely plausible -- it is the seed written into a shipped checkpoint, which is why the guard is worth having at load rather than trusting the default. --- mlx_lm/models/qwen4_exp.py | 35 ++++++++++++++++++-- tests/test_models.py | 66 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 2 deletions(-) diff --git a/mlx_lm/models/qwen4_exp.py b/mlx_lm/models/qwen4_exp.py index 01b567088..8ad9fef8c 100644 --- a/mlx_lm/models/qwen4_exp.py +++ b/mlx_lm/models/qwen4_exp.py @@ -66,7 +66,10 @@ class TextArgs(BaseModelArgs): ple_embed_dim: int = 2560 ple_layer_ids: list = field(default_factory=lambda: [2]) ple_conv_kernel_size: int = 4 - seed: int = 0 + # The n-gram hash seed of the reference implementation. config.json does + # not carry it, so the default is load-bearing: a different seed rebuilds + # different multipliers and every PLE lookup lands on the wrong rows. + seed: int = 1234 eos_token_id: Any = 248044 partial_rotary_factor: float = 0.25 rope_parameters: dict = field(default_factory=dict) @@ -634,7 +637,9 @@ def __init__(self, args: TextArgs, embed_dim: int, ple_layer_index: int = 0): # Public attributes: only there to absorb the checkpoint tensors. They live # in parameters(), so an astype(float16) would destroy them; the values # actually used live in the `_`-prefixed copies, outside parameters() and - # rebuilt identically from the config. + # rebuilt from the config. `Model.sanitize` checks the rebuilt values + # against the checkpoint's, so a seed or hash mismatch fails loudly + # instead of silently reading the wrong rows. self.layer_multipliers = mx.array(mults, dtype=mx.int64) self.ngram_heads_vocab_sizes = mx.array(sizes, dtype=mx.int64) self.ngram_heads_offsets = mx.array(offsets, dtype=mx.int64) @@ -1127,6 +1132,11 @@ def sanitize(self, weights): elif k.startswith("language_model."): k = k[len("language_model.") :] + # The hash constants are rebuilt from the config; the checkpoint's + # copies are the ground truth they must reproduce. + if k.endswith(self._NGRAM_CONSTANTS): + self._check_ngram_constant(k, v) + # N-gram table: HF names the shards `shard_{i}`, this file `shards.{i}`. k = _NGRAM_SHARD_RE.sub(r".ngram_embedding.shards.\1.", k) @@ -1158,6 +1168,27 @@ def sanitize(self, weights): out[k] = v return out + _NGRAM_CONSTANTS = ( + "ple_embedding.layer_multipliers", + "ple_embedding.ngram_heads_vocab_sizes", + "ple_embedding.ngram_heads_offsets", + ) + + def _check_ngram_constant(self, key: str, value: mx.array) -> None: + layer = int(key.split(".layers.")[1].split(".")[0]) + table = self.model.layers[layer].ple.ple_embedding + rebuilt = { + "layer_multipliers": table._mults, + "ngram_heads_vocab_sizes": table._sizes, + "ngram_heads_offsets": table._offsets, + }[key.rsplit(".", 1)[1]] + if not mx.array_equal(rebuilt, value.astype(rebuilt.dtype)): + raise ValueError( + f"{key}: the n-gram hash constants rebuilt from the config do " + f"not match the checkpoint ({rebuilt.tolist()} vs " + f"{value.tolist()}); check `seed` and the hash parameters" + ) + @property def quant_predicate(self): # mlx-lm 0.31.3 calls predicates with two arguments, later versions with diff --git a/tests/test_models.py b/tests/test_models.py index 12dcc2ce4..3c9ebed72 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -711,6 +711,72 @@ def test_olmo(self): args.n_layers, ) + def test_qwen4_exp_ngram_constants_are_checked(self): + """The n-gram hash constants (layer_multipliers and friends) are rebuilt + from the config -- the seed is not in config.json -- and the checkpoint + carries the reference's copies. A rebuild that disagrees must fail loudly + at load, not read the wrong rows of the n-gram table in silence.""" + from mlx_lm.models import qwen4_exp + + text_config = dict( + hidden_size=64, + num_hidden_layers=4, + num_attention_heads=4, + num_key_value_heads=2, + head_dim=32, + vocab_size=10_000, + rms_norm_eps=1e-6, + full_attention_interval=4, + num_experts=8, + num_experts_per_tok=2, + moe_intermediate_size=32, + shared_expert_intermediate_size=32, + linear_num_key_heads=2, + linear_num_value_heads=4, + linear_key_head_dim=16, + linear_value_head_dim=16, + linear_conv_kernel_dim=4, + hc_count=4, + hc_lowrank=16, + indexer_n_heads=2, + indexer_kv_heads=1, + indexer_head_dim=16, + indexer_budget=8, + indexer_compress_ratio=4, + ngram_size=3, + heads_per_ngram=2, + ngram_vocab_size_base=101, + split_ngram_parts=4, + ple_embed_dim=64, + ple_layer_ids=[2], + eos_token_id=1, + rope_parameters={ + "rope_theta": 10000000, + "partial_rotary_factor": 0.25, + }, + ) + model = qwen4_exp.Model( + qwen4_exp.ModelArgs(model_type="qwen4_exp", text_config=text_config) + ) + weights = dict(tree_flatten(model.parameters())) + key = next(k for k in weights if k.endswith("ple_embedding.layer_multipliers")) + layer = int(key.split(".layers.")[1].split(".")[0]) + table = model.model.layers[layer].ple.ple_embedding + self.assertTrue(mx.array_equal(weights[key], table._mults)) + model.sanitize(dict(weights)) # matching constants pass + + # A different seed rebuilds the hash constants, so the checkpoint's copies + # no longer match and sanitize must reject them instead of degrading. + wrong = qwen4_exp.Model( + qwen4_exp.ModelArgs( + model_type="qwen4_exp", text_config={**text_config, "seed": 0} + ) + ) + bad = dict(tree_flatten(wrong.parameters())) + self.assertFalse(mx.array_equal(bad[key], weights[key])) + with self.assertRaises(ValueError): + model.sanitize(bad) + def test_qwen4_exp(self): from mlx_lm.models import qwen4_exp