系统学习 AI 学习路径:从 GPU 运行时到推理、微调与 RAG 评估

torch-compile

torch.compile:用 TorchDynamo 捕获计算图,再由 Inductor 生成融合 kernel

补充说明

torch.compile 在运行时捕获 Python 代码中的张量计算图,交给 TorchInductor 编译成更高效的 kernel。它能融合逐元素操作、减少 Python 开销、生成 Triton/C++ kernel,常用于训练和推理加速。它不是“万能加速器”:动态控制流、图断裂、不支持的算子、频繁变化的 shape 都会削弱收益。

常见模式:default 平衡编译时间和性能,reduce-overhead 降低 Python/启动开销(适合小模型/推理),max-autotune 花更多时间搜索 kernel(适合稳定负载)。先用小步数 warmup,再测稳定后的吞吐,不要把首次编译时间算进性能。

常用示例

import torch

model = MyModel().cuda()
model = torch.compile(model)

# 训练循环:先 warmup 几步,再开始计时
for i, batch in enumerate(loader):
    if i == 5:
        torch.cuda.synchronize()
        start = torch.cuda.Event(enable_timing=True)
        start.record()
    loss = model(batch).sum()
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
# 不同模式
model = torch.compile(model, mode="reduce-overhead")
model = torch.compile(model, mode="max-autotune")

# 动态 shape:减少因 shape 变化导致的重复编译
model = torch.compile(model, dynamic=True)

# 强制整图编译,遇到图断裂直接报错,便于定位
model = torch.compile(model, fullgraph=True)
# 查看图断裂原因
TORCH_LOGS=graph_breaks python train.py

# 查看编译/重编译统计
TORCH_LOGS=recompiles python train.py

易错点与排错

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. torch.compile 的 default、reduce-overhead、max-autotune 分别适合什么场景?
  2. 什么是 graph break?怎样定位?
  3. 为什么动态 shape 会导致性能下降?
答案
  1. default 平衡编译时间和性能;reduce-overhead 降低 Python/启动开销,适合小模型和推理;max-autotune 花更多时间搜索 kernel,适合稳定负载。
  2. graph break 是 Dynamo 无法继续捕获计算图的位置,会回退到 eager 执行;用 TORCH_LOGS=graph_breaks 定位。
  3. shape 变化会触发重新编译,编译和缓存开销抵消收益;固定 shape 或使用 dynamic=True 减少重编译。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令