Skip to content

[BUG] AWQ calibration replay crashes with KeyError for KV-shared layers (Gemma3n / Gemma4) #6316

Done

Description

@Qubitium

Summary

AWQ calibration replay crashes on the KV-shared tail of the Gemma decoders
(Gemma 3n, Gemma 4, Gemma 4-Unified) with KeyError: 'sliding_attention' /
KeyError: 'full_attention'.

Only the first decoder layer's kwargs are captured
(gptqmodel/looper/stage_inputs_capture.py). The Gemma text stacks create one
KVSharingDict before the decoder loop and pass it to every layer as
shared_kv_states. At the first-layer pre-hook the dict is still empty, so the
captured value is {} (a plain dict snapshot for these UserDicts). AWQ then
replays a packed [1, rows, hidden] tensor through a consumer attention:

  • gptqmodel/models/ports/native/gemma3n/modeling_gemma3n.py:1224
  • gptqmodel/models/ports/native/gemma4/modeling_gemma4.py:1225
  • gptqmodel/models/ports/native/gemma4_unified/modeling_gemma4_unified.py:405

and the consumer executes key_states, value_states = shared_kv_states[self.layer_type].

Gemma 3n defaults to num_kv_shared_layers=15, so a default-config quantize has
a 15-layer consumer tail. Gemma 4 / Gemma 4-Unified have the same structure and
only avoid it when num_kv_shared_layers == 0.

Reproduction

CPU-only, tiny native ports, no downloads. Build a tiny Gemma 3n
(num_hidden_layers=6, num_kv_shared_layers=2) or Gemma 4 / Gemma 4-Unified
(num_hidden_layers=4, num_kv_shared_layers=2), then drive the definition's
awq_module_replay_inputs hook with the capture boundary AWQ uses:

model = Gemma3nForCausalLM(Gemma3nTextConfig(
    ..., num_hidden_layers=6, num_kv_shared_layers=2,
    layer_types=["sliding_attention", "full_attention"] * 3,
    attn_implementation="eager",
)).eval()
attention = model.model.layers[4].self_attn          # sliding consumer
x = torch.randn(1, 8, model.config.hidden_size)     # packed replay rows
positions = torch.arange(8).unsqueeze(0)
cos, sin = model.model.rotary_emb(x, positions, attention.layer_type)
captured = {
    "shared_kv_states": {},                          # first-layer capture
    "position_embeddings": (cos, sin),
    "position_ids": positions,
    "attention_mask": causal_mask,
}
_, kwargs = Gemma3nTextQModel.awq_module_replay_inputs(attention, x, captured)
attention(x, **kwargs)

At origin/main (89dbcf91) this fails:

../gptqmodel/models/ports/native/gemma3n/modeling_gemma3n.py:1224: KeyError
E           KeyError: 'sliding_attention'

The same failure reproduces at
gemma4/modeling_gemma4.py:1225,
gemma4_unified/modeling_gemma4_unified.py:405, and through the composite
Gemma4ForConditionalGenerationGPTQ definition. The full test matrix is
tests/test_awq_shared_kv_states_replay.py (10 failed, 1 passed at
89dbcf91; 11 passed after the fix).

An end-to-end tiny AWQ run can accidentally mask the crash: the producer
layers' AWQ replays write into the live captured dict before the consumer
layers are processed, so the dict happens to be populated. That path is
order-dependent and still not token-aligned in general (the dict holds the last
layer-replay batch, while the consumer replay packs rows from all batches), and
it fails as soon as a producer group is skipped, falls back, or is excluded.

Additional finding: the consumer group folds o_proj into the input norm

For a KV-shared consumer, the layer owns no v_proj. The AWQ tree tracker
therefore anchors o_proj on input_layernorm (the last gain norm) and
_merge_shared_source_nodes merges it with q_proj's group:

layer 2 sanitized groups: [['self_attn.q_proj', 'self_attn.o_proj'], ...]
module2inspect = Gemma4TextAttention (KV-shared)

o_proj reads the attention output, not the input norm. Folding a non-uniform
scale into input_layernorm and multiplying o_proj by it changes the decoder
layer output: a tiny Gemma 4 consumer layer measured 1.839e-01 relative
change for scales = 1 + 0.05*arange(hidden) (the fold is only neutral for a
uniform scale, which the offset-gain norm renormalizes away). The same group is
the one whose replay needs the producer's K/V, so fixing the crash by inventing
K/V alone would leave this silent fold error in place.

Suggested fix

  1. In the owning Gemma definitions, add awq_module_replay_inputs hooks that
    rebuild the producer's K/V for the packed replay rows (project the replay
    rows through the producer layer's k_proj/k_norm/v_proj/v_norm and
    rotate with the replay's own positions) instead of replaying the captured
    empty/stale dict. If the producer cannot be rebuilt, fail closed so the AWQ
    fallback applies; never pass {}.
  2. In awq_get_modules_for_scaling, keep only the consumer projection that
    actually reads the fold source (q_proj) in the norm group and re-anchor
    module2inspect on that linear (the Hymba single-member precedent, [BUG] #5019 (fix of #4891) incomplete: Hymba AWQ still always crashes on the real checkpoint at layer 2 - HymbaBlock replay lacks kv_last_layer for KV-reuse layers (AssertionError, no fallback) #5098).
    o_proj stays quantized plainly because it has no foldable source of its own.

Environment

origin/main = 89dbcf91, Transformers 5.23.0, Torch 2.15.0, CPU-only
(CUDA_VISIBLE_DEVICES="").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions