Skip to content

fix(qwen4_exp): default n-gram hash seed to 1234 + verify constants at load - #1

Closed
beatakouchnir wants to merge 1 commit into
eauchs:add-qwen4-expfrom
beatakouchnir:qwen4-exp-seed-fix
Closed

beatakouchnir wants to merge 1 commit into
eauchs:add-qwen4-expfrom
beatakouchnir:qwen4-exp-seed-fix

Conversation

@beatakouchnir

Copy link
Copy Markdown

Per the thread — just the seed fix and its load-time check, kept separate from the mlx-vlm loader changes (those will be a follow-up).

Bug. config.json doesn't carry seed, and the reference Qwen4ExpTextConfig defaults it to 1234 to build layer_multipliers. This branch defaulted to 0, so every n-gram lookup read the wrong rows of the PLE table — coherent output, quietly wrong. Against mlx-vlm on the same weights (64 tokens) the PLE layer's output had relative error 0.83 (cosine 0.63); 0.017 after this change, in line with neighbouring layers.

Fix. Default seed = 1234, and have sanitize compare the rebuilt multipliers / head vocab sizes / offsets against the checkpoint's copies, raising on mismatch so a seed or hash discrepancy fails at load instead of degrading silently. Adds test_qwen4_exp_ngram_constants_are_checked.

Note — pre-existing failure, not from this PR. test_qwen4_exp already fails on add-qwen4-exp itself (currently 2196836) at the prefill-vs-token-by-token allclose — the identical AssertionError: array(False, dtype=bool) with the file unmodified, so it's independent of this change. This PR's diff doesn't touch that test: it only changes the seed default and sanitize, and adds test_qwen4_exp_ngram_constants_are_checked (which passes).

…rify constants at load

config.json does not carry `seed`. The reference (`Qwen4ExpTextConfig`)
defaults it to 1234 and builds `layer_multipliers` from it as a buffer,
which is the tensor every checkpoint stores. This port defaulted to 0 and
used its own rebuilt multipliers, so every n-gram lookup read the wrong
rows of the 51B-parameter PLE table. Generation stayed coherent, which is
why it went unnoticed; against mlx-vlm on the same weights and 64 tokens
the PLE layer's output had relative error 0.83 (cosine 0.63), and 0.017
after this change, in line with the neighbouring layers.

`sanitize` now compares the rebuilt multipliers, head vocab sizes and
offsets with the checkpoint's copies and raises on mismatch, so a seed or
hash discrepancy fails at load instead of degrading silently.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@beatakouchnir

Copy link
Copy Markdown
Author

While I was in here I looked into the pre-existing test_qwen4_exp failure (the prefill-vs-token-by-token allclose). It isn't a model bug — it's MLX's GEMV-vs-GEMM split.

Single-token decode hits MLX's matrix-vector kernel (M=1); prefill and ≥2-token batches hit the matrix-matrix kernel, and the two round differently:

W = mx.random.normal((64, 64)); x = mx.random.normal((12, 64))
# M=1 vs M=12, row 0:  max diff ~1.4e-2   (GEMV vs GEMM)
# M=2 vs M=12, row 0:  0.0                (both GEMM)

In the test that shows up cleanly: decoding in chunks of ≥2 is bit-identical to prefill, and only chunk=1 diverges — ~2e-3 in the logits after attenuation through the 4 layers. The batched-vs-solo and padded assertions are the same story (each compares an M=1 solo decode against an M≥2 batched path).

So the three atol=1e-4 decode comparisons in test_qwen4_exp can't hold on current MLX; relaxing them to atol=5e-3 makes the test pass (observed gap ~2e-3, so that keeps ~2x headroom while still catching real drift). Happy to push that as a small separate commit if it's useful.

@sje397

sje397 commented Sep 26, 2026

Copy link
Copy Markdown

Heads-up: this is now #2, rebased onto da1148f9 — which is why #1 reads mergeable_state: dirty. da1148f9 reorganised the n-gram shard handling underneath it, so nothing in your change was wrong, only its anchors moved. Authorship is preserved on the commit.

Two things I added while rebasing:

1. Verified the default against a shipped artifact, because the test cannot. test_qwen4_exp_ngram_constants_are_checked builds the model and compares it to itself, so any self-consistent seed satisfies it — it pins that a mismatch is rejected, not that 1234 is the reference's seed. A real conversion can settle that: 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 match no layer index. So the change is right — and it turns out it was hiding a live bug: at the current head's default of 0, that checkpoint loads with the wrong hash rows, in silence.

2. Falsified rather than merely green. Deleting the new check fails the new test; setting the default back to 0 fails it too (the assertFalse on a seed-0 model's constants). Both files restored byte-identical afterwards.

One unrelated thing worth knowing: tests/test_models.py::test_qwen4_exp is red at da1148f9 — prefill vs stepwise diverges 1.07e-3 against a magnitude of 1.20, so it exceeds atol=1e-4. It is green at 365170c and fails identically with and without your change.

If you would rather push this yourself and keep #1 as the PR, say the word and I will close #2 — it is your change.

@beatakouchnir

Copy link
Copy Markdown
Author

Closing in favor of #2, which carries this commit rebased onto da1148f9 along with the checkpoint verification. Thanks @sje397.

eauchs pushed a commit that referenced this pull request Sep 30, 2026
…nts at load

Re-applied onto da1148f by @sje397: #1 no longer applies because
da1148f 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.
michalk8 added a commit to ml-explore/mlx-lm that referenced this pull request Nov 16, 2026
* Add Qwen3.8-Flash-Next (qwen4_exp) model support

Adds the qwen4_exp architecture: a hybrid Gated DeltaNet / Qwen Sparse
Attention trunk wrapped in gated-residual hyper-connection streams, a
sharded n-gram PLE embedding, and a 512-expert MoE.

* Load the official Qwen3.8-Flash-Next checkpoint

- non-gated norms use 1 + weight (checkpoint is zero-centered)
- strip the model.language_model. prefix
- split the fused gate_up_proj experts
- drop the MTP block
- accept an mx.array offset

* Include each query's own partial block in the QSA selection

Without it, queries with fewer than compress_ratio tokens of history ended up with fully masked rows, which softmax turns into a uniform average over all keys, future ones included. The tail is also no longer marked visible for every query.

* Support left padding in the QSA indexer and batched caches

* qwen4_exp: accept both quant_predicate calling conventions

quant_predicate returned fn(path, module, _); mlx-lm 0.31.3 calls predicates
with two arguments, later versions with three, so the conversion failed with
TypeError: fn() missing 1 required positional argument: '_'. The default value
_=None covers both conventions. Reported by @Sofille65. Verified: mlp.gate
remains unquantized in both call cases.

* qwen4_exp: fold RMSNorm +1 into weights during sanitize

Fold the reference +1 into the weight once by sanitize instead of per
call; fold guarded on the model.language_model prefix so converted
checkpoints (model.*) are never folded twice. _FOLD_ONE covers the eight
affected norm suffixes (linear_attn.norm excluded: RMSNormGated scales by
w alone). Init zeros -> ones so unloaded modules stay identity.
Pre-existing conversions load silently without the +1 and must be
redone.

* qwen4_exp: keep n-gram shards in a list, accept both key layouts

The shards were flat `shard_{i}` attributes, so a checkpoint converted by
mlx-vlm (`ngram_embedding.shards.{i}`, quantized) failed a strict load with
missing/unexpected keys. Store them as a list and map the HF `shard_{i}`
names onto it in sanitize.

* qwen4_exp: default the n-gram hash seed to 1234, and check the constants at load

Re-applied onto da1148f by @sje397: eauchs#1 no longer applies because
da1148f 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.

* Update the model

---------

Co-authored-by: Beata Kouchnir <12824699+beatakouchnir@users.noreply.github.com>
Co-authored-by: michalk8 <46717574+michalk8@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants