Skip to content

fix(awq): keep the cached symmetric scale limit free of host reads - #6633

Merged
Qubitium merged 1 commit into
mainfrom
fix/awq-red-tests-main-scale-limit
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/awq-red-tests-main-scale-limit

Conversation

@Qubitium

@Qubitium Qubitium commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read (#3402) fails whenever no symmetric pseudo-quantize call has run earlier in the same process. That covers running it alone, with -k, or next to an unrelated test such as the AWQ hybrid test. It counts 4 == 1 scalar reads. In the full file it passes, which is why it looked flaky.

Root cause is test-order state leakage, and the state is owned by the product. #6002 (dedeb2924) added the functools.lru_cached _awq_symmetric_scale_limit. Its cold path does three _local_scalar_dense reads: two bool(torch.isfinite(limit * factor)) step-down checks and a final float(limit). A warm cache does none. So the "pseudo-quantize does exactly one host read" contract held or failed depending on whether an earlier test had filled this process-global cache. dedeb2924~1 passes the test alone; dedeb2924 fails it.

Impact is limited: the reads are on CPU constants and happen once per (decode_dtype, factor) per process, so there is no GPU stream sync and no measurable runtime cost. The defect is that the contract depended on cache state, which contradicts #6002's own docstring ("no host read is needed").

What Changed

  • _awq_symmetric_scale_limit now computes the limit branch-free, with two torch.where(isfinite(limit * factor), limit, nextafter(limit, 0)) rounds replacing the bool() loop. It caches the resulting 0-d CPU tensor instead of a Python float. The tensor is built with torch.inference_mode(False), so the cached tensor is never an inference tensor handed to a later autograd-enabled caller. torch.where(overflowing, limit, scales) consumes it exactly as it consumed the float.
  • The regression test now calls _awq_symmetric_scale_limit.cache_clear() before counting. It counts a cold and a warm call (each must be exactly 1 read) and asserts one cache miss, so it no longer depends on test order.
  • No API or behaviour change. The stored value is identical (evidence below).
  • Out of scope: the other long-red AWQ test (test_awq_hybrid_recurrent_mask_4671.py::test_awq_batch_size_one_quantizes_a_mamba_hybrid) has an unrelated cause (a fixture tokenizer with colliding ids) and gets its own PR.

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable. (Existing regression made order-independent: it now covers both the cold and the warm cache.)
# env: PYTHONPATH=<clone> HF_HOME=/root/.cache/huggingface, python -P, torch 2.15, transformers 5.23
T=tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read

# Red: origin/main (4f3ba227a) product code + this test
CUDA_VISIBLE_DEVICES= python -P -m pytest -q $T
#   E  assert 4 == 1           -> 1 failed
# Red even with the cache warmed first (whole file, origin/main 44aa0f98e product + this test):
CUDA_VISIBLE_DEVICES= python -P -m pytest -q tests/test_awq_weight_mean.py
#   FAILED ...nan_guard_uses_one_host_read  -> 1 failed, 60 passed, 27 skipped
# Original test on pristine main shows the order dependence:
#   alone -> 1 failed (4 == 1); whole file -> 61 passed, 27 skipped

# Green: this branch
CUDA_VISIBLE_DEVICES= python -P -m pytest -q $T                               # 1 passed
# Order / device / xdist matrix for this test with the hybrid test (A=hybrid, B=this test) on the fix tree:
#   cpu: B alone, A B, B A, -n 2 A B  -> all passed
#   CUDA (one GPU): A B, B A, -n 2 A B -> all passed

# Covering family, CPU (after rebase on 4f3ba227a):
CUDA_VISIBLE_DEVICES= python -P -m pytest -q -n 8 tests/kernels/test_awq_swordfish.py tests/qcfg/test_zero_point.py \
  tests/test_awq_affine_range.py tests/test_awq_balanced_moe_group_5104.py tests/test_awq_clip_consistency.py \
  tests/test_awq_clip_fp32_score_5752.py tests/test_awq_clip_tile_copy_4540.py tests/test_awq_dynamic_group_size.py \
  tests/test_awq_fp16_fallback_bounds_5821.py tests/test_awq_moe_router_scaling.py tests/test_awq_per_module_bits.py \
  tests/test_awq_scale_search_safety.py tests/test_awq_symmetric_grid_finite.py tests/test_awq_weight_mean.py \
  tests/test_config_per_module_validation_4200.py tests/test_rco_formats.py tests/test_awq_hybrid_recurrent_mask_4671.py tests/test_sinq.py
#   571 passed, 101 skipped (skips: CUDA-only parametrizations with CUDA hidden)
#   (test_awq_hybrid_recurrent_mask_4671 is intermittently red on main for its own fixture reason; fixed in the companion PR)

# Same family subset on one CUDA GPU:
python -P -m pytest -q tests/test_awq_weight_mean.py tests/test_awq_symmetric_grid_finite.py tests/test_awq_clip_consistency.py \
  tests/test_awq_fp16_fallback_bounds_5821.py tests/test_awq_scale_search_safety.py
#   241 passed, 1 skipped (cuda:1 not available: a two-GPU parametrization)

bash format/check.sh   # ruff 0.14.2: All checks passed!

Measured Impact

Value equivalence, old Python-float limit vs new cached tensor:

  • _awq_symmetric_scale_limit(dd, factor) is equal for every decode dtype dd in {fp16, bf16, fp32} and every factor in 1..255. For fp16/7 that is 9352.0.
  • torch.where(mask, limit, scales) is bit-identical for every scale dtype in {fp16, bf16, fp32}: 2295 combos on CPU and 1784 on CUDA.
  • On CUDA, the old float path raises "cannot be converted ... without overflow" for (decode bf16, scales fp16) and (decode fp32, scales fp16/bf16). Those combos are unreachable: scales are cast to the weight dtype, and the decode dtype is either the weight dtype or FP16.

End to end: a tiny random-init Granite-MoE-Hybrid (the fixture from test_awq_hybrid_recurrent_mask_4671.py) quantized with sym AWQ GEMM (bits=4, group_size=32) on CPU saves 117/117 bit-identical tensors on origin/main vs this branch, in both bf16 and fp16.

No runtime change is expected or claimed. The removed reads were CPU-only, once per process.

Model Support / Module Plan

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

Model test node IDs and results (or "not applicable"): not applicable.

AWQ onboarding safety

Not applicable: no grouping, search, replay or fold change. The symmetric scale-limit value is proven identical above, and quantized output is bit-identical.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.

Diagram summary: not applicable. The same limit is computed with tensor ops instead of a host-read branch; no control flow, selection order or lifecycle changes.

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

  • Not applicable: no kernel change. Quantizer output is bit-identical (see Measured Impact).

Notes

The leaked state stays owned by the cache, and the cache now has nothing observable in its cold path. The test does not depend on warm-up order, and the assertion is unchanged (exactly one read per call). It now also covers the cold path.

🤖 Generated with Claude Code

`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]>
@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 09:48
@Qubitium
Qubitium merged commit beb713a into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/awq-red-tests-main-scale-limit branch December 1, 2026 09:49
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