Repository navigation
fix: load Gemma 4 checkpoints with KV-shared layers - #44
Merged
Merged
Conversation
mlx-community/gemma-4-e4b-it-4bit could not be loaded at all. It declares
num_hidden_layers 42 and num_kv_shared_layers 18, so layers 24-41 reuse K/V
from earlier layers and the checkpoint ships only q_proj, q_norm and o_proj for
them. Both implementations built the K/V projections for every layer anyway, so
model.update(verify: .all) demanded tensors that do not exist:
Key language_model.model.layers.24.self_attn.k_proj.weight not found
24 is exactly 42 - 18. This is why the audio, omni and opencode integration
jobs in SharpAI/SwiftLM have failed on every PR regardless of its contents
(SharpAI/SwiftLM#120).
MLXVLM/Gemma4: isKVSharedLayer was computed and stored but never used outside
the double-wide MLP check, so k_proj, v_proj and k_norm were created for shared
layers. They are now built only for layers that own their K/V. The forward path
already handled shared state and needed no change; it now traps if a shared
layer is reached without it rather than force-unwrapping.
MLXLLM/Gemma4Text: the gate assumed "the main model has K/V weights for all
layers even if num_kv_shared_layers > 0", treating a missing K/V as unique to
assistant models where numHiddenLayers == numKvSharedLayers. That is not true of
this checkpoint. Replaced with the per-layer rule, which still covers the
assistant case (the boundary lands at 0, so no layer owns K/V).
With that fixed, both paths hit a second defect on the same model:
Mismatched parameter language_model.model.per_layer_model_projection.weight
Actual [10752, 320], expected [10752, 2560]
2560/320 = 8, i.e. 4-bit packing. Gemma4ScaledLinear and ScaledLinear hold a
bare MLXArray rather than wrapping a Linear, so quantize() could not convert
them and they stayed in float form while the checkpoint ships them quantized.
Both now conform to Quantizable, with quantized forms that subclass them —
Module.update can only replace a child with an instance of the declared property
type, which is how Linear and QuantizedLinear are related.
Verified with mlx-community/gemma-4-e4b-it-4bit on both paths (--audio and
plain): the model loads and answers correctly where it previously failed to
load. SwiftLM's integration scripts pass locally for audio, omni, server,
vision and graph; opencode gets past model load and Test 1, then fails on a
local npm install unrelated to this change.
Co-Authored-By: Claude Opus 5 <[email protected]>
- Shared KV state now reaches shared layers on every forward, not only when an explicit cache was passed. Those layers no longer build their own projections, so the previous hasExplicitCache gate turned a nil-cache forward (one-shot logits, perplexity/eval) into a fatalError at the first shared layer. intermediates[] is populated by every non-shared layer regardless of cache, and the LLM path already read it unconditionally. - num_kv_shared_layers now defaults to 0 when absent, in both configurations. The old default of 20 previously affected only cache mapping; it now decides whether K/V weights are built at all, so an absent key would have silently dropped K/V for the last 20 layers — and driven the boundary negative for models shorter than that. - The quantized ScaledLinear subclasses call freeze(), matching QuantizedLinear and QuantizedSwitchLinear, so packed integer weights do not surface as trainable parameters under LoRA or any gradient walk. Re-verified with mlx-community/gemma-4-e4b-it-4bit on both paths: 'Tokyo' with --audio and plain. Co-Authored-By: Claude Opus 5 <[email protected]>
solderzzc
pushed a commit
that referenced
this pull request
Aug 7, 2026
Review of this PR surfaced a regression already merged and shipped in SwiftLM b674. #44 assumed that a checkpoint with num_kv_shared_layers omits k_proj/v_proj/k_norm for its shared layers, which holds for gemma-4-e4b-it-4bit (42 layers / 18 shared, weights for the first 24 only) but not for gemma-4-e2b-it-4bit (35 / 20, weights for all 35). Since #44 the latter fails to load: Error: Unable to set language_model.model.layers.15.self_attn.k_proj Confirmed by bisect: e2b answers correctly on the pre-#44 submodule and fails on it. The config key alone cannot decide whether to build the modules, so the modules are still built per the config and sanitize now discards the vestigial weights — those layers reuse an earlier layer's K/V and never project their own, so the extra tensors are unused at inference. Also in this commit, from the same review: - The MLP site in Gemma4Text kept `firstKvSharedLayerIdx > 0` while this PR removed it from both MLXVLM sites, so the two implementations disagreed on MLP width for an assistant model — the exact divergence the PR claimed to remove. Aligned. - Removed the dead `hasExplicitCache` binding left by #44. Verified against every Gemma 4 checkpoint on hand: e2b, e4b and 26b-a4b all load and answer correctly. 17 Gemma4 tests pass, including a new one pinning the sanitize behaviour. Co-Authored-By: Claude Opus 5 <[email protected]>
solderzzc
added a commit
that referenced
this pull request
Aug 7, 2026
…tests (#45) * fix: Gemma 4 review follow-ups — assistant-case parity and KV-shared tests Deferred LOW findings from the #44 review. - MLXVLM and MLXLLM disagreed on the assistant case. The VLM kept a `firstKVSharedLayer > 0` clause, so for an assistant model (hiddenLayers == numKVSharedLayers, boundary 0) it built K/V for every layer while MLXLLM built none — and the checkpoint ships none. The clause was never needed for numKVSharedLayers == 0 either: the boundary equals hiddenLayers there, so no layer is shared regardless. Removed from both the attention and the double-wide-MLP sites. - Dropped the redundant deprecated `toQuantized(groupSize:bits:)` overloads; the Quantizable protocol extension already supplies them, matching how SwitchLinear implements only the mode variant. - Added the regression tests the changed branch had none of: a 4-layer / 2-shared config asserting that shared layers build no k_proj, v_proj or k_norm while owning layers do, and a forward pass with cache: nil, which is the path that used to fatalError once shared layers stopped building their own projections. Verified red: forcing hasKv = true fails the projection test on every shared layer. All 15 Gemma4 tests pass. Re-checked against the real checkpoints — gemma-4-e4b-it-4bit generates correctly with --audio and plain, and Qwen3.6-27B-OptiQ-4bit is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]> * fix: restore gemma-4-e2b loading, broken by the KV-shared change in #44 Review of this PR surfaced a regression already merged and shipped in SwiftLM b674. #44 assumed that a checkpoint with num_kv_shared_layers omits k_proj/v_proj/k_norm for its shared layers, which holds for gemma-4-e4b-it-4bit (42 layers / 18 shared, weights for the first 24 only) but not for gemma-4-e2b-it-4bit (35 / 20, weights for all 35). Since #44 the latter fails to load: Error: Unable to set language_model.model.layers.15.self_attn.k_proj Confirmed by bisect: e2b answers correctly on the pre-#44 submodule and fails on it. The config key alone cannot decide whether to build the modules, so the modules are still built per the config and sanitize now discards the vestigial weights — those layers reuse an earlier layer's K/V and never project their own, so the extra tensors are unused at inference. Also in this commit, from the same review: - The MLP site in Gemma4Text kept `firstKvSharedLayerIdx > 0` while this PR removed it from both MLXVLM sites, so the two implementations disagreed on MLP width for an assistant model — the exact divergence the PR claimed to remove. Aligned. - Removed the dead `hasExplicitCache` binding left by #44. Verified against every Gemma 4 checkpoint on hand: e2b, e4b and 26b-a4b all load and answer correctly. 17 Gemma4 tests pass, including a new one pinning the sanitize behaviour. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Aegis AI Assistant <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
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.
Fixes SharpAI/SwiftLM#120 —
mlx-community/gemma-4-e4b-it-4bitcannot be loaded, which is why SwiftLM'saudio,omniandopencodeintegration jobs have failed on every PR regardless of contents.Defect 1 — KV-shared layers
The checkpoint declares
num_hidden_layers: 42,num_kv_shared_layers: 18, so layers 24-41 reuse K/V from earlier layers and ship onlyq_proj/q_norm/o_proj:Both implementations built K/V projections for every layer, so
model.update(verify: .all)demanded tensors that do not exist:24 is exactly 42 − 18.
MLXVLM/Gemma4—isKVSharedLayerwas computed and stored but never read outside the double-wide MLP check.k_proj,v_projandk_normare now built only for layers that own their K/V. The forward path already handled shared state and needed no change; it now traps if a shared layer is reached without it instead of force-unwrapping.MLXLLM/Gemma4Text— the gate assumed "the main model has K/V weights for all layers even if num_kv_shared_layers > 0", treating absent K/V as unique to assistant models. Replaced with the per-layer rule, which still covers the assistant case (numHiddenLayers == numKvSharedLayersputs the boundary at 0, so no layer owns K/V).Defect 2 — unquantizable scaled projection
With that fixed, both paths hit:
2560 / 320 = 8 — 4-bit packing density.
Gemma4ScaledLinearandScaledLinearhold a bareMLXArrayinstead of wrapping aLinear, soquantize()could not convert them: they stayed float while the checkpoint ships them quantized.Both now conform to
Quantizable. The quantized forms subclass the originals, becauseModule.updatecan only replace a child with an instance of the declared property type — the same relationshipLinearandQuantizedLinearhave.quantizeSinglealso requires the result to conform toQuantized, which they do.Verification
mlx-community/gemma-4-e4b-it-4bit, both paths:--audio(VLM path)Key …layers.24.self_attn.k_proj.weight not found'Tokyo''Tokyo'SwiftLM's integration scripts run locally against this build:
test-audio.shtest-omni.shtest-server.shtest-vision.shtest-graph.shtest-opencode.shnpm install opencode-ai(Killed: 9), unrelated to this change — that job is alreadycontinue-on-errorNo behaviour change for models without KV-shared layers:
server,visionandgraphexercise other checkpoints and still pass.Note for reviewers
I could not recover the history behind the
isAssistantassumption inGemma4Text(shallow submodule clone). If some checkpoint really does ship K/V for shared layers, the per-layer rule would skip weights it has — but such a checkpoint would also have failed the old assistant check, so I believe the rule is strictly more correct. Worth a look from whoever wrote it.🤖 Generated with Claude Code