Skip to content

fix(awq): supply KV-shared state for Gemma consumer replay - #6317

Merged
Qubitium merged 1 commit into
mainfrom
fix/6302-gemma-kvshare
Nov 29, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/6302-gemma-kvshare

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #6316.

AWQ replays the first decoder layer's captured kwargs. The Gemma text stacks
create one KVSharingDict before the decoder loop and pass it to every layer as
shared_kv_states; the first-layer pre-hook sees it empty, so the captured
value is {}. Replaying a KV-shared consumer attention then executes
shared_kv_states[self.layer_type] and raises KeyError. Gemma 3n defaults to
num_kv_shared_layers=15, so a default-config quantize has a 15-layer consumer
tail.

What Changed

  • New gptqmodel/models/definitions/_kv_shared_replay.py:
    • rebuild_kv_shared_replay_states: for a KV-shared consumer attention,
      resolve its producer layer from config.kv_sharing_modes / layer_types,
      project the packed replay rows through the producer's
      k_proj/k_norm/v_proj/v_norm, rotate with the replay's own positions,
      and return a KVSharingDict aligned to those rows. It never returns {};
      if the producer is unavailable (meta/offload, missing rotary) it raises
      NotImplementedError, which AWQProcessor._prepare_module_forward already
      converts to _AWQScaleGroupError so the configured fallback applies.
    • retarget_kv_shared_attention_groups: keeps only the consumer projection
      that actually reads the fold source (q_proj) in the input-norm group and
      re-anchors module2inspect on that linear.
  • gemma3n.py, gemma4.py (text + composite), gemma4_unified.py (text +
    composite): add awq_module_replay_inputs and
    awq_get_modules_for_scaling hooks delegating to the shared helper.
  • tests/test_awq_shared_kv_states_replay.py: 11 CPU-only tests covering
    Gemma 3n, Gemma 4 text + composite, and Gemma 4-Unified (sliding and full
    consumers), plus the norm-fold neutrality invariant and one end-to-end tiny
    AWQ quantize.

Which option, and why

The task offered (a) supply usable shared_kv_states derived from the packed
replay rows, (b) exclude consumer layers from the packed replay, or (c) capture
the producer layer too. This PR does (a) + (b), because (a) alone leaves a
silent numerics bug:

  1. (a) Rebuild the producer K/V from the packed rows. The producer's own
    activation is not in the first-layer capture, so the only row-aligned source
    is the replay's own input. Applying the producer's K/V projections to those
    rows reproduces exactly what the producer layer would store for the same
    tokens (verified: the rebuilt tensors equal a producer attention forward on
    the same x/positions). This keeps the consumer's shared-KV behaviour and
    never passes {}. This hook is the crash fix for any consumer-attention
    replay.
  2. (b) Score the consumer's norm-fed projection alone. For a KV-shared
    consumer the tree tracker cannot anchor o_proj on a missing v_proj, so it
    falls back to input_layernorm and merges o_proj into q_proj's group.
    o_proj reads the attention output, not the norm, so folding a non-uniform
    scale into it changes the decoder layer output (measured 1.839e-01
    relative change on a tiny Gemma 4 consumer with
    scales = 1 + 0.05*arange(hidden)). Re-anchoring on q_proj makes the fold
    exactly neutral (~2e-07) and removes the attention-block replay from the
    AWQ path; o_proj is still AWQ-quantized plainly (asserted end-to-end).
    This follows 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).

Option (c) was rejected: capturing every producer layer would change the
first-layer-only capture contract and keep full-length K/V for every calibration
batch (the OOM class #3245 already dealt with).

Tests

Red at origin/main 89dbcf91 (fix files reverted, new test kept):

cd /root/openai-audit/issue-6302/tests
PYTHONPATH=/root/openai-audit/issue-6302:/root/openai-audit/issue-6302/tests \
  CUDA_VISIBLE_DEVICES="" /root/venv/bin/python -m pytest \
  test_awq_shared_kv_states_replay.py -q -p no:cacheprovider
FAILED test_awq_shared_kv_states_replay.py::test_gemma3n_consumer_replay_rebuilds_producer_kv[sliding-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma3n_consumer_replay_rebuilds_producer_kv[full-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_consumer_replay_rebuilds_producer_kv[sliding-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_consumer_replay_rebuilds_producer_kv[full-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_unified_consumer_replay_rebuilds_producer_kv[sliding-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_unified_consumer_replay_rebuilds_producer_kv[full-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_composite_consumer_replay_rebuilds_producer_kv[sliding-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_composite_consumer_replay_rebuilds_producer_kv[full-consumer]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_consumer_fold_scores_only_the_norm_fed_projection[gemma4-text]
FAILED test_awq_shared_kv_states_replay.py::test_gemma4_consumer_fold_is_neutral[gemma4-text]
10 failed, 1 passed

KeyError tracebacks (origin/main):

../gptqmodel/models/ports/native/gemma3n/modeling_gemma3n.py:1224: KeyError
E           KeyError: 'sliding_attention'
../gptqmodel/models/ports/native/gemma4/modeling_gemma4.py:1225: KeyError
E           KeyError: 'sliding_attention'
../gptqmodel/models/ports/native/gemma4_unified/modeling_gemma4_unified.py:405: KeyError
E           KeyError: 'sliding_attention'

Green after the fix:

cd /root/openai-audit/issue-6302/tests
PYTHONPATH=/root/openai-audit/issue-6302:/root/openai-audit/issue-6302/tests \
  CUDA_VISIBLE_DEVICES="" /root/venv/bin/python -m pytest \
  test_awq_shared_kv_states_replay.py test_gemma3_vl_support.py test_gemma4_support.py \
  test_gemma4_unified_support.py module_tree/test_gemma_olmo_family_plan_coverage.py \
  test_awq_scaling_groups.py module_tree/test_awq_relationships.py \
  -q -rs -p no:cacheprovider
279 passed, 2 skipped in 44.12s

The two skips are pre-existing in test_awq_scaling_groups.py
(opt350/muse_glimmer are not buildable CausalLM families there). The new
test file alone is 11 passed in 4.05s.

Also run:

cd /root/openai-audit/issue-6302/tests
PYTHONPATH=/root/openai-audit/issue-6302:/root/openai-audit/issue-6302/tests \
  CUDA_VISIBLE_DEVICES="" /root/venv/bin/python -m pytest \
  test_awq_scale_search_safety.py test_awq_empty_groups.py \
  test_model_port_policy.py test_transformers_unpatched.py \
  test_native_definition_loading_1.py -q -rs -p no:cacheprovider
# 42 passed (scale-search/empty-groups) and 47 passed (policy/native loading)

/root/venv/bin/ruff check \
  gptqmodel/models/definitions/_kv_shared_replay.py \
  gptqmodel/models/definitions/gemma3n.py \
  gptqmodel/models/definitions/gemma4.py \
  gptqmodel/models/definitions/gemma4_unified.py \
  tests/test_awq_shared_kv_states_replay.py
# All checks passed!

Skips / unverified

  • CPU-only (CUDA_VISIBLE_DEVICES=""); no GPU end-to-end checkpoint was
    quantized.
  • tests/models/test_gemma3n.py was not run: it quantizes the 11 GB
    /monster/data/model/gemma-3n-E2B-it checkpoint on CPU and was still running
    after several minutes (killed). The tiny native-port fixtures plus the
    module-tree/AWQ suites cover the changed code paths.
  • Composite Gemma 3n (Gemma3nForConditionalGenerationGPTQ) has the same
    two-line hooks as the text class but was not instantiated in the tests;
    Gemma 4's composite class is covered.
  • The producer layer may already be AWQ-packed when a consumer replay runs; the
    rebuild uses the producer module as-is (dequantizing forward), but that path
    is not exercised end-to-end here because the group retarget removes the
    consumer-attention replay from the real AWQ flow.

Model Support / Module Plan

No module-tree changes: awq_get_modules_for_scaling only narrows the emitted
scaling group for KV-shared consumer layers. Every quantizable linear still
quantizes; the end-to-end test asserts the consumer q_proj and o_proj are
AwqTorchLinear after quantize().

Gemma 3n / Gemma 4 / Gemma 4-Unified replay their KV-sharing tail with the
first decoder layer's captured kwargs. That capture holds an empty (or
last-batch) shared_kv_states dict, so a consumer attention raised
KeyError: '<layer_type>'.

The definitions now rebuild the producer layer's K/V for the exact packed
replay rows and never substitute the empty/stale dict. The consumer's
input-norm group is also re-anchored on q_proj: o_proj reads the attention
output, so folding the norm into it changed the decoder layer output.
@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 07:57
@Qubitium
Qubitium merged commit c2f5b4f into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/6302-gemma-kvshare branch November 29, 2026 07:57
Qubitium pushed a commit that referenced this pull request Nov 29, 2026
…transformers 5.23 drift (#5325 section C)

Rebased onto 356a5e0, keeping #6317's KV-shared consumer replay hooks
(awq_module_replay_inputs / awq_get_modules_for_scaling) alongside this
PR's unused full-length KV-store guard.
Qubitium added a commit that referenced this pull request Nov 29, 2026
…transformers 5.23 drift (#5325 section C) (#6282)

Rebased onto 356a5e0, keeping #6317's KV-shared consumer replay hooks
(awq_module_replay_inputs / awq_get_modules_for_scaling) alongside this
PR's unused full-length KV-store guard.

Co-authored-by: rebuild <rebuild@local>
Qubitium added a commit that referenced this pull request Nov 29, 2026
…folds

Rebased onto main after the 07:55-08:05 merge wave.

`main` already carries #6317's KV-shared fold retarget
(`retarget_kv_shared_attention_groups`). This branch's
`_retarget_attention_output_folds` is the broader form of the same rule --
it also covers `attention_k_eq_v` layers, which own `q_proj`/`k_proj` but no
`v_proj` -- so the merged code keeps #6317's `awq_module_replay_inputs`
replay wiring and uses the broader retarget for `awq_get_modules_for_scaling`.
The two are idempotent with respect to each other: once `o_proj` is gone the
second pass is a no-op.
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.

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

1 participant