Pidoku

Compilers: torch.compile and Beyond

Module 13 Lesson 13.m 1h 15m Difficulty 4/5

Prerequisites 11.i, 11.j, 6.e, 13.j


Before you start: words you need#

WordPlain meaning
GraphThe model’s operations written down as a list of nodes and data dependencies, instead of being run line by line (11.b).
DynamoThe part of torch.compile that watches Python run and records the PyTorch operations into a graph.
InductorThe part that turns the graph into fused kernels — usually Triton (6.e) for elementwise work, library calls for big matmuls.
Graph breakA point where Dynamo cannot keep recording (for example .item()), so the graph splits in two and nothing can be fused across the split.
RecompilationCompiling again because an input changed in a way the compiled code did not allow, such as a new shape.
Symbolic (dynamic) shapeA dimension the compiler treats as “some number n” instead of a fixed value, so one compiled version serves many sizes.
AOT (ahead-of-time)Compiling before deployment, into an artifact that is loaded at start-up — TensorRT engines work this way.

11.i covered graph optimization in theory and 11.j static versus dynamic shapes. This lesson is the practical side: how to use torch.compile for inference, what breaks it, what it is worth, and how vLLM uses it for you.


1. What is it?#

An ML compiler takes a model written as framework operations and produces fused, specialized kernels for one kind of hardware:

INPUT:  a model expressed as framework operations
OUTPUT: fused, specialized, hardware-tuned kernels

  fusion              fewer HBM round trips (11.h, 13.j)
  specialization      constants folded, shapes known
  memory planning     buffer reuse (11.i)
  kernel selection    the best implementation per shape
  layout assignment   fewer transposes
  code generation     Triton (Inductor) or a vendor backend

Facts checked on 12 November 2026 (vLLM v0.32.0).


2. Why does it exist?#

Eager PyTorch runs one kernel per operation, in the order the Python reaches them. That is easy to debug and slow to run: every elementwise op makes a round trip to HBM and pays a launch. Hand-fusing kernels fixes the standard layers (13.j) but not the long tail — a new activation, a new norm, a new MoE router. A compiler finds and fuses those automatically, for any model.


3. Simple analogy#

A translator versus a phrasebook.

Eager mode is reading a phrasebook one sentence at a time: correct, flexible, and slow, with a pause between every sentence. A compiler reads the whole speech first and rewrites it into fluent paragraphs. It is much faster to deliver — but if the speaker keeps changing the speech (new shapes, Python side trips), the translator must start over, and if a page is unreadable (a graph break), the speech is delivered in two halves with a pause in the middle.


4. Tiny example: compiling a model, and the classic break#

Python
model = AutoModelForCausalLM.from_pretrained(...).cuda().eval()

model = torch.compile(model)                           # default
model = torch.compile(model, mode="reduce-overhead")   # + CUDA graphs (13.k)
model = torch.compile(model, mode="max-autotune")      # + kernel autotuning
model = torch.compile(model, dynamic=True)             # symbolic shapes
model = torch.compile(model, fullgraph=True)           # ERROR on a graph break
MODES
  default          balanced fusion, quick compile
  reduce-overhead  + CUDA graphs → good for small batch
  max-autotune     + benchmarks candidate kernels → slowest compile, fastest result

FLAGS
  dynamic=True     symbolic shapes; fewer recompilations, sometimes slower kernels
  fullgraph=True   raise on a graph break instead of silently splitting
                   → USE THIS IN TESTS

The most common break in inference code, and its fix:

Python
# BAD — a graph break AND a GPU→CPU sync every step
if logits.argmax().item() == eos_token_id:
    break

# GOOD — keep it on the GPU; check on the host only every N steps
finished = (next_token == eos_token_id)       # a tensor
if step % 16 == 0 and finished.all().item():   # sync rarely
    break

Graph breaks and hidden syncs usually share one cause: moving data to the host in the hot loop. Fix one and you fix the other.


5. Technical explanation#

Graph breaks#

Shell
TORCH_LOGS="graph_breaks,recompiles" python your_script.py
COMMON CAUSES IN INFERENCE CODE
  .item(), .cpu(), .numpy(), .tolist()
  print(tensor)
  data-dependent control flow:  if x.sum() > 0: ...
  unsupported library or C-extension calls
  Python exceptions inside the traced region
  in-place mutation of module attributes

WHAT A BREAK COSTS
  the graph splits there; fusion cannot cross the boundary.
  A model with 40 breaks gets a fraction of the possible benefit.

Recompilation#

Dynamo specializes on shapes by default. A new shape → recompile.

  batch 1 → compile;  batch 2 → compile;  batch 4 → compile; ...
  after recompile_limit (default 8; the old name cache_size_limit still works):
    "torch._dynamo hit config.recompile_limit (8)"
    → that function runs in EAGER mode from then on

That fallback is silent. Performance degrades and nothing errors.

Python
torch._dynamo.config.recompile_limit = 32      # allow more variants
model = torch.compile(model, dynamic=True)     # symbolic shapes everywhere
torch._dynamo.mark_dynamic(input_ids, 0)       # only the batch dimension is dynamic
FOR LLM INFERENCE
  decode: (batch, 1, d) — only batch varies
    → mark the batch dimension dynamic, or bucket it (as CUDA graph capture does, 13.k)
  prefill: (batch, seq, d) — both vary
    → flatten to (tokens, d), as serving engines do, so one dimension varies

Monitor it in production:

Shell
TORCH_LOGS="recompiles" python serve.py 2>&1 | grep -c "Recompiling"

Compile cost and caching#

COMPILE TIME (a 7B model, rough)
  default mode:      tens of seconds
  reduce-overhead:   longer (adds graph capture)
  max-autotune:      minutes

→ added to your COLD START (20.g)

CACHING
  export TORCHINDUCTOR_CACHE_DIR=/persistent/inductor-cache
  export TRITON_CACHE_DIR=/persistent/triton-cache
  keyed by: graph, shapes, GPU architecture, PyTorch and Triton versions
  → invalidated by any upgrade
  → build it at image build time, or keep it on a persistent volume

The same lesson as TensorRT engines (15.c): never compile on the request path, and never make every pod start from zero.

The compiler landscape#

TORCH.COMPILE / INDUCTOR           [ESTABLISHED]
  ✓ part of PyTorch; works on almost any model
  ✓ generates Triton → runs on NVIDIA and AMD
  ✓ strong elementwise and reduction fusion
  ✗ large GEMMs mostly go to cuBLAS/CUTLASS (autotuned in max-autotune)
  ✗ graph breaks and recompilation are real friction
  → the default choice

TENSORRT / TENSORRT-LLM            [ESTABLISHED]
  ✓ aggressive optimization, measured kernel selection, strong FP8/FP4
  ✗ NVIDIA only; engines are tied to GPU architecture and shape ranges (15.c)
  → stable, high-volume NVIDIA deployments

ONNX RUNTIME                        [ESTABLISHED]
  ✓ cross-platform, many execution providers
  ✗ export lags new architectures; few LLM-specific features
  → small models, CPU, edge (15.d, 15.e)

XLA (JAX / PyTorch-XLA)             [ESTABLISHED]
  ✓ excellent on TPU; whole-graph optimization
  ✗ wants static shapes; different programming model
  → if you are on TPU

TVM / MLIR-based stacks             [EMERGING for LLMs]
  ✓ hardware portability; research vehicle
  ✗ less mature for LLM serving

ENGINE-INTERNAL COMPILATION         [ESTABLISHED]
  vLLM and SGLang run torch.compile internally, plus hand-written kernels
  for attention, MoE and quantized GEMMs
  → you usually get compilation without asking for it (section 6)

6. Under the hood: how vLLM uses torch.compile#

vLLM does not call torch.compile(model) and hope. Its default mode, VLLM_COMPILE, works like this (18.d walks the code):

1. TRACE ONCE   Dynamo records the model's forward pass with the token count as a
                symbolic dimension. Inputs are flattened to (num_tokens, hidden), so
                that is the only dimension that changes.
2. SPLIT        The graph is cut at the attention ops ("splitting_ops"). Attention
                stays a custom kernel; the pieces between are compiled.
3. COMPILE      Inductor compiles each piece once for the symbolic size, and again
                for any sizes listed in compile_sizes (fully static, faster kernels).
4. CUSTOM PASSES vLLM's own pattern-matching passes swap in fused kernels: RMSNorm +
                quant, SiLU-mul + quant, attention + quant, all-reduce + RMSNorm,
                QK-norm + RoPE (13.j).
5. CUDA GRAPHS  Piecewise and full graphs are captured over the compiled pieces (13.k).
6. CACHE        Results go to ~/.cache/vllm/torch_compile_cache, keyed by a hash of
                the model and config. Disable with VLLM_DISABLE_COMPILE_CACHE=1.

All compilation happens at start-up. No request ever triggers a recompile.

The modes, set with --compilation-config '{"mode": ...}':

NONE (0)                 eager PyTorch
STOCK_TORCH_COMPILE (1)  plain torch.compile, no vLLM passes
DYNAMO_TRACE_ONCE (2)    one Dynamo trace, no recompiles
VLLM_COMPILE (3)         the pipeline above — the default

What changed in v0.32.0 (18 October 2026):

  • The torch.compile sequence-parallel and AsyncTP passes were removed, together with the PassConfig.enable_sp, fuse_gemm_comms and sp_min_token_num options. These passes split activations across tensor-parallel ranks and overlapped GEMMs with communication. Model-level sequence parallelism is unaffected. Configs that still set those keys must be cleaned up.
  • Model Runner V2 (the default for dense models since v0.25.0) gained the STOCK_TORCH_COMPILE mode, useful for checking whether a problem comes from vLLM’s custom passes or from torch.compile itself.
  • Fusion passes were made to work again on the newest PyTorch release.

7. Performance implications#

TYPICAL GAINS over eager PyTorch, for LLM inference (rough, model-dependent):

  torch.compile (default)          1.1–1.3×
  torch.compile (reduce-overhead)  1.3–1.6× at small batch
  torch.compile (max-autotune)     1.3–1.8×
  TensorRT-LLM                     2–5× vs eager; vs vLLM or SGLang, usually small

CONTEXT: a production engine already gives several times more than eager
         PyTorch, and MOST of that is continuous batching and paged KV —
         not compilation.

→ compilation is a tens-of-percent lever
→ scheduling is a several-times lever
→ fix them in that order (13.a)

Compilation is worth having, but it is not where the big wins are, and teams that focus on it before fixing batching are optimizing the wrong thing.


8. Production implications#

Numerics#

COMPILATION CHANGES RESULTS IN THE LAST BITS.
  fusion changes the order of operations
  kernel selection changes reduction order
  max-autotune may choose a numerically different algorithm
  → after sampling, a last-bit change can change the generated text (11.k)

VALIDATE after enabling compilation:
  □ logit difference vs eager (max, mean)
  □ top-1 agreement
  □ generation comparison on a fixed prompt set

The same discipline as validating a quantization change.

Operations#

  • Use compilation; in vLLM it is on by default.
  • Cache the artifacts on persistent storage or bake them into the image.
  • Use fullgraph=True in tests to find graph breaks.
  • Monitor recompilation in your own torch.compile code; the silent eager fallback is a real failure mode.
  • Check your vLLM config after upgrading to v0.32.0 for removed PassConfig keys.
  • When a compiled model misbehaves, bisect the modes: VLLM_COMPILE → STOCK_TORCH_COMPILE → NONE, to find which layer introduced the problem.

9. Common mistakes#

  1. Compiling in the request path. Seconds to minutes of stall.
  2. Not caching artifacts. Every cold start recompiles.
  3. Ignoring graph breaks. Silently losing most of the benefit.
  4. Hitting recompile_limit. Silent fallback to eager.
  5. .item() in the decode loop. Graph break and sync.
  6. Not validating numerics.
  7. Expecting compilation to fix a scheduling problem.
  8. Deploying a TensorRT engine built for a different GPU architecture.

10. Hands-on exercise#

A. Measure the gain. For a model you can run, measure throughput and latency in eager, torch.compile default, reduce-overhead and max-autotune. Record compile time for each.

B. Find graph breaks. Run with fullgraph=True and fix the errors one at a time. Measure the improvement after each fix.

C. Trigger the recompilation cliff. Call a compiled function with 12 different shapes. Watch it hit recompile_limit and fall back. Then mark the dimension dynamic and confirm it stops.

D. Measure caching. Time a vLLM cold start with an empty and a warm ~/.cache/vllm/torch_compile_cache. How much does the cache save?

E. Read the generated code. With TORCH_COMPILE_DEBUG=1, find the generated Triton for a fused RMSNorm. Compare it with your hand-written version from 6.e.

F. Bisect the modes. Serve the same model in vLLM with mode 3, 1 and 0. Compare decode latency and the logits on 200 prompts at temperature 0. Where do generations diverge?


11. Interview questions#

  1. What does a compiler do for inference, and which optimizations need graph visibility?
  2. What is a graph break and how do you find them?
  3. What happens when you hit the recompile limit, and why is it dangerous?
  4. Why must you cache compilation artifacts?
  5. How does vLLM avoid recompiling while batch size changes every step?
  6. Why does compilation change numerical results, and what do you do about it?
  7. When would you choose TensorRT-LLM over torch.compile?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in