Repository navigation
fix(rocm): fuse bias before output rounding - #3700
Conversation
There was a problem hiding this comment.
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.
-
[P1, existing bug left unresolved] Fused GPTQ GEMV/GEMM still round before adding bias.
TorchLinear._forward_eagercallsgptq_gemv/gptq_gemmwithoutout_dtype, then performsout.add_(self.bias). Both kernels default to the activation dtype, so an overflowing partial sum has already becomeinfbefore cancellation.Reproduced on gfx1201 using this PR's
_gptq(torch.float16, streaming=False)fixture, followed bymodule.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: despiteformat=FORMAT.GPTQ_V2, the fixture returnsqzero_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. -
[P2, new regression] Autocast can overflow the bias before the new fused addition.
At
_numerics.py:87-98, matchingx.dtypeandbias.dtypedoes not protect the operands from autocast. Under the defaulttorch.autocast("cuda"),addmmconverts 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
TorchLinearwith 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. -
[P2, test portability] The added TritonV2 cases do not skip when Triton is absent.
_tritonv2adds a mandatory Triton execution path to a suite gated only on GPU availability. Simulating a missing Triton import causesTritonV2Linear.forwardto raiseModuleNotFoundError. Please use a helper-localpytest.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.
d949f48 to
70ee558
Compare
|
#3700 (review) 1. [P1] Fused GPTQ GEMV/GEMM — confirmed exactly as described: FP16 Test gap also fixed: 2. [P2] Autocast regression — reproduced ( 3. [P2] Triton portability — Lower-priority points
Validation on
|
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.
70ee558 to
30b2a42
Compare
Qubitium
left a comment
There was a problem hiding this comment.
Reviewed against current main.
The bias-before-rounding contract is correct and the scope is well chosen:
_can_fuse_hip_biaskeeps the fused epilogue ROCm-only for low-precision activations, excludes autocast (whereaddmmnarrows a BF16 bias to FP16) and excludes biases that need broadcasting beyond the flattened 2D output.matmul_fp32_reduceuses that branch for HIP;fp8.pynow requests FP32 whenever a bias is present;TorchLinear._fused_bias_out_dtype/_apply_fused_biasrequest a widegptq_gemv/gptq_gemmoutput and add the bias before narrowing; the streaming path fuses the bias withaddmminstead ofout.add_after rounding.test_cuda_bias_epilogue.pycovers the ROCm fusion scope, autocast, broadcast bias, and the one-rounding GPTQ epilogues.
Two follow-ups were needed and are in the branch:
matmul_fp32_reduce's CUDA wide path still fused the bias unconditionally. Under autocast that narrows a BF16 bias (the-65536case overflows as FP16), and a[B, 1, out]bias cannot be passed to the 2Daddmmat all. The wide path now keeps the original expression under autocast and adds a broadcast bias after reshaping; 1D/exact-shape biases keep the wideaddmmepilogue.tests/kernels/test_gptq_ada_gemm.pystill 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.
|
Review found six CUDA bias oracles expected the old rounding order. #3756 corrected those tests; the current focused bias suite passes. |
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 toinf. Add the bias inside a wide epilogue instead. Thematmul_fp32_reducebranch 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_reduceexcludes ROCm:so on ROCm the fallback ran:
linear_fp32_reducealready had a HIP fused-bias fix (_numerics.py:100-112);matmul_fp32_reducedid not.The default fused GPTQ path had the same shape of bug for a different reason:
gptq_gemv/gptq_gemmstore into the output tensor's dtype, andTorchLinear._forward_eagerthen ranout.add_(self.bias)on the already-narrowed result.Measured reproductions (gfx1201, torch 2.16+rocm10.1)
Fused GPTQ (K=N=32, x=50, logical weight 41.25, bias -1000,
qzero_format(2)):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,tritonv2viatriton_utils/dequant.py:352,gguf.py,fp8.py,paroquant_triton.py.tests/kernels/test_cuda_bias_epilogue.pyskipped ROCm entirely, and its GPTQ fixture leftqzero_format()==1, so CI never reached the fused gate.2. The fix
matmul_fp32_reduce(_numerics.py:124)torch.matmul(x, weight)then+ biason ROCmtorch.addmm(flat_bias, flat_x, weight)behind_can_fuse_hip_biasTorchLinear._forward_eagerfused GEMV/GEMM (torch.py:376-399)out.add_(self.bias)out_dtype=torch.float32, add bias, then cast tox.dtypeTorchLinear._forward_streaming(torch.py:609-612)addmm(beta=0)per tile, thenout.add_(bias)addmm(tile_bias, ..., beta=1); post-add only when unfusedTorchFP8Linear._forward_scaled_mm(fp8.py:626)out_dtype=float32only when_wants_fp32_reduceout_dtype=float32whenever a bias exists_can_fuse_hip_bias(_numerics.py:43) is deliberately narrow:maintorch.autocast("cuda")activeaddmmnarrows a BF16 bias to FP16; the standalone add kept its range via type promotionaddmminputaddmmcannot express it; keeps the previous expressionThe unbiased paths are unchanged, so ROCm keeps the measured no-extra-cast behaviour documented in
_numerics.py:8-17.3. Failure and ambiguity contract
add_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
gptqmodel/nn_modules/qlinear/_numerics.py_can_fuse_hip_bias,autocast_active, fused epiloguegptqmodel/nn_modules/qlinear/torch.pygptqmodel/nn_modules/qlinear/fp8.pytests/kernels/test_cuda_bias_epilogue.py5. Tests
test_matmul_fp32_reduce_fuses_bias_before_roundingtest_rocm_fused_gptq_bias_rounds_once[1,2,16]_can_use_rocm_gemv/_can_use_rocm_gemmfire, then bitwise-equal to the FP64 oracle; skips only where the device's gate is closedtest_matmul_fp32_reduce_keeps_bias_range_under_autocasttorch.autocast("cuda"), same dtype and value as the replaced expressiontest_matmul_fp32_reduce_matches_broadcast_bias_expression(2,1,48)bias against(2,3,32)input matches the unfused expression bitwisetest_hip_bias_fusion_scopetest_cuda_bias_cancellation_rounds_once[gptq,gptq_streaming,awq,tritonv2,fp8_dense,fp8_scaled,gguf_dense]The GPTQ fixture now takes
fused=Trueto setqzero_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 assertsdequantize_weight()still equals the logical weight so it cannot drift. The default fixture keeps the v1 flag and the dense-fallback case._tritonv2now callspytest.importorskip("triton").6. Validation
Hardware: 2x AMD Radeon AI PRO R9700 (gfx1201),
ROCR_VISIBLE_DEVICES=2,3, torch2.16.0.dev20261029+rocm10.1, Triton 3.9.0, Python 3.14t. Head70ee558b6, rebased ontoorigin/mainfeffa4a0d.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(oracle64992), autocast-32768in FP32 (oracle-32768), broadcast bias matches the unfused expression bitwise.ruff checkandgit diff --checkpass on all touched files.7. Reviewer notes
matmul_fp32_reducebranch requiresIS_ROCM, and the fused-kernel output widening only changes the case where a bias is present, which previously ranout.add_on a narrowed output on both vendors. That fused-kernel widening does apply to Ada as well, since it has the sameout.add_-after-narrow sequence.