Skip to content

fix(awq): keep checkpoint scales and bias precision in Torch forward - #3800

Merged
Qubitium merged 3 commits into
mainfrom
fix/awq-forward-precision
Nov 12, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/awq-forward-precision

Conversation

@ZX-ModelCloud

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

Copy link
Copy Markdown
Collaborator

TL;DR

AwqTorchLinear permanently rewrote its stored scales and bias with the
current activation dtype. Convert those operands temporarily instead, and pass
the stored bias to the existing wide epilogue. Packing and checkpoint loading
also preserve source operand dtypes. Net change: 5 files,
+370/−22, no new public API.

1. The problem

post_init() narrowed any non-half scales/bias to FP16, and
_ensure_runtime_dtype() replaced both buffers in place on every forward whose
activation dtype differed. The converted values were stored back into the
registered buffers, so the checkpoint precision was lost for all later
forwards and for a re-saved checkpoint.

flowchart TD
    A["AwqTorchLinear.forward"] --> B["_ensure_runtime_dtype"]
    B --> C["self.scales = self.scales.to(device, dtype)"]
    B --> D["self.bias = self.bias.to(device, dtype)"]
    C --> E["dequantize_gemm reads the mutated scales"]
    D --> F["matmul_fp32_reduce sees a bias already narrowed"]
    F --> G["wide-bias path cannot select"]
    E --> H["output"]
    G --> H
    C -. "permanent" .-> X["stored BF16 scale below FP16 range becomes 0"]
    D -. "permanent" .-> Y["stored FP32 bias becomes -inf or rounds"]
    classDef failure fill:#fce8e6,stroke:#a33,color:#111
    class X,Y failure
Loading
Path Previous mechanism Evidence
post_init Cast non-half scales/bias to FP16 torch_awq.py:89-94 before this change
Runtime dtype Replace scales/bias in place torch_awq.py:145-150 before this change
Call site _ensure_runtime_dtype(device, compute_dtype) torch_awq.py:279 before this change
Bias epilogue matmul_fp32_reduce(..., bias=self.bias) after narrowing torch_awq.py:288 before this change
Checkpoint load Accelerate cast Torch AWQ scales and bias to the requested model dtype utils/model.py:2805 before this change
Dense pack pack cast FP32 source scales and bias to FP16 torch_awq.py:122-126 before this change

Observed on revision e17a1a29b, with an independent FP64 Torch oracle:

Case Oracle Before
FP32 bias -65535 cancelling a 65536 reduction, FP16 1 -inf
Same case, BF16 1 0
BF16 scale 1e-40, FP16 forward, then BF16 forward 1.469e-39 0 (scale stored as 0)
FP32 checkpoint buffers after post_init FP32 FP16

This contradicts the documented Torch AWQ contract in
docs/cuda-quantized-bias-epilogue.md: a checkpoint bias stored in FP32 is
added after a wide reduction and rounded once.

2. The new flow

flowchart TD
    L["load_checkpoint_in_model_then_tie_weights"] --> M["Accelerate model-dtype cast"]
    M --> N["_restore_checkpoint_buffers: restore Torch AWQ source dtype"]
    N -- "source present and shape matches" --> A["AwqTorchLinear.forward"]
    N -- "missing or mismatched source" --> X["RuntimeError"]
    P["AwqTorchLinear.pack: keep source scales and bias dtypes"] --> A
    A --> B["_scales_for_compute: temporary activation-dtype copy"]
    B --> C["dequantize_gemm with the temporary scales"]
    C --> D["temporary dequantized weight in activation dtype"]
    D --> E["_bias_for_compute: move/contiguous only, keep stored dtype"]
    E --> F{"matmul_fp32_reduce"}
    F -- "bias wider or incomparable" --> G["linear_wide_bias: wide reduction, bias added in FP32"]
    F -- "same dtype" --> H["FP32-output addmm with bias"]
    G --> I["single cast to activation dtype"]
    H --> I
    I --> J["adapter, reshape, return"]
    C -. "stored scales/bias unchanged" .-> K["checkpoint precision retained"]
    D -. "released after matmul" .-> K
    classDef failure fill:#fce8e6,stroke:#a33,color:#111
    classDef stored fill:#e6f4ea,stroke:#137333,color:#111
    class X failure
    class K stored
Loading

_scales_for_compute returns the stored tensor unchanged when it already
matches the activation device and dtype, so the common FP16/BF16 path adds no
allocation. _bias_for_compute never casts; matmul_fp32_reduce selects
linear_wide_bias when the bias cannot be represented exactly in the
activation dtype, adds it to the FP32 reduction, and rounds once.

load_checkpoint_in_model_then_tie_weights restores source
scales and bias after Accelerate's model-dtype cast, and pack retains the
source dtypes when producing a Torch AWQ checkpoint.

3. Failure and ambiguity contract

Situation Before After
BF16 scale below FP16 subnormal range, FP16 then BF16 forward Scale and weight become 0; BF16 output 0 Scale preserved; BF16 output matches the oracle
FP32 bias cancelling a large reduction, FP16 Bias becomes -inf; output -inf or NaN Bias stays FP32; output 1
Same case, BF16 Bias rounds to -65536; output 0 Output 1
FP32 checkpoint buffers Narrowed at post_init Kept as FP32
FP32 bias -65535 loaded with FP16 model dtype Accelerate changed it to -inf Loader restores FP32 -65535
FP32 source bias passed to pack Stored as FP16 -inf Stored as FP32 -65535
FP32 source scale near 1e-40 passed to pack Stored as FP16 0 Stored at its original FP32 value

The native AwqGEMMLinear CUDA kernel has its own activation-dtype operand
contract and is not changed here.

4. Change inventory

Area File Change
Torch AWQ runtime gptqmodel/nn_modules/qlinear/torch_awq.py Remove stored-buffer casts; preserve source scales and bias in pack; add _scales_for_compute / _bias_for_compute
Checkpoint loading gptqmodel/utils/model.py Restore Torch AWQ source operand dtypes after Accelerate's model-dtype cast
Regression tests tests/kernels/test_awq_torch.py Wide-bias cancellation, cross-dtype forwards, dense pack, and checkpoint reload
Reference page docs/awq-runtime-dtype-precision.md Flow, before/after, failure contract
Docs link README.md Link the new page

5. Tests

Test Invariant
test_awq_torch_wide_checkpoint_bias_rounds_after_wide_accumulation A stored FP32 bias cancels the reduction in FP16 and BF16; buffers stay FP32
test_awq_torch_forward_preserves_checkpoint_scales_and_bias A BF16 scale survives an FP16 forward and the later BF16 forward, and the output matches the FP64 oracle
test_awq_torch_pack_keeps_fp32_source_bias / test_awq_torch_pack_keeps_fp32_source_scales Packing preserves FP32 source operands, including a scale that underflows in FP16
test_awq_torch_loader_preserves_checkpoint_operand_dtypes FP32 and BF16 checkpoint operands survive FP16 model loading and produce oracle outputs

The original forward regressions fail on e17a1a29b and pass with this change. The existing
tests/kernels/test_awq_torch.py::test_awq_torch_matches_manual_dequant
continues to pass for FP16 and BF16. The new oracle decodes the packed INT4
words independently in FP64.

6. Validation

Commands (from the repository root):

python -m pytest tests/kernels/test_awq_torch.py -q
python -m pytest tests/kernels/test_paroquant.py tests/kernels/test_paroquant_bias_epilogue.py -q
python -m pytest tests/kernels/test_awq_cpu_fused_post_init.py tests/test_awq_pack_vectorized.py \
  tests/test_awq_per_module_bits.py tests/test_awq_gptq_lifecycle.py tests/test_awq_loader_dtype.py \
  tests/test_awq_rank_and_empty.py tests/test_awq_affine_range.py tests/test_awq_rotary_device.py -q
python -m pytest tests/kernels/test_cuda_bias_epilogue.py tests/module_tree/test_llama_fusion.py -q

The focused AWQ/ParoQuant selection completed with 597 passed. Three
tests/test_awq_weight_mean.py cases and two tests/test_paroquant.py
rotation/autotune cases also fail on unmodified main; they are unrelated to
this change and reproduce on e17a1a29b.

Numerical results were reproduced on NVIDIA CUDA and AMD ROCm devices with the
same values in the table above. No expanded or dequantized weight is retained:
the temporary weight is released after the matmul, and only packed weights,
scales, zeros, and bias persist.

Review follow-up on the current NVIDIA CUDA host: the focused Torch AWQ and
packing selection passed 13 tests; FP8/GGUF checkpoint loader regressions
passed 38 tests; Ruff passed. Four FP8 native CUDA cases fail in this local
runtime on both the untouched PR head and this revision. Two ParoQuant native
cases cannot run because local nvcc fails to produce the AWQ extension.

7. Reviewer notes

  • post_init() no longer normalizes a non-half checkpoint to FP16. A module
    whose scales are FP32 is still served for FP16/BF16 activations; fusion
    eligibility checks read the stored dtype and remain fail-closed.
  • The helper names avoid _runtime_scales/_runtime_bias, which are existing
    ParoLinear cache attributes.
  • The native AWQ GEMM epilogue is deliberately out of scope; it has a separate
    activation-dtype operand contract.
  • Public Qwen AWQ and GPTQ checkpoint headers store their scales and non-null
    biases in FP16, so FP32 is not assumed for every W4A16 model. The Torch AWQ
    path nevertheless preserves FP32 when a source or checkpoint provides it.

`AwqTorchLinear.post_init` and `_ensure_runtime_dtype` rewrote `scales`
and `bias` in place with the activation dtype. The rewrite was permanent:
a BF16 scale below the FP16 subnormal range became zero and a later BF16
forward stayed zero, and a stored FP32 bias was narrowed before the
reduction, so a finite cancellation became `-inf`/`NaN` in FP16 or a
rounded `0` in BF16.

Convert the scales for dequantization and the bias for the epilogue as
temporary operands only. `matmul_fp32_reduce` now receives the stored
bias, so a wide bias is added after the wide reduction and rounded once.

Add FP64-oracle regressions for the wide-bias cancellation and the
BF16-to-FP16-to-BF16 scale case, and document the flow.
@Qubitium
Qubitium marked this pull request as ready for review November 12, 2026 08:59

Copy link
Copy Markdown
Collaborator

Review completed. I found two precision-loss boundaries beyond the original forward fix and pushed corrections in a9af874 and c95d424:

  • AwqTorchLinear.pack() narrowed FP32 source scales and bias to FP16. It now retains each source dtype; the forward path makes temporary activation-dtype scale copies.
  • Accelerate cast Torch AWQ checkpoint scales and bias to the requested model dtype before forward(). load_checkpoint_in_model_then_tie_weights() now restores their exact source dtypes and values. The FP32 bias -65535 previously became FP16 -inf during an FP16 load.

I checked actual safetensors JSON headers with HTTP byte-range reads (no weight payloads). These public W4A16 checkpoints do not support a general assumption that bias or scales are FP32:

Checkpoint Non-null quantized biases Quantized scales
Qwen2-1.5B-Instruct-AWQ 84/84 FP16 196/196 FP16
QwQ-32B-AWQ 192/192 FP16 448/448 FP16
OPT-125m-AWQ 72/72 quantized bias tensors FP16 72/72 FP16
Qwen2-1.5B-Instruct-GPTQ-Int4 196/196 FP16 196/196 FP16

For comparison, the unquantized Qwen2-1.5B-Instruct checkpoint stores its sampled q_proj.weight and q_proj.bias in BF16. Quantization can change the stored dtype. W4A16 specifies 4-bit weights and 16-bit activations; it does not require FP32 scales. The GPTQ paper explicitly uses FP16 group scales in its extreme-quantization example (page 9). These examples establish actual formats, not a population-wide frequency estimate.

The code audit also found backend-specific contracts: AWQ GEMM/GEMV allocate or pack FP16 operands, while FP8 and VPTQ explicitly allocate FP32 bias. Native AWQ kernels cannot be made FP32-safe by a blanket buffer change. This PR preserves any higher precision source operands in the Torch AWQ path; other backends need their own kernel and loader validation before claiming that support.

Verification: focused Torch AWQ and packing tests 13 passed on the current NVIDIA host, including an independent packed-code FP64 oracle and checkpoint reload; FP8/GGUF loader regressions 38 passed; Ruff workflow is green. Four FP8 native CUDA tests fail identically on the untouched PR head in this local runtime, and two native ParoQuant tests are blocked by local nvcc extension build failures.

@Qubitium Qubitium left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed and verified the Torch AWQ precision fix, including pack and checkpoint-load regressions. Detailed findings and public checkpoint dtype audit are in the PR discussion.

@Qubitium
Qubitium merged commit 8cc5ae3 into main Nov 12, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/awq-forward-precision branch November 12, 2026 09:32
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Reviewed after the merge (8cc5ae3d4). Two findings remain; both are fixed in #3802.

  1. The regression oracle read the live module.scales/module.bias. On e17a1a29b post_init/_ensure_runtime_dtype already corrupt those buffers, so the oracle reproduced the corruption and the tests failed only on a dtype assertion. fix(awq): pin Torch forward precision regressions and restore non-half dequantize #3802 passes the original checkpoint-precision values to the oracle and asserts the numeric output first; base now fails with -inf/0.
  2. _dequantize_weight_for_inference(dtype=fp32) (the ParoLinear dense fallback) dequantized at FP32 and raised the half-weight assertion; e17a1a29b returned FP32. fix(awq): pin Torch forward precision regressions and restore non-half dequantize #3802 keeps the half dequantization and widens the finished weight.

Minor: the BF16 row in the failure table is inaccurate for the post_init path. post_init narrows the FP32 bias to FP16 -inf first, so a BF16 forward also returns -inf; the -65536/0 case is the runtime-cast-only path. #3802 corrects the page. The loader/pack changes are sound, and the loader test also passes on ROCm.

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.

2 participants