Skip to content

fix(awq): replay with the layer's attention type, real rotary positions and explicit fallbacks (#4176) - #4243

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4176-token-row-aggregation
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4176-token-row-aggregation

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4176

TL;DR

Four AWQ replay defects fixed in gptqmodel/looper/awq_processor.py and
gptqmodel/models/definitions/bloom.py:

  1. token-row replay now uses the layer's own attention type instead of layer 0's mask;
  2. Bloom ALiBi is rebuilt from the retained rows' positions, or refused with both shapes, instead of silently accepting a stale shape-compatible tensor;
  3. the retained rows' real positions reach the rotary rebuild for attention modules that take position_embeddings but not position_ids;
  4. an all-NaN scale grid raises _AWQScaleGroupError so the configured fallback applies.

Item 1 (token budget / x_mean stratification) was implemented, measured and
deliberately not shipped: raising the budget to 8192, computing x_mean
over 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 only
inputs_cache.attention_masks, which holds the first decoder layer's mask.
transformers 5 builds one mask per config.layer_types entry and the capture
stage already stores every type under _gptqmodel_layer_type_replay_kwargs
(models/base.py:3624), but AWQ never selected by type. On gemma-3-1b a
full_attention layer was replayed with the sliding window: 0 allowed pairs
at distance >= sliding_window
, identical to the sliding layers.

Fix. AWQProcessor._token_row_layer_type_masks (:1579) resolves the layer
being quantized with BaseQModel._resolve_layer_replay_type (read-only; no
models/base.py edit) and returns that type's mask per capture batch.
_token_row_replay_kwargs accepts mask_overrides and prefers it over the
layer-0 mask. _layer_input_features passes it through.

Fail-before / pass-after (tests/test_layer_type_replay.py::test_awq_token_row_replay_uses_the_layer_attention_type):

parent:  AssertionError: full-attention layer replayed with the sliding mask:
         allowed pairs at distance 5 = False
branch:  1 passed

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 the
shapes coincide by accident, and in that case the captured sample's alibi —
built for 0..N-1 — was accepted unchanged. With variable-length calibration
the shapes miss and the group fell back to plain quantization.

Fix. The definition rebuilds ALiBi from the replay position_ids /
_awq_rotary_position_ids via BloomQModel._awq_rebuild_alibi (:96):
_get_alibi_slopes(num_heads) * retained_position in float32, cast to the
activation dtype, which is bit-identical to build_alibi_tensor for contiguous
positions (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):

parent:  test_..._rebuilds_alibi_for_packed_positions
         AssertionError: Tensor-likes are not equal!   (stale alibi accepted)
         test_..._rebuilds_alibi_matching_the_native_builder
         AssertionError: Tensor-likes are not equal!
         test_..._refuses_a_mismatched_alibi_with_shape_context
         AssertionError: assert ('expected' in 'Bloom AWQ replay requires captured, batch/sequence-aligned alibi')
branch:  3 passed

3. Item 4 — rotary rebuilt from arange(N)

Root cause. HF Llama/Qwen3/Gemma attention takes position_embeddings, not
position_ids. AWQProcessor._sanitize_kwargs (:4100) therefore dropped the
replay position_ids, and _prepare_module_forward (:3556) rebuilt rotary
from torch.arange(seq_len). The retained rows' positions were
[0, 51, 102, ...], contradicting
docs/awq-calibration-aggregation.md ("evaluated at the real positions").

Fix. _token_row_replay_kwargs also returns the positions under the private
_awq_rotary_position_ids key; _sanitize_kwargs keeps that key;
_prepare_module_forward pops it and uses it for the rotary rebuild before
falling 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):

parent:  AssertionError: rotary was rebuilt from synthetic arange positions
         instead of the retained rows' real positions
branch:  1 passed

4. Item 5 — all-NaN grid raised a bare Exception

Root cause. _compute_best_scale raised a message-less Exception when
every candidate loss was non-finite (awq_processor.py:3428 on the parent),
bypassing the _AWQScaleGroupError contract that drives the configured
fallback, so one fp16 NaN replay aborted the whole run.

Fix. It now raises _AWQScaleGroupError naming 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):

parent:  E   Exception
         gptqmodel/looper/awq_processor.py:3428: Exception
branch:  1 passed (asserts _AWQScaleGroupError, module name and reason)

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 budget 1024), 40 x 2048-token wikitext-2 chunks,
save-then-reload before evaluation, 4 torch threads:

Run PPL quantize wall-clock
FP16 12.6343 –
RTN 15.8825 15.6 s
HEAD default (1024 rows) 13.8790 (13.8791 on a repeat) 48.6 s (48.6 s)
HEAD + budget 8192 13.9253 58.8 s
HEAD + full-corpus x_mean 13.9321 (13.9321 on a repeat) 54.5–64.8 s
HEAD + full-corpus x_mean + budget 8192 13.9076 63.2 s
HEAD + full-corpus x_mean + bin-centre sampling 14.0543 51.4 s
Final branch (items 2–5) 13.8902 47.7 s

FP16 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_mean because both measured worse. docs/awq-calibration-aggregation.md now
carries 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:#b00020
Loading

7. Tests

New tests (all 6 fail on the parent commit, all pass on the branch):

Test Parent Branch
test_awq_token_row_replay_uses_the_layer_attention_type FAIL PASS
test_bloom_awq_replay_rebuilds_alibi_for_packed_positions FAIL PASS
test_bloom_awq_replay_rebuilds_alibi_matching_the_native_builder FAIL PASS
test_bloom_awq_replay_refuses_a_mismatched_alibi_with_shape_context FAIL PASS
test_awq_token_rows_replay_rotary_uses_the_retained_rows_positions FAIL PASS
test_awq_best_scale_all_nan_losses_raise_scale_group_error FAIL PASS

Related existing suites, re-run after merging origin/main:

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

PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest tests/test_awq_weight_mean.py \
  -k "token_row or all_nan_losses_raise_scale_group or retained_rows_positions" -q
# 30 passed, 58 deselected

PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest tests/test_bloom_awq_replay.py tests/test_layer_type_replay.py -q
# 52 passed

Every command used OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4 and torch.set_num_threads(4). The host was heavily
loaded 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

  • Item 1's sampling bias is documented but not fixed; the measured remedies are worse on this corpus.
  • The layer-type override falls back to layer 0's mask when a type has no captured entry (unsupported builder); that path is unchanged.
  • Bloom ALiBi rebuild assumes the model uses HF's _get_alibi_slopes; if that private helper disappears, the code derives slopes from the captured tensor and raises NotImplementedError (explicit fallback) otherwise.
  • _search_best_clip still reduces the packed sample; it compares activations against their own mean, so it does not inherit the scale-grid bias.

…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
@Qubitium
Qubitium merged commit 241087a into main Nov 16, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/issue-4176-token-row-aggregation branch November 16, 2026 05:43
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]>
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] Default token-row aggregation samples ~2% of calibration tokens; replay ignores per-layer attention type, Bloom ALiBi and real positions

1 participant