Write triton gemm kernel

From tensormux/kernel-skills · View interactive version

Write triton gemm kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a correct, performant blocked matrix multiplication kernel in Triton. This covers tile assignment via `program_id`, pointer arithmetic for A/B/C tiles, accumulatio

How to use this skill

Skill file

Skill: Write a Triton GEMM Kernel

Purpose

Guide the agent through implementing a correct, performant blocked matrix multiplication kernel in Triton. This covers tile assignment via program_id, pointer arithmetic for A/B/C tiles, accumulation with tl.dot, boundary masking for non-divisible shapes, swizzled tile ordering for L2 reuse, and autotuning for BLOCK_M/BLOCK_N/BLOCK_K/num_stages/num_warps.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. M, N, K — exact values or the range of values expected at runtime (static vs dynamic shapes).
  2. Input dtype — fp16, bf16, fp32, or mixed (e.g., bf16 inputs, fp32 accumulation).
  3. Layout of A and B — row-major or column-major. If transposed, clarify whether the caller passes the transpose or the kernel should handle it internally.
  4. Output dtype — same as input or upcast.
  5. Epilogue — plain C = A @ B, or is there a scaling factor alpha, bias addition, activation function, or in-place accumulation into an existing C?
  6. Batch dimension — standard 2D matmul, batched (B, M, K) x (B, K, N), or broadcasted batch?
  7. Hardware target — A100, H100, or other. This determines tensor core eligibility and the optimal pipeline depth.
  8. Whether autotuning is allowed — production kernels that ship with a fixed config need to justify that choice; autotuned kernels need a representative benchmark shape.

Required reasoning process

  1. Confirm tensor core eligibility. For fp16/bf16 inputs on A100/H100, tl.dot maps to tensor core instructions when BLOCK_K >= 16 and BLOCK_M, BLOCK_N >= 16. Confirm the dtypes support this path.
  1. Determine tile assignment. Each Triton program handles one (BLOCK_M, BLOCK_N) output tile. Compute the total number of tiles: num_pid_m = ceil(M / BLOCK_M), num_pid_n = ceil(N / BLOCK_N). Assign via:

```

pid = tl.program_id(0)

num_pid_in_group = GROUP_SIZE_M * num_pid_n

group_id = pid // num_pid_in_group

first_pid_m = group_id * GROUP_SIZE_M

group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)

pid_m = first_pid_m + (pid % group_size_m)

pid_n = (pid % num_pid_in_group) // group_size_m

```

This swizzled ordering groups tiles that share rows of A into a cache group, improving L2 reuse for B tiles.

  1. Compute base pointers. For row-major A (shape M x K, stride_am=K, stride_ak=1):

```

offs_am = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)

offs_k = tl.arange(0, BLOCK_K)

a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)

```

Advance similarly for B. Update pointers inside the K loop with a_ptrs += BLOCK_K * stride_ak.

  1. Accumulate in fp32. Initialize acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32). Call acc += tl.dot(a_tile, b_tile). Downcast to output dtype only after the loop ends.
  1. Apply boundary masking. When M, N, or K are not divisible by the tile size:
  1. Apply epilogue. After the K loop, apply alpha scaling, bias, or activation to acc before the store.
  1. Configure autotuning. Define a list of configs over BLOCK_M, BLOCK_N, BLOCK_K, num_stages, num_warps. Key parameters for cache invalidation should include M, N, K so the autotuner re-runs when shapes change.
  1. Validate correctness against a reference. Run torch.mm on cpu or with torch.float64 and compare with torch.allclose(tol=1e-2) for fp16 kernels.

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through all of the following before finalizing the kernel:


Output format

The agent should produce:

  1. The Triton kernel function annotated with @triton.autotune and @triton.jit, with all tile parameters as tl.constexpr, all strides and dimensions as regular arguments.
  2. The Python launcher function that computes the grid, handles contiguity checks (tensor.contiguous()), extracts strides, and calls the kernel.
  3. A brief design note (inline comment block or docstring) explaining: chosen tile sizes and why, accumulation dtype, masking strategy, and epilogue handling.
  4. A correctness test using torch.mm as reference with torch.allclose.
  5. An autotune config list with at least 6 configs covering the likely Pareto frontier for the target shape range.

Common failure modes


Review checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.