Repository navigation
fix(gptq): fuse BF16 GPTQ decode with FP16 scales - #5921
Merged
Merged
Conversation
GPTQ checkpoints store FP16 scales while a BF16 model runs BF16 activations, so `_can_use_rocm_fused` rejected every BF16 model before `gptq_gemv`/`gptq_gemm` and paid the dense dequantize + matmul fallback. - admit a mixed scale/activation pair when both are half dtypes via `fused_scale_pair_supported`; FP32/FP64 pairs still take the dense path. The fused kernels widen scales to FP32, and the existing `_decoded_weight_fits` range guard still rejects an overflowing decode. - decode the dense fallback directly in the activation dtype when every weight fits it, instead of FP16-decode -> BF16-cast double rounding and a full-matrix copy per forward. - let `dequantize_weight` take the base class's `dtype` argument and resolve it against the range-safe decode. Adds the mixed-pair gate, dispatch, overflow and unmeasured-dtype tests, and documents the flow in docs/gptq-bf16-fused-gate.md. Measured on RTX 4090 (SM 8.9), BF16 acts + FP16 scales, 4-bit gs=128: 4096x11008 M=1 0.4277 -> 0.0529 ms (8.08x), M=8 0.4700 -> 0.0475 ms (9.89x), 11008x4096 M=1 0.4668 -> 0.0563 ms (8.29x).
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.
Summary
Fixes #5740. A GPTQ checkpoint stores FP16 scales, while a BF16 model runs BF16
activations.
TorchLinear._can_use_rocm_fusedrequiredself.scales.dtype == x.dtype, so every BF16 model missedgptq_gemvandgptq_gemmand paid the dense dequantize + matmul fallback even on Ada,Blackwell and the registered ROCm families where a fused launch entry exists.
The fused kernels already load every scale and widen it to FP32 before the
product, so the stored scale dtype never had to equal the activation dtype.
What Changed
fused_scale_pair_supported(scale_dtype, activation_dtype)(
gptqmodel/nn_modules/qlinear/torch.py:143). It admits an equal pair(previous behaviour, including FP32/FP64) or any FP16/BF16 pair, and rejects
every other mixed pair (for example FP32 scales with BF16 activations) because
those were not measured. Range safety stays a separate predicate:
_decoded_weight_fits(x.dtype)still rejects a decode that overflows theactivation dtype ([BUG] GPTQ_TORCH eval decode bypasses the range-safe base decoder: BF16 linear returns NaN and embedding returns inf #5606).
_can_use_rocm_fused(
gptqmodel/nn_modules/qlinear/torch.py:779).TritonV2Linear.forwarddelegates to the same gate, so the mixed pair is fused there too.
dequantize_weight(dtype=self._forward_decode_dtype(x.dtype))(
torch.py:621) so it decodes once in the activation dtype when every weightfits it. Before, a BF16 model decoded FP16 and narrowed the whole matrix to
BF16 on every forward (double rounding plus a full-matrix copy).
TorchLinear.dequantize_weightaccepts the base class'sdtypeargument(
torch.py:455) and resolves it with_resolve_decode_dtype(torch.py:1272)in the Triton and cached 2/4/8-bit decoders.
_forward_decode_dtypeis attorch.py:1287.tests/kernels/test_gptq_bf16_fp16_scales_5740.py.docs/gptq-bf16-fused-gate.md, linked fromREADME.mdanddocs/README.md.No API removal. The only signature change is the additive
dtype=Nonekeywordon
TorchLinear.dequantize_weight, which already exists on the base class andthe sibling backends.
Follow-up out of scope: ROCm/gfx timing. The gate was already
architecture-gated; this change only removes the dtype equality inside it.
Tests
The new test forces
module.scales = module.scales.half()on a BF16 module,asserts the gate and the dispatch, and compares the fused output with the
non-fused dense result and an independent FP64 oracle on seven shapes
(M=1/8/64, act-order, bias, bits 2/4/8). It also covers the two rejection
paths: an unmeasured scale dtype (FP32 scales) and a decode that overflows the
activation dtype (FP16 scales x 60000). Reverting only the gate and the dense
decode makes 8 of the 20 tests fail at the
_can_use_rocm_gemvassertions.Measured Impact
RTX 4090 (SM 8.9), CUDA device 4, torch 2.15.0+cu132, Triton 3.9.0, 4-bit
gs=128, BF16 activations with FP16 scales,
triton.testing.do_benchmedian(warmup 25, rep 100). Before is
origin/main(c1eb3ca05, notorch.pydifference from the branch base); after is this PR. The harness is
/tmp/bench_5740.pyand/tmp/measure_err_5740.py(not committed; both usegptqmodel.nn_modules.qlinear.torch.TorchLineardirectly withgptq_gemv/gptq_gemmdispatch enabled).M=128is outside both fused bands; its gain is the single-rounding densedecode. The dense fallback itself is bit-exact against
round(matmul_fp32_reduce(x, dequantize_weight(dtype=x.dtype)))on all testedshapes.
Model Support / Module Plan
Not applicable: no
MODEL_MAP, definition, registry or fusion-plan change.Logic Flow Documentation
file:lineevidence.docs/, titled for the mechanism, linked fromREADME.md.Shipped flow:
flowchart TD A["TorchLinear._forward_eager(x)"] --> B{"_can_use_rocm_gemv(x)"} B -- "yes" --> F["gptq_gemv<br/>scales widened to FP32"] B -- "no" --> C{"_can_use_rocm_gemm(x)"} C -- "yes" --> G["gptq_gemm<br/>scales widened to FP32"] C -- "no" --> H["dequantize_weight(<br/>dtype=self._forward_decode_dtype(x.dtype))"] H --> I{"decoded weight fits x.dtype"} I -- "yes" --> J["matmul_fp32_reduce<br/>one decode, one narrowing"] I -- "no" --> K["linear_wide_bias<br/>wide decode, wide reduction"]:::fallback F --> L["_apply_fused_bias + adapter + reshape"] G --> L J --> M["adapter + reshape"] K --> MGate detail with the explicit failure paths:
flowchart TD S["_can_use_rocm_gemv / _can_use_rocm_gemm"] --> A["_can_use_rocm_fused(x)"] A --> B{"arch has a fused entry<br/>(Ada, Blackwell, gfx*)"} B -- "no" --> X["dense dequantize + matmul"]:::fallback B -- "yes" --> C{"Triton dequant eligible, bits 2/4/8,<br/>int32 v2 qzeros, aligned, contiguous, no grad"} C -- "no" --> X C -- "yes" --> D{"fused_scale_pair_supported(<br/>scales.dtype, x.dtype)"} D -- "no: FP32/FP64 scales with BF16/FP16 acts" --> X D -- "yes: equal, or FP16/FP16, BF16/BF16, FP16/BF16, BF16/FP16" --> E{"_decoded_weight_fits(x.dtype)"} E -- "no: decode overflows the activation dtype" --> X E -- "yes" --> F["gptq_gemv / gptq_gemm"] classDef fallback fill:#ffdddd,stroke:#cc0000,color:#660000Before/after with
file:lineevidence (torch.pyisgptqmodel/nn_modules/qlinear/torch.py):origin/mainc1eb3ca05)self.scales.dtype == x.dtypeattorch.py:736fused_scale_pair_supported(...)attorch.py:779; helper attorch.py:143_decoded_weight_fits(x.dtype)attorch.py:740torch.py:783dequantize_weight(num_itr=num_itr)attorch.py:586, then a full-matrixweights.to(dtype=x.dtype)attorch.py:614dequantize_weight(num_itr=num_itr, dtype=self._forward_decode_dtype(x.dtype))attorch.py:621dequantize_weightsignature(self, num_itr=1)attorch.py:430(self, num_itr=1, dtype=None)attorch.py:455, matching the base class_decode_dtype()attorch.py:1166_resolve_decode_dtype(dtype)attorch.py:1205-1209_decode_dtype()attorch.py:1255_resolve_decode_dtype(dtype)attorch.py:1321-1334tritonv2.py:171-174)Failure contract: an unmeasured scale dtype keeps the dense path and still
matches the oracle; a decode that overflows the activation dtype closes the
fused gate and keeps the wide
linear_wide_biasreduction; a caller-requesteddecode dtype is ignored when the decode does not fit. Extension point: add a
measured pair to
fused_scale_pair_supportedafter measuring the kernels forit.
Review Requirements
I or an AI agent (such as Codex or Claude) have:
Kernel Accuracy Requirements
docs/triton-dispatch.mdis unchanged. Architecture coverage: Ada measured; ROCmgfx*untimed here (no AMD GPU); unsupported widths, v1 qzeros, non-contiguous input and autograd keep the dense path and are covered bytests/kernels/test_tritonv2_dispatch.py.Notes
architecture-gated and the kernels widen scales to FP32 on both backends, so
the mixed-pair admission is the same code path; only the Ada/Blackwell
measurements above were taken.
M=1is bit-equal between fused and dense FP32 reduction on the testedshapes;
M=8/64differ by at most 5.7e-4 in the FP32 reduction and one BF16ulp in the visible output.
docs/gptq-bf16-fused-gate.md.