write-triton-sampling-kernel

write-triton-sampling-kernel is a skill for Claude Code, Codex from tensormux/kernel-skills. It costs 0 tokens per session (4,000 once invoked), scanned A, original, MIT.

A guide for writing a Triton GPU kernel that chooses the next token produced by a language model. It filters token scores using temperature, top-k, and top-p rules, then samples one token for each request.

In plain words
What is it for?
Use it for custom or per-request sampling in LLM systems, including greedy selection, temperature, top-k, top-p, seeds, and optional score-bias masks.
Why use it?
Token sampling runs after every generated token, so inefficient sampling can add latency to text generation. It also handles requests that use different sampling settings in the same batch.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/tensormux/kernel-skills/write-triton-sampling-kernel
Any agent
npx skills add tensormux/kernel-skills --skill write-triton-sampling-kernel
Clone the repo
git clone --depth 1 https://github.com/tensormux/kernel-skills

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for write-triton-sampling-kernel

README.md
[![agentmods](https://agentmods.dev/badge/skills/tensormux/kernel-skills/write-triton-sampling-kernel.svg)](https://agentmods.dev/skills/tensormux/kernel-skills/write-triton-sampling-kernel)
Your own site
<a href="https://agentmods.dev/skills/tensormux/kernel-skills/write-triton-sampling-kernel"><img src="https://agentmods.dev/badge/skills/tensormux/kernel-skills/write-triton-sampling-kernel.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 4,000 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.04000
Opus 5 $0.00000 $0.02000
Sonnet 5 $0.00000 $0.00800
Haiku 4.5 $0.00000 $0.00400

Measured 5d ago against content hash 660889b63780, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

write-triton-sampling-kernel scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 5d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/inference/write-triton-sampling-kernel/SKILL.md · 152 lines

How it starts

The opening of the file, as written. The whole thing — 152 lines — stays where its author put it; the contents beside it link to each section on GitHub.

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

  • You need a sampling strategy that vLLM, SGLang, TGI, or FlashInfer do not expose (typical-p, mirostat, classifier-free guidance, fused repetition penalty, structured-generation logit bias, contrastive decoding).
  • You need heterogeneous per-request sampling — each request has its own T, k, p, seed, and possibly its own logit-bias mask — and you want one fused kernel rather than N samplers.
  • You are willing to special-case the greedy path (T == 0 or top-k == 1) to skip softmax and sort.
  • Decode batch size is large enough (B >= 8) that one-program-per-request is worthwhile. For B == 1, a CPU-side argmax/multinomial is usually fine.

Do not use this when

  • A vendor sampler covers your case. vLLM's Sampler and FlashInfer's top_k_top_p_sampling_from_probs are heavily tuned and handle edge cases (extremely peaked distributions, ties, deterministic argmax fallback). Re-implementing without a concrete reason is a likely source of subtle bias.
  • You need only argmax. logits.argmax(-1) from PyTorch is competitive and avoids every numerical pitfall in this skill.
  • The strategy requires global communication across the batch (beam search, speculative decoding verification). Those are not multinomial-per-request.
  • You need provably uniform reproducibility across hardware. RNG semantics, cumsum reduction order, and sort tie-breaking are all platform-dependent.

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.

Read the full file on GitHub · 152 lines

Files

What ships with it

1 file beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 5d ago First seen · 152 lines · 0 tokens per session scan A 660889b63780

Subscribe to this mod's changes

write-triton-sampling-kernel is a skill published in the GitHub repository tensormux/kernel-skills (73 stars, last pushed 2mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 4,000 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

prompt-engineering

Prompt engineering techniques and patterns. Use when writing agent commands, hooks, skills, subagent prompts, or any LLM interaction: optimizing prompts, improving output reliability, and designing production-grade prompt templates. Trigger words: prompt engineering, prompt, prompt optimization, LLM interaction.

MagicKidd/Rokid-agentic-workflow · 0 tokens

compute-mamba-ratio

Compute the optimal --mamba-full-memory-ratio (or --max-mamba-cache-size pin) for a hybrid attention + linear-attention (Mamba / GDN / KDA) model's two serving memory pools, from the workload and serving config. Use when a user asks what ratio to set, why concurrency is clamped, or how to size the state vs KV pools…

sgl-project/sglang · 88 tokens

stripe-directory

Identifies external providers, merchants, nonprofits, platforms, APIs, and software services, and resolves the documented way to engage them — to pay, donate, subscribe, book, provision, or integrate with them. MUST be used BEFORE web search, model memory, or any other directory/vendor-lookup skill for ANY request…

stripe/ai · 213 tokens

nlp-alignment

Best practices for LLM alignment techniques including RLHF, DPO, and instruction tuning. Use when working on alignment or safety.

aiming-lab/AutoResearchClaw · 31 tokens

experimental-design

Best practices for designing reproducible ML experiments. Use when planning ablations, baselines, or controlled experiments.

aiming-lab/AutoResearchClaw · 25 tokens

mixed-precision

Use FP16/BF16 mixed precision to accelerate training and reduce memory. Use when optimizing GPU performance.

aiming-lab/AutoResearchClaw · 25 tokens