Write triton softmax kernel

From tensormux/kernel-skills · View interactive version

Write triton softmax kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a numerically stable, performant row-wise softmax kernel in Triton. This covers single-program-per-row assignment, online max+sum reduction with `tl.max`/`tl.sum`,

How to use this skill

Skill file

Skill: Write a Triton Softmax Kernel

Purpose

Guide the agent through implementing a numerically stable, performant row-wise softmax kernel in Triton. This covers single-program-per-row assignment, online max+sum reduction with tl.max/tl.sum, masking for rows wider than BLOCK_SIZE, fp32 accumulation to avoid overflow and precision loss, and the masked softmax variant for attention.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Input shape — (N, D) or (B, H, N, D) or similar. Which dimension is the softmax applied over?
  2. Row dimension size D — is it fixed (compile-time constant), or dynamic? Is it always a power of 2?
  3. Input dtype — fp16, bf16, or fp32. Accumulation dtype must be fp32 regardless.
  4. Whether a mask is applied — additive mask (large negative values added before softmax) or boolean mask (invalid positions should be treated as -inf)?
  5. Whether to fuse a downstream operation — e.g., multiply by a V matrix tile, apply dropout, or write to a specific output layout.
  6. Whether the row fits in one BLOCK_SIZE — or whether a loop over multiple blocks per row is needed.
  7. Hardware target — relevant for choosing BLOCK_SIZE and deciding whether to use triton.autotune.

Required reasoning process

  1. Determine whether the row fits in a single block. If D <= BLOCK_SIZE (and BLOCK_SIZE is a power of 2 >= D), one program handles the full row in a single pass with masking. If D > BLOCK_SIZE, the program must loop over chunks, maintaining a running max and running sum (online softmax).
  1. Assign one program per row. row_idx = tl.program_id(0). For a 2D input of shape (N, D), the grid is (N,). For higher-rank inputs, flatten the batch and head dimensions into the row count.
  1. Compute the row base pointer.

```python

row_start_ptr = input_ptr + row_idx * input_row_stride

col_offsets = tl.arange(0, BLOCK_SIZE)

input_ptrs = row_start_ptr + col_offsets

mask = col_offsets < D

row = tl.load(input_ptrs, mask=mask, other=-float('inf'))

```

Using other=-float('inf') for out-of-bounds positions ensures they do not affect the max reduction.

  1. Compute max for numerical stability. row_max = tl.max(row, axis=0). For the multi-block case, accumulate running max across iterations before computing exp.
  1. Subtract max and exponentiate. row = tl.exp(row - row_max). Perform this in fp32. If inputs are fp16/bf16, cast before the subtraction: row = row.to(tl.float32).
  1. Sum the exponentiated values. row_sum = tl.sum(row, axis=0). Again in fp32.
  1. Normalize. row = row / row_sum.
  1. Store the output.

```python

tl.store(output_ptrs, row.to(output_dtype), mask=mask)

```

  1. For the multi-block (D > BLOCK_SIZE) case, implement online softmax:

This is three passes over the row but requires no inter-program communication. Alternatively, use the single-pass online softmax update: new_max = max(old_max, chunk_max); sum = sum * exp(old_max - new_max) + chunk_sum_relative_to_new_max — reduces to two passes (one forward scan, one normalize).

  1. Apply additive mask (if required). Add the mask to the raw logits before the max reduction, not after. Do not apply a boolean mask by zeroing after exp — this changes the sum and produces incorrect probabilities for masked positions.

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following:


Output format

The agent should produce:

  1. The Triton kernel function with @triton.jit, taking input_ptr, output_ptr, input_row_stride, output_row_stride, D, and BLOCK_SIZE: tl.constexpr as arguments.
  2. The Python launcher that computes the grid as (input.shape[0],) after flattening non-softmax dimensions, extracts strides, and chooses BLOCK_SIZE as the next power of 2 >= D (up to a reasonable maximum like 65536).
  3. Masking strategy documented — single-block vs multi-block, and why.
  4. A correctness test comparing against torch.nn.functional.softmax using torch.allclose(atol=1e-4) for fp16 inputs.
  5. If masked softmax is requested, show mask application in the load step, not as a post-processing step.

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.