Skip to content

fix(awq): cap packed token-row replay at the model position limit - #5120

Merged
Qubitium merged 1 commit into
mainfrom
fix/5085-gptneo-awq-replay
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5085-gptneo-awq-replay

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Problem

AWQ packs the captured rows of several calibration documents into one
[1, retained_tokens, hidden] replay sequence
(AWQProcessor._pack_token_rows). _token_row_budget is
max(largest batch's kept tokens, number of batches), so with
batch_size > 1 the packed sequence is about batch_size x seq_len tokens.
A block-diagonal mask and the retained rows' positions keep that semantically
correct for attention implementations that read their causal structure from
attention_mask.

GPTNeoSelfAttention does not. It slices a fixed
[max_position_embeddings, max_position_embeddings] buffer:

causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
attn_weights = torch.where(causal_mask, attn_weights, mask_value)

When the packed replay is longer than max_position_embeddings the slice is
clipped and torch.where raises. That is a plain RuntimeError, not an
_AWQScaleGroupError, so the configured fallback never ran and quantize()
aborted in layer 0. Reproduced on main at e75181df5 with the real
gpt-neo-125m position geometry (max_position_embeddings=2048,
window_size=256, 2 layers x 128 hidden, four 1100-token rows):

Run Result
AWQ, batch_size=1 OK
AWQ, batch_size=2 RuntimeError: The size of tensor a (2048) must match the size of tensor b (2200) at non-singleton dimension 3
GPTQ, batch_size=2 OK

OpenAI GPT has the same fixed [n_positions, n_positions] buffer and clips it
without raising (self.bias[:, :, :w.size(-2), :w.size(-1)]); rows past the
limit would be scored against a silently truncated causal mask.

Old flow

flowchart TD
    A["_layer_input_features"] --> B["_token_row_budget<br/>max(largest_batch, batches)"]
    B --> C["_pack_token_rows<br/>batch_size x seq_len rows"]
    C --> D["_search_best_scale reference replay"]
    D --> E{"torch.where against fixed<br/>causal buffer"}
    E -- "fits" --> F["20-candidate grid"]
    E -- "over limit" --> G["RuntimeError<br/>quantize aborts<br/>fallback never runs"]
    style G fill:#f8d7da,stroke:#842029,stroke-width:2px
Loading

New flow

flowchart TD
    A["_layer_input_features"] --> B["policy max_tokens?"]
    B -- yes --> C["int(max_tokens)"]
    B -- no --> D["_token_row_budget<br/>max(largest_batch, batches)"]
    C --> E["_cap_token_rows<br/>min(budget, position_limit)"]
    D --> E
    E --> F["_pack_token_rows<br/>[1, retained, hidden]"]
    F --> G["_search_best_scale reference replay"]
    G --> H{"Torch tensor geometry error?"}
    H -- yes --> I{"configured fallback?"}
    I -- yes --> J["plain quantization<br/>every leaf packed"]
    I -- no --> K["_AWQScaleGroupError"]
    H -- no --> L["20-candidate grid<br/>apply_scale"]
    style K fill:#f8d7da,stroke:#842029,stroke-width:2px
    style J fill:#ffe9b3,stroke:#b38600,stroke-width:2px
Loading
Situation Before After
Packed replay exceeds the declared limit RuntimeError, run aborts budget clamped to the limit
Definition declares its own max_tokens used unclamped clamped the same way
Residual replay geometry failure, fallback set RuntimeError, run aborts _AWQScaleGroupError, group quantized plainly
Residual replay geometry failure, fallback=None RuntimeError _AWQScaleGroupError
Memory / kernel / numerical RuntimeError propagates propagates unchanged
Config declares no limit unclamped budget unclamped budget

Changes

File Purpose
gptqmodel/utils/model.py new resolve_position_limit() + POSITION_LIMIT_CONFIG_KEYS, reading the same config keys calibration truncation uses and recursing into nested decoder configs
gptqmodel/looper/awq_processor.py _position_limit() (cached), _cap_token_rows(), clamped budget and max_tokens, _is_replay_geometry_error() and the _AWQScaleGroupError conversion around the reference replay
docs/awq-calibration-aggregation.md budget formula, clamp rationale, new flow diagram, fallback contract, regression table
tests/test_awq_gpt_neo_packed_replay_5085.py new regression family

The bound is applied only where the packed replay is built; per-batch capture
and the chunked forward are unchanged, and no mask, position or numerical
behavior changes when the packed rows already fit.

Validation

Commands run from the repository root. Environment: Python 3.14 free-threaded,
Torch 2.15, Transformers 5.22.

Red evidence on the unmodified base (origin/main before this branch), the
same test bodies against the broken code:

$ python -m pytest tests/_red_5085.py -q -ra
FAILED tests/_red_5085.py::test_awq_gpt_neo_batch_of_two_quantizes_within_the_limit
E   RuntimeError: The size of tensor a (64) must match the size of tensor b (80) at non-singleton dimension 3
    transformers/models/gpt_neo/modeling_gpt_neo.py:119: RuntimeError
PASSED tests/_red_5085.py::test_control_batch_of_one_keeps_every_row    # control
1 failed, 1 passed

Green evidence on this branch:

$ python -m pytest tests/test_awq_gpt_neo_packed_replay_5085.py -q -ra
5 passed

Covered by that file: the limit resolver (all keys + nested config), the clamp
(limit present / absent / zero), native GPT-Neo AWQ with batch_size=2 under a
64-position limit (all 12 leaves pack, logits finite), the batch_size=1
control (all 40 rows replayed), and the fallback contract (configured fallback
packs every leaf; fallback=None raises _AWQScaleGroupError).

End-to-end issue reproduction, real max_position_embeddings=2048 geometry,
four 1100-token rows, batch_size=2:

before: FAILED awq 2 RuntimeError The size of tensor a (2048) must match the size of tensor b (2200)
after:  OK awq 2

Affected family suites (CPU):

$ python -m pytest -q 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

$ python -m pytest -q tests/test_awq_weight_mean.py tests/test_awq_hash_moe_kept_rows_5015.py \
    tests/test_awq_mpt_replay_4872.py tests/test_awq_conv1d_gpt2_4887.py
102 passed

$ bash format/check.sh
All checks passed!

Skips: none in the nodes above. One pre-existing GPT-Neo test-family gap
remains closed by this PR: no AWQ test ran GPT-Neo with batch_size > 1.

Scope limits

  • The clamp uses the config-declared limit. A model that bounds its context
    below the declared value (or a definition-declared max_tokens larger than
    the limit) now reaches the fallback instead of aborting, but the scale search
    cannot run there. No such definition exists in this repository today.
  • The packer still concatenates rows from several documents; the clamp reduces
    how many rows are retained, it does not replay per document.
  • test_awq_position_kwargs.py::test_variable_length_awq_runs_on_remote_family
    skips here because its local model fixtures are absent. It covers variable
    length replay, not the packed-length bound, and is unaffected by this change.

Fixes #5085

AWQ packs the captured rows of several calibration documents into one
[1, retained, hidden] replay sequence, so with batch_size > 1 the packed
length is about batch_size * seq_len. The block-diagonal mask and the
retained rows' positions keep that correct for mask-driven attention, but
GPTNeoSelfAttention slices a fixed [max_position_embeddings,
max_position_embeddings] causal buffer. An over-long replay clips the
slice and torch.where raises a plain RuntimeError, so AWQ aborted in
layer 0 for every GPT-Neo checkpoint with batch_size > 1 (#5085).

Bound the token-row budget (and a definition-declared max_tokens) by the
model's declared sequence limit through a shared resolve_position_limit()
helper, and report a residual replay tensor-geometry failure as an
_AWQScaleGroupError so the configured fallback applies instead of
aborting quantize(). OpenAI GPT's [n_positions, n_positions] buffer is
clipped the same way without raising, so it benefits from the same bound.

Fixes #5085
Comment thread gptqmodel/utils/model.py Dismissed
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