Write triton silu mul kernel

From wenyi-li/awesome-agent-kernel-skills · View interactive version

Write triton silu mul kernel is an AI agent skill from the GitHub repository wenyi-li/awesome-agent-kernel-skills. Guide the agent through implementing a correct, numerically stable Triton kernel that computes `y = silu(a) * b`, the elementwise activation step inside SwiGLU MLPs used by LLaMA, Mistral, Qwen, Gemma

How to use this skill

Skill file

Skill: Write a Triton SiLU-Mul (SwiGLU) Kernel

Purpose

Guide the agent through implementing a correct, numerically stable Triton kernel that computes y = silu(a) * b, the elementwise activation step inside SwiGLU MLPs used by LLaMA, Mistral, Qwen, Gemma, and similar modern LLMs. The full MLP is down_proj( silu(gate_proj(x)) * up_proj(x) ); this skill covers the fused activation that sits between the two GEMMs. It also generalizes to GeGLU (gelu(a) * b) and ReGLU (relu(a) * b), which share the same kernel structure with a different activation.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Activation choice — SiLU (LLaMA, Mistral, Qwen, Gemma), GELU (some PaLM-style models), or ReLU. SiLU is x * sigmoid(x). Confirm which one the model was trained with — using GELU when the model expects SiLU silently produces wrong outputs.
  2. GELU variant (if GELU) — erf-based (0.5 * x * (1 + erf(x/sqrt(2)))) or tanh-approximation. These are not interchangeable. LLaMA does not use GELU at all; Gemma uses GeGLU with the exact erf form.
  3. Input shape — typically (B, T, intermediate_size) or (B*T, intermediate_size). Is the activation dimension the last (contiguous) dimension?
  4. Layout of a and b — separate tensors of identical shape, or interleaved as a single (B, T, 2*intermediate_size) tensor with a = x[..., :intermediate_size] and b = x[..., intermediate_size:]? The interleaved form is common when gate_proj and up_proj are fused into a single GEMM.
  5. Input dtype — fp16, bf16, or fp32. fp16 and bf16 require fp32 sigmoid; fp32 inputs do not.
  6. Output dtype — usually matches input dtype, but the next op (down_proj) may want a specific dtype. Confirm.
  7. In-place vs out-of-place — can y overwrite b? In inference, in-place is common to save memory.
  8. Backward needed — forward-only is the inference case; backward requires saving inputs.
  9. intermediate_size — typical values: 11008 (LLaMA-7B), 14336 (LLaMA-13B), 28672 (LLaMA-70B), 18944 (Qwen2-7B). These are not powers of 2; masking matters.

Required reasoning process

  1. Pick the program decomposition. Treat a and b as flat 1D buffers of length N = prod(shape). One program handles a BLOCK_SIZE-element tile. Grid is (triton.cdiv(N, BLOCK_SIZE),). This is bandwidth-bound; the 1D decomposition is the simplest correct choice.
  1. Compute tile offsets and mask.

```python

pid = tl.program_id(0)

offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)

mask = offsets < N

```

Mask must be applied on every load and the final store.

  1. Load a and b with masking.

```python

a = tl.load(a_ptr + offsets, mask=mask, other=0.0)

b = tl.load(b_ptr + offsets, mask=mask, other=0.0)

```

other=0.0 is safe here because masked positions are not written.

  1. Cast to fp32 for the activation.

```python

a_f32 = a.to(tl.float32)

```

b does not need fp32 for the multiply itself, but cast it if you want to keep the multiply in fp32 before downcasting the result.

  1. Compute SiLU in fp32.

```python

silu_a = a_f32 * tl.sigmoid(a_f32)

```

Equivalently a_f32 / (1.0 + tl.exp(-a_f32)). tl.sigmoid is preferred — it is numerically stable for large negative inputs.

  1. Multiply and downcast.

```python

y = silu_a * b.to(tl.float32)

tl.store(y_ptr + offsets, y.to(a.dtype), mask=mask)

```

Cast the final result back to the storage dtype right before the store.

  1. For GeGLU, replace step 5 with the GELU formula. Use the erf form unless the model card specifies tanh-approximation:

```python

gelu_a = 0.5 * a_f32 * (1.0 + tl.erf(a_f32 * 0.7071067811865475))

```

  1. For the interleaved layout, the kernel takes a single input pointer and computes a and b offsets inside the kernel:

```python

row = offsets // intermediate_size

col = offsets % intermediate_size

a = tl.load(in_ptr + row * (2 * intermediate_size) + col, mask=mask)

b = tl.load(in_ptr + row * (2 * intermediate_size) + intermediate_size + col, mask=mask)

```

This is more arithmetic per element but avoids splitting the tensor.

  1. For backward, compute and save sigmoid(a) (or silu(a)) during forward. The backward kernel reads a, b, and dy, and produces:

```

dx_a = dy * b * silu'(a) where silu'(a) = silu(a) + sigmoid(a) * (1 - silu(a))

dx_b = dy * silu(a)

```

Recomputing silu(a) and sigmoid(a) from saved a is usually cheaper than storing extra activations.


Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following before finalizing:


Output format

The agent should produce:

  1. Activation and layout summary — one short paragraph: which activation (SiLU/GELU-erf/GELU-tanh/ReLU), which layout (split vs interleaved), input/output dtypes, in-place flag.
  2. The Triton kernel with @triton.jit, taking a_ptr, b_ptr, y_ptr, N, and BLOCK_SIZE: tl.constexpr. For the interleaved layout, take in_ptr, y_ptr, intermediate_size, N, BLOCK_SIZE.
  3. A Python launcher that flattens a and b to 1D, computes the grid, validates a.shape == b.shape and dtype, and handles contiguity (call .contiguous() if needed, and document that this allocates).
  4. The variant kernel(s) if GeGLU or ReGLU is also requested — same skeleton, different activation expression, clearly labeled.
  5. A correctness test comparing against torch.nn.functional.silu(a) * b with appropriate tolerances per dtype, on shapes that include non-power-of-2 intermediate_size (e.g., 11008).
  6. A benchmark comparing the kernel against torch.compile(lambda a,b: F.silu(a)*b) and reporting GB/s achieved and percent of theoretical peak HBM bandwidth.
  7. An explicit statement of when the user should NOT ship this kernel: "if torch.compile fusion is within 10%, or if matmul epilogue fusion is available."

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.