Skip to content

fix(gptq): fuse BF16 GPTQ decode with FP16 scales - #5921

Merged
Qubitium merged 2 commits into
mainfrom
fix/5740-bf16-fused-gptq-gemv
Nov 20, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/5740-bf16-fused-gptq-gemv

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5740. A GPTQ checkpoint stores FP16 scales, while a BF16 model runs BF16
activations. TorchLinear._can_use_rocm_fused required
self.scales.dtype == x.dtype, so every BF16 model missed gptq_gemv and
gptq_gemm and 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

  • Added 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 the
    activation dtype ([BUG] GPTQ_TORCH eval decode bypasses the range-safe base decoder: BF16 linear returns NaN and embedding returns inf #5606).
  • Replaced the equality check in _can_use_rocm_fused
    (gptqmodel/nn_modules/qlinear/torch.py:779). TritonV2Linear.forward
    delegates to the same gate, so the mixed pair is fused there too.
  • The dense fallback now asks dequantize_weight(dtype=self._forward_decode_dtype(x.dtype))
    (torch.py:621) so it decodes once in the activation dtype when every weight
    fits 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_weight accepts the base class's dtype argument
    (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_dtype is at
    torch.py:1287.
  • New tests: tests/kernels/test_gptq_bf16_fp16_scales_5740.py.
  • New reference page docs/gptq-bf16-fused-gate.md, linked from README.md and
    docs/README.md.

No API removal. The only signature change is the additive dtype=None keyword
on TorchLinear.dequantize_weight, which already exists on the base class and
the 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

cd /root/work/bf16-fused-gemv-5740
export CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=4 PYTHONPATH=$PWD \
  MAX_JOBS=8 HF_HUB_OFFLINE=1
/root/venv/bin/python -m pytest -q tests/kernels/test_gptq_bf16_fp16_scales_5740.py
# 20 passed

/root/venv/bin/python -m pytest -q tests/kernels/test_gptq_ada_gemv.py \
  tests/kernels/test_gptq_ada_gemm.py tests/kernels/test_gptq_ada_dequant.py \
  tests/kernels/test_tritonv2_dispatch.py tests/kernels/test_tritonv2_bias_epilogue.py
# 241 passed

/root/venv/bin/python -m pytest -q tests/kernels/test_gptq.py \
  tests/kernels/test_gptq_torch_cpu_bias_epilogue.py \
  tests/kernels/test_torch_wide_bias_fallback.py \
  tests/kernels/test_inference_numeric_range.py \
  tests/kernels/test_torch_weight_storage.py \
  tests/kernels/test_cuda_bias_epilogue.py \
  tests/kernels/test_triton_fp32_reduce.py
# 713 passed, 8 skipped

/root/venv/bin/python -m pytest -q tests/module_tree/test_fusion_kernel_backends.py \
  tests/test_dequantize_model_compute_dtype_4370.py \
  tests/test_dequantize_model_dtype_4455.py tests/test_dequant_launch_config.py
# 192 passed, 34 skipped
  • Unit tests have been executed and passed.
  • Added a new simple/fast unit test for this change.

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_gemv assertions.

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_bench median
(warmup 25, rep 100). Before is origin/main (c1eb3ca05, no torch.py
difference from the branch base); after is this PR. The harness is
/tmp/bench_5740.py and /tmp/measure_err_5740.py (not committed; both use
gptqmodel.nn_modules.qlinear.torch.TorchLinear directly with
gptq_gemv/gptq_gemm dispatch enabled).

Metric (unit) Before After Change (after − before)
Latency, 4096x4096, M=1 (ms) 0.1157 0.0348 −0.0809 (−69.9%, 3.32x)
Latency, 4096x4096, M=8 (ms) 0.0952 0.0276 −0.0676 (−71.0%, 3.45x)
Latency, 4096x11008, M=1 (ms) 0.4277 0.0529 −0.3748 (−87.6%, 8.08x)
Latency, 4096x11008, M=8 (ms) 0.4700 0.0475 −0.4225 (−89.9%, 9.89x)
Latency, 11008x4096, M=1 (ms) 0.4668 0.0563 −0.4105 (−87.9%, 8.29x)
Latency, 11008x4096, M=8 (ms) 0.4291 0.0604 −0.3687 (−85.9%, 7.10x)
Latency, 4096x4096, M=128 (dense, ms) 0.1175 0.0799 −0.0376 (−32.0%, 1.47x)
Latency, 4096x11008, M=128 (dense, ms) 0.4721 0.2461 −0.2260 (−47.9%, 1.92x)
Latency, 11008x4096, M=128 (dense, ms) 0.4729 0.2580 −0.2149 (−45.4%, 1.83x)
Max abs error, fused vs non-fused FP32 reduction, worst shape (abs) not reachable (fused gate closed) 5.684e-4 n/a
Max abs error, fused vs FP64 oracle, worst shape (abs) not reachable (fused gate closed) 2.643e-4 n/a
Visible BF16 output, fused vs dense, worst shape (ulp) not reachable (fused gate closed) 1 (bit-equal at M=1) n/a

M=128 is outside both fused bands; its gain is the single-rounding dense
decode. The dense fallback itself is bit-exact against
round(matmul_fp32_reduce(x, dequantize_weight(dtype=x.dtype))) on all tested
shapes.

Model Support / Module Plan

Not applicable: no MODEL_MAP, definition, registry or fusion-plan change.

Logic Flow Documentation

  • Diagrams and docs page are included.
  • New-flow Mermaid diagrams use real symbol names.
  • The replaced mechanism is tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct.
  • Reference page under docs/, titled for the mechanism, linked from README.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 --> M
Loading

Gate 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:#660000
Loading

Before/after with file:line evidence (torch.py is
gptqmodel/nn_modules/qlinear/torch.py):

Mechanism Before (origin/main c1eb3ca05) After
Fused gate scale check self.scales.dtype == x.dtype at torch.py:736 fused_scale_pair_supported(...) at torch.py:779; helper at torch.py:143
Range guard _decoded_weight_fits(x.dtype) at torch.py:740 unchanged, still after the pair check at torch.py:783
Dense fallback decode dequantize_weight(num_itr=num_itr) at torch.py:586, then a full-matrix weights.to(dtype=x.dtype) at torch.py:614 dequantize_weight(num_itr=num_itr, dtype=self._forward_decode_dtype(x.dtype)) at torch.py:621
dequantize_weight signature (self, num_itr=1) at torch.py:430 (self, num_itr=1, dtype=None) at torch.py:455, matching the base class
Triton decode dtype _decode_dtype() at torch.py:1166 _resolve_decode_dtype(dtype) at torch.py:1205-1209
Cached 2/4/8-bit decode _decode_dtype() at torch.py:1255 _resolve_decode_dtype(dtype) at torch.py:1321-1334
TritonV2 delegation gate inherited, equality rejected BF16 same gate, mixed pair admitted (tritonv2.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_bias reduction; a caller-requested
decode dtype is ignored when the decode does not fit. Extension point: add a
measured pair to fused_scale_pair_supported after measuring the kernels for
it.

Review Requirements

I or an AI agent (such as Codex or Claude) have:

  • 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

  • Accuracy drift was measured against an applicable independent Torch FP64 oracle.
  • Not a model-fusion change: AUTO's native class and packed storage are untouched; actual-device BF16 tests cover the mixed pair and both rejection paths.
  • This PR adds no kernel, launch entry, shape/workspace/descriptor or dtype kernel variant, so the launch inventory in docs/triton-dispatch.md is unchanged. Architecture coverage: Ada measured; ROCm gfx* untimed here (no AMD GPU); unsupported widths, v1 qzeros, non-contiguous input and autograd keep the dense path and are covered by tests/kernels/test_tritonv2_dispatch.py.

Notes

  • ROCm/gfx could not be timed here (no AMD GPU). The gate was already
    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=1 is bit-equal between fused and dense FP32 reduction on the tested
    shapes; M=8/64 differ by at most 5.7e-4 in the FP32 reduction and one BF16
    ulp in the visible output.
  • The reference page is docs/gptq-bf16-fused-gate.md.

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).
@Qubitium
Qubitium marked this pull request as ready for review November 20, 2026 14:46
@Qubitium
Qubitium merged commit a47804c into main Nov 20, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5740-bf16-fused-gptq-gemv branch November 20, 2026 14: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.

[Audit][torch/tritonv2] Fused GPTQ GEMV/small-M GEMM unreachable for BF16 models: gate requires scales.dtype == x.dtype but GPTQ scales load as FP16

1 participant