Repository navigation
fix(quantization): unify FP8 scale semantics, resave bias dtype, sym fallbacks, 3-bit validate (#4003) - #4025
Merged
Merged
Conversation
…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.
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 #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=Truefallback 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_moduleput the checkpoint'sweight_scale_invintoTorchFP8Linear, which always divided (gptqmodel/models/base.py:4387on this branch)._build_decoder_quant_source_modulecalleddequantize_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) resolvesquantization_config.weight_scale_semanticsonce per checkpoint and caches it. The default forweight_scale_invis the HF/DeepSeekmultiplier; a directweight_scaleis normalized to an inverse tensor and forcesinverse. Both decode paths consume that one value (:4026,:4412).TorchFP8Linearnow 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):
scale_inv=0.017.81e-1/7.82e-4, ratio9.99e+037.81e-4/7.82e-4, ratio0.999scale_inv=1007.81e-4/7.82e+0, ratio1.0e-047.81e-4/7.82e-4, ratio0.999The 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;2. Re-saving a loaded BF16 GPTQ model wrote FP16 biases (inf)
Root cause.
writer.get_model_with_quantizecalledmake_quant(...)without a dtype (gptqmodel/models/writer.py:2299region), soBaseQuantLinear.__init__andGPTQQuantLinear._register_gptq_buffersregistered the bias placeholder astorch.float16(gptqmodel/nn_modules/qlinear/__init__.py:283,:1188).load_checkpoint_in_modelkeeps the destination buffer dtype, so a finite BF1699840becameinf.Fix. A
bias_dtypeoption is threaded from the re-save rebuild (gptqmodel/models/writer.py:2299) throughmake_quant/create_quant_layer/create_quant_moduleto 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_dtypenow 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].[inf, 2.98e-07, -inf][99840.0, 3.0e-07, -70144.0]bit pattern3. MIDPOINT/MEAN/MEDIAN/STDCLIP ignored
sym=TrueRoot cause.
_affine_quantizealways extended the strategy endpoints to include zero (affine_range_with_zero), so a positive-only group stored zero points0/6/7at 4 bits even though every symmetric kernel expects2**(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 asQuantizer.find_params. Both fallback implementations use it whensym=Trueand 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:
04.94e-013.2982.44e-045.55e-044. The 3-bit contract was not enforced in
validateRoot cause.
GPTQQuantLinear._validaterejected only planar 5/6/7, soTorchLinear.validate(bits=3, in=64, out=48)returnedTrue. The continuous 10-1-10-1-10 packer and the planargptq_psplit planes both consume 32-code blocks, so the failure surfaced only after the full quantization pass (pack_originalcould raiseIndexError).Fix.
_validaterejects a 3-bit contract whenin_features % 32 != 0orout_features % 32 != 0(gptqmodel/nn_modules/qlinear/__init__.py:1172), so kernel selection or module skipping happens before calibration.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;Documentation
docs/fp8-scale-semantics.mdwith the old/new flow, before/after table, failure contract, and measured numbers; linked fromREADME.md.docs/3bit-zero-point-packing.mdnow documents the validate-before-calibration contract.docs/dtype-boundary-preservation.mdrecords 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 withHIP_VISIBLE_DEVICES=4(torch 2.16.0.dev+rocm10.1). The RTX 5090 was never used;nvidia-smi --query-compute-appswas checked before GPU runs.CUDA:
->
145 passed, 2 skippedROCm:
->
111 passed, 9 skippedLint:
->
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), twotests/test_hf_config_compat.pycache-length/trust-remote-code failures (transformers 5.22), and threetests/test_fp8_nonfinite_source.pysmoother cases that monkeypatch a module-level symbol that does not exist.Tests added
tests/test_auto_module_decoder.py::test_fp8_forward_and_quant_source_share_the_declared_scale_semanticstests/test_fp8_dequant_inplace.py::test_fp8_native_multiplier_dequant_and_forward_match_fp64_oracle_scaled_mmpathstests/test_save_loaded_quantized_model_dtype.py::test_loaded_quantized_resave_preserves_bf16_non_quantized_bitstests/test_gptq_fallback_offset.py::test_symmetric_fallback_stores_the_fixed_kernel_zero_point2**(bits-1)tests/test_gptq_fallback_offset.py::test_sym_fallback_marlin_matches_torch_on_a_positive_only_grouptests/test_pack_3bit_out_features.py::test_validate_enforces_the_3bit_32_alignment_before_packingvalidatetests/test_hf_config_compat.py::test_get_hf_config_dtype_accepts_the_torch_prefixed_string"torch.bfloat16"resolvesNo
GPTQMODEL_*behavior switches, no dense inference weight caches, no force-push, no merge.