---
name: triton-kernel-writing
description: Write or review Triton kernels for vLLM, with practical guidance for generated-code inspection, launch grids, indexing, specialization, tuning, and representative performance validation. Use when adding, modifying, optimizing, or reviewing a `@triton.jit` kernel in vLLM.
title: triton-kernel-writing
canonical_url: https://skilld.dev/gh/vllm-project/vllm/triton-kernel-writing
last_updated: 2026-10-21T17:06:59.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [agents/openai.yaml](https://skilld.dev/api/skills-raw/vllm-project/vllm/triton-kernel-writing/agents/openai.yaml).
>
> If the user asked to install this Skill, run `npx skilld install vllm-project/vllm/triton-kernel-writing`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/triton-kernel-writing`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/vllm-project/vllm/triton-kernel-writing) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/triton-kernel-writing`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/triton-kernel-writing --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/triton-kernel-writing --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Triton Kernel Writing

## Implementation

- Follow the official
  [Triton semantics](https://triton-lang.org/main/python-api/triton-semantics.html).
  Check it when behavior may differ from Python or NumPy, especially type
  promotion, integer division and modulo, casts, broadcasting, and variable
  scoping.
- Use the Triton kernel generated by `torch.compile` as a possible
  implementation to inspect. Print Inductor's generated code with
  `TORCH_LOGS="output_code" .venv/bin/python <script>` or enable
  `torch._logging.set_logs(output_code=True)` before the compiled function
  runs. Treat generated code as a reference, not as proof of correctness or
  optimality.
- Find reasonable defaults for compile-time knobs such as `BLOCK_SIZE`, or use
  a small, legible heuristic when workloads need different choices. Use
  `triton.autotune` only when tuning is critical to performance, such as for a
  matrix multiplication. Otherwise prioritize simple code and fast startup.
- Avoid unintended runtime JIT compilation. Put unimportant runtime integer
  scalars in `do_not_specialize`, especially values that alternate between 0
  and 1. Pointer alignment also affects specialization: an offset tensor view
  can trigger a new variant after warmup used an aligned allocation. For
  scalar-only pointers whose alignment provides no useful optimization, use
  `@triton.jit(do_not_specialize_on_alignment=["end_ptr"])`. Retain alignment
  specialization when vectorized accesses benefit from it. See the
  [Triton JIT options](https://triton-lang.org/main/python-api/generated/triton.jit.html).
- The Triton compiler does not guarantee safe ordering when a kernel writes to
  a pointer and subsequently reads from the same pointer. This pattern must
  have a `tl.debug_barrier()` between the write and read. The barrier
  synchronizes threads in the block; it does not synchronize separate program
  instances.

## Launch and Indexing

- `grid[1]` and `grid[2]` must be at most 65,535. Choose or flatten the grid
  order so those dimensions cannot exceed the limit for supported shapes.
  For example, `num_tokens` is commonly 8K or 16K, but users may configure 32K
  or more. If `num_tokens` is a grid dimension, it is safe to put it in
  `grid[0]` (or tile it).
- Use `int64` for offset arithmetic when an index can exceed 32-bit range,
  especially for KV-cache addressing. Cast operands before multiplication or
  addition so an intermediate does not overflow in 32-bit arithmetic.
- A `[num_tokens, num_heads]` grid can be a good low-latency mapping for decode,
  but it can be very slow for prefill. If the kernel serves prefill, consider
  tiling tokens or otherwise increasing the work and locality per program.

## Validation

- Check correctness at boundary shapes and at sizes that exercise masks and
  large offsets. Include offset tensor views, not only fresh allocations.
  Warm aligned buffers, then exercise offset views with vLLM's
  `--jit-monitor-mode error --jit-monitor-verbose` to catch missing variants.
- Choose accumulation and intermediate dtypes explicitly. Test numerically
  difficult inputs, not only random, well-scaled tensors.
- Use `$kernel-microbenchmark` for benchmark construction, measurement, and
  interpretation.
- Benchmark a sweep of `num_tokens` covering decode and representative prefill
  workloads. Include relevant head counts and dimensions when they affect the
  launch shape, and do not select an implementation or tuning heuristic from a
  single setup.
- Include compilation or autotuning overhead when evaluating startup behavior;
  report steady-state kernel performance separately.
