Skip to content

M1 · 10 h · full lesson

Compilation and fusion

Most of a diffusion step is not a mysterious kernel. It is a parade of small memory round-trips. Fusion deletes the parade.

Prerequisite
Module 0.
VRAM
8 GB for the synthetic block. 24 GB if you point it at a small video DiT.
Runtime
Tens of minutes for compile-once benchmarks. First compile can be slow.

What you must be able to show

  1. 01

    Name the compile mode you used and which of fusion, autotune, or a CUDA graph you actually got. A flag you set is not evidence the graph replayed.

  2. 02

    Show the activation-byte model: eager traffic over fused traffic is 2 on the norm’s intermediate, and say why that is not a 2× step.

  3. 03

    Either capture the error from replaying a graph at a new sequence length, or state that you did not capture a graph.

Insights

Compilation is not a speed button. torch.compile traces the region, Inductor fuses and picks kernels, and some modes then capture a CUDA graph so the CPU stops launching every op. Each of those can fail independently. Your job is to say which one happened.

  • Eager: one kernel per op. Correct, chatty, often bandwidth-bound on the chatter.
  • Compiled, default: fusion and kernel choice. Shape changes may recompile.
  • reduce-overhead: CUDA graph. Fixed shapes, no host data dependencies, no surprise allocations.
  • max-autotune: search. Worth it when a large GEMM dominates. Quote the steady state, not the search.
Byte model of a fusion — tested, not a GPU time
def eager_activation_bytes(n: int) -> int:
    # RMSNorm writes y, linear reads y. BF16: 2 bytes. n = B * S * D
    return 2 * n * 2

def fused_activation_bytes(n: int) -> int:
    # Intermediate stays on chip. Count only the final store.
    return n * 2

def activation_traffic_ratio(n: int) -> float:
    return eager_activation_bytes(n) / fused_activation_bytes(n)

That ratio is 2× on the activation traffic of the norm, not 2× on the step. The GEMM still reads the weights. On a compute-bound projection the step-level speedup can be 1.0something. NVIDIA's own RTX 5090 kernel row is 1.08× (1045.4 s to 971.6 s) before sparsity and cache. CLAIMED BY SOURCE. If your kernel pass lands near there, you are in a familiar neighbourhood. You have not reproduced their row.

modules/01-compile/compile_step.py — UNTESTED, requires CUDA and torch
class Block(nn.Module):
    def __init__(self, d: int):
        super().__init__()
        self.w = nn.Parameter(torch.empty(d, d))
        nn.init.normal_(self.w, std=0.02)
    def forward(self, x):
        var = x.pow(2).mean(-1, keepdim=True)
        y = x * torch.rsqrt(var + 1e-6)
        return y @ self.w.T

def bench(d=768, s=1024):
    m = Block(d).cuda().bfloat16()
    x = torch.randn(1, s, d, device="cuda", dtype=torch.bfloat16)
    eager = lambda: m(x)
    fused = torch.compile(m, mode="reduce-overhead")
    # time_ms from Module 0. Do not capture until warmup has run.
    return time_ms(eager), time_ms(lambda: fused(x))

Wrong conclusion. ‘Compiled was slower, so compile does not work.’ You timed the compile. Run the warmup, then time the replay. If it is still slower, then you have a result: say whether a graph recaptured because the address changed. Also capture at sequence 1024 and call it at 2048. Record the error. A graph that has never failed has not been tested.

QKV merge. Stack the three weight matrices that share an input, one GEMM, then split. If K and V are narrower (grouped-query), split with the real widths. The win is one read of the activation and one launch. It shrinks when each projection already fills the GPU.

CheckPassStatus in this preview
activation_traffic_ratio(any n>0)Exactly 2.0MEASURED by unit test
Eager vs compiled step timeBoth numbers, same shape, N statedUNTESTED
Norm kernel in the compiled traceGone, or an explanation of the use that kept itUNTESTED
Shape-change behaviour of the graphDocumented failureUNTESTED