Skip to content

fix(rocm): fuse bias before output rounding - #3700

Merged
Qubitium merged 2 commits into
mainfrom
fix/rocm-bias-epilogue
Nov 9, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/rocm-bias-epilogue

Conversation

@ZX-ModelCloud

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

Copy link
Copy Markdown
Collaborator

TL;DR

matmul_fp32_reduce, the fused GPTQ GEMV/GEMM paths and the FP8 scaled-mm epilogue all rounded the partial sum to the activation dtype before adding the bias on ROCm, so a bias that cancels a large partial sum overflowed to inf. Add the bias inside a wide epilogue instead. The matmul_fp32_reduce branch is scoped to ROCm low-precision activations and yields to autocast and to biases that need broadcasting. Net diff: 4 files, +235/-21.

1. The problem

_wants_fp32_reduce excludes ROCm:

_WIDE_REDUCE_DEVICES = ("cuda",)

def _wants_fp32_reduce(x):
    return (
        x.device.type in _WIDE_REDUCE_DEVICES
        and not IS_ROCM
        and x.dtype in (torch.float16, torch.bfloat16)
    )

so on ROCm the fallback ran:

output = torch.matmul(x, weight)   # rounds in FP16/BF16
return output + bias               # then adds bias

linear_fp32_reduce already had a HIP fused-bias fix (_numerics.py:100-112); matmul_fp32_reduce did not.

The default fused GPTQ path had the same shape of bug for a different reason: gptq_gemv/gptq_gemm store into the output tensor's dtype, and TorchLinear._forward_eager then ran out.add_(self.bias) on the already-narrowed result.

Measured reproductions (gfx1201, torch 2.16+rocm10.1)

x = full((129,128), 516, fp16); w = ones((128,128), fp16); b = full((128,), -1024, fp16)
ref   = (x.float() @ w.float() + b.float()).half()   -> 65024
mm    = torch.matmul(x, w) + b                        -> inf
addmm = torch.addmm(b, x, w)                          -> 65024, bitwise equal to ref

Fused GPTQ (K=N=32, x=50, logical weight 41.25, bias -1000, qzero_format(2)):

M Selected path Before Oracle
1 GEMV inf 64992
2 GEMM inf 64992
16 GEMM inf 64992
17 dense fallback 64992 64992

BF16 small-M GEMM is disabled on gfx1201, so that part is FP16-specific.

Affected callers

torch.py (eager fused, eager dense, streaming), torch_awq.py, gemm_awq_triton.py, tritonv2 via triton_utils/dequant.py:352, gguf.py, fp8.py, paroquant_triton.py.

tests/kernels/test_cuda_bias_epilogue.py skipped ROCm entirely, and its GPTQ fixture left qzero_format()==1, so CI never reached the fused gate.

2. The fix

Area Before After
matmul_fp32_reduce (_numerics.py:124) torch.matmul(x, weight) then + bias on ROCm torch.addmm(flat_bias, flat_x, weight) behind _can_fuse_hip_bias
TorchLinear._forward_eager fused GEMV/GEMM (torch.py:376-399) kernel default dtype, then out.add_(self.bias) out_dtype=torch.float32, add bias, then cast to x.dtype
TorchLinear._forward_streaming (torch.py:609-612) addmm(beta=0) per tile, then out.add_(bias) per-tile addmm(tile_bias, ..., beta=1); post-add only when unfused
TorchFP8Linear._forward_scaled_mm (fp8.py:626) out_dtype=float32 only when _wants_fp32_reduce out_dtype=float32 whenever a bias exists

_can_fuse_hip_bias (_numerics.py:43) is deliberately narrow:

Condition Fused? Why
ROCm, FP16/BF16, 1-D bias, no autocast yes the case that rounds before the add
ROCm, FP32 activations no FP32 never rounds before the add
NVIDIA CUDA (any dtype) no unchanged from main
torch.autocast("cuda") active no addmm narrows a BF16 bias to FP16; the standalone add kept its range via type promotion
bias broadcast beyond the flattened 2D addmm input no addmm cannot express it; keeps the previous expression

The unbiased paths are unchanged, so ROCm keeps the measured no-extra-cast behaviour documented in _numerics.py:8-17.

3. Failure and ambiguity contract

Situation Before After
ROCm FP16/BF16, 1-D bias rounds, may overflow fused epilogue, one rounding
ROCm, fused GPTQ GEMV/GEMM narrows, then add_ FP32 fused output, add, cast
ROCm, autocast active add promoted, range kept unchanged (fusion skipped)
Bias needing broadcast works unchanged (fusion skipped)
NVIDIA CUDA unchanged unchanged
No bias unchanged unchanged

This stays a localized numerical fix inside one helper plus its two call sites; per the logic-flow guidance's exclusion for numerical tweaks inside one function, no docs/ reference page is added.

4. Change inventory

File +/- Purpose
gptqmodel/nn_modules/qlinear/_numerics.py +44/-4 _can_fuse_hip_bias, autocast_active, fused epilogue
gptqmodel/nn_modules/qlinear/torch.py +61/-14 fused-output dtype + bias helpers, streaming tile bias
gptqmodel/nn_modules/qlinear/fp8.py +8/-4 wide scaled-mm output whenever biased
tests/kernels/test_cuda_bias_epilogue.py +143/-18 ROCm unskip, fused gates, autocast, broadcast

5. Tests

Test Invariant
test_matmul_fp32_reduce_fuses_bias_before_rounding finite and bitwise-equal to the FP64 oracle on the 516/-1024 case
test_rocm_fused_gptq_bias_rounds_once[1,2,16] asserts _can_use_rocm_gemv/_can_use_rocm_gemm fire, then bitwise-equal to the FP64 oracle; skips only where the device's gate is closed
test_matmul_fp32_reduce_keeps_bias_range_under_autocast BF16 bias stays finite under torch.autocast("cuda"), same dtype and value as the replaced expression
test_matmul_fp32_reduce_matches_broadcast_bias_expression (2,1,48) bias against (2,3,32) input matches the unfused expression bitwise
test_hip_bias_fusion_scope fusion is ROCm-only, low-precision-only, off under autocast and for broadcast biases
test_cuda_bias_cancellation_rounds_once[gptq,gptq_streaming,awq,tritonv2,fp8_dense,fp8_scaled,gguf_dense] every fallback rounds once against the FP64 oracle

The GPTQ fixture now takes fused=True to set qzero_format(2). Its packed zero points are literally zero, which is already the v2 encoding of zero point 0, so only the gate flag changes; the fixture asserts dequantize_weight() still equals the logical weight so it cannot drift. The default fixture keeps the v1 flag and the dense-fallback case. _tritonv2 now calls pytest.importorskip("triton").

6. Validation

Hardware: 2x AMD Radeon AI PRO R9700 (gfx1201), ROCR_VISIBLE_DEVICES=2,3, torch 2.16.0.dev20261029+rocm10.1, Triton 3.9.0, Python 3.14t. Head 70ee558b6, rebased onto origin/main feffa4a0d.

tests/kernels/test_cuda_bias_epilogue.py                                    57 passed, 2 skipped
tests/kernels/test_tritonv2_bias_epilogue.py                                20 passed
test_cuda_bias_epilogue + test_tritonv2_bias_epilogue + test_linear_fp32_reduce
  + test_triton_fp32_reduce + test_fp8_kernel + test_torch
  + test_rocm_backend_gating                                                207 passed, 17 skipped

The two skips are BF16 M=2/M=16 on gfx1201, where the fused small-M GEMM gate is closed by design; the FP16 GEMV (M=1) and GEMM (M=2, 16) cases run and pass.

Re-ran the review reproductions after the fix: fused GEMV/GEMM 64992 (oracle 64992), autocast -32768 in FP32 (oracle -32768), broadcast bias matches the unfused expression bitwise.

ruff check and git diff --check pass on all touched files.

7. Reviewer notes

  • NVIDIA CUDA is unchanged by this PR: the matmul_fp32_reduce branch requires IS_ROCM, and the fused-kernel output widening only changes the case where a bias is present, which previously ran out.add_ on a narrowed output on both vendors. That fused-kernel widening does apply to Ada as well, since it has the same out.add_-after-narrow sequence.
  • The FP8 change is in scope because the ROCm scaled-mm path showed the same overflow, which the newly un-skipped test caught.
  • Under autocast the ROCm low-precision overflow still exists for the standalone expression; this PR restores the previous autocast behaviour rather than changing autocast semantics.

@ZX-ModelCloud ZX-ModelCloud left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review of d949f486d25fd3a8a3c3fe00c3ba2c4930ccdcdc: recommendation: request changes before merging. Submitted as a COMMENT review because GitHub does not allow the PR author to submit REQUEST_CHANGES on their own PR.

The ROCm dense fallback, streaming and FP8 changes fix the tested cancellation cases. However, the default fused GPTQ path still has the same failure, and the new addmm branch introduces an autocast regression.

  1. [P1, existing bug left unresolved] Fused GPTQ GEMV/GEMM still round before adding bias.

    TorchLinear._forward_eager calls gptq_gemv / gptq_gemm without out_dtype, then performs out.add_(self.bias). Both kernels default to the activation dtype, so an overflowing partial sum has already become inf before cancellation.

    Reproduced on gfx1201 using this PR's _gptq(torch.float16, streaming=False) fixture, followed by module.qzero_format(2). With K=N=32, x=50, logical weight=41.25 and bias=-1000:

    M Selected path PR output Fused disabled / rounded independent FP64 oracle
    1 GEMV inf 64992
    2 GEMM inf 64992
    16 GEMM inf 64992
    17 dense fallback 64992 64992

    This is reachable for real checkpoints: the loader marks native GPTQ_V2 modules as format 2. The gfx1201 small-M GEMM gate admits FP16 M=2..16; BF16 small-M GEMM is disabled on this architecture, so that part of the claim is FP16-specific.

    Please add bias before the fused output is narrowed. Both kernel wrappers already accept out_dtype, so requesting FP32 output for biased calls, adding bias in FP32 and then casting is one possible fix.

    The corresponding test gap is in _gptq: despite format=FORMAT.GPTQ_V2, the fixture returns qzero_format()==1, bypassing the fused gate. Keep the fallback case and add separate M=1 GEMV and eligible small-M GEMM cases with explicit gate assertions. Mark the fixture's logical-zero layout correctly; setting the format flag and converting actual v1 packed zeros are not interchangeable operations.

  2. [P2, new regression] Autocast can overflow the bias before the new fused addition.

    At _numerics.py:87-98, matching x.dtype and bias.dtype does not protect the operands from autocast. Under the default torch.autocast("cuda"), addmm converts a BF16 bias to FP16, whereas the previous standalone addition retained it for dtype promotion.

    Minimal ROCm reproduction:

    x = torch.full((129, 32), 1024, device="cuda", dtype=torch.bfloat16)
    w = torch.ones((32, 32), device="cuda", dtype=torch.bfloat16)
    b = torch.full((32,), -65536, device="cuda", dtype=torch.bfloat16)
    with torch.autocast("cuda"):
        before = torch.matmul(x, w) + b
        after = matmul_fp32_reduce(x, w, b)
    # before: float32, -32768, finite
    # after:  float16, -inf
    # independent FP64 oracle: -32768

    Also reproduced through a real TorchLinear with unit packed weights and BF16 bias, comparing the base helper with the PR helper. Please preserve bias range under autocast and add a regression test; the current suite does not exercise this context.

  3. [P2, test portability] The added TritonV2 cases do not skip when Triton is absent.

    _tritonv2 adds a mandatory Triton execution path to a suite gated only on GPU availability. Simulating a missing Triton import causes TritonV2Linear.forward to raise ModuleNotFoundError. Please use a helper-local pytest.importorskip("triton") so the portable backend tests can still run.

Two lower-priority points:

  • The new helper branch loses higher-rank bias broadcasting. With x=(2,3,32), w=(32,48), bias=(2,1,48), the old expression succeeds and the PR raises from addmm. Current production callers use one-dimensional bias, so this is a helper compatibility concern rather than a demonstrated model failure. A dimensionality check alone does not cover every broadcast interaction after flattening.
  • The PR's statement that NVIDIA CUDA is untouched is too broad: NVIDIA FP32 inputs also enter the new branch, since only FP16/BF16 take the earlier wide-reduction path. Please narrow that statement or deliberately scope the branch.

Validation already performed on this head: 339 passed, 14 skipped, plus 24 additional boundary cases passed (both visible GPUs, empty/vector/batched/noncontiguous inputs, streaming tail tiles and repeated-forward storage checks). These passing cases do not cover the two failing scenarios above. The fused-path and autocast reproductions were run separately.

All terminal commands ran outside the sandbox in an isolated git worktree. GPU execution used only AMD Radeon AI PRO R9700/gfx1201, Torch 2.16.0.dev20261029+rocm10.1. No NVIDIA CUDA tests were used.

@ZX-ModelCloud
ZX-ModelCloud force-pushed the fix/rocm-bias-epilogue branch from d949f48 to 70ee558 Compare November 9, 2026 08:24
@ZX-ModelCloud

ZX-ModelCloud commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

#3700 (review)
All three points were real and are fixed in 70ee558b6 (rebased onto feffa4a0d).

1. [P1] Fused GPTQ GEMV/GEMM — confirmed exactly as described: FP16 M=1 GEMV and M=2/16 GEMM returned inf (oracle 64992), M=17 dense fallback was already correct, BF16 small-M GEMM is gated off on gfx1201. Fixed in torch.py:376-399 via _fused_bias_out_dtype/_apply_fused_bias: biased calls request out_dtype=torch.float32 from both wrappers, add the bias there, then cast to the activation dtype. All three shapes now return 64992.

Test gap also fixed: _gptq takes fused=True, which sets qzero_format(2) and asserts dequantize_weight() still equals the logical weight, so the flag cannot silently mis-encode the packed zeros. test_rocm_fused_gptq_bias_rounds_once[1,2,16] asserts _can_use_rocm_gemv / _can_use_rocm_gemm fire before comparing against the FP64 oracle, and skips only where the device's gate is closed (BF16 M=2/16 on gfx1201). The v1-flag dense-fallback case is kept.

2. [P2] Autocast regression — reproduced (before: float32 -32768, after: float16 -inf). Fixed by scoping _can_fuse_hip_bias (_numerics.py:43) to ROCm low-precision calls without autocast; the streaming path uses the same guard. Under autocast the helper now returns exactly the previous matmul + bias expression (FP32, -32768), covered by test_matmul_fp32_reduce_keeps_bias_range_under_autocast. I also reverted my earlier claim of NVIDIA being untouched: the branch is now explicitly IS_ROCM-scoped, so the CUDA non-HIP expression is byte-identical to main. (The fused-kernel widening does apply to Ada too, since it had the same out.add_-after-narrow sequence — noted in the PR.)

3. [P2] Triton portability — _tritonv2 now calls pytest.importorskip("triton").

Lower-priority points

  • Broadcast bias: reproduced ((2,1,48) bias with (2,3,32) input raised from addmm). _can_fuse_hip_bias now requires a 1-D bias or a bias whose shape already equals the output shape; everything else keeps the unfused expression. Covered by test_matmul_fp32_reduce_matches_broadcast_bias_expression.
  • CUDA statement: narrowed as above.

Validation on 70ee558b6, gfx1201 (2x R9700, ROCR_VISIBLE_DEVICES=2,3), torch 2.16.0.dev20261029+rocm10.1:

tests/kernels/test_cuda_bias_epilogue.py            57 passed, 2 skipped
tests/kernels/test_tritonv2_bias_epilogue.py        20 passed
+ test_linear_fp32_reduce, test_triton_fp32_reduce,
  test_fp8_kernel, test_torch, test_rocm_backend_gating
                                                   207 passed, 17 skipped

ruff check and git diff --check clean. No NVIDIA CUDA tests were run and gp_314t was not used.

matmul_fp32_reduce took the non-wide fallback on ROCm, so matmul + bias rounded (and could overflow) the partial sum in the activation dtype before the bias cancelled it. Route biased calls through addmm on the CUDA runtime, including HIP, and fuse the bias into the streaming and FP8 scaled epilogues. Remove the ROCm test skip and cover TorchLinear eager/streaming, AWQ dense, TritonV2, FP8 and GGUF bias cancellation on ROCm.
The fused GEMV/small-M GEMM kernels store into the output tensor's dtype, so 'out.add_(bias)' still rounded (and overflowed) the partial sum before the bias could cancel it; request an FP32 fused output whenever a bias is present and add it there. Scope the matmul_fp32_reduce epilogue to ROCm low-precision activations so NVIDIA keeps its previous expression, and keep the unfused add under autocast, where addmm narrows a BF16 bias to FP16 while the standalone addition kept its range through type promotion. Keep the unfused expression for biases that need broadcasting beyond the flattened 2D addmm input. Add fused GEMV/GEMM gate cases, autocast and broadcast regressions, and skip the TritonV2 cases when Triton is unavailable.
@Qubitium
Qubitium force-pushed the fix/rocm-bias-epilogue branch from 70ee558 to 30b2a42 Compare November 9, 2026 11:04

@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 against current main.

The bias-before-rounding contract is correct and the scope is well chosen:

  • _can_fuse_hip_bias keeps the fused epilogue ROCm-only for low-precision activations, excludes autocast (where addmm narrows a BF16 bias to FP16) and excludes biases that need broadcasting beyond the flattened 2D output.
  • matmul_fp32_reduce uses that branch for HIP; fp8.py now requests FP32 whenever a bias is present; TorchLinear._fused_bias_out_dtype/_apply_fused_bias request a wide gptq_gemv/gptq_gemm output and add the bias before narrowing; the streaming path fuses the bias with addmm instead of out.add_ after rounding.
  • test_cuda_bias_epilogue.py covers the ROCm fusion scope, autocast, broadcast bias, and the one-rounding GPTQ epilogues.

Two follow-ups were needed and are in the branch:

  1. matmul_fp32_reduce's CUDA wide path still fused the bias unconditionally. Under autocast that narrows a BF16 bias (the -65536 case overflows as FP16), and a [B, 1, out] bias cannot be passed to the 2D addmm at all. The wide path now keeps the original expression under autocast and adds a broadcast bias after reshaping; 1D/exact-shape biases keep the wide addmm epilogue.
  2. tests/kernels/test_gptq_ada_gemm.py still asserted the old “round the GEMM, then add bias” order for the fused path. Its oracle now adds the bias before narrowing, matching the new contract.

Validation: ruff check clean; test_cuda_bias_epilogue.py 59 passed; test_gptq_ada_gemm.py 69 passed, 6 failed — the 6 are the shape7 split-path cases that fail identically on main; test_linear_fp32_reduce.py and test_triton_fp32_reduce.py pass.

No other blocking issues found.

@Qubitium
Qubitium marked this pull request as ready for review November 9, 2026 11:04
@Qubitium
Qubitium merged commit b6f8913 into main Nov 9, 2026
5 checks passed
@Qubitium
Qubitium deleted the fix/rocm-bias-epilogue branch November 9, 2026 11:04

Copy link
Copy Markdown
Collaborator

Review found six CUDA bias oracles expected the old rounding order. #3756 corrected those tests; the current focused bias suite passes.

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