← Back to Pull requests

Experimental Triton GEMM backend for TE PyTorch (BF16/FP16/FP32/FP8/MXFP8) #667

Closed
unknown closed this pull request without merging on Aug 13, 2026 15:06 UTC
View on GitHub
unknown unknown commented on Jul 09, 2026 19:42 UTC
Author

Summary

Adds a Triton-based GEMM backend for the PyTorch bindings as an alternative to the default hipBLASLt path. Opt-in via NVTE_USE_GEMM_TRITON=1; the C++/hipBLASLt path remains the default and is unchanged when the flag is unset.

The backend is exercised end-to-end through TE's Linear, LayerNormLinear, and general_gemm() entry points, so anything that dispatches through general_gemm transparently picks up the Triton kernels when the flag is on.

Motivation. Give TE a Python-side GEMM path we can iterate on for AMD-specific work — MXFP8, MoE-style grouped shapes, autotune experiments, gfx950 kernel tuning — without going through the hipBLASLt release cadence. Not yet a perf replacement for hipBLASLt; BF16 in particular is slower today.

Precision support

| Format | Status | Kernel |
|---|---|---|
| FP32 | Supported | matmul_kernel |
| FP16 | Supported | matmul_kernel |
| BF16 | Supported | matmul_kernel (perf below hipBLASLt) |
| Regular FP8 (E4M3 × E4M3, E5M2 × E5M2) | Supported | matmul_kernel with INPUT_FP8=True |
| Mixed FP8 (E4M3 × E5M2 — HYBRID recipes' bwd) | Gated on PyTorch 2.14.0.dev20260626+ | Triton compiler bug (triton-lang/triton#9567) |
| MXFP8 (block-scaled, 32 elems/block, E8M0 scales) | Supported (torch ≥ 2.10) | mxfp8_matmul_kernel via tl.dot_scaled() |
| NVFP4 / other QuantizedTensorStorage | Refused with clear ValueError | — |

Epilogues: DEFAULT, BIAS, BGRADB (bias gradient). Fused FP8 output quantization is applied by calling the caller-provided quantizer on the fp32 accumulator output — the kernel's OUTPUT_FP8 path with c_scale + c_amax is present but not wired through the wrapper yet (follow-up perf work).

Architecture

TE Linear.forward
    → transformer_engine.pytorch.cpp_extensions.gemm.general_gemm()
        └─ if NVTE_USE_GEMM_TRITON=1 → te_generic_gemm_triton()      (new)
        └─ else                       → tex.generic_gemm() (hipBLASLt, existing)

te_generic_gemm_triton()  (transformer_engine/pytorch/gemm_triton.py)
    ├── Float8TensorWrapper / MXFP8TensorWrapper — extract data, scales, columnwise copies
    ├── Handle BLAS column-major ↔ Triton row-major (operand swap for MXFP8)
    ├── Dispatch to matmul() or mxfp8_matmul()
    └── If caller passed a quantizer, apply it to the fp32 output → returns Float8Tensor

Key files (matches the triton_kernels/gmm/ subpackage layout):

  • transformer_engine/pytorch/triton_kernels/gemm/

  • - gemm_kernels.py — the two @triton.jit kernels: matmul_kernel, mxfp8_matmul_kernel
    - gemm_wrapper.py — Python wrappers (matmul, mxfp8_matmul) and TE-shaped entry points (te_gemm_triton, te_generic_gemm_triton)
    - gemm_common.py — dtype conversions, shape helpers, Float8TensorWrapper, MXFP8TensorWrapper
    - __init__.py — re-exports the public API
  • transformer_engine/pytorch/quantization.py — recipe-support gate that refuses HYBRID under NVTE_USE_GEMM_TRITON=1 (until torch 2.14)
  • Testing

    Three dedicated Triton GEMM test files under tests/pytorch/triton_kernels/, matching the sibling test layout (test_cast.py, test_cast_mxfp8.py, test_grouped_gemm.py, test_norms.py, ...):

    | File | Purpose |
    |---|---|
    | tests/pytorch/triton_kernels/test_gemm.py | general_gemm() under Triton — equivalence vs. torch.matmul and vs. C++ backend, across regular / FP8 / mixed-FP8 / MXFP8, all layouts, plus a batched-fp8 multidim case |
    | tests/pytorch/triton_kernels/test_gemm_kernel.py | Low-level te_gemm_triton() kernel correctness across dtype × shape × layout × bias × grad (1056 parametrizations of one test_correctness fn) |
    | tests/pytorch/triton_kernels/test_gemm_mxfp8.py | MXFP8 wrapper sanity + one direct-kernel-with-simulated-data case |

    Plus a repo-wide pytest hook (tests/pytorch/conftest.py) that converts the three backend-refusal ValueErrors (HYBRID, mixed FP8, unsupported QuantizedTensorStorage) into pytest.skip. Self-retiring — when the runtime gates are relaxed (e.g. torch ≥ 2.14 lands, NVFP4 kernel gets implemented), the marker text disappears from the error and the hook stops firing without code changes.

    Eight grouped-GEMM equivalence tests in test_numerics.py (comparing a grouped GEMM to a sequence of individual GEMMs at rtol=0, atol=0) get a _skip_grouped_under_gemm_triton marker: under NVTE_USE_GEMM_TRITON=1 the two sides no longer share a backend, so bit-exact equivalence is broken by design. Comment on upstream's assertion literally says # cuBLAS implementation should be bit-wise match.

    CI wiring

    ci/pytorch.sh (invoked from .github/workflows/rocm-ci.yml on push to dev/release_v2._rocm and on workflow_dispatch):

    "triton" label — direct Triton GEMM tests, level 1 (runs at every CI level):

    NVTE_USE_GEMM_TRITON=1 run_default_fa_lbl "triton" 1 triton_kernels/test_gemm.py
    NVTE_USE_GEMM_TRITON=1 run_default_fa_lbl "triton" 1 triton_kernels/test_gemm_kernel.py
    NVTE_USE_GEMM_TRITON=1 NVTE_ROCM_ENABLE_MXFP8=1 run_default_fa_lbl "triton" 1 triton_kernels/test_gemm_mxfp8.py
    

    "gemm-triton" label — TE integration sweep with the Triton backend:

    NVTE_USE_GEMM_TRITON=1 run_default_fa_lbl "gemm-triton" 3 test_numerics.py
    NVTE_USE_GEMM_TRITON=1 run_default_fa_lbl "gemm-triton" 1 test_fusible_ops.py
    NVTE_USE_GEMM_TRITON=1 run_default_fa_lbl "gemm-triton" 1 test_float8_current_scaling_exact.py
    

    Results on gfx950 / PyTorch 2.10

    Direct Triton GEMM suites:

    | Suite | Result |
    |---|---|
    | triton_kernels/test_gemm.py | 212 passed / 72 skipped (mixed-FP8 gated) |
    | triton_kernels/test_gemm_kernel.py | 450 passed / 606 skipped (mixed-FP8 gated) |
    | triton_kernels/test_gemm_mxfp8.py | 4 passed |
    | test_float8_current_scaling_exact.py under Triton | 5 passed / 2 skipped |

    Full test_numerics.py under NVTE_USE_GEMM_TRITON=1: 0 failed / 1058 passed / 2644 skipped / 28 xfailed in ~6 min.

    Known limitations

  • Perf: BF16 performance is below hipBLASLt today; the backend is intended as a correctness-first / experimentation vehicle, not a drop-in perf replacement.

  • Mixed FP8 (HYBRID recipes' backward): blocked on triton-lang/triton#9567. The fix lives only on Triton main; first ships in PyTorch 2.14.0.dev20260626+ nightlies (verified against pytorch/pytorch release-branch Triton pins). Refused with a clear ValueError until torch ≥ 2.14 is detected.

  • NVFP4: not implemented in the Triton kernels. Refused with a clear ValueError; user is directed to unset NVTE_USE_GEMM_TRITON for NVFP4 recipes.

  • Fused FP8 output quantization currently applies the quantizer to the fp32 result outside the kernel; the fused OUTPUT_FP8 path (c_scale + c_amax in-kernel) is present but not yet wired. Follow-up.

  • Grouped GEMM is not routed through this backend; grouped paths (GroupedLinear, test_grouped_gemm, ...) fall through to hipBLASLt / CUTLASS / AITER Triton grouped kernels as before.
  • Notable correctness fixes surfaced during the v2.15 rebase

  • int64 pointer promotion in matmul_kernel and mxfp8_matmul_kernel — fixes SIGABRT under Triton autotune benchmarking when (M-1) stride > 2^31. Concrete repro: test_fp8_current_scaling_linear_large_numel_e4m3[bs33-fp32], M=143616, K=15360 → 2.2G.

  • Bias epilogue wiring through te_generic_gemm_triton (previously the wrapper silently dropped α / β / accumulate).

  • restore_value=['c_ptr'] on the mxfp8 autotuner so ACCUMULATE=True benchmark iterations don't multi-copy the result.

  • Float8TensorWrapper batched-columnwise permutation rewritten to match fp8_transpose's actual output layout (old formula silently scrambled batch dims for ndim ≥ 3).

  • gfx950 NaN-safety in the mxfp8 direct-kernel test: route test data through the architecture-native E4M3 dtype (e4m3fn on gfx950 vs e4m3fnuz on gfx942) so 0x7F/0xFF bytes are not NaN encodings under OCP e4m3fn.

  • ci/pytorch.sh pytest_run bug workaround — "$TEST_DIR/$@" only prefixes the first positional arg, so passing two file paths silently collected 0 items on the second. Split into two calls.
  • Test plan

  • pip install -e . --no-build-isolation builds cleanly on gfx950

  • Four dedicated Triton GEMM test files pass with no regression

  • Full test_numerics.py under NVTE_USE_GEMM_TRITON=1 completes with 0 failures

  • Local ci/pytorch.sh smoke run exercises the new CI wiring end-to-end

  • CI green under Build and Test Branch on push

  • Follow-up: fused OUTPUT_FP8 kernel path wired through te_generic_gemm_triton

  • Follow-up: revisit BF16 perf against hipBLASLt
  • 🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: aris134 Review duration: 50123m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #667"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%