Skip to content

fix(awq): preserve the captured mask form and fallback precedence (#4121, #4125) - #4131

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4121-awq-replay-regression
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4121-awq-replay-regression

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4121 (items 1, 4, 5)
Part of #4125 (item 4)

TL;DR

  1. [BUG] Follow-up on #4093/#4087 fixes: #4110 regresses TeleChat2 AWQ (PR test fails on main), native load skips before_model_load (Ouro/Spark crash), legacy remote-code generate still broken, dynamic fallback overrides ignored, AWQ VL rotary crash, 4 more AWQ trees fold #4121 item 1 (regression from fix(awq): replay packed calibration rows with their own mask and positions (#4091) #4110). The AWQ token-row replay converted
    every captured attention grid with dim >= 3 into an additive float mask.
    TeleChat2's attention calls masked_fill, so tests/test_telechat2_coverage.py
    failed on main. The replay now rebuilds the mask in the captured form and
    polarity: additive stays additive, a Hugging Face bool keep grid stays bool,
    and a masked_fill bool grid (TeleChat2 triu(1)) stays bool with
    True = masked.
  2. [BUG] Follow-up on #4103/#4110: HF save_pretrained on ExLlamaV2/Marlin no longer refuses and writes runtime layout (reload = garbage, regression), AWQ CPU kernels still serialize int4pack, v1<->v2 copy lost via safetensors, per-document mask never built #4125 item 4. The kept-token set came from allowed_grid.any(dim=-1).
    A real Hugging Face bool mask keeps padding keys masked but a padding
    query row still sees the real keys, so every padding row counted as a real
    token, the != row_count check failed, and the per-document mask was never
    built for real padded batch_size>1 captures. It now comes from the grid
    diagonal.
  3. [BUG] Follow-up on #4093/#4087 fixes: #4110 regresses TeleChat2 AWQ (PR test fails on main), native load skips before_model_load (Ouro/Spark crash), legacy remote-code generate still broken, dynamic fallback overrides ignored, AWQ VL rotary crash, 4 more AWQ trees fold #4121 items 4 and 5. A per-module dynamic fallback override was
    applied and then overwritten by the processor-level fallback in GPTQ, MACaQ,
    QQQ and VPTQ (the last three never applied it at all), and
    normalize_fallback dropped smooth.

1. The problem

1a. masked_fill consumers got a float mask (#4121 item 1)

AWQProcessor._token_row_replay_kwargs (gptqmodel/looper/awq_processor.py:1439)
decided the replay mask's form from the captured rank alone:

if mask.dim() >= 3:
    # The model consumes an additive [B, 1, S, S] style mask.
    extended_mask = True            # main: awq_processor.py:1450
...
attention_mask = additive.unsqueeze(0).unsqueeze(0)   # main: :1498

TeleChat2QModel.awq_module_replay_inputs
(gptqmodel/models/definitions/telechat2.py:37) only supplies its own mask when
kwargs.get("attention_mask") is None, so the float grid went straight into the
remote attention's masked_fill:

pytest tests/test_telechat2_coverage.py
FAILED test_telechat2_awq_quantizes_attention_projections
  RuntimeError: masked_fill_ only supports boolean masks, but got mask with dtype c10::Half
  modeling_telechat2.py:507

The captured grid for that model is a bool [1, 1, S, S] whose True marks a
masked key (torch.ones(S, S).triu(1), sum S*(S-1)/2), i.e. the opposite
of the Hugging Face keep convention. So the form and the polarity both have to
be preserved.

1b. Real padded masks never recovered the document grid (#4125 item 4)

allowed_grid = (m >= 0) if m.dtype != torch.bool else m
keep = allowed_grid.any(dim=-1)          # main: awq_processor.py:1373

For a real right-padded Hugging Face bool mask, a padding query row still
attends to the real keys (only padding keys are masked), so any(dim=-1) is
true for every row: keep_sum = B * S while the capture holds only the real
rows, the check at awq_processor.py:1397 fails, and
_token_row_replay_kwargs takes the fallback at :1458 — one causal sequence
across the whole batch, with synthetic positions. The old unit test built a
hand-made mask with fully-masked padding rows, so it never saw this.

1c. Fallback precedence and smooth (#4121 items 4 and 5)

clone_gptq_config_for_module applied the override and then overwrote it
(gptq_processor.py:182 on main):

qcfg_clone.fallback = normalize_fallback(fallback_override, qcfg_clone.fallback)  # :153
...
qcfg_clone.fallback = normalize_fallback(fallback, qcfg_clone.fallback)           # :182

The looper always passes quantize_config.fallback (stage_subset.py:686 ->
module_looper.py:2278), so the override never survived. MacaqProcessor
(macaq_processor.py:114), QQQProcessor (qqq_processor.py:141) and
VPTQProcessor (vptq_processor.py:101) had the same line and never applied
the override at all.

utils/fallback.py:26-31 forwarded only strategy and threshold to
_normalize_fallback, so a dict override lost both its own smooth and the
inherited one.

2. The fix

2a. Mask form and polarity

AWQProcessor._captured_mask_form (awq_processor.py:1354) classifies the
captured grid and the replay rebuilds it in the same form:

Captured Replay
float [B, 1, S, S] (eager) float block grid, finfo.min on masked cells
bool, True = attended (SDPA) bool block grid, True = attended
bool, True = masked (TeleChat2) bool block grid, True = masked
planar [B, S] keep mask planar [1, retained] keep mask

The polarity is read from the grid diagonal (True on the diagonal = keep
convention), and _align_module_kwargs_to_input (:1566) now leaves a mask
that already matches the packed length untouched instead of repacking it with
the keep convention.

2b. Keep set from the diagonal

_token_row_source_structure (:1377) normalizes the grid to "True = attended"
using the form, then takes allowed_grid.diagonal(-2, -1). A real token always
attends to itself; a padding query row does not. That recovers the document and
position grid for real padded masks.

flowchart TD
    A["AWQProcessor._token_row_replay_kwargs"] --> B["AWQProcessor._captured_mask_form"]
    B --> C{"captured form"}
    C -- additive --> D["float block grid, finfo.min masked"]
    C -- bool_keep --> E["bool block grid, True attended"]
    C -- bool_masked --> F["bool block grid, True masked"]
    C -- planar --> G["1, retained keep mask"]
    C -- none --> D
    B --> H["AWQProcessor._token_row_source_structure"]
    H --> I["keep from the grid diagonal"]
    I --> J["documents and original positions"]
    J --> D
    J --> E
    J --> F
    style G fill:#ffe9b3,stroke:#b38600
Loading

2c. Fallback precedence

The processor fallback is the run's default; the per-module override is the
narrowest layer and wins.

flowchart TD
    A["config fallback<br/>qcfg.fallback"] --> B["normalize_fallback(processor fallback, config)"]
    B --> C{"dynamic override for this module?"}
    C -- yes --> D["normalize_fallback(override, processor-under-config)"]
    C -- no --> E["processor-under-config"]
    D --> F["task fallback used by the quantizer"]
    E --> F
Loading

normalize_fallback now merges every field, including smooth, and an
override that names a smoother through a smooth_*/clip_method alias replaces
the inherited one.

The same diagrams are committed in docs/awq-calibration-aggregation.md and
docs/awq-scale-search-memory.md.

3. Failure and ambiguity contract

Situation Before After
TeleChat2 masked_fill bool grid float mask, RuntimeError bool grid, True = masked
Real padded batch_size>1 bool grid keep from any(dim=-1), structure never recovered keep from the diagonal, structure recovered
Planar [B, S] captured mask 2-D keep mask unchanged (cross-document separation still not expressible)
No captured mask at all additive causal fallback unchanged
dynamic fallback override in a real run overwritten by the processor fallback override wins
dynamic fallback in QQQ/VPTQ/MACaQ never applied applied (VPTQ/MACaQ configs reject the key, so only the processor fallback applies there)
normalize_fallback({...}, default) with smooth smooth dropped merged, alias-aware

4. Validation

Item 1 — TeleChat2 (real quantize, tiny remote-code fixture, CPU)

Before (origin/main 13ee428f, pristine worktree):

$ pytest -q tests/test_telechat2_coverage.py
E  RuntimeError: masked_fill_ only supports boolean masks, but got mask with dtype c10::Half
   modeling_telechat2.py:507
FAILED tests/test_telechat2_coverage.py::test_telechat2_awq_quantizes_attention_projections
=================== 1 failed, 2 passed ===================

After:

$ pytest -q tests/test_telechat2_coverage.py
======================== 3 passed ========================

Item 4 — the resolved fallback in a real quantize

tests/test_fallback.py::test_dynamic_fallback_override_survives_a_real_quantize
quantizes a one-layer Llama on CPU with
dynamic={"+:.*\\.mlp\\.down_proj$": {"fallback": {"strategy": "median", "threshold": 1e9}}}
and records what the looper actually passed to preprocess:

main this branch
processor_arg=Fallback(RTN, '0.5%') -> resolved=Fallback(RTN, '0.5%') processor_arg=Fallback(RTN, '0.5%') -> resolved=Fallback(MEDIAN, 1000000000.0)

Siblings (gate_proj, q_proj, ...) keep Fallback(RTN, '0.5%') on both.

tests/test_fallback.py::test_processor_merges_the_processor_fallback_under_the_override
covers GPTQ and QQQ at the preprocess(..., fallback=...) boundary;
test_vptq_and_macaq_apply_the_processor_fallback_without_dynamic_overrides
covers the other two (their configs reject a per-module fallback key, so only
the processor fallback can apply).

Item 5 — smooth

tests/test_fallback.py::test_normalize_fallback_merges_every_field_including_smooth:
inherited SmoothMAD(k=2) survives a {"threshold": "3%"} override, an
override's own SmoothPercentile replaces it, and a smooth_percentile alias
also replaces it. Before: smooth=None in all three cases.

Tests run

Command Result
pytest -q tests/test_telechat2_coverage.py tests/test_fallback.py (CUDA venv, CPU) 72 passed, 12 pre-existing failures
pytest -q tests/test_awq_weight_mean.py tests/test_awq_scale_search_memory.py tests/test_dynamic.py::test_dynamic_overrides_apply_per_module (ROCm) 90 passed, 4 pre-existing failures, 1 skipped
GPTQMODEL_AWQ_PPL_WIKITEXT=... pytest -q tests/test_awq_variable_length_ppl.py (CUDA, RTX 4090) 2 passed
ruff check gptqmodel docs/eora tests setup.py All checks passed

The 12 tests/test_fallback.py failures are
test_fallback_near_dead_scale_survives_smoothing_and_packing, which #4121
lists as failing on main for every sym=True non-RTN case; the same 12 fail
on main in this environment. The 4 tests/test_awq_weight_mean.py failures
(test_awq_early_layer_completion_releases_all_feature_state x2,
test_awq_search_best_scale_coalesces_cpu_activation_replay, and the flaky
test_awq_weight_mean_matches_legacy_impl_* timing assertion) also fail on
main.

The AWQ batch_size=4 end-to-end PPL in
tests/test_awq_variable_length_ppl.py moved from 25.52 to 25.13 on
Qwen2.5-0.5B (RTN 22.77, batch_size=1 AWQ 22.09 unchanged): the per-document
mask is now actually built for the real padded captures.

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

5. Scope

Only _captured_mask_form, _token_row_source_structure,
_token_row_replay_kwargs and _align_module_kwargs_to_input changed in
awq_processor.py; _get_root_rotary and the rest of the rotary resolution are
untouched. gptqmodel/models/loader.py, gptqmodel/utils/hf.py,
gptqmodel/models/definitions/ and gptqmodel/utils/cpu_features.py are not
modified.

)

- AWQ token-row replay rebuilds the packed mask in the captured form:
  additive grids stay additive, HF bool keep grids stay bool, and
  masked_fill bool grids (TeleChat2) stay bool with True = masked
- derive the keep set from the grid diagonal so a real padded batch_size>1
  mask recovers the document structure instead of falling back
- merge the processor fallback under a per-module dynamic override in
  GPTQ, MACaQ, QQQ and VPTQ; the last three never applied it at all
- normalize_fallback merges every field, including smooth

Part of #4121 (items 1, 4, 5)
Part of #4125 (item 4)
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