Repository navigation
fix(awq): replay packed calibration rows with their own mask and positions (#4091) - #4110
Merged
Merged
Conversation
…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.
This was referenced Nov 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #4091 (item 1)
TL;DR
AWQ with
batch_size>1crashed in the scale-search replay because the packedtoken-row replay dropped
attention_mask. The same drop also let rows fromdifferent 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:1337on
main) packs every module's captures into one[1, retained, hidden]token-row tensor with
_pack_token_rows(:930). Formode == "token_rows"itsets
feature_kwargs[name] = {}(:1370), because the packed rows no longermatch any single captured batch.
_search_best_scalethen merges the processor-wide_module_forward_kwargs.For
batch_size>1that mask is[4, 1, S, S], and_align_module_kwargs_to_input(:1210) cannot map it onto the packed rows, soit drops both
attention_maskandposition_ids._build_chunked_reference_outputs(:2486) ->_iter_prepared_forward_outputs(
:3028) then calls the attention module without its required mask:Even where the module does not require the argument,
attention_mask=Nonemakes 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-1range. 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 backto its
[document, position]cell from the cached mask. A[B, S, S]masksupplies the model's own per-query relation (causal, padding, sliding
window); a
[B, S]mask supplies the kept set and the replay adds causalorder among the kept rows.
AWQProcessor._token_row_replay_kwargs(:1298) builds an additive[1, 1, retained, retained]mask that is block-diagonal per document, plusposition_ids[1, retained]with the original offsets (the cachedposition_idswhen they are available)._layer_input_featuresinstalls those as the per-feature kwargs._align_module_kwargs_to_inputpasses them through unchanged (its repack isthe identity for a one-document packed mask), and
_prepare_module_forwardrecomputes rotary from the real positions.
q/k/v,gate/up) share one capture list, so thequadratic 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):TypeErroras above. After:QUANTIZE_OKfor the sameQwen2.5-0.5B-Instructrun (32 C4 documents, AWQ 4-bit g128 sym), then save,reload and evaluate:
batch_size_4_ppl = 25.5186on 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
mainat1732d2ae3; "AWQ after" is this branch. RTN does notuse the AWQ replay, so one RTN column serves both.
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, whichmeasures 59.6 PPL unquantized in this harness; the #4095 row was taken with a
different checkpoint (inference: the base
gemma-3-1b-pt, not presentlocally). The Llama values also differ from #4095 because
mainmoved afterthat 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:#38761dBefore/after of the replay kwargs:
batch_size>1captureTypeErrorin attentiontoken_rowsreplayattention_mask=None, cross-document causal, synthetic positionsNone(batch_size=1)attention_mask=None, synthetic positionsattention_mask=NoneThe committed reference page is
docs/awq-calibration-aggregation.md(alreadylinked from
README.md).Tests
tests/test_awq_weight_mean.py::test_awq_token_rows_replay_mask_stays_inside_each_documentbuilds 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 intothe other. On
origin/mainit fails withKeyError: 'attention_mask'.tests/test_awq_weight_mean.py::test_awq_token_rows_replay_keeps_a_2d_mask_two_dimensionalpins 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.
tests/test_awq_variable_length_ppl.py::test_awq_quantize_with_batch_size_greater_than_onereproduces the issue's
batch_size=4call end to end (quantize, save,reload, PPL). On
origin/mainit raises theTypeErrorabove.This branch also fixes cross-file test pollution from the merged #4104 helper:
ShapeOnlyAwqGemmwas aBaseQuantLinearsubclass declaringAWQ_GEMM/GEMM,so collecting
tests/test_awq_variable_length_ppl.pyandtests/test_awq_dynamic_group_size.pyin one process madeget_kernel_for_backendreject the realAwqGEMMLinearas ambiguous. It is nowa non-subclass stub that calls
AwqGEMMLinear._validate(check_platform=False).CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-... GPTQMODEL_AWQ_PPL_WIKITEXT=/tmp/wikitext2_test.txt pytest -q tests/test_awq_variable_length_ppl.pytests/test_awq_dynamic_group_size.pyHIP_VISIBLE_DEVICES=1 pytest -q tests/test_awq_dynamic_group_size.pyHIP_VISIBLE_DEVICES=1 ... pytest -q tests/test_awq_variable_length_ppl.py::test_awq_quantize_with_batch_size_greater_than_oneHIP_VISIBLE_DEVICES=1 pytest -q tests/test_awq_weight_mean.pyruff check gptqmodel docs/eora tests setup.pyThe remaining
tests/test_awq_weight_mean.pyfailures(
test_awq_early_layer_completion_releases_all_feature_statex2 andtest_awq_search_best_scale_coalesces_cpu_activation_replay) also fail onorigin/mainin the same ROCm environment. Thetest_awq_weight_mean_matches_legacy_impl_*timing assertion is pre-existingand flaky: it failed on 2 of 3 parametrizations on
mainand on 0-2 of 3 here,depending on the run. The file does not collect on the CUDA venv because
parameterizedis absent, which is why the unit tests were run on the ROCmvenv.
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.