Unit 7 of 10 · about 3 hours · implement
Custom operators, stream semantics and autograd contracts
An invisible custom op cuts every framework graph it touches. Registration plus a tested backward keeps the fast path composable.
You'll be able to
- Register a Triton kernel as a PyTorch custom op that
torch.compilecan see through instead of breaking on. - Implement a fused forward plus backward with saved tensors, stream-safe launches and a correct fallback.
- State the autograd contract your op keeps: what it saves, what it differentiates, and what higher-order use it refuses.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Layer Normalization: backward pass and wrapperTriton Programming Guide and Tutorials
Backward pass: the
dxformula withc1andc2constants, two-stagedwanddbreduction withLock,Countandtl.debug_barrier; Benchmark: theLayerNormautograd.Functionwithsave_for_backward,GROUP_SIZE_Mheuristics andtest_layer_norm(1151, 8192, torch.float16) - Custom Triton ops in PyTorchAI Systems Performance Engineering - Chapter 14
Chapter 14, Registering Custom Kernels with PyTorch (
torch.library.triton_opwith autograd and fake-tensor support) and Debugging Compiler Phases (unknown custom ops force graph breaks)
Focus on
- The backward needs saved
x,w,meanandrstdplus the launch config. Missing state cannot be recomputed fromdyalone. dwanddbreduce across rows through grouped buffers with locks. The grouping is an implementation choice, not math.- Registration declares mutation and schema so Dynamo and Inductor can reason about the op. An unregistered op is opaque and breaks the graph.
- Kernel launches must stay on the current CUDA stream with no hidden synchronization, or composition with streams and graphs breaks.
Common mistakes · 3
- Allocating locks wrong. The tutorial uses
torch.zeros(2 * GROUP_SIZE_M, dtype=torch.int32)for locks plus counts; any other shape or dtype breaks the protocol. - Promising double backward. The tutorial backward supports first-order gradients only; state that limit instead of letting a caller discover it.
- Synchronizing inside the op for timing or debugging and shipping it. The hidden sync serializes every stream composition around the op.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does the backward save
meanandrstdinstead of recomputing them?AnswerRecomputation repeats two full passes over
xand risks a different rounding. Saved statistics keep forward and backward consistent.2.What do the
GROUP_SIZE_Mbuffers change about thedwresult?AnswerNothing mathematically: they partition the row reduction across buffers that a second kernel sums. Only performance and memory change.
3.What happens to
torch.compilewhen it meets an unregistered custom CUDA op?AnswerDynamo cannot reason about it, so it emits a graph break and runs that region eagerly, keeping the Python overhead the compile was meant to remove.
4.Which stream must a custom op launch on, and why?Answer
The current stream from
torch.cuda.current_stream. Any other choice breaks event dependencies that callers built around the op.
Practice
- Triton LayerNorm tutorial: forward-backward acceptance
Run
test_layer_norm(1151, 8192, torch.float16)for forward,dx,dwanddbagreement, thenbench_layer_normwithmode='backward'Implement in your own repository. Keep the lock protocol and both reduction stages, and record the higher-order limitation in your tests.
You're done when
Your op passes the tutorial acceptance test, stays on-stream under composition, and explain shows no new break where it runs.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 10 more in the section
- Triton Programming Guide and TutorialsTriton Project · primary
Complete the vector add, fused softmax, matrix multiplication, LayerNorm and fused-attention tutorials that run on your hardware. For each, add adversarial tails, independent references, cold and warm timing, resource inspection and a correct fallback.
- AI Systems Performance Engineering - Chapter 14Chris Fregly · required
Read Chapter 14 on the PyTorch compiler, OpenAI Triton and XLA backends. Trace one framework operation from graph capture through generated GPU code, and identify graph breaks and specialization guards.
Also in this section
- UCSD CSE 291A/DSC 291 (Spring 2026) PA2 Part 1 - Triton matmul, add and ReLUUC San Diego · required
Implement the fused kernel and its configuration search, and test with
student_local_test.pyon your own GPU. The remote grader needs a course token, so replace its speedup score with your own interleaved timing against the PyTorch reference. - TensorTonic Language Modeling from Scratch - Triton problemsTensorTonic · support
Solve Masked Triton GELU Kernel, Tiled Triton Row Sum, Triton Row-Wise Softmax and Fused Tiled Matmul and ReLU, and rerun each with your own adversarial shapes.
- AI Systems Performance Engineering companion code - Chapters 9, 10, 13 and 14Chris Fregly · support
Use
code/ch09,code/ch10,code/ch13andcode/ch14selectively for Triton, warp specialization, persistent kernels and compiler comparisons. Strip local compatibility shims when diagnosing upstream failures and record every guard in the measurement context. - CUTLASS 3.x Design and CuTe Layout AlgebraNVIDIA · required
Study the collective and kernel hierarchy, then the CuTe layout algebra guide. Reconstruct one GEMM configuration down to layouts, copy atoms and MMA atoms and compare it with the equivalent Triton blocked program.
- LeetGPU - CUDA and Triton Parity SetAlphaGPU · required
Re-solve one primitive, one GEMM and one transformer challenge from GPU-4 through GPU-6 in Triton. Compare CUDA, Triton, compiler and library paths on identical tests and hardware; leaderboard rank does not replace local raw evidence.
- GPU MODE - Triton, CuTe and Machine CodeGPU MODE · support
Use Lectures 14, 15, 29, 37, 57, 86, 103, 104 and 114 selectively. Assign one lecture to each actual implementation question rather than watching the collection linearly.
- PTX ISA and CUDA Binary UtilitiesNVIDIA · reference
Inspect generated PTX and SASS for the matched CUDA and Triton kernels. Check instruction, memory-space and target assumptions in the versioned ISA and use binary tools to confirm which device code ships.
- CUDA Tile IR Programming ModelNVIDIA · depth
Read the programming model and inspect the official repository after CUDA, Triton and CuTe mappings are clear. Implement one tiny parity kernel only if the toolchain supports it and record compiler-version constraints.
- Modern GPU Programming for MLSys - TIRxMLC · depth
Use Parts II and III plus the compiler reference as a Blackwell-specific comparison of layouts, dispatch, TMA pipelines and persistent scheduling. Do not make TIRx a required dependency for the portable track.
- MIT 6.S894 Lecture 10 - Domain Languages and AcceleratorsMIT · support
Use the Higher-level kernel languages slides comparing Triton, Pallas, cuTile (Tile IR) and the CuTe DSL on mapping, effort and performance for the programming-model comparison. Do not use the TPU lab.