Write triton sampling kernel

From tensormux/kernel-skills · View interactive version

Write triton sampling kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a Triton kernel for LLM decode-time token sampling: take a `[batch, vocab]` logits tensor, apply per-request temperature, top-k, and top-p (nucleus) filtering, ren

How to use this skill

Skill file

Skill: Write a Triton Sampling Kernel

Purpose

Guide the agent through implementing a Triton kernel for LLM decode-time token sampling: take a [batch, vocab] logits tensor, apply per-request temperature, top-k, and top-p (nucleus) filtering, renormalize, and draw one token per request. This is the last hot kernel on every decode step — it runs once per generated token, so latency directly translates into tokens/second.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Vocab size V. Typical: 32k (Llama-2), 128k (Llama-3), 256k (Gemma). Determines whether the row fits in one BLOCK or needs multi-block streaming.
  2. Batch size B. Number of concurrent requests in the decode step. Each request maps to one program.
  3. Per-request sampling params. Are T, k, p scalars (uniform) or tensors of shape [B] (heterogeneous)? Heterogeneous is the realistic case in continuous-batching servers.
  4. Logits dtype. Almost always fp16 or bf16 from the LM head. Sampling internally promotes to fp32.
  5. RNG source. Stateful Philox seed/offset (advanced once per decode step) or a precomputed [B] tensor of uniforms. Stateful is more flexible; precomputed is simpler and easier to test.
  6. Greedy fallback policy. Is T == 0 legal? Is top_k == 1 legal? Both must short-circuit to argmax.
  7. Logit bias / mask. Per-request additive bias (e.g., grammar-constrained decoding) is added to logits before temperature scaling.
  8. Maximum top_k. A hard upper bound (e.g., K_MAX = 1024) lets you pick a sort strategy at compile time. Without a bound, you cannot size a fixed on-chip sort buffer.

Required reasoning process

  1. Parallelism axis. Sampling is embarrassingly parallel across the batch. One Triton program per request: req_idx = tl.program_id(0), grid (B,). All work for one request — temperature, softmax, top-k, top-p, multinomial draw — happens inside that program. No inter-program communication.
  1. Vocab tiling. Choose BLOCK_V as a power of 2 (4096 or 8192 typical). For V <= BLOCK_V, the row fits in one block. For V > BLOCK_V (common at V >= 32k), the program loops over ceil(V / BLOCK_V) chunks. Running state (max, sum, top-k buffer) lives in registers across iterations.
  1. Short-circuit greedy. Read T = T_ptr[req_idx] and k = k_ptr[req_idx]. If T == 0.0 or k == 1, run an argmax-only pass: streaming reduction over V tracking (max_logit, max_idx), then store max_idx. Skip softmax, sort, and RNG. Tie-break deterministically by smaller index.
  1. Temperature and logit bias before softmax. Inside each chunk: chunk = (chunk + bias_chunk) / T. Promote to fp32 first — when T is small (e.g., 0.1 multiplies logits by 10), fp16 dynamic range is insufficient.
  1. Numerically stable softmax over V. Same problem as write-triton-softmax-kernel. For V <= BLOCK_V, single-pass online softmax. For V > BLOCK_V, online algorithm: track running_max and running_sum, rescale running_sum by exp(old_max - new_max) whenever the max updates. Accumulate in fp32.
  1. Top-k before top-p. Top-p alone requires sorting all V probabilities — too expensive at V >= 32k. Apply top-k first with a moderate K (50–1024), then top-p on the K survivors. If the user's k is unset, treat it as K_MAX — caps sort cost without changing semantics for typical p.
  1. Top-k as streaming partial sort. Maintain a fixed-size sorted buffer of size K in registers. For each streamed value, if it exceeds the current min of the buffer, replace the min and re-sort. For K <= 256, an in-register sorted array with binary insertion is competitive on Triton. For larger K, prefer radix-select or fall back to FlashInfer — pure Triton tl.sort over the full vocab is too slow at V = 128k. Output: top_probs[K] and top_indices[K], sorted descending.
  1. Top-p on the K survivors. Read p = p_ptr[req_idx]. Cumsum over top_probs (already sorted descending). Find the smallest prefix with cumsum >= p; keep that prefix, zero the rest. Always keep at least one token — if top_probs[0] > p, the top-1 alone forms the nucleus. Missing this guard produces an all-zero distribution.
  1. Renormalize. After top-k and top-p masking, surviving probs no longer sum to 1. Divide by sum(top_probs_after_masking). Skipping this is the single most common sampling-bias bug.
  1. Multinomial draw. Generate u ~ U(0, 1). Walk the sorted, masked, renormalized top_probs accumulating cumsum; pick the first index j with cumsum >= u. Chosen token is top_indices[j]. With Philox: tl.rand(seed, offset + req_idx) or precomputed u_ptr[req_idx]. The offset must advance every decode step — reusing the same offset gives identical samples each step.
  1. Store. tl.store(out_ptr + req_idx, token_id).

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through:


Output format

The agent should produce:

  1. The Triton kernel with @triton.jit, taking: logits_ptr, out_token_ids_ptr, per-request param pointers (T_ptr, k_ptr, p_ptr, optionally seed_ptr, offset), optional logit_bias_ptr, B, V, logits_row_stride, and BLOCK_V: tl.constexpr, K_MAX: tl.constexpr.
  2. The greedy short-circuit path as an explicit branch on T == 0.0 or k == 1.
  3. The sampling path: temperature scale → online softmax → streaming partial top-k → top-p prefix-cumsum mask → renormalize → multinomial draw via cumsum-vs-uniform.
  4. The Python launcher that builds the per-request param tensors, picks BLOCK_V and K_MAX based on V and the user-specified max k, and computes the grid as (B,). Driver code increments the RNG offset between calls.
  5. A correctness test comparing against a reference PyTorch implementation: for fixed seed, the chosen token must match the reference for several (T, k, p) settings. Also test the limit cases: T = 0 matches argmax; k = 1 matches argmax; k = V and p = 1.0 matches plain multinomial sampling from softmax.
  6. A statistical test for the sampling path: with a known logit distribution, draw N >> 1 samples and verify the empirical histogram matches the post-filter probabilities within chi-squared tolerance.
  7. Documented assumptions: max supported K, behavior on T < 0 or p > 1 (reject or clamp), tie-breaking policy.

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.