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
35 changes: 33 additions & 2 deletions mlx_lm/models/qwen4_exp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down