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.compile can 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

Custom operator registration, stream semantics and autograd contracts
1

Read

In this order, only the parts listed

0 of 2 done

  1. Layer Normalization: backward pass and wrapperTriton Programming Guide and Tutorials

    Backward pass: the dx formula with c1 and c2 constants, two-stage dw and db reduction with Lock, Count and tl.debug_barrier; Benchmark: the LayerNorm autograd.Function with save_for_backward, GROUP_SIZE_M heuristics and test_layer_norm(1151, 8192, torch.float16)

  2. Custom Triton ops in PyTorchAI Systems Performance Engineering - Chapter 14

    Chapter 14, Registering Custom Kernels with PyTorch (torch.library.triton_op with autograd and fake-tensor support) and Debugging Compiler Phases (unknown custom ops force graph breaks)

2

Focus on

  • The backward needs saved x, w, mean and rstd plus the launch config. Missing state cannot be recomputed from dy alone.
  • dw and db reduce 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.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive the LayerNorm vector-Jacobian product: with and , where and . State which means run over the row.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does the backward save mean and rstd instead of recomputing them?Answer

    Recomputation repeats two full passes over x and risks a different rounding. Saved statistics keep forward and backward consistent.

  2. 2.What do the GROUP_SIZE_M buffers change about the dw result?Answer

    Nothing mathematically: they partition the row reduction across buffers that a second kernel sums. Only performance and memory change.

  3. 3.What happens to torch.compile when it meets an unregistered custom CUDA op?Answer

    Dynamo 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. 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.

5

Practice

  • Triton LayerNorm tutorial: forward-backward acceptance

    Run test_layer_norm(1151, 8192, torch.float16) for forward, dx, dw and db agreement, then bench_layer_norm with mode='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.py on 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/ch13 and code/ch14 selectively 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.