Skip to content

fix(awq): replay packed calibration rows with their own mask and positions (#4091) - #4110

Merged
Qubitium merged 4 commits into
mainfrom
fix/awq-replay-mask
Nov 15, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/awq-replay-mask

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4091 (item 1)

TL;DR

AWQ with batch_size>1 crashed in the scale-search replay because the packed
token-row replay dropped attention_mask. The same drop also let rows from
different calibration documents attend to each other. The replay now carries a
per-document block-diagonal mask and each retained row's original position, so
the crash is gone and the scale-search objective is per document.

Root cause

AWQProcessor._layer_input_features (gptqmodel/looper/awq_processor.py:1337
on main) packs every module's captures into one [1, retained, hidden]
token-row tensor with _pack_token_rows (:930). For mode == "token_rows" it
sets feature_kwargs[name] = {} (:1370), because the packed rows no longer
match any single captured batch.

_search_best_scale then merges the processor-wide _module_forward_kwargs.
For batch_size>1 that mask is [4, 1, S, S], and
_align_module_kwargs_to_input (:1210) cannot map it onto the packed rows, so
it drops both attention_mask and position_ids.
_build_chunked_reference_outputs (:2486) -> _iter_prepared_forward_outputs
(:3028) then calls the attention module without its required mask:

model.quantize(c4_texts, batch_size=4)   # Qwen2.5-0.5B-Instruct, AWQ 4-bit g128
  awq_processor.py:2069 _search_best_scale -> :2506 _build_chunked_reference_outputs -> :3054 _iter_prepared_forward_outputs
  TypeError: Qwen2Attention.forward() missing 1 required positional argument: 'attention_mask'
39b6276^ (before #4071): OK      batch_size=1: OK

Even where the module does not require the argument, attention_mask=None
makes Hugging Face treat the concatenated rows as one causal sequence. Rows
sampled from document A attend to document B, and rotary sees a synthetic
0..retained-1 range. That is the semantic defect recorded as "plausible" in
#4095.

The fix

  • AWQProcessor._pack_token_rows(..., with_provenance=True) also returns
    (source batch, row) for every retained row.
  • AWQProcessor._token_row_source_structure (:1244) maps each kept row back
    to its [document, position] cell from the cached mask. A [B, S, S] mask
    supplies the model's own per-query relation (causal, padding, sliding
    window); a [B, S] mask supplies the kept set and the replay adds causal
    order among the kept rows.
  • AWQProcessor._token_row_replay_kwargs (:1298) builds an additive
    [1, 1, retained, retained] mask that is block-diagonal per document, plus
    position_ids [1, retained] with the original offsets (the cached
    position_ids when they are available).
  • _layer_input_features installs those as the per-feature kwargs.
    _align_module_kwargs_to_input passes them through unchanged (its repack is
    the identity for a one-document packed mask), and _prepare_module_forward
    recomputes rotary from the real positions.
  • Sibling projections (q/k/v, gate/up) share one capture list, so the
    quadratic mask is built once per unique list per layer. When no mask was
    captured, the previous kwargs are left unchanged.

Chosen approach: block-diagonal mask, not per-document replay chunks. The
reference and every grid step already stream one packed tensor through the same
prepared forward; a mask keeps that chunking and the reference/loss pairing
intact, and it also preserves model-specific masks (sliding window) exactly.
Splitting the replay per document would have needed a second replay structure
for the loss accumulation.

Before / after

Before (main): TypeError as above. After: QUANTIZE_OK for the same
Qwen2.5-0.5B-Instruct run (32 C4 documents, AWQ 4-bit g128 sym), then save,
reload and evaluate: batch_size_4_ppl = 25.5186 on 8 x 512 wikitext chunks.

Re-run of the #4095 AWQ-vs-RTN table

Same harness as tests/test_awq_variable_length_ppl.py: 128 C4 documents,
batch_size=1, group_size=128, 80 x 512 wikitext-2 chunks, save then reload.
"AWQ before" is main at 1732d2ae3; "AWQ after" is this branch. RTN does not
use the AWQ replay, so one RTN column serves both.

Model sym AWQ before sym AWQ after sym RTN asym AWQ before asym AWQ after asym RTN
Qwen2.5-0.5B-Instruct 24.92 24.26 24.84 22.23 22.09 22.77
Llama-3.2-1B-Instruct 22.61 22.57 25.35 21.23 21.29 24.03
gemma-3-1b-it 66.52 68.79 76.62 70.32 68.29 73.00

AWQ still beats RTN in all six cells after the fix. Qwen improves by 0.66
(sym) and 0.14 (asym) PPL. Llama sym improves by 0.04 and asym moves 0.06 the
other way. gemma sym loses 2.27 and gemma asym gains 2.03.

The absolute gemma values are higher than the 44.19 / 48.01 quoted in #4095
because the only gemma-3-1b checkpoint available here is gemma-3-1b-it, which
measures 59.6 PPL unquantized in this harness; the #4095 row was taken with a
different checkpoint (inference: the base gemma-3-1b-pt, not present
locally). The Llama values also differ from #4095 because main moved after
that table was taken (#4089 changed replay chunk sizing). Qwen RTN reproduces
#4063's 24.84 / 22.77 exactly, which anchors the harness.

Flow

flowchart TD
    A["capture hook stores per-batch rows"] --> B["AWQProcessor._layer_input_features"]
    B --> C["AWQProcessor._pack_token_rows with_provenance=True"]
    C --> D["provenance: source batch and row per retained token"]
    D --> E["AWQProcessor._token_row_source_structure"]
    E --> F["document and position per retained row"]
    F --> G["block-diagonal attention_mask 1,1,retained,retained"]
    F --> H["position_ids 1,retained with original offsets"]
    G --> I["_prepare_module_forward"]
    H --> I
    I --> J["attention replay: same-document causal only"]
    style G fill:#d9ead3,stroke:#38761d
    style H fill:#d9ead3,stroke:#38761d
Loading

Before/after of the replay kwargs:

Situation Before After
batch_size>1 capture mask dropped, TypeError in attention per-document block mask + positions
Any token_rows replay attention_mask=None, cross-document causal, synthetic positions same-document causal, original positions
Cached mask does not match the captured rows mask dropped each capture batch replayed as one contiguous document
Captured masks are all None (batch_size=1) attention_mask=None, synthetic positions additive block-diagonal fallback with original positions
No captured mask entries at all attention_mask=None kwargs unchanged
2-D captured mask (FlashAttention) mask dropped 2-D packed keep mask and original positions; causal masking stays inside the attention implementation, so cross-document separation is not expressible

The committed reference page is docs/awq-calibration-aggregation.md (already
linked from README.md).

Tests

  • New tests/test_awq_weight_mean.py::test_awq_token_rows_replay_mask_stays_inside_each_document
    builds one batch with two documents and asserts the packed mask is
    block-diagonal, the positions are [0,1,2,0,1], and no document crosses into
    the other. On origin/main it fails with KeyError: 'attention_mask'.
  • New tests/test_awq_weight_mean.py::test_awq_token_rows_replay_keeps_a_2d_mask_two_dimensional
    pins the form contract for a captured 2-D mask (FlashAttention): the replay
    keeps a 2-D packed keep mask instead of injecting a 4-D one.
  • New tests/test_awq_variable_length_ppl.py::test_awq_quantize_with_batch_size_greater_than_one
    reproduces the issue's batch_size=4 call end to end (quantize, save,
    reload, PPL). On origin/main it raises the TypeError above.
  • The existing variable-length AWQ-vs-RTN test still passes.

This branch also fixes cross-file test pollution from the merged #4104 helper:
ShapeOnlyAwqGemm was a BaseQuantLinear subclass declaring AWQ_GEMM/GEMM,
so collecting tests/test_awq_variable_length_ppl.py and
tests/test_awq_dynamic_group_size.py in one process made
get_kernel_for_backend reject the real AwqGEMMLinear as ambiguous. It is now
a non-subclass stub that calls AwqGEMMLinear._validate(check_platform=False).

Command Result
CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-... GPTQMODEL_AWQ_PPL_WIKITEXT=/tmp/wikitext2_test.txt pytest -q tests/test_awq_variable_length_ppl.py 2 passed (113.1 s)
same, together with tests/test_awq_dynamic_group_size.py 7 passed (103.7 s), no kernel-registry ambiguity
HIP_VISIBLE_DEVICES=1 pytest -q tests/test_awq_dynamic_group_size.py 5 passed
HIP_VISIBLE_DEVICES=1 ... pytest -q tests/test_awq_variable_length_ppl.py::test_awq_quantize_with_batch_size_greater_than_one 1 passed (74.9 s), PPL 26.05
HIP_VISIBLE_DEVICES=1 pytest -q tests/test_awq_weight_mean.py 75 passed, 3 pre-existing failures, 1 skipped (see below)
ruff check gptqmodel docs/eora tests setup.py All checks passed

The remaining tests/test_awq_weight_mean.py failures
(test_awq_early_layer_completion_releases_all_feature_state x2 and
test_awq_search_best_scale_coalesces_cpu_activation_replay) also fail on
origin/main in the same ROCm environment. The
test_awq_weight_mean_matches_legacy_impl_* timing assertion is pre-existing
and flaky: it failed on 2 of 3 parametrizations on main and on 0-2 of 3 here,
depending on the run. The file does not collect on the CUDA venv because
parameterized is absent, which is why the unit tests were run on the ROCm
venv.

Hardware: RTX 4090 (GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e), CUDA 13.0 /
torch 2.16.0.dev for the quantization and PPL runs; AMD R9700 (gfx1201) via
HIP_VISIBLE_DEVICES=1, ROCm 10.1 / torch 2.16.0.dev for the unit tests.

…tions (#4091)

- carry per-row provenance out of token-row packing
- build a per-document block-diagonal attention mask and original position ids
- fixes the batch_size>1 TypeError and cross-document attention in scale search
- docs/awq-calibration-aggregation.md: replay flow and measured A/B table

Part of #4091 (item 1)
The merged #4104 test helper subclassed AwqGEMMLinear, so it registered a
second AWQ_GEMM/GEMM kernel. Collecting the PPL test file and the group-size
test file in one process made get_kernel_for_backend reject the real kernel as
ambiguous. Use a non-subclass stub that delegates to AwqGEMMLinear._validate.
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.

1 participant