← PyTorch From First Principles

编译:哪个假设不再成立?

把 torch.compile 当运行时契约:区分正确与捕获、稳定、价值,检查图断裂、守卫、缓存变体、动态形状、重编译、冷热代价,找到编译器第一个不再成立的假设。

这里有个推理服务。它载入模型,编译一次,serve 每个请求序列长都变的请求——吃文本的东西的 ordinary 情形。

model = load_model().eval()
compiled = torch.compile(model, dynamic=False)   # "dynamic shapes are slow, force static"

for request in stream:
    with torch.no_grad():
        output = compiled(request.tokens)         # [1, T], T varies per request

十三个请求。每编译输出与 eager 模型最大绝对差 7e-7 一致。什么都不抛。

   req  seqlen     eager (ms)    compiled
      0      60      112.45          11.42 s  <- compiling
      1      63        2.08           8.49 s  <- compiling
      2      69        1.95           8.61 s  <- compiling
      3      16        4.42           5.92 s  <- compiling
      4      19        6.03           8.91 s  <- compiling
      5      75        2.63           8.40 s  <- compiling
      6      19        2.40            2.1 ms   <- reuse (seq length 19 seen at request 4)
      7      55        2.03           8.68 s  <- compiling
      8      25        2.07           8.39 s  <- compiling
      9      35        1.95            7.8 ms
     10      37        5.15            1.6 ms
     11      66        3.08            1.9 ms
     12      52        1.80            5.1 ms

  eager    total:    0.148 s
  compiled total:   68.838 s     (465x)
  output agreement with eager (max |Δ|): 7.15e-07

eager 服务十三个请求 0.15 秒答完。编译服务花 69 秒——慢 465 倍——答案相同。

读 trace。前八个不同序列长各产出一缓存静态特化,8 到 11 秒编译 stall。请求 6 复用已见过的 T=19 特化,毫秒。请求 9 第九个不同长度(T=35)八个缓存守卫全挂,发出 cache-limit 警告,没建第九个特化。剩下没见过的长度毫秒 eager 跑。后面匹配八个现存守卫集之一的请求仍可复用它的编译图。政策变化的唯一解释是没人要看的一行:

torch._dynamo.convert_frame: torch._dynamo hit config.cache_size_limit (8)
   last reason: 0/0: tensor 'L['idx']' size mismatch at index 1. expected 60, actual 35

(这次跑用冷 Inductor 缓存。盘上缓存热的早跑复用,每形状 stall 缩到约一秒,慢速降到 90×——仍比 eager 慢得多,仍每个输出正确。)

每请求都答对了。torch.compile 调了。核生成了。服务现在付全额编译代价,大多数请求收不到任何好处。

产出正确数的编译程序只证明它正确。它没证明捕获了什么、图复用了、workload 变好了。

我们在哪

第 12 章把 torch.compile 当几个优化候选之一。问了一个问题:这个 workload 编译帮忙了吗?——hold-constant 契约下 eager 稳态对编译稳态测得,GEMM-bound 模型上调用大致中性、fusable pointwise 链上大加速,编译结果不对时停住交接。

本章就是交接。第 12 章的方法——测量、定位、干预、再测——编译器本身行为怪异时没问题可问:首调用几秒交代不清、新输入形状停下再编、日志提重编译说不出什么让图失效、forward 里图断裂打碎程序、一后端 work 一后端挂。

第 12 章问:编译帮忙了吗?

第 13 章问:编译器捕获什么,什么假设让图失效,为什么又编?

本章建在的思想:

编译后的 PyTorch 程序还是你的 Python 程序。但运行时须决定其中哪些部分能成图,那些图何时仍 valid。编译是契约。调它就是找到运行时 keep 不住的第一个假设。

契约有结构,每层可检查:

your Python function
      │   what could the tracer capture as a graph?
      ▼
captured graphs, and the graph breaks between them
      │   what did each graph assume in order to specialize?
      ▼
guards  (shape, dtype, device, some Python values)
      │   did those assumptions survive the next call?
      ▼
graph reuse   ·   recompilation   ·   silent fallback to eager

本书每章让一隐藏结构可见。这章让编译器的可见。

边界

  • 第 12 章拥有 benchmark hygiene:预热、同步、测量契约、延迟 vs 吞吐 vs 峰值内存 vs 冷启动代价、profiler、forensic vs 性能模式。本章用那些仪器——编译器实验要 benchmark 就是第 12 章 harness——不重教。第 13 章对代价故事的新贡献窄:重编译把一次性冷代价变成 recurring。
  • 第 14 章拥有跑间可比性、噪声阈值、回归政策。本章说“记录证据”不再多。
  • 第 15 章是 capstone。这里不建 GPT。

五层

第 10 章在四层测注意力正确,因为“正确”是四种意思。编译函数一样:“work”能是五种里任何一种,本章失败按哪层先抓住最好分类。

LEVEL 1  RUNS       compiled code executes without raising
LEVEL 2  CORRECT    output agrees with eager at a stated tolerance
LEVEL 3  CAPTURED   the hot region became one graph, not a chain of breaks
LEVEL 4  STABLE     guards hold in steady state; no recurring recompilation
LEVEL 5  WORTH IT   the workload metric improved, after amortizing compile cost

开篇失败到 Level 2——跑,对——Level 4、Level 5 壮烈挂。错位置 print 的模型到 Level 2、Level 3 挂。每层都容易错当上一层。

环境

本章每数、日志行、跟踪都由跑出的代码产出,一台机器:

Python        3.11.4
PyTorch       2.6.0+cu118        CUDA runtime 11.8
GPU           NVIDIA GeForce RTX 2060, compute capability 7.5, 12 GiB
torch.compile Inductor backend; triton 3.2.0 (triton-windows); MSVC toolchain
config        torch._dynamo.config.cache_size_limit == 8
              torch._dynamo.config.accumulated_cache_size_limit == 256

三环境事实 shape 本章。

核心 Dynamo 机制不是 CUDA-only。 图捕获、守卫、重编译、动态形状特化 CPU、CUDA 都可查。但别变成“行为全一样”:设备本身是被守卫 state 的一部分,后端/核覆盖按设备不同,确切图断裂、编译代价、生成代码随后端 PyTorch 版本变。本章 CUDA 计时因而属于这台机器,诊断方法 transfer 时也一样。

这台机器首调用计时强烈依赖盘上 Inductor 缓存。 之前的编译在盘上留下可复用 artifact,新进程付的比真冷缓存少得多。缓存键不只“结构形状”——生成代码、配置、环境、输入特化都有关。测得的开篇失败,新形状约 8 秒降到盘 artifact 热后约 1 秒,465× 慢速降到约 90×。冷代价重要处实验用 fresh TORCHINDUCTOR_CACHE_DIR 并说清。

实验间调 torch._dynamo.reset() / torch.compiler.reset() 清进程本地编译 state。 防一实验的内存 Dynamo 缓存与编译计数悄悄改变下个。不删 Inductor 文件系统缓存,冷缓存实验要单独缓存目录或显式盘缓存重置。

命名本书跳不过的一点。torch.compiler.* 是公开 API:torch.compile、torch.compiler.reset、torch.compiler.disable、torch.compiler.set_stance、torch.compiler.list_backends。本章诊断价值最好的仪器——torch._dynamo.explain、torch._dynamo.mark_dynamic、torch._dynamo.config——住 torch._dynamo 下,不是稳定公开 surface。值得用,值得知道 internal。

受控 workload

一 workload,每实验复用:[B, T, E] 上小 Transformer——词元与位置嵌入、pre-norm 自注意力加 MLP 块堆、输出投影。

class Block(nn.Module):
    def forward(self, x):
        B, T, E = x.shape
        h = self.ln1(x)
        q, k, v = self.qkv(h).split(self.dim, dim=-1)
        q, k, v = (t.view(B, T, self.heads, E // self.heads).transpose(1, 2) for t in (q, k, v))
        a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        x = x + self.proj(a.transpose(1, 2).reshape(B, T, E))
        return x + self.mlp(self.ln2(x))

选它两属性:干净捕获成一图,坏捕获 obviously 坏;序列长 T 是自然变化轴,重编译实验不用 contrived 形状。

共享仪器在 complab.py:hard_reset()、capture_logs(**categories) 上下文管理器开指定 TORCH_LOGS 类别并捕获输出、explain_summary() 包装、第 12 章计时 helper。

最便宜的二分:先 eager 跑

任何编译器问题前,一测量把搜索空间劈半。

eager_out = model(x)                      # does the ordinary program work?
compiled = torch.compile(model)
torch.testing.assert_close(eager_out, compiled(x), rtol=1e-4, atol=1e-4)
HEALTHY MODEL
  eager forward: ok, output (8, 64, 512)
  assert_close(eager, compiled, rtol=1e-4, atol=1e-4): PASS
  max |Δ| eager vs compiled: 1.43e-06

tolerance deliberate 并说清。这个实验 Inductor 生成代码与 eager 差 1.4e-6,不同浮点求值 schedule 一致。健康编译有的 workload 逐比特相同,有的数值接近。用算子 tolerance 的 assert_close;exact 相等真是契约才要求逐比特相等。

现在有普通 bug 的模型——固定序列长的 reshape:

def forward(self, x):        # x: [B, T, 256]
    return self.lin(x).reshape(x.shape[0], 64, x.shape[2])   # only valid when T == 64
  eager, T=48:    RuntimeError: shape '[8, 64, 256]' is invalid for input of size 98304
  compiled, T=48: TorchRuntimeError: Failed running call_method reshape(*(FakeTensor(..., size=(8, 48, 256)), 8, 64, 256), **{})

同样根因,一个包着编译器 framing。只跑编译版,“torch.compile 坏了”正是错结论。

eager 挂 → 普通模型问题,编译器是 distraction。eager work、编译挂 → 编译器路径问题,搜索值了。

之后全 assumed eager 程序正确。

捕获了什么:图断裂

torch.compile 把函数跟踪成张量算子图。走到放不进图的 Python——数据依赖分支、调不支持库、张量里拔值——它断裂:编好到此的图,回 Python 解释器跑不支持的部分,之后恢复跟踪。

受控模型干净捕获。torch._dynamo.explain 报告发生什么:

torch._dynamo.explain(model, tokens):
  graph_count        1
  graph_break_count  0
  break_reasons      []

一图,零断裂——嵌入到输出投影的整个前向成编译器可跨优化的一区。这是 Level 3 过,下面每失败的基线。

现在典范断裂——张量数据上的分支:

def with_break(x):
    y = torch.sin(x) @ x
    if x.sum().item() > 0:          # tensor -> Python float -> control flow
        y = y * 2
    return torch.cos(y)

三仪器看见它。按此顺序拿。

torch._dynamo.explain——结构化交代,不解析日志:

torch._dynamo.explain(with_break):
  graph_count        2
  graph_break_count  1
  break_reasons      ['Tensor.item']

TORCH_LOGS=graph_breaks(或 capture_logs(graph_breaks=True))——编译器原话的确切位置与原因:

torch._dynamo.symbolic_convert.__graph_breaks: Graph break in user code at e3_graph_breaks.py:24
Reason: Unsupported: Tensor.item
  if x.sum().item() > 0:              # tensor -> Python value -> control flow

fullgraph=True——静默断裂变成抛出的异常, hunting 时要的就是它:

torch.compile(with_break, fullgraph=True)(x)
  -> Unsupported: Tensor.item

fullgraph=True 当诊断有用因为它把图断裂变成错,要求该区一捕获图。单图捕获是要求时生产或库测试的合法约束。它不是通用性能修复:普通 fullgraph=False 代码故意断裂也能正确快速。

图断裂不是正确性失败

坏函数与没坏版算同样意图结果。图断裂建 Dynamo 回 Python、不跨两编译区优化的边界。代价取决于边界发生什么。这个例子 .item() 还把张量值拔进 Python,能同步 CUDA work 与主机;别的图断裂不一定有同样同步代价。

测它。编译坏函数与分支改写成图内(torch.where)的编译版、eager 比:

eager (with break)          median 0.184 ms
compiled, with break        median 0.323 ms
compiled, no break          median 0.184 ms

这个小 workload 上编译没坏版与 eager 持平——编译本来中性。但编译坏版比两者慢 75%。断裂不只去掉好处;断裂恢复的机器让它比不编还差。

这个数不通用——别的跑 gap 40–50%——方向稳定,教训稳定:断裂的代价是测量,不是假设。有时是零。那也是发现。

断裂位置比断裂数重要

两模型,受控 Transformer,各一数据依赖分支。一在 block 堆前;一在两 block 间。

TORCH_LOGS=graph_breaks 确认两都恰一断裂:

  no break               breaks=0
  break before blocks    breaks=1   at forward line 26
  break mid-stack        breaks=1   at forward line 40

稳态代价不同:

  no break              1.867 ms    1.00x the no-break graph    0.60x eager
  break before blocks   1.856 ms    0.99x the no-break graph    0.59x eager
  break mid-stack       2.359 ms    1.26x the no-break graph    0.76x eager

堆前断裂这个 benchmark 无 resolved 代价:1.856 ms 对没断裂图 1.867 ms,差小到不叫。贵的 block 堆还在后面捕获成一图。中间断裂把堆切成两图,每次前向中途回解释器——这里慢 26%,编译加速大半被吃。

同样数,相反代价。“最小化图断裂数”是错目标。

问断裂在哪、那代码路径多久跑一次、测得代价多少。setup 里的断裂与 hot loop 里的断裂是不同发现。

仪器分歧,一个对

中间断裂,torch._dynamo.explain 报告:

  break mid-stack        graphs=1  breaks=0

零断裂——而 TORCH_LOGS=graph_breaks 在期待源码行记了断裂,fullgraph=True 拒绝同样构造。这个 PyTorch 2.6 实验里 torch._dynamo.explain 因而 undercount。别把任一诊断 promote 成通用“ground truth”:explain 要结构化 summary,图断裂日志要 tracer 发出的位置/原因,fullgraph=True 测这次调用能不能一图捕获。独立仪器 agree 比指定一权威强。

别凭记忆或单仪器报告某构造“导致图断裂”。tracer 覆盖版本间变;给证据,说版本。

假设:守卫与重编译

编译器特化图时,记下依赖的输入事实——守卫(guards)。守卫是便宜运行时检查:这张量二维、这个尺寸、这个 dtype、在这个设备;这个 Python 值还是 4。复用编译图前 runtime 查守卫。挂了,图对这些输入 invalid,PyTorch 编另一个。

dynamic=False——开篇“强制静态更快”设置——每维形状成守卫。编译模型按序列长调用序列跑,捕获 TORCH_LOGS=recompiles:

call sequence T = [32, 32, 32, 48, 48, 32, 64, 48, 80, 96, 112]

  call  T     wall (s)   note
     0   32      8.393   compile (new shape)
     1   32      0.001   reuse
     2   32      0.001   reuse
     3   48      6.135   compile (new shape)
     4   48      0.001   reuse
     5   32      0.001   reuse       <- guard still holds, graph 0 reused
     6   64      6.359   compile (new shape)
     ...
  distinct shapes seen: 6   recompiles logged: 5

新长度编新图(6–8 s);重复毫秒复用。重编译日志精确说哪个假设挂了:

Recompiling function forward in complab.py:211
    triggered by the following guard failure(s):
    - 0/0: tensor 'L['idx']' size mismatch at index 1. expected 32, actual 64
    - 0/1: tensor 'L['idx']' size mismatch at index 1. expected 48, actual 64

两行仔细读。T=64 调用时重编译日志 show runtime 先拒绝 T=32、T=48 缓存特化,再建 T=64 的。缓存条目 guard-check 到 valid 特化找到或需要编译。守卫查找有代价,但这个实验没 isolate 它:开篇编译 stall 没单调变慢,秒级代码生成 dwarf 守卫求值。日志证明哪些假设挂了;没证明守卫扫描导致编译时间曲线。

守卫不只关于形状

同样编译函数喂 int32 词元而不是 int64:

Recompiling function forward in complab.py:211
    triggered by the following guard failure(s):
    - 0/0: tensor 'L['idx']' dtype mismatch. expected Long, actual Int

dtype 守卫。设备同样守卫,图 close over 的某些 Python 值也守卫——配置 flag、到达 .view() 的整数。守卫失败文本不是形状的重编译是不同调查、不同修复。

过 limit:静默 fallback

torch._dynamo.config.cache_size_limit 这个 PyTorch 2.6 环境里 8。这个代码对象八缓存特化后,另一输入要编译,Dynamo 不建新变体,没匹配的调用 eager 跑。已编变体仍缓存,守卫过仍可复用。 开篇请求 9(T=35)是八变体后第一没匹配调用;重编译尝试 hit limit 而不是产出第九个图:

torch._dynamo hit config.cache_size_limit (8)

这个失败容易漏,因为正确性活着而执行成混合政策。匹配八缓存守卫集之一的输入仍可用编译代码;新没匹配输入 eager 跑因为不再建新变体。服务已付八次编译,形状多样的请求流大半收不到编译稳态好处。

让它响

torch.compiler.set_stance 把“稳态重编吗”从读日志练习变成断言。包住相信稳定的区:

compiled(warmup_batch)                                  # compile once

with torch.compiler.set_stance("fail_on_recompile"):
    for batch in steady_state_loader:
        compiled(batch)
  same shape (T=32): reused, no error
  new shape (T=48): RuntimeError: Detected recompile when torch.compile stance is 'fail_on_recompile'

抛了,以为稳定的守卫在挂。别的 stance 也诊断用:"force_eager" 忽略进程里每个 torch.compile(不改调用处二分编译器 bug 对 eager),"eager_on_recompile" 重编时 eager 跑不付重编钱。

recurring 的代价

第 12 章确立编译代价不是一数。这个章的模型上测得:冷 Inductor 缓存首编译调用约 13 s;复用缓存的新进程约 3.4 s。第 13 章的增量是重编译对它做什么。

一次性冷代价可摊销。重编译不同:缓存守卫集没接受输入、limit 还允许另一特化,新编译代价再付。单守卫失败不蕴含编译——后面缓存特化可能 match——limit-hit fallback 本身不付完整代码生成代价。开篇服务付了八静态特化,T=19 的复用一次,第九个不同形状 hit limit 毫秒 eager 跑。

冷编译是 deposit。重编译循环是 subscription。

动态形状:对 proved variation 的回应

开篇失败有 obvious 的修复:别在形状上特化。但“加 dynamic=True”是 flag reach,本书不做 flag reach。同样形状变化 workload 四选项全测——13 调用、10 不同序列长:


结果和“动态更好”的预测不一样。

`dynamic=False` 是开篇失败:建八静态特化,第九次编译尝试 hit 缓存 limit,sweep `30.4` 秒里约 `30` 秒花在编译重的 prefix。那个列叫“九次编译”会 overcount 被拒绝的特化。

`dynamic=None`——默认——这个 PyTorch 2.6 实验里产出两次编译尝试:初始特化,形状变化出现后一次重编译。之后 workload 不再发重编译日志,缓存编译代码跨测得长度复用;稳态(`1.322` ms)四里最快。这与默认在重编译后检测动态的政策一致。**不是**每形状变化程序恰一次重编译后 generalize 的保证:算子与守卫仍能强制特化。重要的发现更窄——默认处理了这个 workload 的序列长变化,强制 `dynamic=False` 拦住了它。

`dynamic=True` 跳过特化 pass——编译一次,稳态比让它先特化略慢。

`mark_dynamic(x, 1)`——只标序列维动态——编译一次,sweep 秒数最少,但稳态(`1.918` ms)没比 eager `1.776` ms 好。这个模型上这个精确干预没付钱。

这个 workload 编译稳态四动态政策小范围(eager `1.8` 对 `1.3`–`2.0` ms),编译代价差巨大。defensible verdict 因而 specific:**`dynamic=False` 对这个测得的形状分布造了重编译失败,默认无手工帮忙处理了 variation。** 这是关于这个 workload 的证据,不是默认解决每动态形状程序的规则。

工作流,重编译*真*有时:

```text
prove the recompilation is caused by shape variation   (recompile log: "size mismatch")
        ↓
try the default first; it may already generalize
        ↓
if not, mark exactly the varying dimension dynamic
        ↓
measure compile count AND steady-state time
        ↓
keep it only if the real workload improved

静态还是动态是关于数据的问题

生产永远一形状,全特化图 ideal,动态灵活性白买。生产收几十序列长,特化就是开篇失败。编译器问题从来不是“动态形状更好吗”。而是实际程序看到什么形状分布?——真请求流的测量,不是猜。

观察者效应

编译函数干净捕获成一图。想看中间值,加个 print:

if i == D // 2:
    print("  [debug] mid mean:", float(x.mean()))
  graph breaks (TORCH_LOGS=graph_breaks):
    clean (debug=False)      breaks = 0
    same class, debug=True   breaks = 1      (Unsupported: Tensor.item, at the print)

  steady-state compiled forward:
    clean / debug=False          0.164 ms    1.00x clean    0.09x eager
    debug=True (print inside)     1.987 ms   12.12x clean    1.06x eager

干净函数比 eager 快 11×——fusable 链,正是编译最擅长的 workload。print——经 float(x.mean()) 把 Python 数拔出张量——在那行断图,整个加速擦掉。带 print 的编译函数比不带的慢 12×,与 eager 持平。

两是同样类。只 Python flag 不同。debug=True 是与生产跑不同的图,试图观察的东西不是跑的东西。

修复按 prefer 顺序:

中间件返回,编译区外检查。

def forward(self, x):
    ...
        return x, mid          # stays capturable; extra outputs can still affect liveness/memory
  inspecting the RETURNED intermediate outside the graph: mid mean 1.6448  (0 breaks, clean-graph speed)

diagnostic 门控 flag,测的配置里 False——Dynamo 在该 Python 值上特化,死分支 fold 出该特化。flag 本身是被守卫程序 state 的变化,可能触发不同特化;benchmark 与 ship 同一 flag 值。

诊断 helper 标 @torch.compiler.disable,tracer 不试图捕获它——注意调用处仍断图,去掉的是“编译器被 print 噎住”问题,不是代价。setup 时诊断用,hot-path 不用。

这是第 12 章 forensic vs 性能模式的区别,下一层。那里开着的 profiler 改测的数。这里编译区里的调试 print 改编的图。

仪器是系统的一部分。测 ship 的版本,诊断挡在编译区外。

缩小编译区

不必编译整个训练步。只编模型前向与编整个步——zero_grad、前向、损失、backward、optimizer.step——对比:

  config                  graph breaks   steady ms   first call
  eager                              -       6.235        -
  compile(forward)                   0       5.353       4.4 s
  compile(whole step)                4       4.632       3.9 s

这个跑整步编译比只编前向快约 13%(4.632 vs 5.353 ms),同时产出四图断裂。单测量确立重要的一点:断裂少不蕴含步时间最低。它不确立宽 wrapper 因“捕获反向”或 fuse 某优化器算子赢——训练模型编译已涉及 AOTAutograd 反向机器,实验没 profile 额外加速的来源。宽 wrapper 确实改变的是 Dynamo 推理的区:损失、优化器调用、更多 Python 编排进编译函数了。

缩小区因而是调试干预,不是通用速度规则。它常让编译器行为好检查,因为边界里 Python 机制少,但性能决定仍归测得的 workload。

后端二分

torch.compile 是栈。TorchDynamo 观测 Python 执行,把可编译张量区捕获成 FX 图。"aot_eager" 路加 AOTAutograd 变换如 functionalization,需要 autograd 时提前处理/划分前向反向算子。默认 Inductor 后端把编译图 lower 成生成核或优化库调用——Triton 是重要 GPU 代码生成路,CPU lowering 常发 C++/OpenMP 代码。失败或数值变化进的层不同,backend= 参数给有用的 ablation:

torch.compile(model, backend="eager")       # TorchDynamo capture only, then run eagerly
torch.compile(model, backend="aot_eager")   # + AOTAutograd, then run eagerly
torch.compile(model)                         # + TorchInductor (the default)
  backend        first call (s)         loss   max|Δ| vs eager
  eager                   0.380     6.601730          0.00e+00
  aot_eager               2.267     6.601730          0.00e+00
  inductor                7.732     6.601730          9.54e-07

受控模型上无失败可定位,表仍演示 ablation。首调用代价随编译器机器增多而涨(0.4 → 2.3 → 7.7 s)。这个实验里 eager 与 aot_eager 输出报告精度逐比特相等,第一个测得的差(9.5e-7)随 Inductor 出现。那把假设的数值调查引向 Inductor/代码生成阶段;不证明另一程序每数值差必源于那里。

解释是搜索空间缩小,不是定理:

fails at backend="eager"      -> Dynamo capture / program interaction
ok eager, fails aot_eager     -> AOTAutograd (functionalization, the joint forward-backward graph)
ok aot_eager, fails inductor  -> Inductor lowering / kernel generation

大模型 raw TORCH_LOGS 输出淹没时,TORCH_TRACE 加 tlparse 工具把编译渲染成可浏览结构——编译帧、断裂、重编译——读单日志行前先找到贵区。先结构,再 zoom。

编译成功不是优化成功

这张表合了四配置的测量,但列不全同一实验填。特别 e10_ledger_table.py 测两固定形状编译行的输出一致;形状变化行记整十调用循环 wall 时间与重编译日志,不算 max-difference、峰值内存值。那些格诚实空着:

编译台账

可复用仪器,零件挣到后组装。记录编译器结果须暴露的东西,让读者问哪个假设有风险。

COMPILATION LEDGER

region        what is inside torch.compile
capture       frames compiled / graphs produced / graph breaks + reasons  (explain, then TORCH_LOGS)
assumptions   the guards that specialize each graph: shape, dtype, device, Python values
stability     calls / recompiles / distinct shapes seen / cache_size_limit reached?
cost          cold first call (fresh cache) / warm first call (fresh process) / steady-state ms
correctness   agreement with eager at a stated tolerance
verdict       did the compiled version improve the Chapter 12 contract metric, after amortizing cost?

开篇失败填好:

跑。对。干净捕获。契约死在 Level 4,修复一参数:dynamic=False → 默认。

观察者效应节的调试 print,台账早一层挂:

region        fusable chain, torch.compile(model)  with print(x.mean().item()) inside
capture       2 graphs, 1 break: "Unsupported: Tensor.item" at the print statement  (Level 3 FAILS)
assumptions   n/a -- the question stops here
stability     n/a
cost          irrelevant -- the graph you measured is not the graph you ship
correctness   output still matches eager
verdict       Level 3 FAILS: the print fragments the fusable region; 12x slower than without it

同样仪器,不同第一挂层,不同修复——诊断挪出编译区。

完整走一遍:开篇失败端到端

五层是流程。开篇失败按顺序跑,第一无证据处停。

Level 1 — RUNS。 编译服务每请求无抛回答。过。

Level 2 — CORRECT。 eager 对 max |Δ| 7e-7,本章陈述的 rtol=1e-4, atol=1e-4 对比契约内。过。这个请求下编译器路径没引入数值 significant 分歧。

Level 3 — CAPTURED。 torch._dynamo.explain(model, request.tokens) 报告 graph_count=1, graph_break_count=0。fullgraph=True 不抛。前向一图捕获。过。问题不是碎程序。

Level 4 — STABLE。 一 epoch 请求上 TORCH_LOGS=recompiles:

Recompiling function forward ...
    triggered by: tensor 'L['idx']' size mismatch at index 1. expected 60, actual 63
Recompiling function forward ...
    triggered by: tensor 'L['idx']' size mismatch at index 1. expected 63, actual 69
... (eight times)
torch._dynamo hit config.cache_size_limit (8)

这里挂。 守卫失败文本精确点名机制:size mismatch at index 1——词元张量的序列长维。不是 dtype,不是 Python 值。按请求变的轴上的形状。

Level 4 停诊断。开篇 Level 5 端到端已测(465× 慢),但 limit 后没见形状没有单“编译稳态”:匹配缓存守卫的调用仍可用编译变体,没匹配形状 eager 跑。稳定失败足以解释服务为什么在这个请求流上摊销不了编译。

测诊断的最小实验。 病因是形状特化,去掉守卫里的形状就去掉重编译。改一处——dynamic=False 到默认 torch.compile(model)——同样 epoch TORCH_LOGS=recompiles 下重跑:

Recompiling function forward ...
    triggered by: tensor 'L['idx']' size mismatch ...
(one recompile, then silence)

这个实验两次成功编译变体够——初始特化加形状变化后 generalize 的变体。之后日志静:后面请求复用守卫接受的缓存编译变体。诊断成立。

第 12 章契约下再测。 eager 十三请求 0.15 s。默认政策下服务付两编译变体,这个形状分布不再发重编译日志;后面调用缓存编译代码约 1.3 ms/请求对 eager 1.8。足够长寿的服务稳态 edge 摊销启动代价。只十三个请求,编译代价主导。决定回到第 12 章的问题——workload 活得够长摊销编译吗?——第 13 章去掉重复特化失败后。

测量替代的反射:“编译慢,加 dynamic=True。”那也 work——编译一次不是两次——但是猜,dynamic 实验数里稳态比让默认先特化略慢。守卫失败文本把猜变成诊断。

在编译器问题上用 AI

问助手 torch.compile 为什么慢,伸手拿 flag 面——dynamic、fullgraph、mode=、换后端——因为训练数据里全是那个。flag 在四便宜问题下游。下面 prompt 拒绝 flag,先要证据。

My torch.compile'd model is slower than eager (or recompiles, or behaves oddly).

Do not suggest dynamic=True, fullgraph=True, mode=, a different backend,
mark_dynamic, region narrowing, or abandoning compilation yet. Not until a
measurement identifies a mechanism one of those could affect.

Reconstruct the compilation evidence from what I give you:
  1. REGION   - exactly what is inside torch.compile
  2. CORRECT  - eager output vs compiled output, max abs difference, at a
                stated tolerance
    3. CAPTURED - torch._dynamo.explain: graph count, break count, break reasons;
                and TORCH_LOGS=graph_breaks output. If they disagree, preserve
                both observations and use fullgraph=True on the same call to test
                whether single-graph capture actually succeeds.
  4. STABLE   - TORCH_LOGS=recompiles: how many recompiles, the guard-failure
                text for each, how many distinct shapes the workload produced,
                and whether cache_size_limit was reached
  5. COST     - first call on a cold Inductor cache, first call in a fresh
                process with a warm cache, steady-state ms
  6. CONTRACT - the Chapter 12 measurement contract the compiled version is
                supposed to improve, and the eager baseline under it

Identify the FIRST level that lacks evidence:
  RUNS -> CORRECT -> CAPTURED -> STABLE -> WORTH IT

Stop there. If CORRECT fails, it may be an eager bug the compiler surfaced -
check eager alone. If STABLE fails, tell me which guard is failing and on what
input property, and what the smallest change to the workload or the compile
call would be to test that it is the cause.

三句 carry weight。测量 justify 前禁 flag,不让 plausible 下游修复用在上游病因。要守卫失败文本迫使诊断 specific:“它重编”不可行动;“size mismatch at index 1”点名轴、指向输入契约。问哪层缺证据让调查有序。fullgraph=True 有用的捕获约束/诊断;开了它不修慢图。

让 AI 先说编译器捕获什么,再问它设哪个编译器 flag。

编译器调试序列

 1. Prove eager correctness. If the model is wrong eager, the compiler is a
    distraction. Fix the model.

  2. Compare eager and compiled output with assert_close at a stated tolerance.
    A healthy compile may be bitwise equal or may differ slightly because of a
    different floating-point schedule. The tolerance belongs to the computation.

  3. Ask what was captured before asking how fast it is. Use
    torch._dynamo.explain for a structured summary and TORCH_LOGS=graph_breaks
    for emitted source locations/reasons. If they disagree, reproduce the same
    input under fullgraph=True to test whether single-graph capture is possible;
    do not declare one diagnostic universally infallible.

  4. Judge graph breaks by location, frequency and measured cost, not count.
    A break before the hot region may have no resolvable cost; a break inside
    it can fragment optimization and execute Python on every call.

  5. Measure what a break costs. Compare against the same function with the
    data-dependent construct removed. A break with no measured cost is a finding.

  6. Enable one log category at a time. graph_breaks, then recompiles, then
    guards. The goal is to answer one question, not to drown in output.

  7. Read the guard-failure text. "size mismatch at index N" identifies a shape
    assumption on that tensor axis; "dtype mismatch" or a Python-value guard is
    a different mechanism and needs a different intervention.

  8. Count the shapes the real workload produces before reaching for dynamic
    shapes. Distinguish compile attempts from successfully cached variants.
    Try the default first, then mark only the dimension whose variation is proved,
    and measure both compile behavior and steady-state time.

  9. Check whether cache_size_limit was hit. After the limit, existing compiled
    variants remain reusable, but unmatched calls run eagerly because no new
    specialization is created. Use fail_on_recompile earlier when "no steady-state
    recompile is acceptable" should be an assertion rather than a log surprise.

10. Bisect the backend when behavior differs: eager, then aot_eager, then
    inductor. The first that changes localizes the layer. Search-space
    reduction, not proof.

11. Narrow the compiled region to the numerical hot path. Keep logging, I/O,
    metrics and orchestration outside it.

12. Keep diagnostics out of the compiled region. A print inside it changes the
    graph you are measuring.

13. Re-measure the uninstrumented workload against Chapter 12's baseline, under
    the same contract.

14. Record the compilation ledger. Region, capture, assumptions, stability,
    cost, verdict.

你现在应该能回答什么

“torch.compile 不 work。” eager work 吗?不 work,编译器 surfacing 的模型 bug。eager work、编译挂?后端二分:eager、aot_eager、inductor。“死在 aot_eager”是 bug 报告;“不 work”不是。

“有图断裂,得去掉。” 在哪——TORCH_LOGS=graph_breaks 给发出的源码位置。路径多久跑一次?去掉断裂的版测得代价多少?堆前断裂这个跑 1.856 ms 对没断裂 1.867 ms——这个跑无 resolved penalty——同样构造堆中 26% 代价。先修贵的再修没测的或 negligible 的是白干。

“重编很多。” TORCH_LOGS=recompiles 给守卫失败文本。“size mismatch at index 1”意思是那张量序列长轴违反缓存形状假设——真 workload 产出多少不同值?这个 PyTorch 2.6 实验默认特化一次、重编一次后 generalize。别 assumed 每模型那个 exact 模式;验证日志真静了。dynamic=False 给真变量轴逼新静态变体,设置先测。

“设 dynamic=True 吧。” 重编译真是形状 variation 导致的,还是 dtype、设备、Python 值守卫?形状,先测默认。本章默认最快 1.322 ms;dynamic=True 仍比 eager 快(1.415 vs 1.776 ms)但比默认慢,mark_dynamic 测 1.918 ms 比 eager 慢。“更动态”不是单调性能改进。

“编了,所以编译 work 了。” 到 Level 1 了。hot 区一图捕获吗(Level 3)?守卫稳态 hold 还是重编(Level 4)?首调用摊销后指标改善吗(Level 5)?开篇失败 Level 1、2 过,慢 465×。

“打印看着怪。” 打印改了可捕获的东西。编译区里 float(x.mean()) 在那里断图。返回值拿到外面看。

“编译比 eager 慢。” 哪个代价?冷 Inductor 缓存首调用(开篇每形状 8–11 s)、热缓存首调用(每形状 ~1 s)、recurring 重编译(465×)、真稳态慢(第 13 章止的情形)?修复各不同。

“torch._dynamo.explain 说零断裂但慢。” 这个 PyTorch 2.6 实验中间情形 explain undercount。同样调用 TORCH_LOGS=graph_breaks 交叉查 tracer 发出的位置/原因,fullgraph=True 测一图捕获成不成。仪器全支持干净捕获,守卫、重编译、普通 workload 经济学往下走,别把 summary 当证明。

“上周快这周慢,代码一样。” 编译是跑间差的新轴:看到的输入形状序列不同、缓存一跑热一跑冷、一跑到 cache_size_limit 一跑没到。两跑都捕获 TORCH_LOGS=recompiles,比编译数与守卫失败。这就是第 13 章交第 14 章处。

练习

  1. 复现 cache-limit fallback。 受控模型 dynamic=False 编,serve 超 cache_size_limit 的不同序列长。捕获 TORCH_LOGS=recompiles。区分 (a) 成功的缓存特化、(b) 现存特化复用、(c) hit limit 的重编译尝试、(d) limit 后没匹配 eager 调用。记警告,验证 limit 后见过的形状仍可复用它的缓存编译变体。
  2. 二分。 有普通形状 bug 的模型拿来,eager、编译都挂证明。再修 bug,eager、编译 assert_close 在陈述 tolerance 下比。也测 torch.equal;不等解释数值接近为什么是对的契约,恰好相等解释为什么编译一般不保证 exact 相等。
  3. 三仪器,一断裂。 分支里放 x.sum().item()。torch._dynamo.explain、TORCH_LOGS=graph_breaks、fullgraph=True 各记报告。再 summary 与日志分歧的情形构造。reconcile 证据:哪个给结构化计数、哪个给发出的源码原因,fullgraph=True 结果对那次调用确立什么?
  4. 断裂位置。 同样数据依赖分支 (a) 放模型主要算子前、(b) 放中间。确认两都一断裂。稳态代价各测。用编译器 fuse 什么解释差。
  5. 守卫 forensics。 函数编译,调:新形状、新 dtype、新设备(有的话)、到达张量算子的 Python 常量改了。各捕获守卫失败文本并分类。哪些 dynamic=True 修,哪些不修?
  6. 动态形状,测得。 变化维 dynamic=False、dynamic=None、dynamic=True、该维 mark_dynamic sweep。记重编译日志条目、cache limit hit 否、看得到的成功缓存变体、sweep wall 时间、稳态 ms。说出 ship 哪个、为什么——编译对这个 workload 值不值。
  7. 观察者效应。 fusable 函数编译,eager 上加速测得。中间加 print(x.mean().item())。再测。三修复(返回值、flag 门控、@torch.compiler.disable)各用,报告哪个恢复加速、哪个只让 tracer 静音。
  8. 缩小区。 全训练步编译,再只编前向。图数、断裂数、首调用代价、稳态时间各记。决定用哪个,速度之外的理由 defend。
  9. break-even。 固定形状模型,eager 稳态、编译稳态、冷热首调用代价测得。两种缓存 state 下编译回本要多少调用。再描述一种永远回不了本的 workload。
  10. 别人代码的台账。 仓库里拿 torch.compile 调用。不改填编译台账:区、捕获、假设、稳定、代价、verdict。认出第一缺证据的层。

下一步:跑间差

第 13 章让编译器可检查。图断裂有位置有代价。重编有可读的守卫失败原因。cache limit 与静默 fallback 能弄响。编译版与 eager 每层 honest 比,从“跑”到“值”。

但本章造了新问题。编译给同样代码的两跑加了 invisible 不同的整维:看到的输入形状序列不同、装的守卫集不同、选的图不同、一跑缓存热一跑冷、一周到 cache_size_limit 一周没到。单元测试里一个不现。一个不抛。

第 14 章正是这类 bug——不在一跑里失败,在跑间差。没崩。图编了。模型训了。测试过了。而这周版比上周差。

第 13 章把编译列为 workload 需要那门纪律的又一原因——然后停,不教可比性、噪声阈值、CI,因为那些归下一章。

编译程序赌一套假设持续成立。调它就是找到第一个没成立的假设——问替代它的图值不值建。