Skip to content

fix(awq): score Hymba's mixer input instead of replaying the KV-reuse block (#5098) - #5172

Merged
Qubitium merged 1 commit into
mainfrom
fix/5098-hymba-awq-kv-reuse
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5098-hymba-awq-kv-reuse

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5098.

#4891/#5019 made Hymba's AWQ replay receive the captured kwargs, but it was
only verified on a synthetic fixture and on a slice with no KV reuse. On a real
nvidia/Hymba-1.5B-Base checkpoint, AWQ still aborts at layer 2 — the first
KV-reuse consumer — with AssertionError: assert kv_last_layer is not None.

Root cause. Every Hymba checkpoint shares K/V across layers
(kv_reuse_group; 15 consumer layers of 32). A consumer's HymbaBlock projects
no K/V of its own: it reads the producing layer's kv_last_layer, which
ForwardExecutor injects for the real layer forward
(looper/forward_executor.py, enabled by HymbaQModel.write_shared_kv_cache).
That value is token-aligned ([b, heads, seq, d]) and is never part of the
per-linear activation capture, so it cannot be reconstructed from the retained
token rows. The input_layernorm -> mamba.in_proj group declared mamba as its
inspection module, so the scale search replayed HymbaBlock(x, **captured_kwargs)
without it.

The failure was a bare AssertionError raised inside the replayed module, which
the existing geometry-error path (_is_replay_geometry_error, RuntimeError
only) does not convert, so AWQConfig.fallback never ran and quantize() died.

Confirmation the bug is real and still on main: reproduced on the real
checkpoint at the current base 8a2fbeb2e, with the issue's exact traceback
(modeling_hymba.py, cuda_kernels_forward: assert kv_last_layer is not None)
at layer 2, after layer 2 sanitized 3 scaling groups. git log origin/main
contains nothing that touches this path, so main does not fix it.

What Changed

  • gptqmodel/models/definitions/hymba.py: HymbaQModel.awq_get_modules_for_scaling
    re-anchors the input_layernorm -> mamba.in_proj group's module2inspect
    onto the mamba.in_proj nn.Linear. That group has exactly one member and
    in_proj is the norm's only consumer, so the projection's own reconstruction
    error is precisely the group objective; the mixer's cross-layer K/V and packed
    causal mask are not needed to rank the scale. The fold is unchanged: the norm
    is still divided and in_proj's input rows still receive the scale. The
    re-anchor is skipped when the group has multiple members, the norm has
    declared _scale_consumers (the fold would leave the boundary), or the member
    is not an nn.Linear; those cases keep the mixed replay so the existing
    validation decides.
  • gptqmodel/looper/awq_processor.py: new AWQProcessor._invoke_replay_module,
    used by both the unchunked and chunked replay branches of
    _iter_prepared_forward_outputs. It converts an AssertionError raised by the
    replayed module into _AWQScaleGroupError, so an unscorable replay takes the
    configured plain-quantization fallback (or raises when fallback=None).
    Scope is deliberately narrow: the processor's own assertions and every
    non-AssertionError exception still propagate; there is no catch-all.
  • docs/awq-scaling-groups.md: new "Module replay failures and the scale-group
    fallback" and "hymba: KV-reuse layers" mechanism sections with the diagrams
    and the before/after table below.
  • tests/test_hymba_awq_4891.py: KV-reuse fixture (producer/consumer/reuse
    layers, a mixer that asserts on kv_last_layer, and a HymbaModel forward
    that threads it) plus 3 regressions.

No public API, config, CLI or checkpoint-format change. No behaviour switch.

Tests

Red evidence (broken implementation)

tests/test_hymba_awq_4891.py copied onto the pre-fix tree (04e745269), so it
fails for the intended reason and not on import or collection:

python -m pytest tests/test_hymba_awq_4891.py -q
# 3 failed, 7 passed
# FAILED ...::test_hymba_kv_reuse_group_scores_the_projection_not_the_mixer
# FAILED ...::test_hymba_kv_reuse_group_search_completes_without_cross_layer_kv
# FAILED ...::test_hymba_mixer_replay_without_cross_layer_kv_uses_the_configured_fallback
# E  AssertionError: assert kv_last_layer is not None   (fixture model, test 2 and 3)
# E  AssertionError: ... is _ReuseMamba(...).mamba     (test 1, boundary is the mixer)

Green

python -m pytest tests/test_hymba_awq_4891.py -q -rs
# 10 passed

Full AWQ CPU regression baseline from the AWQ skill, on this branch:

python -m pytest -q -rs \
  tests/test_awq_scale_search_safety.py \
  tests/test_awq_moe_router_scaling.py \
  tests/test_awq_empty_groups.py \
  tests/test_awq_position_kwargs.py \
  tests/test_awq_scale_search_memory.py \
  tests/test_bloom_awq_replay.py \
  tests/module_tree/test_awq_relationships.py \
  tests/module_tree/test_bloom_awq_relationships.py \
  tests/module_tree/test_registered_module_plans.py \
  tests/module_tree/test_definition_subset_ordering.py
# 581 passed

Additional affected AWQ suites:

python -m pytest -q -rs \
  tests/test_awq_mpt_replay_4872.py \
  tests/test_awq_moe_bypass_4223.py \
  tests/test_awq_rotary_device.py \
  tests/test_awq_scaling_groups.py \
  tests/test_awq_deepseek_v4_hash_moe_4880.py \
  tests/test_awq_weight_mean.py
# 262 passed, 5 skipped

Skips (not counted as validation): 3× mamba_ssm CUDA-only CPU fold cases; 2×
model families whose CausalLM is not constructible from the registry fixture
(opt350, muse_glimmer).

Real checkpoint, nvidia/Hymba-1.5B-Base (32 layers, BF16, sdpa)

q = GPTQModel.load(path, AWQConfig(bits=4, group_size=128), dtype=torch.bfloat16,
                   trust_remote_code=True, attn_implementation="sdpa")
q.quantize(CalibrationConfig(dataset=c4_128_rows, batch_size=1))
Before After
Result AssertionError at layer 2 QUANTIZE OK
Coverage aborted at the first KV-reuse consumer 32 layers / 160 modules
Fallbacks n/a (crash) 0 plain-quantization fallbacks; every group scored
save() n/a OK

Verified out of scope, not claimed by this PR: generation on that checkpoint path
currently fails in the remote HybridMambaAttentionDynamicCache.__init__
(KeyError: '0' on config.conv_dim). It reproduces identically on a
non-quantized model loaded through GPTQModel, so it is unrelated to #5098 and is
tracked separately.

Lint

ruff check gptqmodel tests setup.py docs
# All checks passed

Model Support / Module Plan

Not a new model or alias. HymbaQModel.module_tree is unchanged; the fix only
re-points an existing group's inspection module, so declared paths, ownership,
tags and roles are untouched. Module-plan tests above still pass.

Model test node IDs and results: tests/module_tree/test_registered_module_plans.py
and tests/module_tree/test_awq_relationships.py — passed (within the 581).

AWQ onboarding safety

  • Native forward evidence identifies the source, consumers and replay scope:
    input_layernorm → mamba.in_proj (single Linear member), and the mixer
    also reads kv_last_layer from the producing layer, which the capture
    never records.
  • Real-model neutral-fold and candidate-search coverage:
    test_hymba_awq_fold_is_output_preserving still pins that folding these
    groups reproduces the logits; test_hymba_kv_reuse_group_search_completes_without_cross_layer_kv
    drives the real _search_best_scale and asserts a finite per-channel scale
    is produced for the projection.
  • Failure rollback and configured fallback/error behaviour:
    test_hymba_mixer_replay_without_cross_layer_kv_uses_the_configured_fallback
    re-introduces the broken boundary, asserts the group is quantized plainly,
    that the layer is marked quantized, and that the fallback is logged; a
    non-assertion failure or fallback=None still raises.
  • Variant policy: KV-reuse consumer layers and producer layers both use the
    projection boundary (verified on the real 32-layer checkpoint); multi-member
    groups, norms with declared extra consumers and non-Linear members keep
    the pre-existing block replay and validation.

AWQ evidence: tests/test_hymba_awq_4891.py (10 nodes) plus the 581/262 suites
above. Limits: generation, GPU kernels and non-Hymba KV-reuse families were not
qualified by this change.

Logic Flow Documentation

  • This change alters a major logic flow, so the diagrams and docs page are
    included here and in docs/awq-scaling-groups.md (already linked from
    README.md).
  • Diagrams use shipped symbol names (awq_get_modules_for_scaling,
    _invoke_replay_module, _iter_prepared_forward_outputs,
    _AWQScaleGroupError, AWQConfig.fallback).
  • The removed mechanism is shown with file:line-level pointers below.
  • Failure and ambiguity paths are visually distinct.
  • The reference page repeats both diagrams and the table.

Removed / replaced mechanism

Before After
awq_get_modules_for_scaling emitted input_layernorm -> [mamba.in_proj] with module2inspect = HymbaBlock; _search_best_scale (gptqmodel/looper/awq_processor.py:3479 at e75181df5) replayed the mixer through _iter_prepared_forward_outputs (:4816) the same group is emitted with module2inspect = mamba.in_proj; the search replays the Linear only
a module-raised AssertionError propagated through _build_chunked_reference_outputs (:4039) and aborted quantize() _invoke_replay_module converts it to _AWQScaleGroupError; _quantize_layer (:3045-3051) applies the configured fallback or raises
only RuntimeError geometry failures were convertible (_is_replay_geometry_error, :99) AssertionError from the module is convertible too; processor assertions and other exception types are not
flowchart LR
    subgraph OLD["before: boundary is the mixer"]
        N1["input_layernorm"] --> M1["HymbaBlock.forward"]
        M1 --> R1["needs kv_last_layer<br/>and packed causal mask"]
        R1 --> X1["AssertionError<br/>aborts quantize()"]
    end
    subgraph NEW["after: boundary is the projection"]
        N2["input_layernorm"] --> P2["mamba.in_proj Linear"]
        P2 --> S2["score scale on the projection"]
        S2 --> F2["fold the norm; consumer stays quantized"]
    end
    style X1 fill:#f8d7da,stroke:#842029,stroke-width:2px
    style F2 fill:#d1e7dd,stroke:#0f5132,stroke-width:2px
Loading

New flow

flowchart TD
    A["HymbaQModel.awq_get_modules_for_scaling"] --> B["super(): input_layernorm -> mamba.in_proj<br/>module2inspect = HymbaBlock"]
    B --> C{"single Linear member,<br/>inspect is mamba,<br/>no _scale_consumers?"}
    C -- "no" --> D["keep the mixed block replay<br/>existing validation decides"]
    C -- "yes" --> E["module2inspect = mamba.in_proj"]
    E --> F["AWQProcessor._search_best_scale"]
    D --> F
    F --> G["_iter_prepared_forward_outputs"]
    G --> H["_invoke_replay_module"]
    H --> I{"module forward raised?"}
    I -- "no" --> J["score candidates and fold"]
    I -- "AssertionError" --> K["_AWQScaleGroupError"]
    K --> L{"AWQConfig.fallback set?"}
    L -- "yes" --> M["plain quantization for the group<br/>layer stays quantized"]
    L -- "no" --> N["raise; no unsafe fold"]
    I -- "other exception" --> O["propagate; abort quantize()"]
    style N fill:#f8d7da,stroke:#842029,stroke-width:2px
    style O fill:#f8d7da,stroke:#842029,stroke-width:2px
    style M fill:#fff3cd,stroke:#997404,stroke-width:2px
    style J fill:#d1e7dd,stroke:#0f5132,stroke-width:2px
Loading

Review Requirements

  • Reviewed this PR.
  • Matches existing structure and extension points: the definition overrides
    the documented awq_get_modules_for_scaling hook; the replay conversion
    sits beside the existing geometry-error conversion.
  • No monkeypatching, no env switch, no new dependency.
  • Surface minimized: one definition override, one helper used by the two
    existing replay call sites, docs and tests.

Kernel Accuracy Requirements

Not applicable: no kernel, dispatch, fusion or packed-storage change. The AWQ
math and folding path is unchanged.

Notes

  • The AssertionError conversion is generic (any replayed module can assert on
    missing cross-block context) but deliberately not a catch-all: only
    AssertionError from the module call itself becomes a scale-group error, and
    it still raises when fallback=None.
  • The re-anchor is a definition-level statement about hymba only, so other
    architectures keep their declared inspection boundaries.

… block (#5098)

A Hymba reuse_kv layer projects no K/V of its own: HymbaBlock reads the
producing layer's kv_last_layer, which ForwardExecutor threads between
layers and the per-linear activation capture never records. The
input_layernorm -> mamba.in_proj group replayed the whole HymbaBlock, so
every real checkpoint aborted at the first KV-reuse consumer with a bare
AssertionError, which the configured fallback could not catch.

Anchor that group's module2inspect on the mamba.in_proj Linear: it is the
single member of the group and its reconstruction error is the objective.
Keep the fold itself unchanged.

Also convert an AssertionError raised by a replayed module into
_AWQScaleGroupError so an unscorable replay takes the configured plain
quantization fallback instead of aborting quantize(). Processor-side
assertions and other exceptions still propagate.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 18, 2026 07:40
@Qubitium
Qubitium merged commit b2f1d83 into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5098-hymba-awq-kv-reuse branch November 18, 2026 08:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants