Repository navigation
fix(awq): stage symmetric groups on the finite export grid - #6002
Merged
Merged
Conversation
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
marked this pull request as ready for review
November 23, 2026 05:43
9 tasks done
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]>
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 #6003
Summary
AWQ's symmetric grid decodes code
casc * stored_scalein the checkpoint'sdecode dtype. The RTN stage fits that grid as
amax / max_code, and thedivision rounds to the nearest representable scale. A finite
amaxcantherefore select a scale whose top code is not finite: FP16
65504 / 7roundsup to
9360, and7 * 9360 == 65520is the value FP16 rounds to infinity.Staging then clamped the overflowing product back to
65504, so the stagedtensor and the checkpoint disagreed. The packer still kept code
15,qweightwas0xffffffff,qzeroswas0x88888888, and a narrow decodereturned
inffor every element of the group. The clamp could not fix thesaved 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_dtyperesolves 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-dtypescale whose top code is finite: FP16 with a factor of 7 gives
9352, witha factor of 8 gives
8188. The finite maximum itself is a usable boundbecause a product at or below it rounds back into range, so only a
rounding artefact is stepped over. A
1 - epsmargin would drop a codethat fits (it would cut
7 * 9352down to code 6)._awq_symmetric_code_boundderives a per-groupfloor(limit / scale)infloat64 and rechecks the narrow product, so a quotient that rounds up
cannot admit an overflowing code.
_awq_bound_symmetric_codesnow uses that bound instead of afinfo(codes.dtype).max * (1 - eps)estimate on the code dtype._awq_symmetric_gridstagescodes * scalefrom the repaired scale andthe 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 scalerepair and code bound before writing the reconstruction, so clip search
no longer scores a candidate on a grid the packer would not store.
the decode dtype when
sym. A value that only becomes finite through theinput-dtype clamp was never stored, which is exactly this bug.
docs/quantization-scale-storage.md: new "Finite symmetric AWQ exportgrids" section with the mechanism diagram, the rounding analysis and a
before/after table.
tests/test_awq_symmetric_grid_finite.py: pins staging through packing todecoding.
Out of scope
-2 ** (bits - 1) * scaleoffsetin the checkpoint.
-8 * 9360overflows FP16 even though the top code alonewould fit, and
scaled_zero_offsetalready rejects that pack. Lowering thescale enough to represent the offset would cut the usable range from
65472to about
57312and lose precision on ordinary groups, so those layoutsstay fail-closed instead of silently degrading their grid.
and grid-selection fix. Wide-decode wrappers that choose FP32 are unaffected
by construction and were not modified.
Tests
The failures on the base revision are at the intended assertions: the staged
value is
infand the selected scale is9360instead of9352.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 environmentgap in this container, not a regression from this branch.
Measured Impact
32x32 FP16 constant weight,
bits=4,group_size=32,sym=True, GEMM layout.qweightstays0xffffffffandqzerosstays0x88888888for the positiveendpoint, because code
15is still the top code. What changes is that thestored scale is
9352, so the top code decodes to65472instead of65520.amax = 65504(GEMM, narrow decode)fp16/bf16/fp32x 4 magnitudes)1 - epsmargin (rejected)Native decode of the packed layer, base revision to fix:
infinfnaninfVRAM, 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
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.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:#c33The 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:#c33awq_processor.py:5521-5526on the base revision, never dtype-aware_awq_repair_symmetric_scale_awq_symmetric_gridcall site_pseudo_quantize_tensor_intosymmetric branchw.clamp_(finfo(source))could hide a non-storable gridamax / max_codescaled_zero_offsetrejectsinfdocs/quantization-scale-storage.mdrepeats both diagrams and the table under"Finite symmetric AWQ export grids".
Review Requirements
Kernel Accuracy Requirements
No kernel, dispatch, packing layout or bias epilogue changed. The oracle
evidence is the exact
qweight/qzeroswords, an independentdequantizereference in the test file, the bit-identical ordinary-range grid fingerprint,
and the native decode values before and after on both accelerated backends.