Skip to content

Fix Gemma 4 VLM load: KV-shared layers must not declare k_proj/v_proj - #390

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
fdagostino:fix/gemma4-vlm-kv-shared-construct
Jul 10, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
fdagostino:fix/gemma4-vlm-kv-shared-construct

Conversation

@fdagostino

Copy link
Copy Markdown
Contributor

Summary

Loading any Gemma 4 (model_type: "gemma4") checkpoint that uses cross-layer KV
sharing — e.g. mlx-community/gemma-4-e4b-it-4bit — fails at weight load with:

keyNotFound(path: ["language_model","model","layers","24","self_attn","v_proj","weight"],
            modules: ["Gemma4","Gemma4TextLanguageModel","Gemma4TextBackbone",
                      "Gemma4TextDecoderLayer","Gemma4TextAttention","Linear"])

(gemma-4-e4b-it-4bit has num_hidden_layers: 42, num_kv_shared_layers: 18, so
the first KV-shared layer is exactly 42 - 18 = 24 — the layer named in the error.)

Root cause

Gemma 4's tail layers (layer_idx >= num_hidden_layers - num_kv_shared_layers) reuse
an earlier same-type layer's K/V and own no k_proj / v_proj / k_norm. Everything
in the stack already knows this except the module construction:

  • Gemma4TextAttention.init takes kvSharedOnly: and, when set, skips building
    k_proj / v_proj / k_norm / v_norm.
  • Gemma4TextLanguageModel.sanitize drops self_attn.k_proj / v_proj / k_norm
    for layers >= firstKVSharedLayer (added in Fix Gemma4 QAT (E-series) load: KV-shared layers have no k_proj/v_proj/k_norm #330).
  • The runtime forward feeds those layers a sharedKV, so they never compute their own
    K/V (they never touch the projections at all).
  • Gemma4AssistantDraftInner (the MTP drafter) already builds its layers with
    kvSharedOnly: true.
  • Upstream mlx-lm's gemma4_text.py gates the same tensors on
    has_kv = layer_idx < num_hidden_layers - num_kv_shared_layers, and the third-party
    VincentGourbin/gemma-4-swift-mlx (which runs E4B) likewise omits k_proj/v_proj
    for isKvSharedLayer layers.

But Gemma4TextBackbone.init builds every layer with the default
kvSharedOnly: false:

self._layers.wrappedValue = (0 ..< config.hiddenLayers).map {
    Gemma4TextDecoderLayer(config: config, layerIdx: $0)   // ← never kvSharedOnly: true
}

So the module tree declares a v_proj (and k_proj / k_norm) on the KV-shared
layers that sanitize has just removed from the checkpoint. The strict loader verify
(model.update(parameters:verify: [.all]) in MLXLMCommon/Load.swift) then throws
keyNotFound on the first such tensor — layers.24.self_attn.v_proj.weight.

This is the construction-side complement of #330: that PR fixed the checkpoint side
(drop the redundant tensors) but the module side still instantiates them, so the two
disagree. Both QAT checkpoints (which omit the tensors) and PTQ checkpoints (whose
redundant tensors #330 now drops) hit this.

Fix

Wire the construction to the same predicate the attention, the sanitizer, and the
drafter already use — build the KV-shared tail with kvSharedOnly: true:

let firstKVSharedLayer = config.hiddenLayers - config.numKVSharedLayers
self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { idx in
    Gemma4TextDecoderLayer(
        config: config, layerIdx: idx,
        kvSharedOnly: firstKVSharedLayer > 0 && idx >= firstKVSharedLayer)
}

The predicate is identical to Gemma4TextAttention.isKVSharedLayer
(layerIdx >= firstKVSharedLayer && firstKVSharedLayer > 0) and to the
sanitize drop condition, so the module tree now matches the sanitized checkpoint
exactly. Runtime behavior is unchanged: those layers already consumed sharedKV and
never invoked the now-absent projections, so no forward output changes — only the
dead, unfillable parameters go away. Gemma4Unified (num_kv_shared_layers: 0) and
any non-sharing config are unaffected (firstKVSharedLayer > 0 && … stays false).

Test

Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift:

  1. Structural — a KV-sharing Gemma4TextLanguageModel's parameter tree contains
    k_proj/v_proj for the head layers and none for the shared tail.
  2. Load round-trip — build a dense checkpoint (K/V on every layer), sanitize it
    the way real Gemma 4 checkpoints are (drop the shared tail's k_proj/v_proj/
    k_norm), then load it into the KV-sharing model via the exact
    update(parameters:verify: [.all]) the production loader uses. This throws
    keyNotFound(… self_attn.v_proj.weight …) before the fix and passes after.

Relation to #282

Issue #282 bundles three Gemma 4 loader gaps (the
gemma4_assistant MTP drafter, the 26B MoE variant, and the 31B SIGTRAP). Those have
since landed. This is a distinct, more basic gap on the same stack: the base
gemma4 E4B/E2B model doesn't finish loading at all when KV sharing is active.


🤖 Generated with Claude Code

Gemma 4's tail layers (`layer_idx >= num_hidden_layers - num_kv_shared_layers`)
reuse an earlier same-type layer's K/V and own no `k_proj`/`v_proj`/`k_norm`.
`Gemma4TextAttention` supports this via `kvSharedOnly:`, `sanitize` drops those
tensors from the checkpoint (ml-explore#330), the forward pass feeds those layers a
`sharedKV`, and `Gemma4AssistantDraftInner` already builds with
`kvSharedOnly: true` — but `Gemma4TextBackbone.init` builds every layer with the
default `kvSharedOnly: false`. So the module tree declares a `v_proj`/`k_proj`/
`k_norm` on the KV-shared layers that `sanitize` has removed, and loading a real
Gemma 4 checkpoint (e.g. mlx-community/gemma-4-e4b-it-4bit: 42 layers, 18 shared
→ first shared layer 24) fails under the strict loader verify with
`keyNotFound(… layers.24.self_attn.v_proj.weight …)`.

Wire the construction to the same predicate the attention, the sanitizer, and
the drafter already use. Runtime behavior is unchanged (those layers already
consumed `sharedKV` and never invoked the now-absent projections); only the
dead, unfillable parameters go away. `Gemma4Unified` and any non-sharing config
(`num_kv_shared_layers: 0`) are unaffected.

Adds Gemma4KVSharedLoadTests: a structural check that KV-shared layers own no
local K/V projections, and a load round-trip that reproduces the exact
`keyNotFound` (sanitized checkpoint → model.update(verify: [.all])).

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

Copy link
Copy Markdown
Member

@fdagostino is this ready for review? There are a couple other PRs referencing this same issue but this is the one I would like to merge.

Thanks!

…ng on main)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@fdagostino
fdagostino marked this pull request as ready for review July 9, 2026 22:35
@fdagostino

Copy link
Copy Markdown
Contributor Author

@davidkoski Yes — marked it ready for review now. Also pushed a one-line swift-format fix for MTPSpeculativeTokenIteratorTests.swift (the lint failure was pre-existing on main from #314, not from this branch), so CI should be green. Thanks!

@davidkoski

Copy link
Copy Markdown
Member

Yeah, the lint one is due to swift-format bumping version (so the CI side is moving on us). See #386. It may require a rebase rather than swift-format.

kingster added a commit to kingster/mlx-swift-lm that referenced this pull request Jul 10, 2026
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>

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this fix!

@davidkoski
davidkoski merged commit 09deb8c into ml-explore:main Jul 10, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…ml-explore#390)

fix: build Gemma 4 KV-shared layers with kvSharedOnly

Tail layers (layer_idx >= num_hidden_layers - num_kv_shared_layers) reuse
an earlier layer's K/V and own no k_proj/v_proj/k_norm. The attention,
sanitizer, and drafter already handled this, but Gemma4TextBackbone.init
built every layer with kvSharedOnly: false — causing strict-loader failures
on real checkpoints (e.g. gemma-4-e4b-it-4bit: 42 layers, 18 shared →
keyNotFound(…layers.24.self_attn.v_proj.weight…)).

Wire init to the same predicate the rest of the stack already uses.
Runtime behavior is unchanged; only the dead, unfillable parameters
are removed. Gemma4Unified and configs with num_kv_shared_layers: 0
are unaffected.

Adds Gemma4KVSharedLoadTests: structural check that KV-shared layers
own no local K/V projections, and a load round-trip reproducing the
exact keyNotFound failure (sanitized checkpoint → model.update(verify: [.all])).
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…avefront-hidden

Qwen35 prompt wavefront: each chunk's hidden rows from the same graph (for assisted TP lanes)
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