Skip to content

fix: load Gemma 4 checkpoints with KV-shared layers - #44

Merged
solderzzc merged 2 commits into
mainfrom
fix/gemma4-kv-shared-layers
Aug 6, 2026
Merged

solderzzc merged 2 commits into
mainfrom
fix/gemma4-kv-shared-layers

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Fixes SharpAI/SwiftLM#120 — mlx-community/gemma-4-e4b-it-4bit cannot be loaded, which is why SwiftLM's audio, omni and opencode integration 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 only q_proj / q_norm / o_proj:

layer 23 self_attn: k_norm, k_proj, o_proj, q_norm, q_proj, v_proj
layer 24 self_attn: o_proj, q_norm, q_proj

Both implementations built K/V projections for every layer, 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.

  • MLXVLM/Gemma4 — isKVSharedLayer was computed and stored but never read outside the double-wide MLP check. k_proj, v_proj and k_norm 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 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 == numKvSharedLayers puts the boundary at 0, so no layer owns K/V).

Defect 2 — unquantizable scaled projection

With that fixed, both paths hit:

Mismatched parameter language_model.model.per_layer_model_projection.weight
Actual [10752, 320], expected [10752, 2560]

2560 / 320 = 8 — 4-bit packing density. Gemma4ScaledLinear and ScaledLinear hold a bare MLXArray instead of wrapping a Linear, so quantize() could not convert them: they stayed float while the checkpoint ships them quantized.

Both now conform to Quantizable. The quantized forms subclass the originals, because Module.update can only replace a child with an instance of the declared property type — the same relationship Linear and QuantizedLinear have. quantizeSingle also requires the result to conform to Quantized, which they do.

Verification

mlx-community/gemma-4-e4b-it-4bit, both paths:

invocation before after
--audio (VLM path) Key …layers.24.self_attn.k_proj.weight not found 'Tokyo'
plain (LLM path) same, then the shape mismatch 'Tokyo'

SwiftLM's integration scripts run locally against this build:

script result
test-audio.sh PASS (red in CI on every PR)
test-omni.sh PASS (red in CI on every PR)
test-server.sh PASS
test-vision.sh PASS
test-graph.sh PASS
test-opencode.sh Server starts, Test 1 passes; Test 2 dies on a local npm install opencode-ai (Killed: 9), unrelated to this change — that job is already continue-on-error

No behaviour change for models without KV-shared layers: server, vision and graph exercise other checkpoints and still pass.

Note for reviewers

I could not recover the history behind the isAssistant assumption in Gemma4Text (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

Aegis AI Assistant and others added 2 commits August 6, 2026 14:47
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
solderzzc merged commit 717d77f into main Aug 6, 2026
@solderzzc
solderzzc deleted the fix/gemma4-kv-shared-layers branch August 6, 2026 22:23
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]>
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.

gemma-4-e4b-it-4bit fails to load: KV-shared layers unimplemented (3 CI jobs permanently red)

1 participant