Skip to content

fix(triton): keep the GPTQ reduction in FP32 and repair kernel test imports - #3526

Merged
Qubitium merged 3 commits into
ModelCloud:mainfrom
Xingyu-Zheng:fix/triton-fp32-reduce
Nov 4, 2026
Merged

Qubitium merged 3 commits into
ModelCloud:mainfrom
Xingyu-Zheng:fix/triton-fp32-reduce

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Problem

TritonV2Linear computed input @ dequantized_weight in the activation dtype, while every other GPTQ backend rounds once after an FP32 reduction. PR #3520 fixed the Torch, GGUF, ExLlamaV2 and Marlin epilogues but missed this path.

On sliuau/Llama-3.2-3B_4bits_128group_size (model.layers.6.self_attn.v_proj, bf16) the dequantized weights are bit-identical between backends, yet the outputs differ by exactly one bf16 ulp (0.0078125) on 32 of 112 samples. Against an independent FP64 oracle:

path max abs error vs FP64
input @ W (old Triton) 0.005235
matmul_fp32_reduce (Torch) 0.003898

The narrow path is strictly worse on 3523 of 8192 elements, so Torch was right and Triton was wrong.

Fix

Both quant_matmul branches now route through the existing matmul_fp32_reduce helper, so Triton and Torch agree bit-for-bit on CUDA. HIP already accumulates in FP32 for low-precision operands, so the ROCm result is unchanged (verified on gfx1201).

Test-collection bugs fixed alongside

These made the CI command pytest tests/kernels/<file>.py collect nothing:

  • test_inference_numeric_{fusion,range}.py imported sibling helpers by bare module name. Those only resolve via tests/conftest.py's sys.path injection, which does not cover tests/kernels/. The fusion file therefore died with ModuleNotFoundError and collected 0 tests.
  • test_inference_numeric_range.py pointed at test_exllamav3_cpu, which lives in tests/, not tests/kernels/ — all 4 test_exl3_transform_range cases failed.

Oracle bug in test_torch_int8.py

The oracle pre-rounded the channel scale to the activation dtype:

raw = (activation.float() @ codes.float()) * channel_scale.to(current_dtype).float()

but Int8PackedModule.forward passes int8_channel_scale.float() and rounds only the final output. The kernel was correct; the test was not. Every bf16 case failed (15 failed → 29 passed after the fix). The oracle now computes in FP64 and reports arithmetic error separately from visible low-precision output error, per the repo's numerics guidance.

Verification

  • tests/kernels/test_gptq.py::TestKernelOutput — 16 passed, 8 skipped (was failing for both Triton dtypes)
  • New tests/kernels/test_triton_fp32_reduce.py — 10 passed; reverting the fix makes 2 fail, so the regression is pinned
  • test_torch_int8.py 29 passed, test_inference_numeric_range.py 320 passed, test_inference_numeric_fusion.py 89 passed
  • ROCm gfx1201 (GPUs 2,3): 96 passed, 92 skipped
  • ruff check gptqmodel tests clean

No dense/dequantized weight cache is introduced or retained; the dequantized tile is consumed by the matmul and released.

…mports

The Triton dequant path computed `input @ dequantized_weight` in the
activation dtype, so every output drifted by about one bf16 ulp relative to
the Torch backend, which rounds once after an FP32 reduction. PR ModelCloud#3520 fixed
the Torch, GGUF, ExLlamaV2 and Marlin epilogues but missed this path.

- Route both quant_matmul branches through matmul_fp32_reduce so Triton and
  Torch agree bit-for-bit on CUDA. HIP already accumulates in FP32 for
  low-precision operands, so the ROCm result is unchanged.
- tests/kernels/test_triton_fp32_reduce.py pins the FP32 epilogue against an
  independent FP64 oracle and asserts Triton/Torch bit equality; arithmetic
  error is reported separately from the visible low-precision output error.
- test_inference_numeric_{fusion,range}.py referenced sibling helpers through
  bare module names that only resolve when tests/ is on sys.path, so
  `pytest tests/kernels/test_inference_numeric_fusion.py` (the exact CI form)
  died with ModuleNotFoundError and collected nothing.
- test_torch_int8.py pre-rounded the channel scale to the activation dtype in
  its oracle. The kernel multiplies the canonical FP32 scale and rounds only
  the output, so the oracle disagreed with a correct kernel for every bf16
  case; compare arithmetic in FP64 and keep the visible rounding separate.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as draft November 4, 2026 06:54
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Review of PR #3526 — measured on real hardware

Reviewed head 679c359e9 on RTX 4090 (torch 2.15.0+cu132, triton 3.9.0) and Radeon AI PRO R9700 / gfx1201 (torch 2.16.0.dev+rocm10.1, triton 3.9.0).

Verdict: the numerics fix is correct; the perf/memory cost and two test issues should be addressed before merge.

Correctness — confirmed

  • CUDA: Triton and Torch now agree bit-for-bit as claimed. Synthetic 2/4/8-bit × group 32/128 × M=1..512 → 84/84 cases identical; the real model.layers.6.self_attn.v_proj (3072→1024, bf16) from sliuau/Llama-3.2-3B_4bits_128group_size is bit-exact at M=1/16/32/64/128 (both backends' dequantize_weight() are already bit-identical).
  • Reverting the fix reproduces the failure: tests/kernels/test_gptq.py -k TRITON → main 4 failed, PR 4 passed; whole file PR 17 passed, 8 skipped.
  • test_torch_int8.py: main 15 failed → PR 29 passed. The old oracle rounded the channel scale to bf16 (measured 3.906e-3 ulp drift); the kernel does FP32-scale × FP32-accumulate with a single output rounding. Test was wrong, kernel was right — this fix is correct.
  • torch.compile(fullgraph=True) through matmul_fp32_reduce works and is bit-identical to eager.

Blocker: latency and peak-memory regression, and zero benefit on ROCm

matmul_fp32_reduce always takes torch.mm(..., out_dtype=float32).to(dtype) on cuda, which includes ROCm. Measured deltas vs. main's input @ W:

Case Regression
real layer-6 v_proj, bf16 forward M=1 +22.3%, M=16 +12.4%, M=64 +28.3%, M=128 +22.3%, M=512 +9.0%
raw matmul, 4090 +3.8% … +28.2% (worst at 4096×4096×14336)
TritonV2 module, gfx1201 +4.1% … +16.2%
peak allocated (4096×4096×14336 / 8192×4096×14336) +215.9 MiB / +439.9 MiB

Two facts that matter for the fix's scope:

  1. For M ≤ 16 (the decode band) CUDA narrow and wide are bitwise identical — 0 differing elements across 216 forward cases at M=1/8/16; divergence only starts at M≥32. So the "strictly worse on 3523 of 8192 elements" argument does not apply where most of this kernel's forwards happen.
  2. On gfx1201 all 216/216 forward cases are bitwise identical between narrow and wide; HIP already accumulates in FP32 for these operands. The x.device.type == "cuda" branch therefore buys nothing there and only pays the cost above.

Suggested resolution (either is fine):

  • (a) accept it, but add the latency and peak-memory numbers to the PR — the repo's numerics guidance requires reporting speed and temporary storage alongside accuracy, and this PR currently reports neither; or
  • (b) gate the wide path (e.g. not IS_ROCM and/or x.shape[0] > 16). Note _numerics.py is shared by Torch/GGUF/AWQ/FP8, so any gate must be re-validated for those too. Per my measurements the gate would not change any current output, but that relies on cuBLAS/HIP behaviour and needs a test to pin it.

Test issues

  • tests/kernels/test_triton_fp32_reduce.py imports quant_matmul at module scope, so the pytest.importorskip("triton") inside _require_triton_gpu() is unreachable. With triton absent the file is collected 0 items / 1 error (ImportError), not skipped. Same pre-existing pattern as test_awq_triton_accum.py, but worth fixing in the new file (move the import, or importorskip at module top).
  • The "arithmetic error" assertions do not test the kernel:
    • test_torch_int8.py: fp32_arithmetic = activation.float() @ codes.float() * channel_scale.float() compares Torch against itself (measured rel ≈ 5e-8, two orders under the 1e-6 limit — always passes).
    • test_triton_fp32_reduce.py: wide = torch.mm(x, dequantize_weight(), out_dtype=float32) is likewise self-referential.
      The comments claim these verify the kernel accumulates in FP32, but they cannot. The assertion that actually constrains the kernel is actual == wide.to(dtype) (atol=0), which is an implementation-equivalence check rather than a numerical-accuracy check, and is brittle across architectures.

Minor

  • "16 passed, 8 skipped" for test_gptq.py::TestKernelOutput: I get 17 passed, 8 skipped here (BitBLAS availability differs), which is harmless but means the number came from a different machine config — worth stating the GPU/SM.
  • "both quant_matmul branches agree bit-for-bit on CUDA" holds. The transpose=True (backward) branch does not stay bitwise identical to main on ROCm (several fp16 diff cases), with unchanged error magnitude and no test coverage. TritonV2Linear.SUPPORTS_TRAINING = True, so either add a bwd dtype/error check or narrow that claim.

Verification run

test_triton_fp32_reduce.py 10 passed (both 4090 and gfx1201); test_torch_int8.py 29 passed; test_inference_numeric_fusion.py + test_inference_numeric_range.py 409 passed / 8 skipped (main: fusion collects 0 + 1 error); test_gptq.py 17 passed / 8 skipped; test_awq_triton_accum.py + the new file 48 passed; ruff check gptqmodel tests clean.

No dense/dequantized weight cache is retained by this change — the FP32 reduction output is the same forward result tensor, freed with the normal output lifetime.

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Follow-up pushed: 5f4b0bbc9

I reproduced every measurement in this review on the same two machines, and all of it held. Fixes below; the numerics conclusion (Torch right, Triton wrong on CUDA) is untouched.

Blocker (b) adopted — the wide path is now CUDA-only

I gated rather than just documenting the cost, because the ROCm half buys nothing:

Claim Reproduction
narrow == wide on gfx1201 400/400 configs bitwise identical (matmul + linear w/ bias, incl. the transpose=True backward branch), plus 96 shape/dtype/bit cases and 150 random matmuls — 0 differing elements
narrow is not worse there 150 matmuls / 90.3M elements vs an FP64 oracle: narrow worse on 0, wide worse on 0
backward was not bitwise-identical on ROCm with the gate, transpose=True is bitwise identical to main — 0/48 cases differ
wide costs latency/memory confirmed +4.1%…+39.5% latency and +144 MiB peak on gfx1201; both are now gone (peak delta 0.0 MiB on every shape)

_numerics.py is shared by Torch/GGUF/AWQ/FP8/VPTQ, so I re-ran those consumers on both backends as you suggested: 77 passed / 7 skipped on CUDA, 72 passed / 12 skipped on ROCm. The gate does not change any current output.

CUDA is unchanged, so the test_gptq.py -k TRITON fix and the bit-for-bit Triton/Torch agreement still hold there.

I did not gate on x.shape[0] > 16. Your M ≤ 16 observation is correct on the shapes you measured, but it is not stable: on 3072x1024 the split reduction also fires at M=2 and M=8 (bf16 M=8: 3515/8192 differing elements) and not at M=64 or M=512. A row-count gate would silently drop the fix on decode shapes, so the commit comment records this.

Test issues — both fixed

  • Unreachable importorskip: confirmed collected 0 items / 1 error. The import is now lazy; a Triton-less run gives 12 skipped.
  • Self-referential "arithmetic error" assertions: you were right that they compared Torch against itself. Both now assert the actual kernel constraint against an independent FP64 oracle — half an output-dtype ulp plus the FP32 accumulation slack, 8·eps32·(|x|@|W|). Evidence it bites: injecting the old narrow matmul fails 8 cases (e.g. M=32: 4091/16384 outputs exceed, max excess 3.8e-4).
  • Backward coverage: added test_quant_matmul_backward_matches_fp64_oracle (3 row counts × 2 dtypes), since TritonV2Linear.SUPPORTS_TRAINING = True and that branch had none.
  • Visible-error check: atol=2e-3 alone rejected a correct kernel — a bf16 half-ulp at magnitude 2 is 7.8e-3. The visible check now allows the mandatory output rounding on top of the 2e-3/2e-3 limit, which is what caught this on ROCm.

On your minor points

  • "17 passed / 8 skipped" — agreed, differs with BitBLAS availability; the message no longer quotes a single count as canonical.
  • The _dequantize storage claim re-verified directly: no dense weight retained (1 MiB layer → only 8 KiB of scales), and dequant() temporaries are collected by the time the forward returns (weakref: 0 alive).

Verification on this head

RTX 4090 / torch 2.15.0+cu132 / triton 3.9.0; gfx1201 / torch 2.16.0.dev+rocm10.1.

  • test_triton_fp32_reduce.py + test_torch_int8.py: 51 passed (CUDA), 39 passed / 12 skipped (ROCm)
  • test_gptq.py, test_inference_numeric_{range,fusion}.py, test_awq_triton_accum.py: 464 passed, 16 skipped
  • test_torch_int8.py on main: 15 failed → 29 passed
  • ruff check gptqmodel tests clean; CI ruff-check green on this commit

One note on the PR itself: the head ref stayed pinned to 679c359e9 after pushing (the branch was already correct upstream), so I re-opened the PR to get GitHub to recompute it. It now points at 5f4b0bbc9; no force-push was involved.

@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 4, 2026 09:52
…cles

Follow-up to ModelCloud#3526 addressing review measurements.

The wide `out_dtype=float32` request is only needed on CUDA, where cuBLAS
starts accumulating fp16/bf16 GEMMs in the operand dtype once it splits the
reduction. HIP already accumulates these operands in FP32, so the request
only adds a cast and a transient FP32 output.

Measured on gfx1201 (Radeon AI PRO R9700, HIP 7.16.26385):
- narrow vs wide bitwise identical across 96 shape/dtype/bit cases and 150
  random matmuls, and 400/400 matmul+linear configs including the
  `transpose=True` backward branch.
- wide cost was +4.1% .. +39.5% latency and up to +144 MiB peak allocation;
  both now gone.

CUDA behaviour is unchanged, so the ModelCloud#3526 numerics fix and its bit-for-bit
Torch agreement still hold there.

Test hardening:
- `test_triton_fp32_reduce.py` imported `quant_matmul` at module scope, so
  `pytest.importorskip("triton")` was unreachable and a Triton-less
  environment got a collection error instead of a skip. The import is now
  lazy; verified `1 error` -> `12 skipped`.
- Replace the self-referential "arithmetic error" assertions, which compared
  Torch against itself, with the real constraint the kernels must satisfy:
  half an output-dtype ulp plus the FP32 accumulation slack, measured against
  an independent FP64 oracle. Injecting the old narrow matmul fails 8 cases.
- Add backward (`transpose=True`) coverage; `TritonV2Linear.SUPPORTS_TRAINING`
  is True and this branch had none.
- Allow mandatory output rounding in the visible-error check: a bf16 half-ulp
  at magnitude 2 is 7.8e-3, which `atol=2e-3` rejected on a correct kernel.

Verification (RTX 4090 / torch 2.15.0+cu132 / triton 3.9.0, and gfx1201 /
torch 2.16.0.dev+rocm10.1):
- `test_triton_fp32_reduce.py` + `test_torch_int8.py`: CUDA 45 passed,
  ROCm 39 passed / 12 skipped.
- `test_gptq.py`, `test_inference_numeric_{range,fusion}.py`,
  `test_awq_triton_accum.py`: 464 passed, 16 skipped.
- Torch/GGUF/AWQ/FP8 consumers of the shared helper: 77 passed / 7 skipped
  (CUDA), 72 passed / 12 skipped (ROCm).
- `test_torch_int8.py` on main: 15 failed -> 29 passed.
- `ruff check gptqmodel tests` clean.

No weight cache is introduced: the dequantized tile is still consumed by the
matmul and released (verified by weakref after forward), and a 1 MiB dense
layer weight is not retained -- only 8 KiB of scales.

Qubitium commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Review of 80438ac54 on RTX 4090 (CUDA) and Radeon AI PRO R9700/gfx1201 (ROCm, GPUs 2/3).

P1 — the ROCm bypass loses the FP32 bias epilogue for non-contiguous batched inputs. linear_fp32_reduce now falls through to F.linear on HIP. For a non-contiguous 3D input, that path can round the matmul to the activation dtype before adding bias. Reproduced on actual gfx1201 hardware: FP16 x = full((2,3,4), 300).transpose(0,1), weight = full((8,4), 100), bias = full((8,), -60000) returns inf; the previous wide helper and independent FP64 oracle both return 60000. FP32 accumulation alone is insufficient if the bias is applied after output rounding. Keep the ROCm optimization but force a fused bias epilogue, e.g. a flattened 2D linear/addmm followed by restoring the batch shape.

P2 — the new backward oracle accepts NaN outputs. test_quant_matmul_backward_matches_fp64_oracle only counts excess > 0; comparisons with NaN are false. Fault injection replacing the kernel output with all NaNs passed both FP16 and BF16 backward checks. Add explicit finite-output assertions. The forward test has the same comparison pattern; on HIP it also calls pytest.skip after performing its checks, so successful HIP oracle checks are reported as skips. Make only the CUDA-specific narrow comparison conditional.

Baseline verification: the existing four numerical suites pass 460 / 8 skipped on CUDA and 381 / 87 skipped on ROCm. These results do not cover the reproduced biased non-contiguous case. The Triton CUDA reduction fix and import repairs otherwise checked out. Fixed and pushed in c6f145b73. Both findings are resolved.

  • HIP low-precision batched linear calls with bias now flatten to a 2D linear operation and restore the batch shape. This preserves the fused addmm bias epilogue without reinstating the FP32 output allocation. CUDA behavior is unchanged.
  • Added FP16/BF16 matrix, batched, transposed, and sliced-input checks against an independent FP64 oracle, plus an actual VPTQ biased-forward regression with repeated calls, weight mutation, weakref lifetime checks, and persistent-storage checks. Before the fix, transposed/sliced FP16 outputs overflowed and BF16 outputs differed by 256; the FP16 VPTQ consumer also overflowed. The corrected targeted outputs match the rounded FP64 oracle exactly.
  • Forward/backward oracles explicitly reject non-finite outputs, with NaN/Inf fault-injection coverage. HIP forward accuracy checks now report passes rather than late skips.

Final validation: test_linear_fp32_reduce, test_triton_fp32_reduce, test_torch_int8, and test_inference_numeric_{range,fusion}: 482 passed / 8 skipped on CUDA, 415 passed / 75 skipped on ROCm. The two targeted files alone pass all 44 tests on each backend. Ruff and whitespace checks pass.

ROCm latency and transient memory: physical GPU 3, gfx1201; non-contiguous batched inputs, resident operands, 10 warmups, median of five 30-call CUDA-event batches with synchronization. Shapes below are original (B,S,K,N) before transposing the first two activation dimensions. Times are microseconds per call; the prior-PR path is the numerically unsafe comparison.

dtype / shape Prior PR F.linear Fixed fused path Previous wide-output path
FP16 / (8,32,1024,512) 19.41 19.51 27.64
BF16 / (8,32,1024,512) 19.82 19.03 27.92
FP16 / (32,128,1024,512) 94.14 60.48 93.98
BF16 / (32,128,1024,512) 104.14 61.18 92.21

Peak allocator increments, including backend workspace, were respectively 80.25 / 80.75 / 81 MiB for the smaller shape and 84 / 92 / 96 MiB for the larger shape (prior PR / fixed / wide). Flattening may require a temporary activation copy, hence +0.5/+8 MiB versus the unsafe path; it still saves 0.25/4 MiB versus wide output. Random-input max error versus raw FP64 was 3.06e-5 (FP16) / 2.36e-4 (BF16); versus dtype-rounded FP64 it was 3.06e-5 / 2.45e-4, within rtol=atol=2e-3.

Storage: the 128→64 VPTQ regression retained the same 1,280 bytes of packed/codebook/bias storage before and after forward, with zero additional retained bytes; its 16,384-byte temporary dense reconstruction was released after each call. No dense or expanded weight cache was introduced.

@Qubitium
Qubitium merged commit f20deb2 into ModelCloud:main Nov 4, 2026
1 check passed
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