Skip to content

fix(awq): stage symmetric groups on the finite export grid - #6002

Merged
Qubitium merged 1 commit into
mainfrom
fix/awq-sym-clamp-finite
Nov 23, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/awq-sym-clamp-finite

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #6003

Summary

AWQ's symmetric grid decodes code c as c * stored_scale in the checkpoint's
decode dtype. The RTN stage fits that grid as amax / max_code, and the
division rounds to the nearest representable scale. A finite amax can
therefore select a scale whose top code is not finite: FP16 65504 / 7 rounds
up to 9360, and 7 * 9360 == 65520 is the value FP16 rounds to infinity.

Staging then clamped the overflowing product back to 65504, so the staged
tensor and the checkpoint disagreed. The packer still kept code 15,
qweight was 0xffffffff, qzeros was 0x88888888, and a narrow decode
returned inf for every element of the group. The clamp could not fix the
saved grid because the grid had already been chosen one step past it.

This stages each symmetric group on the grid the packer will actually store:
the scale is repaired when its top product overflows, and the codes are bounded
by the finite range of the decode dtype. Ordinary groups keep their exact
previous scale and grid.

What Changed

  • gptqmodel/looper/awq_processor.py
    • _awq_symmetric_decode_dtype resolves the dtype the kernel decodes in:
      the checkpoint scale width, not the source weight width (GEMM and Marlin
      keep an FP16/BF16 source scale and otherwise store FP16; GEMV and
      GEMV-fast always store FP16; BitBLAS keeps the packed source precision).
    • _awq_symmetric_scale_limit (cached) returns the largest decode-dtype
      scale whose top code is finite: FP16 with a factor of 7 gives 9352, with
      a factor of 8 gives 8188. The finite maximum itself is a usable bound
      because a product at or below it rounds back into range, so only a
      rounding artefact is stepped over. A 1 - eps margin would drop a code
      that fits (it would cut 7 * 9352 down to code 6).
    • _awq_symmetric_code_bound derives a per-group floor(limit / scale) in
      float64 and rechecks the narrow product, so a quotient that rounds up
      cannot admit an overflowing code.
    • _awq_bound_symmetric_codes now uses that bound instead of a
      finfo(codes.dtype).max * (1 - eps) estimate on the code dtype.
    • _awq_symmetric_grid stages codes * scale from the repaired scale and
      the bounded codes, and returns both so the caller stores what it staged.
      It replaces both the strategy (fallback) symmetric branch and the RTN
      symmetric branch, which previously had different grids.
    • _pseudo_quantize_tensor_into's symmetric branch applies the same scale
      repair and code bound before writing the reconstruction, so clip search
      no longer scores a candidate on a grid the packer would not store.
    • The staging guard additionally requires the staged value to be finite in
      the decode dtype when sym. A value that only becomes finite through the
      input-dtype clamp was never stored, which is exactly this bug.
  • docs/quantization-scale-storage.md: new "Finite symmetric AWQ export
    grids" section with the mechanism diagram, the rounding analysis and a
    before/after table.
  • tests/test_awq_symmetric_grid_finite.py: pins staging through packing to
    decoding.

Out of scope

  • GEMV-fast and LLM-AWQ store an additional -2 ** (bits - 1) * scale offset
    in the checkpoint. -8 * 9360 overflows FP16 even though the top code alone
    would fit, and scaled_zero_offset already rejects that pack. Lowering the
    scale enough to represent the offset would cut the usable range from 65472
    to about 57312 and lose precision on ordinary groups, so those layouts
    stay fail-closed instead of silently degrading their grid.
  • The native CUDA/HIP kernels themselves were not changed; this is a staging
    and grid-selection fix. Wide-decode wrappers that choose FP32 are unaffected
    by construction and were not modified.

Tests

# New regression, fix branch
python -m pytest tests/test_awq_symmetric_grid_finite.py -q
# 24 passed

# Same test file on the base revision (947390c25)
python -m pytest tests/test_awq_symmetric_grid_finite.py -q
# 15 failed, 9 passed

# Documentation contract checks
python -m pytest tests/test_docs_contract_refs.py -q
# 33 passed

bash format/check.sh
# All checks passed

The failures on the base revision are at the intended assertions: the staged
value is inf and the selected scale is 9360 instead of 9352.

The file is picked up by the existing CI planner in the same group as the
sibling tests/test_awq_pack_scale_representability.py.

Skips

The two native-kernel nodes skip on a host with no accelerated device, or when
the AWQ extension is unavailable. Both were executed on CUDA and on ROCm in
this branch (see below); they are not verified on any other backend.

A broader AWQ family run has six failures that reproduce identically on the
base revision and are unrelated to this change: five model-level load tests
and one fallback-range test fail with
ModuleNotFoundError: No module named 'tokenicer.ernie_vl', an environment
gap in this container, not a regression from this branch.

Measured Impact

32x32 FP16 constant weight, bits=4, group_size=32, sym=True, GEMM layout.

Source weight Staged value before Staged value after Scale before Scale after Packed code FP32 decode FP16 decode before FP16 decode after
60000 59968 59968 8568 8568 15 59976 59968 59968
65472 65472 65472 9352 9352 15 65464 65472 65472
65504 65504 65472 9360 9352 15 65520 inf 65472
-65504 -65504 -65472 9360 9352 1 -65520 -inf -65472

qweight stays 0xffffffff and qzeros stays 0x88888888 for the positive
endpoint, because code 15 is still the top code. What changes is that the
stored scale is 9352, so the top code decodes to 65472 instead of 65520.

Metric Before After Change
Non-finite decode elements at amax = 65504 (GEMM, narrow decode) 1024 0 -1024
Staged/checkpoint grid agreement at the endpoint No Yes fixed
Ordinary-range grids (fp16/bf16/fp32 x 4 magnitudes) 12 grids Same 12, bit-identical 0
Bound with a 1 - eps margin (rejected) - would drop code 7 avoided

Native decode of the packed layer, base revision to fix:

Backend Layout Before After
CUDA GEMM inf 65472
CUDA GEMV inf 65472
ROCm Triton GEMM nan 65472
ROCm GEMV inf 65472

VRAM, throughput and model-level accuracy were not measured. The change moves
at most one scale step per affected group, touches no persistent tensor shape
and adds no checkpoint state.

Model Support / Module Plan

Not applicable: no model, alias, definition or module-plan change.

AWQ onboarding safety

No AWQ grouping, group search, replay or folding change. The grouping rules,
the search objective's candidates and the fold path are untouched. What
changes is the grid a symmetric group is staged on: a scale whose top code
cannot be stored is repaired before staging, and codes that cannot be decoded
finitely are excluded. The clip search applies the same repair so its scores
still describe the exported layer.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md.

The old flow chose the scale and the codes independently of the dtype the
kernel decodes in, then clamped the product after the fact:

flowchart TD
    A["RTN: scales = max_val / max_int"] --> B["codes = clamp(round(w / scales), min_int, max_int)"]
    B --> C["w = codes * scales"]
    C --> D{"finite in source dtype?"}
    D -- "yes" --> E["w.clamp_(finfo(source))"]
    D -- "no, becomes finite only here" --> E
    E --> F["packer stores unchanged code 15"]
    F --> G["kernel decodes 15 * 9360 = inf"]
    style G fill:#fee,stroke:#c33
Loading

The new flow resolves the decode dtype first and stages on its grid:

flowchart TD
    A["decode_dtype = _awq_symmetric_decode_dtype(input_dtype, format)"] --> B["scale = (amplitude / max_code).to(w.dtype)"]
    B --> C{"_awq_repair_symmetric_scale:<br/>max_code * scale.to(decode_dtype) finite?"}
    C -- "no (rounding artefact)" --> E["scale = _awq_symmetric_scale_limit(decode_dtype, max_code)"]
    C -- "yes (ordinary group)" --> D["keep scale"]
    D --> F["codes = round(w / scale)"]
    E --> F
    F --> G["bound = _awq_symmetric_code_bound(scales, max_code, decode_dtype)"]
    G --> H["_awq_bound_symmetric_codes"]
    H --> I["staged = codes * scale; return (staged, scales)"]
    I --> J{"staging guard:<br/>staged finite in decode dtype?"}
    J -- "yes" --> K["packer stores scale and codes"]
    J -- "no" --> L["assert fires before a corrupt checkpoint is written"]
    K --> M["kernel decodes c * stored_scale finitely"]
    style E fill:#d1e7dd,stroke:#0f5132,color:#0f5132
    style M fill:#d1e7dd,stroke:#0f5132,color:#0f5132
    style L fill:#fee,stroke:#c33
Loading
Mechanism Previous behavior New behavior Evidence
Symmetric RTN scale Fitted at awq_processor.py:5521-5526 on the base revision, never dtype-aware Repaired only when the top product overflows _awq_repair_symmetric_scale
Strategy symmetric branch Same fit, code clamp only when bounds were widened Same helper as RTN _awq_symmetric_grid call site
Clip-search staging Repaired nothing, scored the unrepaired grid Same repair and bound as staged weights _pseudo_quantize_tensor_into symmetric branch
Post-hoc clamp w.clamp_(finfo(source)) could hide a non-storable grid Kept for value range, plus a decode-dtype finite guard staging guard
Ordinary group grid amax / max_code Same value, bit-identical ordinary-range control test
GEMV-fast / LLM-AWQ offsets scaled_zero_offset rejects inf Unchanged, still fail-closed offset rejection test

docs/quantization-scale-storage.md repeats both diagrams and the table under
"Finite symmetric AWQ export grids".

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • For kernel-related changes, accuracy drift was measured against an applicable independent Torch FP32/FP64 oracle, or the reason this is not applicable is documented.

No kernel, dispatch, packing layout or bias epilogue changed. The oracle
evidence is the exact qweight/qzeros words, an independent dequantize
reference in the test file, the bit-identical ordinary-range grid fingerprint,
and the native decode values before and after on both accelerated backends.

AWQ's symmetric grid decodes code `c` as `c * stored_scale` in the kernel's
decode dtype, but the RTN stage fitted it as `amax / max_code`, which rounds to
the *nearest* representable scale. A finite `amax` could therefore select a
scale whose top code is not finite: FP16 `65504 / 7` rounds up to 9360, and
`7 * 9360 == 65520` is the value FP16 rounds to infinity. The staging clamp
then rewrote the staged value to 65504 while the packer kept code 15, so the
checkpoint decoded `inf`. For a 32x32 FP16 constant layer with bits=4,
group_size=32, sym, GEMM, that produced `qweight = 0xffffffff`,
`qzeros = 0x88888888` and 1024 non-finite decoded weights.

Stage the symmetric group on the grid the packer will actually store:

- Resolve the decode dtype from the checkpoint scale width (GEMM/Marlin keep
  an FP16/BF16 source scale, the others store FP16, BitBLAS keeps the source
  precision) rather than from the source weight dtype.
- Repair only the scales whose top code cannot be exported, to the largest
  decode-dtype scale whose top product is finite. An ordinary group keeps its
  exact previous scale, so its grid stays bit-identical. The finite maximum
  itself is a usable bound; a `1 - eps` margin would discard a code that fits.
- Cap the codes a group may select by `floor(limit / scale)`. This keeps the
  selected interval unchanged for amplitudes that already exceed the decode
  dtype (STDCLIP's `3 * std`), where the clip decision has already given up
  the top codes.
- Score clip-search candidates on the same repaired scale and code bound, so a
  candidate is never judged on a grid the packer would not store.

The GEMV-fast and LLM-AWQ offset layouts keep `scaled_zero_offset` as their
fail-closed guard: they store `-2 ** (bits - 1) * scale`, which overflows FP16
for these amplitudes, and lowering the scale enough to represent it would lose
real precision on ordinary groups.

The staging guard now checks the staged values in the decode dtype instead of
relying on the later input-dtype clamp to hide a non-finite product.

Adds `tests/test_awq_symmetric_grid_finite.py`, which drives staging, packing
and decoding for both ±65504, 65472 and 60000 in the GEMM and GEMV layouts,
pins the exact `qweight`/`qzeros` words, the in-place candidate-search parity,
the offset layouts' rejection, an FP32 source narrowed to FP16 storage, a
subnormal-scale control, a bit-identical ordinary-range control, and native
GEMM/GEMV decode nodes on CUDA and ROCm.

Documents the mechanism in `docs/quantization-scale-storage.md`.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 23, 2026 05:43
@Qubitium
Qubitium merged commit dedeb29 into main Nov 23, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/awq-sym-clamp-finite branch November 23, 2026 08:42
Qubitium added a commit that referenced this pull request Dec 1, 2026
…6633)

`test_awq_pseudo_quantize_nan_guard_uses_one_host_read` (#3402) has been
red whenever it runs without an earlier symmetric pseudo-quantize call in the
same process, for example alone, with -k, or next to an unrelated test. It
counted 4 scalar reads instead of 1.

Cause: #6002 added `_awq_symmetric_scale_limit`, an lru_cached helper that
steps the per-dtype limit down with `bool(torch.isfinite(...))` and returns
`float(limit)`. That is three `_local_scalar_dense` reads, but only on the
first call per `(decode_dtype, factor)` in a process. So the "one host read
per pseudo-quantize" contract held or failed depending on whether an earlier
test had already warmed this process-global cache. In the full file it passed,
which is why the failure looked flaky. The reads are on CPU constants, so no
GPU stream sync and no measurable runtime cost; the defect is that the
contract depended on cache state, against #6002's own "no host read" claim.

Fix at the cache owner: compute the limit branch-free (two `torch.where`
step-down rounds in place of the `bool()` loop) and cache the 0-d CPU tensor
instead of a Python float. Build it with inference mode disabled, so the cached
tensor is not an inference tensor for later autograd-enabled callers. The
value is unchanged: every decode dtype (fp16/bf16/fp32) x factor 1..255 gives
the same limit, and `torch.where` against fp16/bf16/fp32 scales is
bit-identical on CPU and CUDA. A tiny Granite hybrid sym AWQ quantize saves
bit-identical tensors before and after in bf16 and fp16.

The regression now clears the cache before counting and counts a cold and a
warm call, so it no longer depends on test order.

Co-authored-by: Claude Opus 5.5 <[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 symmetric staging clamp cannot guarantee a finite export grid

2 participants