Skip to content

perf(triton): fuse TritonV2 dispatch and pack-load small-M GEMM (#3982) - #3999

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-3982
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-3982

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3982

TL;DR

Two changes, both measured on an RTX 4090 (SM 8.9), cold-L2, FP16/BF16, 4-bit gs=128:

  1. TritonV2Linear.forward now reuses TorchLinear._forward_eager when the existing fused GEMV / small-M GEMM gates allow. Decode and small-batch forward are 1.7x-5.4x faster and no longer allocate the dense K x N weight.
  2. _gptq_gemm_small_m_kernel loads each packed word once and unpacks it in registers, uses one scale/zero row per K-tile for identity g_idx, and optionally splits K deterministically. The Ada gate widens to M <= 64 with no K/N caps; Blackwell gets a launch entry. The fused GEMM is 1.7x-6.8x faster than "best today" across 2048^2 .. 14336x4096.

Split-K off is bitwise identical to the pre-rewrite kernel (torch.equal, bits 2/4/8, gs128, act-order, FP16/BF16, CUDA and ROCm). Split-K on has lower FP32 drift than the single-pass kernel against an FP64 Torch oracle.

Root cause

1. TritonV2 bypassed the fused dispatch

gptqmodel/nn_modules/qlinear/tritonv2.py:149-175 (main) overrode TorchLinear.forward and always called QuantLinearFunction.apply. That path dequantizes the whole K x N weight to the activation dtype and then runs matmul_fp32_reduce; it never reaches _forward_eager, so the _can_use_rocm_gemv / _can_use_rocm_gemm dispatch (torch.py:534, :573) that BACKEND.TORCH uses on Ada/ROCm was skipped. BACKEND.GPTQ_TRITON decode was slower than BACKEND.TORCH on the same GPU.

2. The small-M kernel refetched packed data and gathered per element

gptqmodel/nn_modules/triton_utils/gptq_gemm.py:215-275 (main) loaded qweight with [block_k, block_n] addresses, so every int32 word was fetched 32 / bits times (8x for 4-bit). It also loaded g_idx, scales and qzeros per element even when the group was constant across the K tile. The tile was (16, 16, 256) with no split-K, so the Ada gate had to stop at M <= 16, K <= 2048, N <= 2048 (gptq_gemm.py:144-146, arch.py:70-71); every 7B+ projection above 2048 fell back to writing and re-reading a 33-117 MB dense FP16 weight. Blackwell had no entry.

Fix

  • TritonV2Linear.forward: reshape to 2-D, ask _can_use_rocm_gemv / _can_use_rocm_gemm, then call TorchLinear._forward_eager. Training, autograd, 3-bit, v1 qzeros, non-contiguous input and gate misses keep the existing QuantLinearFunction path.
  • _gptq_gemm_small_m_kernel: one [BLOCK_K / pack_factor, BLOCK_N] word load per K tile, register unpack + tl.reshape to [BLOCK_K, BLOCK_N]; one [BLOCK_N] scale/zero row per K tile when g_idx is the identity and group_size >= BLOCK_K; the g_idx gather is kept for act-order. The tl.dot and FP32 accumulator are unchanged.
  • Deterministic split-K: FP32 [S, M, N] partials, .sum(0), no atomics. S is the largest of {2, 4, 8} with K % (128*S) == 0 and K/S >= 512, capped at 4 for M > 32. Auto-split is enabled only for the retiled CUDA entries; ROCm keeps its measured single-pass launch.
  • M-banded tiles: (BLOCK_M, BLOCK_N) = (16, 32), (32, 64), (64, 64) for M <= 16, <= 32, <= 64. BLOCK_K=128, 4 warps, 2 stages.
  • Ada gate (small_m_max, max_in_features) = (64, 0) (0 = no cap) and no output cap; new blackwell entry with the same kernel. M == 1 stays on gptq_gemv.
  • TorchLinear.post_init caches _gptq_gemm_uniform_group once, so the forward path does no g_idx comparison.
  • Docs: docs/triton-dispatch.md, linked from README.md.

Logic flow

flowchart TD
    A["TritonV2Linear.forward"] --> B{"self.training"}
    B -->|"yes"| C["super().forward<br/>TorchLinear"]
    B -->|"no"| D["x2 = x.reshape(-1, K)"]
    D --> E{"_can_use_rocm_gemv(x2)<br/>or _can_use_rocm_gemm(x2)"}
    E -->|"yes"| F["_apply_rotation_to_input(x2)"]
    F --> G["TorchLinear._forward_eager<br/>gptq_gemv / gptq_gemm"]
    E -->|"no"| H["QuantLinearFunction.apply<br/>dequantize + matmul"]
    G --> I["adapter then out.to(x.dtype)"]
    H --> I
Loading
flowchart LR
    A["qweight words<br/>K/pack_factor x N"] --> B["load once<br/>BLOCK_K/pack_factor x BLOCK_N"]
    B --> C["shift and mask<br/>reshape to BLOCK_K x BLOCK_N"]
    D{"uniform_group and<br/>group_size >= BLOCK_K"} -->|"yes"| E["one scales row<br/>one qzeros row per K-tile"]
    D -->|"no"| F["g_idx gather<br/>per-row scales and zeros"]
    C --> G["weights = (code - zero) * scale<br/>cast to activation dtype"]
    E --> G
    F --> G
    G --> H["tl.dot with FP32 accumulator"]
    H --> I{"split_k > 1"}
    I -->|"yes"| J["FP32 partials S x M x N<br/>then sum over dim 0"]
    I -->|"no"| K["store in the output dtype"]
Loading
flowchart TD
    A["forward gate"] --> B{"architecture has a launch entry"}
    B -->|"no"| X["dequantize + matmul"]:::fallback
    B -->|"yes"| C{"2 <= M <= small_m_max<br/>and dtype in fused set"}
    C -->|"no"| X
    C -->|"yes"| D{"bits in 2/4/8, int32 pack<br/>v2 qzeros, contiguous, no grad"}
    D -->|"no"| X
    D -->|"yes"| E["fused GEMV or small-M GEMM"]

    classDef fallback fill:#ffdddd,stroke:#cc0000,color:#660000
Loading

Accuracy contract

  • Split-K off is bitwise equal to the pre-rewrite gptq_gemm, for FP32 and the visible output, for bits 2/4/8, gs128, act-order on/off, FP16 and BF16. Proven with torch.equal against a frozen copy of the old kernel (tests/kernels/_gptq_gemm_pre_rewrite.py):
    • CUDA: test_ada_split_off_is_bitwise_equal_to_pre_rewrite_kernel (24 cases).
    • ROCm: test_fused_gemm_split_off_is_bitwise_equal_to_pre_rewrite on gfx1201 (24 cases); a gfx1201 probe with the same tile also returned bitwise equality for all 24.
  • Split-K on is no worse than the single-pass kernel against an independent FP64 Torch oracle and inside 1e-3 + 1e-5 * max|ref|. On K=14336, M=16, FP16: single-pass drift 1.08e-3, split-K 1.23e-4; M=64: 1.39e-3 vs 2.81e-4. The test asserts both the bound and split_drift <= single_drift + 1e-6.
  • M == 1 never enters the small-M GEMM; gptq_gemv keeps it.
  • The FP64 oracle decodes the packed words with Torch integer shifts; it never calls the kernel.

Fail-before / pass-after

Base origin/main (105602e2b) with the new tests applied:

$ pytest -q tests/kernels/test_gptq_ada_gemm.py
ERROR tests/kernels/test_gptq_ada_gemm.py
ImportError: cannot import name 'split_k_for' from ...gptq_gemm

$ pytest -q tests/kernels/test_tritonv2_dispatch.py
FAILED test_tritonv2_forward_uses_fused_eager_path
FAILED test_tritonv2_m1_still_uses_gemv
2 failed, 20 passed

Behaviour probe on the same base:

gate_limits sm_89 = (16, 2048)
gate_limits sm_100 = (0, 0)
_can_use_rocm_gemm M=8 -> True
_can_use_rocm_gemm M=32 -> False
_can_use_rocm_gemm M=64 -> False
TritonV2 M=8 _forward_eager calls: []
gptq_gemm(split_k=1): TypeError: gptq_gemm() got an unexpected keyword argument 'split_k'

After (this branch):

gate_limits sm_89 = (64, 0)
gate_limits sm_100 = (64, 0)
_can_use_rocm_gemm M=8 -> True
_can_use_rocm_gemm M=32 -> True
_can_use_rocm_gemm M=64 -> True
TritonV2 M=8 _forward_eager calls: [(8, 2048)]
gptq_gemm(split_k=1): accepted

Validation

CUDA RTX 4090 (GPU-1ece7ec2-...):

$ pytest -q tests/kernels/test_gptq_ada_gemm.py tests/kernels/test_tritonv2_dispatch.py \
    tests/kernels/test_gptq_ada_gemv.py tests/kernels/test_tritonv2_bias_epilogue.py
206 passed
$ pytest -q tests/test_hw_parity_contract.py tests/kernels/test_selection.py
137 passed, 39 skipped
$ pytest -q tests/kernels/test_triton_fp32_reduce.py tests/kernels/test_cuda_bias_epilogue.py
85 passed

ROCm R9700 (HIP_VISIBLE_DEVICES=1):

$ pytest -q tests/kernels/test_gptq_rocm_gemm.py tests/kernels/test_gptq_rocm_gemv.py
101 passed, 92 skipped

The 92 skips are gfx950-only cases; the gfx1201 cases run and the new bitwise test passes. tests/kernels/test_gptq.py cannot be collected on this host because the optional parameterized package is not installed (pre-existing, unrelated).

Lint:

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

Benchmarks

tests/benchmark/benchmark_gptq_triton_small_m.py, RTX 4090, FP16, 4-bit gs=128,
triton.testing.do_bench (L2 flushed before every timed iteration), medians in us.

TritonV2Linear.forward (old QuantLinearFunction path -> new dispatch):

K x N M=1 M=8 M=64
4096 x 4096 78.9 -> 20.5 (3.85x) 53.3 -> 18.4 (2.89x) 63.6 -> 25.8 (2.47x)
4096 x 11008 204.8 -> 45.1 (4.55x) 232.5 -> 39.9 (5.82x) 244.0 -> 64.5 (3.78x)
11008 x 4096 231.2 -> 48.1 (4.80x) 201.1 -> 53.3 (3.78x) 204.1 -> 74.8 (2.73x)
4096 x 14336 267.3 -> 54.3 (4.92x) 321.5 -> 50.6 (6.36x) 323.6 -> 82.7 (3.91x)
14336 x 4096 322.6 -> 59.4 (5.43x) 282.0 -> 54.1 (5.22x) 299.0 -> 68.6 (4.36x)
2048 x 2048 31.0 -> 12.1 (2.57x) 28.7 -> 11.3 (2.55x) 27.5 -> 16.4 (1.68x)

gptq_gemm ("best today" = pre-rewrite kernel inside its old gate, otherwise dequantize + matmul):

K x N M=2 M=8 M=16 M=64
4096 x 4096 63.5 -> 18.1 (3.52x) 57.3 -> 19.5 (2.95x) 72.7 -> 21.5 (3.38x) 68.4 -> 27.3 (2.50x)
4096 x 11008 228.4 -> 37.9 (6.03x) 228.4 -> 39.9 (5.72x) 230.4 -> 42.9 (5.38x) 240.6 -> 63.5 (3.79x)
11008 x 4096 202.1 -> 54.3 (3.72x) 202.8 -> 54.4 (3.72x) 205.8 -> 55.3 (3.72x) 209.9 -> 75.8 (2.77x)
4096 x 14336 317.4 -> 46.9 (6.76x) 317.4 -> 49.2 (6.46x) 318.6 -> 54.3 (5.87x) 319.5 -> 82.6 (3.87x)
14336 x 4096 282.6 -> 50.2 (5.63x) 283.7 -> 52.2 (5.43x) 284.7 -> 53.9 (5.29x) 297.0 -> 68.6 (4.33x)
2048 x 2048 22.5 -> 11.3 (2.00x) 22.5 -> 11.3 (2.00x) 22.5 -> 11.3 (2.00x) 27.7 -> 16.4 (1.69x)

BF16 measured the same 1.4x-6.9x band (for example 4096x14336 M=2: 322.6 -> 47.1 us, 6.85x; M=64: 324.6 -> 78.9 us, 4.12x).

Reviewer notes

  • Blackwell provenance: the blackwell entry ships the same packed-load kernel and gate as Ada. This host has no Blackwell GPU, and the RTX 5090 on it was off-limits, so the entry follows the issue's indicative sm_120 report (1.3x-5.9x). No sm_120 timing was taken here.
  • ROCm: auto_split is off for cdna4/rdna4, so their launch is unchanged except for the packed-load rewrite (which is bitwise equal). The ROCm gfx1201 suite and the new bitwise test pass.
  • Split-K is not used at M=1; gptq_gemv owns that band.
  • scripts/benchmark_ada_kernels.py now passes uniform_group and reports the M-banded tile.

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.

[PERF] GPTQ Triton decode/small-batch: TritonV2 bypasses the fused GEMV (4-5x at M=1); small-M GEMM gate excludes all 7B+ shapes (2.4-5.8x at M=2..64)

1 participant