Skip to content

Fix Gemma4 VLM weight loading: skip K/V modules for KV-shared layers - #407

Closed
kingster wants to merge 2 commits into
ml-explore:mainfrom
kingster:fix/gemma4-kv-shared-layer-construction
Closed

kingster wants to merge 2 commits into
ml-explore:mainfrom
kingster:fix/gemma4-kv-shared-layer-construction

Conversation

@kingster

@kingster kingster commented Jul 8, 2026

Copy link
Copy Markdown

Problem

Loading a Gemma 4 VLM checkpoint that uses cross-layer KV sharing fails at weight loading:

MLXNN.UpdateError.keyNotFound(path: ["language_model", "model", "layers", "15", "self_attn", "k_norm", "weight"],
  modules: ["Gemma4", "Gemma4TextLanguageModel", "Gemma4TextBackbone", "Gemma4TextDecoderLayer",
            "Gemma4TextAttention", "Gemma4RMSNormZeroShift"])

Reproduced with mlx-community/gemma-4-e2b-it-4bit (num_hidden_layers = 35, num_kv_shared_layers = 20) via VLMModelFactory.shared.loadContainer(from:using:). Present on main and the latest tag (3.31.4).

Root cause

KV-shared layers (layerIdx >= hiddenLayers - numKVSharedLayers) reuse an earlier layer's K/V and ship no k_proj/v_proj/k_norm/v_norm weights. But Gemma4Attention.init gates building those modules only on kvSharedOnly — the speculative-decoding drafter flag — so the main model builds them for KV-shared layers. loadWeights then throws keyNotFound for the first shared layer's k_norm.

This is internally inconsistent with the rest of the model, which already assumes KV-shared layers have no such modules:

  • Gemma4TextBackbone feeds KV-shared layers sharedKV, so k_proj/k_norm/v_proj/v_norm are never used there.
  • sanitize(weights:) drops any self_attn.{k,v}_proj / k_norm for KV-shared text layers, with the comment: "they reuse an earlier layer's K/V and own no K projection or K norm, so the module tree has none."

The construction was the one place that didn't match that assumption.

Fix

Gate construction of the K/V projections and norms on !isKVSharedLayer as well:

if !kvSharedOnly && !isKVSharedLayer {
    // k_proj / v_proj / k_norm / v_norm
}

isKVSharedLayer is already computed in init just above. One-line change; the forward path and sanitize already handle these layers.

Testing

With this change, mlx-community/gemma-4-e2b-it-4bit loads and generates (vision + text) on an M4 iPad. Non-KV-shared checkpoints are unaffected (isKVSharedLayer is false when numKVSharedLayers == 0).

KV-shared layers (index >= hiddenLayers - numKVSharedLayers) reuse an
earlier layer's K/V and ship no k_proj/v_proj/k_norm/v_norm weights.
`Gemma4Attention.init` gated building these modules only on `kvSharedOnly`
(the speculative-decoding drafter flag), so the main model built them for
KV-shared layers and `loadWeights` threw keyNotFound, e.g.:

  MLXNN.UpdateError.keyNotFound(path: ["language_model", "model",
    "layers", "15", "self_attn", "k_norm", "weight"], ...)

loading mlx-community/gemma-4-e2b-it-4bit (35 layers, num_kv_shared_layers=20).

The forward pass already feeds KV-shared layers `sharedKV` in
Gemma4TextBackbone (k_proj/k_norm are never used there), and `sanitize`
already drops these tensors on the assumption "the module tree has none".
Gate construction on `!isKVSharedLayer` too so the module tree matches.

Co-Authored-By: Claude <noreply@anthropic.com>
@davidkoski

Copy link
Copy Markdown
Member

Looks like a dup of #402 and #390. I am leaning toward 390 as it also has a test, but I like the approach in this one.

Ports the regression tests from ml-explore#390 to guard the KV-shared layer fix: one
asserts the module tree omits k_proj/v_proj/k_norm for KV-shared tail layers
(while head layers keep them), the other loads a sanitized checkpoint into a
KV-sharing model via the strict `verify: [.all]` loader — reproducing the
original keyNotFound before the fix.

Verified: both fail without the construction gate and pass with it.

Tests authored by Francisco D' Agostino (@fdagostino) in ml-explore#390.

Co-authored-by: Francisco D' Agostino <fdagostino@users.noreply.github.com>
@kingster

kingster commented Jul 10, 2026 •

Copy link
Copy Markdown
Author

Thanks for flagging the dups (#402, #390).

I've now ported the regression tests from #390 (credit to @fdagostino) so this PR carries them too. Verified locally via xcodebuild test on macOS:

  • without the change: both tests fail — sanitizedCheckpointLoadsWithoutKeyNotFound reproduces keyNotFound(… self_attn.k_norm.weight …);
  • with the change: both pass.

The tests assert the module tree omits the K/V projections for KV-shared tail layers (while head layers keep them) and that a sanitized checkpoint loads through the strict verify: [.all] loader — so they pin the construction side to sanitize/forward regardless of which side implements the gate.

@davidkoski

Copy link
Copy Markdown
Member

After reading through these carefully I agree both (407, 390) fix the issue. I am going with 390 because it matches the structure from the python code in mlx-vlm (which can be useful).

Thank you for this work!

@davidkoski davidkoski closed this Jul 10, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
On the cumulative SDK ml-explore#416 (ml-explore#409 + ml-explore#413 + ml-explore#411 + ml-explore#408 on main
859f641). test-shards.json: gemma-reopened-thought-enabled kept
beside gemma-quoted-number-enabled as its own extra run in the same
shard (the shard tool refuses one run mixing different env). Every
other file merges unchanged: the merge adds exactly ml-explore#407's lines.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
The phase-D SDK pin is main after ml-explore#416, ml-explore#417 and ml-explore#407. ml-explore#417 is ml-explore#416's
head plus two commits and shares no file with ml-explore#407: clean merge, no
change to either side.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ml-explore#414) into O5

test-shards.json: ml-explore#417's map (ml-explore#414's four native shards and hosted
audio shard, with ml-explore#416's two groups) taken as is, plus ml-explore#407's
gemma-reopened-thought-enabled group and one extra run beside
gemma-quoted-number-enabled in shard 2 (+15 s estimate, as for that
run). The seven hosted audio tests are unchanged. Every other file
merges cleanly; against ml-explore#417's head this adds exactly ml-explore#407's lines,
the reviewed test case and the reference text.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
O5 on the phase-D cumulative SDK: ml-explore#407 merged onto ml-explore#416 + ml-explore#417 (opt-in Gemma reopened thoughts)
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