Skip to content

Commit df1d3f3

Browse files
authored
Fix Gemma 4 sanitize() not stripping KV projections for shared layers (#1240)
1 parent ed1fca4 commit df1d3f3

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

mlx_lm/models/gemma4_text.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,7 @@ def __call__(
609609

610610
def sanitize(self, weights):
611611
sanitized = {}
612+
first_kv_shared = self.args.num_hidden_layers - self.args.num_kv_shared_layers
612613
for k, v in weights.items():
613614
if any(
614615
s in k
@@ -622,6 +623,18 @@ def sanitize(self, weights):
622623
):
623624
continue
624625

626+
# KV-shared layers reuse K/V from earlier layers — drop their projections
627+
if any(
628+
s in k
629+
for s in (".self_attn.k_proj", ".self_attn.v_proj", ".self_attn.k_norm")
630+
):
631+
try:
632+
layer_idx = int(k.split("layers.")[1].split(".")[0])
633+
if layer_idx >= first_kv_shared:
634+
continue
635+
except (IndexError, ValueError):
636+
pass
637+
625638
if k.endswith(".experts.gate_up_proj"):
626639
base = k.removesuffix(".gate_up_proj")
627640
gate, up = map(mx.contiguous, mx.split(v, 2, axis=-2))

0 commit comments

Comments
 (0)