Repository navigation
fix(awq): replay with the layer's attention type, real rotary positions and explicit fallbacks (#4176) - #4243
Merged
Merged
Conversation
…xplicit fallbacks (#4176) - token-row replay selects the mask captured for the layer's own attention type (gemma-3/OLMo 3 full-attention layers no longer replay the sliding window) - Bloom ALiBi is rebuilt from the retained rows' positions instead of accepting a stale shape-compatible tensor; a mismatched alibi is refused with both shapes - retained rows' real positions survive _sanitize_kwargs under a private key and feed the rotary rebuild for position_embeddings-only attention modules - an all-NaN scale grid raises _AWQScaleGroupError so the configured fallback applies - the token-row budget and x_mean remain unchanged: raising the budget to 8192 or computing x_mean over all rows measured worse PPL on Llama-3.2-1B-Instruct; the measured table is recorded in docs/awq-calibration-aggregation.md
1 task done
Qubitium
added a commit
that referenced
this pull request
Nov 16, 2026
…ge (#4435) The dense AWQ CPU job failed deterministically per environment: 0.2582 on ubuntu-24.04 x86 CI and 0.2073 on an aarch64 SVE128 host, against a 0.20 bound. Torch dispatches to a CPU-capability-specific kernel, so identical deterministic weights round differently per microarchitecture; the value is stable within an environment (bit-identical at 842d666 and 89fa9f4). Bisect of the value: 0.1827 through 870fb44, 0.2073 from 241087a (#4176/#4243). That commit made token-row replay use the retained rows' real rotary positions instead of a synthetic arange for position_embeddings-only attention modules, which is a documented correctness fix. It lowers the NLL delta against fp16 from 0.2259 to 0.1579 while raising logit RMSE, so this is a metric trade-off, not a quality regression. The 0.20 bound predates the fix and was never re-validated against it. Widen to 0.30: ~16% headroom over the worst observed value, still catches a real quality collapse. NLL-delta, finiteness, packing and dtype checks are unchanged. Co-authored-by: GPTQModel CI Triage <[email protected]>
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.
Fixes #4176
TL;DR
Four AWQ replay defects fixed in
gptqmodel/looper/awq_processor.pyandgptqmodel/models/definitions/bloom.py:position_embeddingsbut notposition_ids;_AWQScaleGroupErrorso the configured fallback applies.Item 1 (token budget /
x_meanstratification) was implemented, measured anddeliberately not shipped: raising the budget to 8192, computing
x_meanover every captured row, and bin-centre sampling each measured worse PPL than
the current default on the issue's own model. The table and the reasoning are
in §5 and in
docs/awq-calibration-aggregation.md.1. Item 2 — replay used layer 0's attention type
Root cause.
AWQProcessor._token_row_replay_kwargs(
gptqmodel/looper/awq_processor.py:1623) read onlyinputs_cache.attention_masks, which holds the first decoder layer's mask.transformers5 builds one mask perconfig.layer_typesentry and the capturestage already stores every type under
_gptqmodel_layer_type_replay_kwargs(
models/base.py:3624), but AWQ never selected by type. On gemma-3-1b afull_attentionlayer was replayed with the sliding window: 0 allowed pairsat distance >=
sliding_window, identical to the sliding layers.Fix.
AWQProcessor._token_row_layer_type_masks(:1579) resolves the layerbeing quantized with
BaseQModel._resolve_layer_replay_type(read-only; nomodels/base.pyedit) and returns that type's mask per capture batch._token_row_replay_kwargsacceptsmask_overridesand prefers it over thelayer-0 mask.
_layer_input_featurespasses it through.Fail-before / pass-after (
tests/test_layer_type_replay.py::test_awq_token_row_replay_uses_the_layer_attention_type):2. Item 3 — Bloom accepted a stale ALiBi
Root cause.
BloomQModel.awq_module_replay_inputs(
gptqmodel/models/definitions/bloom.py:34) required an alibi of shape(batch * heads, 1, seq). A packed[1, N, H]replay only matches when theshapes coincide by accident, and in that case the captured sample's alibi —
built for
0..N-1— was accepted unchanged. With variable-length calibrationthe shapes miss and the group fell back to plain quantization.
Fix. The definition rebuilds ALiBi from the replay
position_ids/_awq_rotary_position_idsviaBloomQModel._awq_rebuild_alibi(:96):_get_alibi_slopes(num_heads) * retained_positionin float32, cast to theactivation dtype, which is bit-identical to
build_alibi_tensorfor contiguouspositions (verified for fp32/fp16/bf16, batch 1/3, heads 1/4). When no positions
are available and the captured alibi does not match the replay shape, it raises
with expected and actual shapes instead of accepting a stale tensor.
Fail-before / pass-after (
tests/test_bloom_awq_replay.py):3. Item 4 — rotary rebuilt from
arange(N)Root cause. HF Llama/Qwen3/Gemma attention takes
position_embeddings, notposition_ids.AWQProcessor._sanitize_kwargs(:4100) therefore dropped thereplay
position_ids, and_prepare_module_forward(:3556) rebuilt rotaryfrom
torch.arange(seq_len). The retained rows' positions were[0, 51, 102, ...], contradictingdocs/awq-calibration-aggregation.md("evaluated at the real positions").Fix.
_token_row_replay_kwargsalso returns the positions under the private_awq_rotary_position_idskey;_sanitize_kwargskeeps that key;_prepare_module_forwardpops it and uses it for the rotary rebuild beforefalling back to
arange. The key never reaches a module forward.Fail-before / pass-after (
tests/test_awq_weight_mean.py::test_awq_token_rows_replay_rotary_uses_the_retained_rows_positions):4. Item 5 — all-NaN grid raised a bare
ExceptionRoot cause.
_compute_best_scaleraised a message-lessExceptionwhenevery candidate loss was non-finite (
awq_processor.py:3428on the parent),bypassing the
_AWQScaleGroupErrorcontract that drives the configuredfallback, so one fp16 NaN replay aborted the whole run.
Fix. It now raises
_AWQScaleGroupErrornaming the module, its input width,and the candidate count (
:3495).Fail-before / pass-after (
tests/test_awq_weight_mean.py::test_awq_best_scale_all_nan_losses_raise_scale_group_error):5. Item 1 — token budget and
x_mean(measured, not shipped)Both remedies the issue proposes were implemented and measured on
Llama-3.2-1B-Instruct, W4 g128 asym GEMM, the first 128 C4 documents
(
raw_tokens=44997, default budget1024), 40 x 2048-token wikitext-2 chunks,save-then-reload before evaluation, 4 torch threads:
x_meanx_mean+ budget 8192x_mean+ bin-centre samplingFP16 12.634 and RTN 15.882 reproduce the issue's numbers exactly, so the model
and harness match. The final branch is 13.8902 (+0.011 vs the default); that
delta comes from item 4's real-position rotary and is within noise, as the
issue predicted. Item 4 is a correctness-of-contract fix, not a PPL win. The repeats are deterministic (13.87899 vs 13.87911,
13.93213 vs 13.93213), so the deltas are not noise: every proposed item-1
remedy is worse than the current default. HEAD default is already at the
level the issue measured for its raised budget (13.890), which is consistent
with intervening AWQ merges (#4091, #4121, #4123, #4151, #4187) having closed
the replay-quality gap.
The BOS over-representation is real (even spacing always takes row 0 and the
last row; BOS was 12.5% of retained rows vs 0.28% of the corpus). It is
documented as a known property of the bounded sample. A future change must move
the scale-grid statistic and the loss sample together, and must beat the default
on the table above; this PR deliberately does not change the default budget or
x_meanbecause both measured worse.docs/awq-calibration-aggregation.mdnowcarries the table and that constraint.
6. New replay flow
flowchart TD A["AWQProcessor._layer_input_features"] --> B["_token_row_budget<br/>bounded replay sample"] B --> C["_pack_token_rows with_provenance"] C --> D["_token_row_replay_kwargs"] D --> E["_token_row_layer_type_masks<br/>resolve this layer's type"] E --> F["_token_row_source_structure<br/>keep from the grid diagonal"] F --> G["block-diagonal attention_mask<br/>allowed & same_document"] F --> H["position_ids<br/>retained rows' real offsets"] H --> I["_awq_rotary_position_ids<br/>survives _sanitize_kwargs"] I --> J["_prepare_module_forward<br/>rotary at real positions"] D --> K["BloomQModel.awq_module_replay_inputs"] K --> L{"captured alibi matches<br/>replay shape and positions?"} L -- positions available --> M["_awq_rebuild_alibi<br/>slopes * retained positions"] L -- no positions, shape mismatch --> N["raise with expected and got shapes"] D --> O["_compute_best_scale"] O --> P{"any finite candidate loss?"} P -- no --> Q["_AWQScaleGroupError<br/>configured fallback applies"] P -- yes --> R["best scale"] style N fill:#ffd6d6,stroke:#b00020 style Q fill:#ffd6d6,stroke:#b000207. Tests
New tests (all 6 fail on the parent commit, all pass on the branch):
test_awq_token_row_replay_uses_the_layer_attention_typetest_bloom_awq_replay_rebuilds_alibi_for_packed_positionstest_bloom_awq_replay_rebuilds_alibi_matching_the_native_buildertest_bloom_awq_replay_refuses_a_mismatched_alibi_with_shape_contexttest_awq_token_rows_replay_rotary_uses_the_retained_rows_positionstest_awq_best_scale_all_nan_losses_raise_scale_group_errorRelated existing suites, re-run after merging
origin/main:Every command used
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4andtorch.set_num_threads(4). The host was heavilyloaded by other workers (load average reached ~990 before the caps); the PPL
numbers are deterministic across repeats, but the wall-clock timings carry
host-load variance and are reported only as rough cost.
8. Residual risk
_get_alibi_slopes; if that private helper disappears, the code derives slopes from the captured tensor and raisesNotImplementedError(explicit fallback) otherwise._search_best_clipstill reduces the packed sample; it compares activations against their own mean, so it does not inherit the scale-grid bias.