Skip to content
Inference Academy

A Triton matmul: tl.dot, autotuning, grouped ordering and fused epilogues

Write a tensor-core matmul in about 40 lines of Triton, see how block shapes map to the tiling you did in CUDA, use the autotuner to pick block sizes, warps and pipeline depth per shape, reorder programs so tiles stay in L2, fuse an activation into the epilogue, and see why decode-sized matmuls need split-K or GEMV-style kernels.

By

26 min · verified 2026-111 animated diagramPro
Share
Open in ColabRuns on a free T4 GPU: pick Runtime → Change runtime type → T4 GPU.

In the tensor-core lesson you saw how much machinery a fast GEMM needs: block tiles, shared-memory staging, swizzled layouts, async copies, multi-stage pipelines. In Triton, almost all of that is generated from one call, tl.dot. What's left for you is what actually decides performance: the block shape, the order programs run in, and what you fuse.

#The kernel

python
import torch, triton, triton.language as tl

@triton.autotune(
    configs=[
        triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "GROUP_M": 8}, num_stages=3, num_warps=8),
        triton.Config({"BLOCK_M": 128, "BLOCK_N": 64,  "BLOCK_K": 32, "GROUP_M": 8}, num_stages=4, num_warps=4),
        triton.Config({"BLOCK_M": 64,  "BLOCK_N": 128, "BLOCK_K": 32, "GROUP_M": 8}, num_stages=4, num_warps=4),
        triton.Config({"BLOCK_M": 64,  "BLOCK_N": 64,  "BLOCK_K": 32, "GROUP_M": 8}, num_stages=4, num_warps=4),
        triton.Config({"BLOCK_M": 32,  "BLOCK_N": 64,  "BLOCK_K": 32, "GROUP_M": 8}, num_stages=5, num_warps=2),
    ],
    key=["M", "N", "K"],
)
@triton.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K,
                  stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
                  BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
                  GROUP_M: tl.constexpr, ACTIVATION: tl.constexpr):
    # 1. Which output tile is mine? (grouped ordering, explained below)
    pid = tl.program_id(0)
    num_pid_m = tl.cdiv(M, BLOCK_M)
    num_pid_n = tl.cdiv(N, BLOCK_N)
    num_pid_in_group = GROUP_M * num_pid_n
    group_id = pid // num_pid_in_group
    first_pid_m = group_id * GROUP_M
    group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
    pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
    pid_n = (pid % num_pid_in_group) // group_size_m

    # 2. Pointers to the first BLOCK_K slices of A and B for this tile.
    offs_m = (pid_m * BLOCK_M + tl.arange(0, BLOCK_M)) % M
    offs_n = (pid_n * BLOCK_N + tl.arange(0, BLOCK_N)) % N
    offs_k = tl.arange(0, BLOCK_K)
    a_ptrs = a_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
    b_ptrs = b_ptr + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn

    # 3. Walk along K, accumulating in FP32 on tensor cores.
    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for k in range(0, tl.cdiv(K, BLOCK_K)):
        a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * BLOCK_K, other=0.0)
        b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_K, other=0.0)
        acc = tl.dot(a, b, acc)
        a_ptrs += BLOCK_K * stride_ak
        b_ptrs += BLOCK_K * stride_bk

    # 4. Epilogue: optional fused activation, then store.
    if ACTIVATION == "silu":
        acc = acc * tl.sigmoid(acc)
    c = acc.to(tl.float16)
    offs_cm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_cn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    c_ptrs = c_ptr + offs_cm[:, None] * stride_cm + offs_cn[None, :] * stride_cn
    tl.store(c_ptrs, c, mask=(offs_cm[:, None] < M) & (offs_cn[None, :] < N))

def matmul(a, b, activation=""):
    M, K = a.shape
    _, N = b.shape
    c = torch.empty((M, N), device=a.device, dtype=torch.float16)
    grid = lambda meta: (triton.cdiv(M, meta["BLOCK_M"]) * triton.cdiv(N, meta["BLOCK_N"]),)
    matmul_kernel[grid](a, b, c, M, N, K, a.stride(0), a.stride(1), b.stride(0), b.stride(1),
                        c.stride(0), c.stride(1), ACTIVATION=activation)
    return c

This follows the official Triton matmul tutorial closely, and it's worth reading in four parts.

Part 2, pointers. offs_m[:, None] is a column vector and offs_k[None, :] a row vector; adding them broadcasts to a BLOCK_M by BLOCK_K grid of addresses. That's a 2D tile of pointers into AA, built from strides, so the kernel works for any layout (row-major, column-major, or a slice). The % M wraps out-of-range rows back into the matrix, so loads stay in bounds; those rows are computed but never stored.

Part 3, the loop. Each iteration loads one slice of AA and one of BB and calls tl.dot, which the compiler turns into tensor-core instructions for your GPU (mma on Turing and Ampere, wgmma on Hopper), with shared-memory staging and swizzling. The mask handles a KK that isn't a multiple of BLOCK_K. The accumulator is FP32, the standard mixed-precision recipe.

Part 4, the epilogue. The output tile is sitting in registers. Anything elementwise you do here is almost free, because the data never makes an extra trip through memory.

Part 1, the ordering, gets its own section below.

#Test and time it

python
a = torch.randn(4096, 4096, device="cuda", dtype=torch.float16)
b = torch.randn(4096, 4096, device="cuda", dtype=torch.float16)
torch.testing.assert_close(matmul(a, b), a @ b, atol=1e-2, rtol=1e-2)
for name, f in [("triton", lambda: matmul(a, b)), ("cuBLAS", lambda: a @ b)]:
    ms = triton.testing.do_bench(f)
    print(f"{name}: {2 * 4096**3 / (ms / 1e3) / 1e12:.1f} TFLOP/s")

The first call is slow: the autotuner compiles and benchmarks all five configs. Later calls with the same MM, NN, KK reuse the winner. Print matmul_kernel.best_config to see which one won.

A note on T4s: Triton officially targets Ampere and newer (compute capability 8.0 and up), but FP16 tl.dot kernels like this one compile and run on a Turing T4, which is why torch.compile works on Colab. If you hit a compiler error that mentions the architecture, an L4 or A10 (both rentable cheaply) removes the problem. BF16 inputs need Ampere or newer.

Pro content

Keep reading with Inference Academy Pro

Unlock the rest of this lesson, including 1 animated diagram, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.

Still to come in this lesson

  1. Autotuning: what the knobs mean
  2. Grouped ordering: making L2 do the work
  3. Fused epilogues
  4. Decode shapes: when tiles don't fit
  5. What you can now do
  6. Common mistakes
  7. Exercise
  8. Going deeper

You will be able to answer

  • In the Triton matmul, what does one program compute?
  • What does the key=['M', 'N', 'K'] argument to @triton.autotune do?
  • Why does grouped ordering (GROUP_M) make a matmul faster?
  • Applying SiLU to the accumulator before the store saves what, compared with a separate SiLU kernel?
  • At decode batch 1 (M = 1), why is a 128 by 128 tiled matmul a poor fit?

Articles that build on this lesson