Log inStart free
LESSON 6.09 · 6 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

torch.compile: from eager to graph

Watch torch.compile trace a function into a graph and fuse its kernels.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 6.09 · COMPILE BAYEAGER · 4 KERNELS · GPU BUSY 24%
01
Stage 1 of 6 · Eager mode
In eager mode, each line runs at once as its own GPU kernel. The GPU idles 76% of the time, waiting for Python.
Explain it simply

Python reads f one line at a time, like a cook who follows a recipe step by step. Each op starts one kernel, and each red band is a result written to GPU memory and read back. Python spends 8 microseconds on each op, but the tiny kernel takes only 2. So the GPU mostly waits.

Eager run of f: 4 ops, 4 kernels, 320 B moved, 34 µs in total.

tensorsweights, guardsmemory traffic, breakskernels, output
def f(x, w, b): y = x * w y = y + b y = y.relu() return y * 2GPU memory · 320 B moved96 B96 B64 B64 Bxwbmuladdrelumul_1eager · CPUeager · GPUmuladdrelumul_1muladdrelumul_10102030 µseager: one kernel per opthe code of feager: 4 ops × 8 µs of Python · 4 kernels · GPU busy 24%def f(x, w, b): y = x * w y = y + b y = y.relu() return y * 2GPU memory · 320 B moved96 B96 B64 B64 Bxwbmuladdrelumul_1eager · CPUeager · GPUmuladdrelumul_1muladdrelumul_10102030 µseager: one kernel per opthe code of feager: 4 ops × 8 µs of Python · 4 kernels · GPU busy 24%
Toy: f on x with 8 columns · times from a cost model
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
Teager≈∑opsmax⁡(cpy, tkernel)\sy{T}{grad}{T_{\text{eager}}} \approx \sum_{\text{ops}} \max(\sy{c}{param}{c_{\text{py}}},\ \sy{k}{out}{t_{\text{kernel}}})
T=34 μs,cpy=8 μs,tkernel=2.0 μsT = 34\ \mu s,\quad c_{\text{py}} = 8\ \mu s,\quad t_{\text{kernel}} = 2.0\ \mu s

Each op costs its Python time or its kernel time, whichever is longer.

Common mix-ups

MYTHtorch.compile puts every Python line into one graph.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With 2M rows, what limits the eager run: Python or GPU memory?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.