Repository navigation
Fix Gemma 4 VLM load: KV-shared layers must not declare k_proj/v_proj - #390
Merged
davidkoski merged 3 commits intoJul 10, 2026
Merged
Conversation
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>
This was referenced Jul 9, 2026
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
marked this pull request as ready for review
July 9, 2026 22:35
Contributor
Author
|
@davidkoski Yes — marked it ready for review now. Also pushed a one-line swift-format fix for |
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>
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Loading any Gemma 4 (
model_type: "gemma4") checkpoint that uses cross-layer KVsharing — e.g.
mlx-community/gemma-4-e4b-it-4bit— fails at weight load with:(
gemma-4-e4b-it-4bithasnum_hidden_layers: 42,num_kv_shared_layers: 18, sothe 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) reusean earlier same-type layer's K/V and own no
k_proj/v_proj/k_norm. Everythingin the stack already knows this except the module construction:
Gemma4TextAttention.inittakeskvSharedOnly:and, when set, skips buildingk_proj/v_proj/k_norm/v_norm.Gemma4TextLanguageModel.sanitizedropsself_attn.k_proj/v_proj/k_normfor layers
>= firstKVSharedLayer(added in Fix Gemma4 QAT (E-series) load: KV-shared layers have no k_proj/v_proj/k_norm #330).sharedKV, so they never compute their ownK/V (they never touch the projections at all).
Gemma4AssistantDraftInner(the MTP drafter) already builds its layers withkvSharedOnly: true.mlx-lm'sgemma4_text.pygates the same tensors onhas_kv = layer_idx < num_hidden_layers - num_kv_shared_layers, and the third-partyVincentGourbin/gemma-4-swift-mlx(which runs E4B) likewise omitsk_proj/v_projfor
isKvSharedLayerlayers.But
Gemma4TextBackbone.initbuilds every layer with the defaultkvSharedOnly: false:So the module tree declares a
v_proj(andk_proj/k_norm) on the KV-sharedlayers that
sanitizehas just removed from the checkpoint. The strict loader verify(
model.update(parameters:verify: [.all])inMLXLMCommon/Load.swift) then throwskeyNotFoundon 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:The predicate is identical to
Gemma4TextAttention.isKVSharedLayer(
layerIdx >= firstKVSharedLayer && firstKVSharedLayer > 0) and to thesanitizedrop condition, so the module tree now matches the sanitized checkpointexactly. Runtime behavior is unchanged: those layers already consumed
sharedKVandnever invoked the now-absent projections, so no forward output changes — only the
dead, unfillable parameters go away.
Gemma4Unified(num_kv_shared_layers: 0) andany non-sharing config are unaffected (
firstKVSharedLayer > 0 && …stays false).Test
Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift:Gemma4TextLanguageModel's parameter tree containsk_proj/v_projfor the head layers and none for the shared tail.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 exactupdate(parameters:verify: [.all])the production loader uses. This throwskeyNotFound(… self_attn.v_proj.weight …)before the fix and passes after.Relation to #282
Issue #282 bundles three Gemma 4 loader gaps (the
gemma4_assistantMTP drafter, the 26B MoE variant, and the 31B SIGTRAP). Those havesince landed. This is a distinct, more basic gap on the same stack: the base
gemma4E4B/E2B model doesn't finish loading at all when KV sharing is active.🤖 Generated with Claude Code