Phase 06/Writing your own kernels/Triton GPU programming
PHASE 06 · Writing your own kernels

Triton GPU programming

0%
14 h6 subtopics3 lessons · 2 required
In plain English

Writing CUDA by hand means telling every one of thousands of GPU threads exactly what to do, like choreographing a stadium card show one seat at a time. Triton lets you describe the work in terms of small tiles of data instead ("this block handles these 64 rows"), and a compiler figures out the per-thread choreography, memory layout and scheduling for you. You write Python that looks like NumPy on blocks, and get kernels that often match hand-tuned CUDA. Most new kernels in vLLM and SGLang are written this way, so learning Triton is how you start contributing real kernels quickly.

Why it matters

Triton is the lingua franca for custom kernels in modern inference engines (vLLM, SGLang, Unsloth, torch.compile). Being able to write, autotune and benchmark a Triton kernel turns a profiler finding into a shipped fix.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain Triton's block-level programming model and how it differs from CUDA's thread model.
  • Write vector add, fused softmax and a tiled matmul kernel in Triton.
  • Use tl.load and tl.store with masks, pointer arithmetic and strides correctly.
  • Apply autotuning with triton.autotune and interpret the chosen configs.
  • Benchmark against PyTorch with triton.testing and report achieved bandwidth or TFLOPs.

Key concepts

Program instance
One launch of the kernel body handling one tile; identified by tl.program_id, analogous to a CUDA block.
Block pointer and mask
tl.arange plus base pointer and strides produce a tensor of addresses; masks guard out-of-bounds elements.
tl.dot
Block-level matrix multiply that the compiler maps to tensor cores.
Autotune
Decorator that benchmarks a set of BLOCK sizes and num_warps for a key and caches the best.
num_warps and num_stages
Launch meta-parameters controlling threads per program and software pipelining depth.
Fusion
Doing several elementwise or reduction operations in one kernel pass to avoid round trips to HBM.
Interpreter mode
TRITON_INTERPRET=1 runs kernels on CPU with NumPy for debugging without a GPU.

Subtopics

  1. 1. Programming model and first kernel

    program_id, tl.arange, tl.load/tl.store with masks; write and verify vector add.

  2. 2. Fused softmax

    One program per row, load the row into SRAM, compute max, exp, sum and normalize in one pass; compare bandwidth against torch.softmax.

  3. 3. Tiled matrix multiplication

    2D tiling, K-loop accumulation with tl.dot, grouped ordering for L2 reuse, fp16 inputs with fp32 accumulation.

  4. 4. Autotuning and launch parameters

    triton.Config, autotune keys, num_warps, num_stages; reading the chosen config and understanding why it won.

  5. 5. Benchmarking and correctness

    triton.testing.do_bench, torch.allclose tolerances for fp16, roofline comparison against peak bandwidth and TFLOPs.

  6. 6. Triton kernels inside inference engines

    Read one Triton kernel in vLLM (e.g. a fused MoE or RMSNorm kernel) and identify the same patterns you wrote.

Resources

tutorial
course

Hands-on lessons

L1

Vector add and fused softmax with bandwidth measurement

Colab T4 · freenotebook150 minrequired

Goal · Write two Triton kernels from scratch, verify them against PyTorch, and report achieved GB/s versus the T4's peak of about 320 GB/s.

  1. 1Open a Colab notebook with a T4 runtime; pip install triton if the preinstalled torch does not ship it.
  2. 2Write add_kernel with program_id, tl.arange, masks and tl.load/tl.store; verify with torch.allclose on a non-multiple-of-BLOCK size.
  3. 3Write softmax_kernel with one program per row and the whole row in registers; handle rows longer than BLOCK with masking.
  4. 4Verify against torch.softmax for shapes (1823, 781) and (4096, 4096) in fp16 and fp32.
  5. 5Benchmark both kernels with triton.testing.do_bench for sizes from 2^12 to 2^26 elements; compute GB/s as bytes moved divided by time.
  6. 6Plot GB/s versus size for your kernel and torch; annotate the peak bandwidth line.
  7. 7Run the add kernel once with TRITON_INTERPRET=1 on a CPU runtime to see the interpreter path work.
Deliverable
A notebook with both kernels, correctness asserts and the bandwidth plot.
Check
Softmax reaches at least 60 percent of T4 peak bandwidth for 4096x4096 fp16 and matches torch within atol 1e-2 for fp16.
Fallback
Use a Kaggle T4 notebook, or run with TRITON_INTERPRET=1 on CPU for correctness only and skip the bandwidth numbers.
L2

Autotuned tiled matmul versus cuBLAS

Colab T4 · freenotebook180 minrequired

Goal · Implement a tiled fp16 matmul in Triton with autotuning and report TFLOPs relative to torch.matmul for square sizes 256 to 4096.

  1. 1Implement matmul_kernel with BLOCK_M, BLOCK_N, BLOCK_K constexprs, grouped program ordering and a K-loop using tl.dot with fp32 accumulator.
  2. 2Add masks for M, N, K not divisible by block sizes; verify with torch.allclose against torch.matmul at rtol 1e-2.
  3. 3Wrap with triton.autotune over at least 6 configs varying block sizes, num_warps and num_stages keyed on M, N, K.
  4. 4Benchmark sizes 256, 512, 1024, 2048, 4096 and compute TFLOPs as 2*M*N*K divided by time.
  5. 5Print the winning config per size and explain in a markdown cell why larger tiles win at 4096 but not at 256.
  6. 6Plot TFLOPs for Triton and torch; T4 peak fp16 tensor core is about 65 TFLOPs.
Deliverable
Notebook with the kernel, autotune log, TFLOPs plot and explanation.
Check
Triton reaches at least 70 percent of torch.matmul throughput at 2048 and 4096, and all sizes pass the allclose assert.
Fallback
Use Kaggle T4; if no GPU at all, run the kernel under TRITON_INTERPRET=1 for small sizes to verify correctness only.
L3

Read and modify a Triton kernel in vLLM

CPU · your Macreading-code90 minoptional

Goal · Annotate one production Triton kernel in vLLM and propose a concrete micro-optimization.

  1. 1In your vLLM clone, list files under vllm/ that import triton and pick a kernel of under 200 lines (RMSNorm, rotary embedding or a MoE helper).
  2. 2Annotate every tl.load and tl.store with the shape and stride of the tensor it touches.
  3. 3Identify the tile size and how the grid is computed in the Python launcher.
  4. 4Write a paragraph proposing one change (block size, fusion, masking) and the measurement you would run to validate it.
Deliverable
A markdown file with the annotated kernel and the proposal.
Check
Every memory access in the kernel is annotated and the proposal names a measurable metric and shape range.

Build your own

Build your own Triton kernel suite

TritonColab T4 · free~10 h

Vector add, fused softmax, an autotuned fp16 matmul and a fused MLP block, each verified against PyTorch and benchmarked against T4 peak bandwidth and torch.matmul.

The real thing: github.com/triton-lang/triton/tree/main/python/tutorials ↗

How you know a stage passes

Write tests/test_kernels.py first; it is parametrized over shapes and dtypes and compares each kernel with a PyTorch reference (torch.testing.assert_close with per-dtype tolerances). A bench.py prints GB/s or TFLOP/s per kernel per shape and appends to results.csv. Run `pytest -q` on the Colab T4 for each stage; run with `TRITON_INTERPRET=1 pytest -q -k small` on the Mac for correctness-only. A stage is done when its tests pass and bench.py records the stage's number.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01vector add with masking
    A `tl.program_id` tiled add_kernel handles any length including non-multiples of BLOCK_SIZE through masks, wrapped in a Python function with the torch signature add(x, y).
    test · assert_close against x + y for lengths 1, 1023, 98432 and 2**24 in fp32 and fp16; bench.py reports at least 200 GB/s at 2**24 fp32 on the T4.
  2. 02fused row softmax
    One program per row loads the row once, computes max, exp and sum in registers, and writes the normalized row; BLOCK_SIZE is the next power of two above n_cols.
    test · Matches torch.softmax within atol 1e-2 for fp16 and 1e-5 for fp32 on 4096x4096 and on a 781-column ragged shape; achieved bandwidth is at least 60 percent of 320 GB/s at 4096x4096 fp16.
  3. 03tiled fp16 matmul
    A BLOCK_M x BLOCK_N x BLOCK_K tiled matmul with fp32 accumulators and masked edge loads, correct for any M, N, K.
    test · assert_close(rtol 1e-2, atol 1e-2) against torch.matmul for square sizes 256 to 4096 and for (1000, 777, 333); bench.py reports TFLOP/s for each size.
  4. 04autotuning and grouped ordering
    A triton.autotune config list over block sizes, num_warps and num_stages plus grouped program ordering for L2 reuse; the chosen config is logged per shape.
    test · Autotuned matmul reaches at least 70 percent of torch.matmul throughput at 2048 and 4096 on the T4 and all correctness tests still pass; results.csv shows the winning config per shape.
  5. 05fused MLP block
    One kernel computes y = silu(x @ W1) * (x @ W3) and a second computes (that @ W2) with the residual add fused into its epilogue, matching a SwiGLU MLP from Llama-style models.
    test · assert_close(rtol 2e-2, atol 2e-2) against the eager PyTorch MLP for x of shape (4096, 1024) with hidden 2752; the two fused kernels launch fewer kernels than eager (count with torch.profiler) and are at least 1.2x faster end to end.
  6. 06package and dispatch
    A pip-installable package exposing add, softmax, matmul and swiglu_mlp through torch.library.custom_op with fake implementations, so a torch.compile model uses them without graph breaks.
    test · `pip install .` in a fresh Colab runtime then `pytest -q` passes; torch.library.opcheck passes for all four ops; TORCH_LOGS=graph_breaks shows zero breaks for a compiled two-layer MLP using swiglu_mlp.

No GPU? Use a Kaggle T4 if Colab has no GPU. With no GPU at all, run every test under TRITON_INTERPRET=1 on the Mac for correctness and skip the bandwidth and TFLOP/s targets, recording that in results.csv.

Knowledge check

QWhat is the unit of parallelism you program in Triton, and what is its CUDA analogue?

A program instance handling one tile of data, identified by tl.program_id; it corresponds roughly to a CUDA thread block, with the compiler deciding per-thread work.

QWhy must tl.load be masked?

Block sizes are powers of two and tensors usually are not multiples of them; the mask prevents reading or writing past the end of the array.

QWhat do num_warps and num_stages control?

num_warps sets threads per program (32 each); num_stages sets the depth of software pipelining for loads in loops, trading registers and shared memory for latency hiding.

QWhy does fused softmax beat torch.softmax on bandwidth?

It reads the row once and writes once, while the unfused version makes multiple passes over HBM for max, exp, sum and divide.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • Lessons l1 and l2 deliverables saved with the required performance thresholds met.
  • Can explain the Triton programming model and write a masked load from memory.
  • All subtopics marked completed.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →