Phase 06/Writing your own kernels/Inside ML compilers, MLIR, lowering and codegen
PHASE 06 · Writing your own kernels

Inside ML compilers, MLIR, lowering and codegen

0%
10 h6 subtopics2 lessons · 2 required
In plain English

A compiler is a factory line for translation. Your model starts at one end as a neat description of tensor math, and comes out the other end as raw machine instructions for one specific GPU. Along the way it is rewritten dozens of times, each rewrite making it a little less abstract and a little more tied to the hardware: first multiply these matrices, then tile this loop nest for 128 threads, then use this exact tensor-core instruction. Learning compiler internals is learning to read that conveyor belt, so when a kernel is slow you can find the station where the wrong decision was made, instead of treating the compiler as a black box that either works or does not.

Why it matters

Most of the industry's kernels are now produced by compilers (Triton, XLA, torch.compile, TensorRT) rather than written by hand. Reading the intermediate languages, understanding the passes, and reasoning about the final PTX is what separates "the compiler is slow, nothing to do" from "the layout got materialized one stage too early, and here is the fix". It is also a hiring lane of its own at NVIDIA.

Hiring signal

NVIDIA staffs compiler teams that ask for strong hands-on experience in compiler implementation, program analysis, code generation, optimization, and deep expertise in low-level compiler stacks such as LLVM, MLIR, PTX, Triton; its GPU code-generation role wants experience with MLIR compiler infrastructure, familiarity with intermediate representations, lowering, optimization passes, and GPU code generation.

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

Learning objectives

  • Describe the lowering ladder from graph IR to tile IR to LLVM IR to PTX to SASS, and name what each stage decides.
  • Read Triton's TTIR, TTGIR, LLIR and PTX dumps for a simple kernel and explain what changed at each stage.
  • Explain MLIR dialects and progressive lowering, and why that design lets one compiler target many accelerators.
  • Implement a tiny compiler for a mini tensor DSL: parse, lower to loop nests, tile, emit pseudo-assembly, and differential-test it.
  • Reason about what a compiler did wrong from the emitted PTX and a slow benchmark.

Key concepts

Lowering
Rewriting a program from a higher-level representation to a lower-level one while preserving meaning.
IR (intermediate representation)
The data structure a compiler rewrites; each stage (graph, tile, LLVM, PTX) has its own.
Dialect (MLIR)
A namespace of operations and types for one abstraction level; MLIR lowers through stacks of dialects.
Pass
One rewrite over the IR (canonicalization, tiling, vectorization, allocation, scheduling); pipelines chain hundreds.
TTIR and TTGIR
Triton's IRs, tensor-level ops first, then GPU-threaded layout-aware ops before LLVM conversion.
PTX and SASS
NVIDIA's portable assembly and the final per-architecture machine code; the two levels you can actually read.
Instruction selection and register allocation
Choosing machine instructions for IR ops and assigning values to a finite register file; where performance is won or spilled.
Differential testing
Checking compiler output against a reference implementation on random inputs; the standard correctness gate for generated code.

Subtopics

  1. 1. The lowering ladder

    Graph capture, operator fusion, layout and tiling decisions, LLVM conversion, PTX emission, ptxas to SASS; what is decided at each rung and what is still fixable afterward.

  2. 2. MLIR and dialects

    SSA basics, operations and regions, progressive lowering through dialect stacks, and why torch-MLIR, XLA and CUDA Tile all build on it.

  3. 3. The Triton compiler

    From @triton.jit source through TTIR and TTGIR to LLVM and PTX; layout conversions, shared-memory planning and pipelining passes; reading the dumps.

  4. 4. Code generation essentials

    Instruction selection, scheduling, register allocation and spills; why occupancy drops when a pass chooses badly.

  5. 5. Tile-based models, CUDA Tile and CuTe

    Tile IRs as first-class programs, how CuTe layouts map to TMA and tensor cores, and where tile models sit between Triton and hand-written CUDA.

  6. 6. Verifying compilers

    Differential testing against eager, tolerance policy, reduction ordering, and the bug patterns (miscompiles versus precision noise) that gates must separate.

Resources

Hands-on lessons

L1

Read the IR ladder for one kernel

Colab T4 · freereading-code150 minrequired

Goal · A side-by-side annotated dump of one Triton kernel at the TTIR, TTGIR, LLIR and PTX stages, plus the PTX of an equivalent hand CUDA kernel from nvcc -ptx.

  1. 1On a Colab T4, take a small Triton kernel (vector add or a fused softmax from p6-triton-programming).
  2. 2Dump its intermediate stages with the kernel's asm dict (ttir, ttgir, llir, ptx) and save each to a file.
  3. 3For each stage transition, write two sentences on what the compiler decided (tiling, layout, vector width, shared memory, register mapping).
  4. 4Write the same operation as a tiny CUDA kernel, compile with nvcc -ptx, and diff its PTX against Triton's PTX at the hot loop.
  5. 5Identify one instruction or pattern in the final PTX that explains the measured performance difference (or similarity) between the two versions.
Deliverable
A folder with the four Triton IR dumps, the CUDA PTX, and a one-page annotation of the stage transitions and the final PTX diff.
Check
Each stage transition has a written explanation; the PTX diff names a concrete instruction or pattern (for example ld.global vector width or a fused multiply-add form) tied to the performance note.
Fallback
Use a pre-generated dump pack (export it from any machine with a GPU and Triton) and do the annotation work offline; the reading skill is the lesson.
L2

Write a tiny tensor compiler

CPU · your Macscript180 minrequired

Goal · A Python program that parses a mini tensor DSL (matmul, bias add, relu), lowers it to loop nests, applies fusion and tiling passes, emits pseudo-assembly, and differential-tests the result against NumPy.

  1. 1Define a DSL with three ops, matmul, add, relu, and a parser from text to an AST.
  2. 2Lower the AST to naive triply-nested loop code (as generated Python source) and execute it; differential-test against NumPy on random shapes and seeds.
  3. 3Add a fusion pass that fuses add and relu into the matmul epilogue; re-test and measure the speed change.
  4. 4Add a tiling pass with a tile-size parameter that restructures the loops into blocks; verify correctness and sweep the tile size on a large matrix.
  5. 5Emit a pseudo-assembly listing (per block, per loop, per op) for one tiled fused version and annotate what a real backend would map it to.
  6. 6Write up the pass pipeline and one example where a pass changed numerical results slightly, and why.
Deliverable
mini_compiler.py with the four stages, a test report of differential runs, the tile sweep plot, and the annotated pseudo-assembly listing.
Check
All differential tests pass within fp32 tolerance across 20 random shape and seed cases; the fused tiled version is measurably faster than the naive version on a 1024-cubed matmul; the listing shows the epilogue fused into the inner loop.

Build your own

Build your own mini tensor compiler

PythonCPU · your Mac~5 h

A mini DSL that parses, lowers to loop nests, fuses, tiles, emits pseudo-assembly, and is differentially tested against NumPy.

The real thing: mlir.llvm.org/ ↗

How you know a stage passes

You write tests/compiler.spec.py first. It feeds randomized programs and inputs through your pipeline and asserts numerical agreement with NumPy, checks that the fusion pass removes the separate epilogue loop, and that the tiling pass preserves results for every tile size.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01parse the DSL to an AST
    matmul, add and relu statements parse into an AST with shapes checked.
    test · pytest asserts a three-op program parses with correct shapes, and shape mismatches raise a clear error.
  2. 02lower to loop nests
    the AST lowers to naive loop-nest Python that executes correctly.
    test · pytest differential-tests 20 random programs against NumPy within fp32 tolerance.
  3. 03the fusion pass
    add and relu fuse into the matmul epilogue, removing the separate pass over the output.
    test · pytest asserts the fused source has no standalone epilogue loop and still matches NumPy.
  4. 04the tiling pass
    loops restructure into parameterizable tiles with results unchanged.
    test · pytest sweeps tile sizes (8, 32, 128) and asserts all outputs match the untiled run.
  5. 05pseudo-assembly emission
    a readable per-block per-loop pseudo-assembly listing for the fused tiled pipeline.
    test · pytest asserts the listing contains the epilogue inside the inner loop and names every loop bound.
  6. 06differential fuzzing and the report
    a fuzzer over random programs, shapes and seeds drives the whole pipeline, and a report lists pass counts, failures found and fixed, and timing.
    test · pytest runs 200 fuzz cases with zero mismatches; the report includes at least one bug the fuzzer caught and how the fix was verified.

Knowledge check

QWhat is lowering, and why does a compiler do it in many small steps instead of one big step?

Lowering rewrites a program toward the hardware while preserving meaning; many small steps keep each decision local, testable and reusable across frontends and targets.

QWhat do TTIR and TTGIR represent in the Triton compiler?

TTIR is the tensor-level IR close to the source ops; TTGIR is the GPU-threaded IR after layout and distribution decisions, before conversion to LLVM and PTX.

QWhy is differential testing the standard correctness gate for compilers?

Because a reference implementation already exists; running both on randomized inputs catches miscompiles without writing a specification of every optimization.

QA compiled kernel is slow and the PTX shows local-memory traffic it should not have. What likely went wrong?

Register allocation spilled, too many live values per thread for the target register file, often from an aggressive unroll or layout choice; the fix is to reduce pressure per thread.

QWhy did MLIR's dialect design make it the default substrate for new AI compilers?

Dialects let one infrastructure host many abstraction levels and lower progressively between them, so frontends (PyTorch, JAX) and targets (GPU, TPU, custom ASICs) share passes instead of each building a compiler from scratch.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 deliverables saved and checks pass.
  • Can walk one kernel from source to PTX naming the decision made at each stage.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →