Skip to content

fix(quantization): unify FP8 scale semantics, resave bias dtype, sym fallbacks, 3-bit validate (#4003) - #4025

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4003
Nov 14, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4003

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4003

TL;DR

All four follow-up items from #4003 are fixed in one branch: FP8 checkpoints now resolve one scale convention per checkpoint and apply it to both decode paths; a loaded GPTQ model re-saves BF16 biases without narrowing them to FP16; the sym=True fallback strategies store the symmetric zero point every kernel expects; and a 3-bit contract with a non-32-aligned dimension is rejected before calibration.

1. FP8 forward vs quant source used opposite scale semantics

Root cause. _build_fp8_forward_module put the checkpoint's weight_scale_inv into TorchFP8Linear, which always divided (gptqmodel/models/base.py:4387 on this branch). _build_decoder_quant_source_module called dequantize_fp8(scale_inv=...) with the post-#3997 default, which multiplies (gptqmodel/models/base.py:3933). The same checkpoint tensor therefore decoded 10^4 apart.

Fix. _decoder_fp8_scale_semantics() (gptqmodel/models/base.py:4073) resolves quantization_config.weight_scale_semantics once per checkpoint and caches it. The default for weight_scale_inv is the HF/DeepSeek multiplier; a direct weight_scale is normalized to an inverse tensor and forces inverse. Both decode paths consume that one value (:4026, :4412). TorchFP8Linear now executes both conventions in _dequantize_native, _dequantize_cpu, dequantize_weight, and _scaled_mm_weight_scale (gptqmodel/nn_modules/qlinear/fp8.py:492, :532, :575, :592).

Measured on the issue repro (FP8 E4M3 weight, one row scale):

Convention Before forward / quant source After
multiplier, scale_inv=0.01 7.81e-1 / 7.82e-4, ratio 9.99e+03 7.81e-4 / 7.82e-4, ratio 0.999
inverse, scale_inv=100 7.81e-4 / 7.82e+0, ratio 1.0e-04 7.81e-4 / 7.82e-4, ratio 0.999

The remaining 0.1% is the quant source's BF16 output rounding; the FP32 forward matches an independent FP64 oracle at 1e-6.

flowchart TD
    A["checkpoint quantization_config"] --> B["_decoder_fp8_scale_semantics"]
    B --> C{"declared weight_scale_semantics"}
    C -- "multiplier" --> D["multiplier"]
    C -- "inverse" --> E["inverse"]
    C -- "absent" --> F["multiplier: HF/DeepSeek default for weight_scale_inv"]
    B --> G["cached for this checkpoint"]
    G --> H["_build_fp8_forward_module"]
    G --> I["_build_decoder_quant_source_module"]
    H --> J["TorchFP8Linear.weight_scale_semantics"]
    I --> K["dequantize_fp8(scale_semantics=...)"]
    J --> L["one decoded weight"]
    K --> L
    M["direct weight_scale tensor"] --> N["reciprocal inverse scale"]
    N --> E
    classDef fail fill:#f8d7da,stroke:#b42318,color:#111;
    classDef ok fill:#d1e7dd,stroke:#0f5132,color:#111;
    class L ok;
Loading

2. Re-saving a loaded BF16 GPTQ model wrote FP16 biases (inf)

Root cause. writer.get_model_with_quantize called make_quant(...) without a dtype (gptqmodel/models/writer.py:2299 region), so BaseQuantLinear.__init__ and GPTQQuantLinear._register_gptq_buffers registered the bias placeholder as torch.float16 (gptqmodel/nn_modules/qlinear/__init__.py:283, :1188). load_checkpoint_in_model keeps the destination buffer dtype, so a finite BF16 99840 became inf.

Fix. A bias_dtype option is threaded from the re-save rebuild (gptqmodel/models/writer.py:2299) through make_quant/create_quant_layer/create_quant_module to the registered bias buffer. It selects only the buffer width, so the re-save does not pass an FP32 activation dtype through kernel validation. get_hf_config_dtype now also accepts the "torch.bfloat16" spelling and rejects non-dtype torch attributes (gptqmodel/utils/hf.py).

Repro: BF16 Llama with attention_bias=True, mlp_bias=True; 7 bias tensors set to [99840, 3e-7, -70144].

Before After
Resaved bias dtype BF16 buffers but [inf, 2.98e-07, -inf] BF16, exact [99840.0, 3.0e-07, -70144.0] bit pattern
Tensors affected 7 / 7 0 / 7

3. MIDPOINT/MEAN/MEDIAN/STDCLIP ignored sym=True

Root cause. _affine_quantize always extended the strategy endpoints to include zero (affine_range_with_zero), so a positive-only group stored zero points 0/6/7 at 4 bits even though every symmetric kernel expects 2**(bits-1). Torch/Triton/ExLlamaV2 read the stored qzeros; Marlin ignores them for symmetric GPTQ.

Fix. symmetric_range() (gptqmodel/quantization/fallback_smooth.py:49) fits [-max|x|, max|x|] with the same all-zero sentinel as Quantizer.find_params. Both fallback implementations use it when sym=True and set the fixed zero point (gptqmodel/quantization/gptq.py:1614, gptqmodel/quantization/qqq.py:432).

Measured on a positive-only 4-bit group, Marlin vs Torch forward:

Stored zero Max abs diff Relative
Before 0 4.94e-01 3.29
After 8 2.44e-04 5.55e-04

4. The 3-bit contract was not enforced in validate

Root cause. GPTQQuantLinear._validate rejected only planar 5/6/7, so TorchLinear.validate(bits=3, in=64, out=48) returned True. The continuous 10-1-10-1-10 packer and the planar gptq_p split planes both consume 32-code blocks, so the failure surfaced only after the full quantization pass (pack_original could raise IndexError).

Fix. _validate rejects a 3-bit contract when in_features % 32 != 0 or out_features % 32 != 0 (gptqmodel/nn_modules/qlinear/__init__.py:1172), so kernel selection or module skipping happens before calibration.

Call Before After
TorchLinear.validate(bits=3, in=64, out=48) (True, None) (False, NotImplementedError: 3-bit packing requires out_features divisible by 32)
TorchLinear.validate(bits=3, in=48, out=64) (True, None) (False, NotImplementedError: 3-bit packing requires in_features divisible by 32)
TorchLinear.validate(bits=3, in=64, out=64) (True, None) (True, None)
TorchLinear.validate(bits=4, in=64, out=48) (True, None) (True, None)
flowchart TD
    A["TorchLinear.validate(bits=3, in_features, out_features)"] --> B["GPTQQuantLinear._validate"]
    B --> C{"bits == 3 and (in_features % 32 or out_features % 32)"}
    C -- "yes" --> D["NotImplementedError: 3-bit packing requires ... divisible by 32"]
    C -- "no" --> E["kernel selection / module quantization continues"]
    D --> F["FAIL-CLOSED before calibration"]
    X["Old path: validate returned True"] --> Y["full quantization pass"]
    Y --> Z["pack_original IndexError or packer ValueError"]
    classDef failure fill:#f8d7da,stroke:#b42318,color:#111;
    class F,Z failure;
Loading

Documentation

  • New reference page docs/fp8-scale-semantics.md with the old/new flow, before/after table, failure contract, and measured numbers; linked from README.md.
  • docs/3bit-zero-point-packing.md now documents the validate-before-calibration contract.
  • docs/dtype-boundary-preservation.md records the re-save bias placeholder row.

Validation

Hardware: NVIDIA RTX 4090 GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 (CUDA 13.0, torch 2.16.0.dev+cu130) and AMD R9700 with HIP_VISIBLE_DEVICES=4 (torch 2.16.0.dev+rocm10.1). The RTX 5090 was never used; nvidia-smi --query-compute-apps was checked before GPU runs.

CUDA:

CUDA_VISIBLE_DEVICES=GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 PYTHONPATH=$PWD \
/opt/venvs/cu130t/bin/python -m pytest -q \
  tests/test_gptq_fallback_offset.py tests/test_pack_3bit_out_features.py \
  tests/test_fp8_dequant_inplace.py tests/test_auto_module_decoder.py \
  tests/test_save_loaded_quantized_model_dtype.py tests/test_fp8.py tests/test_qzero_offsets.py

-> 145 passed, 2 skipped

ROCm:

HIP_VISIBLE_DEVICES=4 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest -q \
  tests/test_gptq_fallback_offset.py tests/test_pack_3bit_out_features.py \
  tests/test_fp8_dequant_inplace.py tests/test_auto_module_decoder.py \
  tests/test_save_loaded_quantized_model_dtype.py

-> 111 passed, 9 skipped

Lint:

ruff check gptqmodel docs/eora tests setup.py

-> All checks passed!

Known pre-existing, unrelated failures in this environment: tests/test_model_dequant_fp8.py::test_ignored_layers_are_honored_by_non_fp8_converters (bitsandbytes absent), two tests/test_hf_config_compat.py cache-length/trust-remote-code failures (transformers 5.22), and three tests/test_fp8_nonfinite_source.py smoother cases that monkeypatch a module-level symbol that does not exist.

Tests added

Test Invariant
tests/test_auto_module_decoder.py::test_fp8_forward_and_quant_source_share_the_declared_scale_semantics Forward and quant source match an independent FP64 oracle for multiplier and inverse
tests/test_fp8_dequant_inplace.py::test_fp8_native_multiplier_dequant_and_forward_match_fp64_oracle Multiplier semantics on the CUDA native, dequant-matmul, and _scaled_mm paths
tests/test_save_loaded_quantized_model_dtype.py::test_loaded_quantized_resave_preserves_bf16_non_quantized_bits All 7 BF16 biases keep their exact bits on re-save
tests/test_gptq_fallback_offset.py::test_symmetric_fallback_stores_the_fixed_kernel_zero_point Every sym fallback stores 2**(bits-1)
tests/test_gptq_fallback_offset.py::test_sym_fallback_marlin_matches_torch_on_a_positive_only_group Marlin and Torch agree on a positive-only sym group
tests/test_pack_3bit_out_features.py::test_validate_enforces_the_3bit_32_alignment_before_packing Misaligned 3-bit contracts fail in validate
tests/test_hf_config_compat.py::test_get_hf_config_dtype_accepts_the_torch_prefixed_string "torch.bfloat16" resolves

No GPTQMODEL_* behavior switches, no dense inference weight caches, no force-push, no merge.

…fallbacks, 3-bit validate (#4003)

- Resolve one FP8 weight_scale_semantics per checkpoint and pass it to both
  TorchFP8Linear and dequantize_fp8. TorchFP8Linear now executes multiplier
  and inverse scales in the native, CPU, and _scaled_mm paths.
- Register quantized-module bias placeholders at the checkpoint/model dtype
  during the re-save rebuild, and accept the "torch." dtype-string prefix.
- Fit a symmetric [-max|x|, max|x|] range with zero=2**(bits-1) for the
  MIDPOINT/MEAN/MEDIAN/STDCLIP fallbacks when sym=True.
- Reject 3-bit contracts whose in_features/out_features are not 32-aligned
  in _validate, before calibration.
- Add fail-before/pass-after tests and the FP8 scale-semantics reference page.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant