PyTorch 2.0 故障排除(旧)¶
作者: Michael Lazos
注意
本文档已过时,现主要作为如何运行 torch.compile
精简工具的主要资源。请参阅 更新的故障排除文档。另有一份更 全面的 torch.compile 手册 可用。
我们正在积极开发调试工具、性能分析工具,并改进错误和警告消息。下表列出了可用工具及其典型用法。如需更多帮助,请参阅 诊断运行时错误。
工具 |
目的 |
用法 |
---|---|---|
信息日志 |
查看编译摘要步骤 |
|
调试日志 |
查看编译详细步骤(打印每个被追踪的指令) |
|
任意后端精简工具 |
查找可复现任意后端错误的最小子图 |
设置环境变量 |
TorchInductor 精简工具 |
如果已知错误发生在 |
设置环境变量 |
Dynamo 精度精简工具 |
当您怀疑问题出在 |
|
Inductor 精度精简工具 |
当您怀疑问题出在后端(例如 inductor)时,查找可在 eager 模式模型和优化模型之间复现精度问题的最小子图。如果此方法无效,请尝试 Dynamo 精度精简工具。 |
|
|
查找图断点并显示其原因 |
|
记录/回放 |
记录并回放可在图捕获期间复现错误的帧 |
|
TorchDynamo 函数名过滤 |
仅编译具有给定名称的函数,以减少调试问题时的干扰 |
设置环境变量 |
TorchInductor 调试日志 |
打印通用 TorchInductor 调试信息和生成的 Triton/C++ 代码 |
|
TorchInductor 追踪 |
显示每个 TorchInductor 阶段花费的时间 + 输出代码和图可视化 |
设置环境变量 TORCH_COMPILE_DEBUG=1 或 |
除了信息日志和调试日志外,您还可以使用 torch._logging 进行更精细的日志记录。
诊断运行时错误¶
从高层次看,TorchDynamo 栈包含从 Python 代码进行的图捕获(TorchDynamo)和一个后端编译器。例如,后端编译器可能包含反向图追踪(AOTAutograd)和图降低(TorchInductor)*。错误可能发生在栈的任何组件中,并会提供完整的栈追踪信息。
要确定错误发生在哪一个组件中,您可以使用信息级别日志 torch._logging.set_logs(dynamo = logging.INFO)
或 TORCH_LOGS="dynamo"
,并查找 Step #: ...
输出。日志在每个步骤开始和结束时记录,因此错误应对应的步骤是最近记录的、其结束尚未被记录的步骤。这些步骤对应于栈的以下部分
步骤 |
组件 |
---|---|
1 |
TorchDynamo |
2 |
编译器后端 |
3 |
TorchInductor |
如果信息日志不足,您可以使用可用的后端选项。这些选项包括
"eager"
: 仅运行 TorchDynamo 前向图捕获,然后使用 PyTorch 运行捕获的图。这表明错误是否由 TorchDynamo 引起。"aot_eager"
: 运行 TorchDynamo 捕获前向图,然后运行 AOTAutograd 追踪反向图,无需任何额外的后端编译器步骤。接着将使用 PyTorch eager 运行前向图和反向图。这对于将问题范围缩小到 AOTAutograd 非常有用。
缩小问题的通用步骤如下
使用
"eager"
后端运行您的程序。如果错误不再发生,则问题出在使用中的后端编译器(如果使用 TorchInductor,请继续执行步骤 2。否则,请参阅 本节)。如果错误在使用"eager"
后端时仍然发生,则这是 在运行 torchdynamo 时发生的错误。仅当使用
TorchInductor
作为后端编译器时,才需要此步骤。使用"aot_eager"
后端运行模型。如果此后端引发错误,则表明错误发生在 AOTAutograd 追踪期间。如果使用此后端不再发生错误,则 错误在 TorchInductor 中*。
以下各节将分析这些情况。
注意
TorchInductor 后端包含 AOTAutograd 追踪和 TorchInductor 编译器本身。我们将通过将 TorchInductor
称为后端,并将 TorchInductor 降低称为降低由 AOTAutograd 追踪的图的阶段来进行区分。
TorchDynamo 错误¶
如果在 "eager"
后端中发生生成的错误,那么 TorchDynamo 很可能是错误的来源。这是一个将生成错误的示例代码。
import torch
import torch._dynamo as dynamo
def test_assertion_error():
y = torch.ones(200, 200)
z = {y: 5}
return z
compiled_test_assertion_error = torch.compile(test_assertion_error, backend="eager")
compiled_test_assertion_error()
上面的代码生成以下错误
torch._dynamo.convert_frame: [ERROR] WON'T CONVERT test_assertion_error /scratch/mlazos/torchdynamo/../test/errors.py line 26
due to:
Traceback (most recent call last):
File "/scratch/mlazos/torchdynamo/torchdynamo/symbolic_convert.py", line 837, in BUILD_MAP
assert isinstance(k, ConstantVariable) or (
AssertionError
from user code:
File "/scratch/mlazos/torchdynamo/../test/errors.py", line 34, in test_assertion_error
z = {y: 5}
Set torch._dynamo.config.verbose=True for more information
==========
如消息所示,您可以设置 torch._dynamo.config.verbose=True
来获取 TorchDynamo 错误和用户代码的完整栈追踪。除了此标志外,您还可以通过 torch._logging.set_logs(dynamo = logging.INFO)
或 TORCH_LOGS="dynamo"
设置 TorchDynamo 的 log_level
。这些级别包括
logging.DEBUG
或TORCH_LOGS="+dynamo"
: 打印遇到的所有指令,以及下面列出的所有日志级别。logging.INFO
: 打印每个被编译的函数(原始和修改后的字节码)和捕获的图,以及下面列出的所有日志级别。logging.WARNING
(默认): 打印图断点,以及下面列出的所有日志级别。logging.ERROR
: 仅打印错误。
如果模型非常大,日志可能会变得非常多。如果错误发生在模型 Python 代码的深层,仅执行发生错误的帧可以有助于更轻松地进行调试。有两种可用工具可以实现这一点
将环境变量
TORCHDYNAMO_DEBUG_FUNCTION
设置为所需函数名称,将仅对该名称的函数运行 torchdynamo。启用记录/回放工具(设置
torch._dynamo.config.replay_record_enabled = True
),该工具在遇到错误时会转储执行记录。然后可以回放此记录,以仅运行发生错误的帧。
诊断 TorchInductor 错误¶
如果错误未在使用 "eager"
后端时发生,则错误源是后端编译器(示例错误)。TorchDynamo 有 不同的后端编译器选择,TorchInductor 符合大多数用户的需求。本节以 TorchInductor 为主要示例,但某些工具也可用于其他后端编译器。
下面是我们关注的栈的部分
选择 TorchInductor 作为后端后,使用 AOTAutograd 从 torchdynamo 捕获的前向图生成反向图。需要注意的是,错误可能在此追踪过程中发生,也可能在 TorchInductor 将前向图和反向图降低到 GPU 代码或 C++ 时发生。一个模型通常包含数百或数千个 FX 节点,因此缩小问题发生的具体节点范围可能非常困难。幸运的是,有一些可用工具可以自动将这些输入图精简到导致问题的节点。第一步是确定错误是发生在 AOTAutograd 追踪反向图期间,还是在 TorchInductor 降低期间。如上文步骤 2 中所述,可以使用 "aot_eager"
后端仅独立运行 AOTAutograd,而不进行降低。如果使用此后端仍然发生错误,则表明错误发生在 AOTAutograd 追踪期间。
以下是一个示例
import torch
import torch._dynamo as dynamo
model = torch.nn.Sequential(*[torch.nn.Linear(200, 200) for _ in range(5)])
def test_backend_error():
y = torch.ones(200, 200)
x = torch.ones(200, 200)
z = x + y
a = torch.ops.aten._foobar(z) # dummy function which errors
return model(a)
compiled_test_backend_error = torch.compile(test_backend_error, backend="inductor")
compiled_test_backend_error()
运行此代码应该会给出此错误,下方附有更长的栈追踪信息
Traceback (most recent call last):
File "/scratch/mlazos/torchdynamo/torchinductor/graph.py", line 246, in call_function
return lowerings[target](*args, **kwargs)
File "/scratch/mlazos/torchdynamo/torchinductor/lowering.py", line 185, in wrapped
return decomp_fn(*args, **kwargs)
File "/scratch/mlazos/torchdynamo/torchinductor/lowering.py", line 810, in _foobar
assert False
AssertionError
...
如果您将 torch.compile(backend="inductor")
更改为 torch.compile(backend="aot_eager")
,它将无错误运行,因为 问题 出在 TorchInductor 降低过程中,而不是在 AOTAutograd 中。
精简 TorchInductor 错误¶
接下来,我们运行精简工具以获取最小的可复现示例。设置环境变量 TORCHDYNAMO_REPRO_AFTER="aot"
(或直接设置 torch._dynamo.config.repro_after="aot"
)将生成一个 Python 程序,该程序会将 AOTAutograd 生成的图缩减到可复现错误的最小子图。(请参阅下方关于精简 TorchDynamo 生成的图的示例)使用此环境变量运行程序应显示几乎 相同的输出,并附加一行指示 minifier_launcher.py
已写入到何处。输出目录可通过将 torch._dynamo.config.base_dir
设置为有效的目录名进行配置。最后一步是运行精简工具并检查它是否成功运行。成功运行看起来像 这样。如果精简工具成功运行,它将生成可运行的 Python 代码,该代码可精确复现错误。对于我们的示例,代码如下
import torch
from torch import tensor, device
import torch.fx as fx
from torch._dynamo.testing import rand_strided
from math import inf
from torch.fx.experimental.proxy_tensor import make_fx
# torch version: 1.13.0a0+gitfddfc44
# torch cuda version: 11.6
# torch git version: fddfc4488afb207971c54ad4bf58130fdc8a4dc5
# CUDA Info:
# nvcc: NVIDIA (R) Cuda compiler driver
# Copyright (c) 2005-2022 NVIDIA Corporation
# Built on Thu_Feb_10_18:23:41_PST_2022
# Cuda compilation tools, release 11.6, V11.6.112
# Build cuda_11.6.r11.6/compiler.30978841_0
# GPU Hardware Info:
# NVIDIA A100-SXM4-40GB : 8
from torch.nn import *
class Repro(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, add):
_foobar = torch.ops.aten._foobar.default(add); add = None
return (_foobar,)
args = [((200, 200), (200, 1), torch.float32, 'cpu')]
args = [rand_strided(shape, stride, dtype, device) for shape, stride, dtype, device in args]
mod = make_fx(Repro())(*args)
from torch._inductor.compile_fx import compile_fx_inner
compiled = compile_fx_inner(mod, args)
compiled(*args)
Repro
模块的 forward
方法包含导致问题的确切算子。提交问题时,请包含任何精简后的可复现示例,以便于调试。
精简后端编译器错误¶
对于 TorchInductor 之外的后端编译器,查找导致错误的子图的过程与 TorchInductor 错误中的过程几乎相同,但有一个重要区别。即精简工具现在将运行在由 TorchDynamo 追踪的图上,而不是 AOTAutograd 的输出图上。让我们来看一个示例。
import torch
import torch._dynamo as dynamo
model = torch.nn.Sequential(*[torch.nn.Linear(200, 200) for _ in range(5)])
# toy compiler which fails if graph contains relu
def toy_compiler(gm: torch.fx.GraphModule, _):
for node in gm.graph.nodes:
if node.target == torch.relu:
assert False
return gm
def test_backend_error():
y = torch.ones(200, 200)
x = torch.ones(200, 200)
z = x + y
a = torch.relu(z)
return model(a)
compiled_test_backend_error = torch.compile(test_backend_error, backend=toy_compiler)
compiled_test_backend_error()
为了在 TorchDynamo 追踪前向图后运行代码,您可以使用 TORCHDYNAMO_REPRO_AFTER
环境变量。使用 TORCHDYNAMO_REPRO_AFTER="dynamo"
(或 torch._dynamo.config.repro_after="dynamo"
)运行此程序应产生此 输出 和 {torch._dynamo.config.base_dir}/repro.py
中的以下代码。
注意
TORCHDYNAMO_REPRO_AFTER
的另一个选项是 "aot"
,它将在生成反向图后运行精简工具。
import torch
import torch._dynamo as dynamo
from torch import tensor, device
import torch.fx as fx
from torch._dynamo.testing import rand_strided
from math import inf
from torch._dynamo.debug_utils import run_fwd_maybe_bwd
from torch.nn import *
class Repro(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, add):
relu = torch.relu(add); add = None
return (relu,)
mod = Repro().cuda()
opt_mod = torch.compile(mod, backend="None")
args = [((200, 200), (200, 1), torch.float32, 'cpu', False)]
args = [rand_strided(sh, st, dt, dev).requires_grad_(rg) for (sh, st, dt, dev, rg) in args]
with torch.cuda.amp.autocast(enabled=False):
ref = run_fwd_maybe_bwd(mod, args)
res = run_fwd_maybe_bwd(opt_mod, args)
精简工具成功将图缩减到在 toy_compiler
中引发错误的算子。与 TorchInductor 错误中的过程的另一个不同之处在于,精简工具在遇到后端编译器错误后会自动运行。成功运行后,精简工具会将 repro.py
写入到 torch._dynamo.config.base_dir
。
性能分析¶
访问 TorchDynamo 性能分析器¶
TorchDynamo 有一个内置的统计函数,用于收集和显示在每个编译阶段花费的时间。在执行 Torch._Dynamo 后,通过调用 torch._dynamo.utils.compile_times()
可以访问这些统计信息。默认情况下,它会返回一个字符串表示,显示每个 TorchDynamo 函数按名称统计的编译时间。
使用 TORCH_COMPILE_DEBUG 调试 TorchInductor¶
TorchInductor 有一个内置的统计和追踪功能,用于显示每个编译阶段花费的时间、输出代码、输出图可视化和 IR 转储。这是一个调试工具,旨在更容易理解和排除 TorchInductor 的内部问题。
我们使用以下测试程序(repro.py
)运行一个示例
import torch
@torch.compile()
def test_model(x):
model = torch.nn.Sequential(
torch.nn.Linear(10, 10),
torch.nn.LayerNorm(10),
torch.nn.ReLU(),
)
return model(x)
y = test_model(torch.ones(10, 10))
设置环境变量 TORCH_COMPILE_DEBUG=1
将创建一个调试追踪目录,默认情况下该目录位于当前目录并命名为 torch_compile_debug(这可以在 torchdynamo 配置字段 debug_dir_root
和 env var TORCH_COMPILE_DEBUG_DIR
中覆盖)。在此目录内,每次运行都将有一个单独的文件夹,以运行的时间戳和进程 ID 命名
$ env TORCH_COMPILE_DEBUG=1 python repro.py
$ cd torch_compile_debug
$ ls
run_2023_03_01_08_20_52_143510-pid_180167
在运行文件夹中,将有一个包含调试日志的 torchdynamo
目录,以及一个 torchinductor
文件夹,该文件夹包含每个已编译内核的子文件夹,其中包含 inductor 调试 artifact。
$ cd
run_2023_03_01_08_20_52_143510-pid_180167
$ ls
torchinductor torchdynamo
进一步进入 torchinductor
目录,\*.log
文件是编译的 AOT Autograd 阶段的日志,model__0_forward_1.0
包含 inductor 调试 artifact。
$ cd torchinductor
$ ls
aot_model___0_debug.log model__0_forward_1.0
$ cd model__0_forward_1.0
$ ls
debug.log fx_graph_readable.py fx_graph_runnable.py fx_graph_transformed.py ir_post_fusion.txt ir_pre_fusion.txt output_code.py
以下是内容的摘要
fx_graph_readable.py
和fx_graph_runnable.py
是 inductor 接收到的fx_graph
的可读和可运行版本。fx_graph_transformed.py
是 inductor 运行所有 fx pass 后的 fx 图。ir\*.txt
是融合前后的 inductor IR。output_code.py
是子图的编译后 triton 内核。
以下是测试程序的 示例调试目录内容
import torch
@torch.compile()
def test_model(x):
model = torch.nn.Sequential(
torch.nn.Linear(10, 10),
torch.nn.LayerNorm(10),
torch.nn.ReLU(),
)
return model(x)
y = test_model(torch.ones(10, 10))
该调试追踪中的每个文件都可以通过 torch._inductor.config.trace.*
进行启用和禁用。性能分析和图表默认情况下都是禁用的,因为生成它们开销很大。
此新调试格式中的单个节点如下所示
buf1: SchedulerNode(ComputedBuffer)
buf1.writes =
{ MemoryDep(name='buf1', index=0, size=()),
MemoryDep(name='buf1', index=0, size=(s0,))}
buf1.unmet_dependencies = {MemoryDep(name='buf0', index=c0, size=(s0,))}
buf1.met_dependencies = {MemoryDep(name='primals_2', index=c0, size=(s0,))}
buf1.group.device = cuda:0
buf1.group.iteration = (1, s0)
buf1.sizes = ([], [s0])
class buf1_loop_body:
var_ranges = {z0: s0}
index0 = z0
index1 = 0
def body(self, ops):
get_index = self.get_index('index0')
load = ops.load('buf0', get_index, False)
get_index_1 = self.get_index('index0')
load_1 = ops.load('primals_2', get_index_1, False)
add = ops.add(load, load_1)
get_index_2 = self.get_index('index1')
reduction = ops.reduction('buf1', torch.float32, torch.float32, 'sum', get_index_2, add)
return reduction
请参阅 示例调试目录输出 以获取更多示例。
图断点¶
给定像这样的程序
def some_fun(x):
...
compiled_fun = torch.compile(some_fun, ...)
...
TorchDynamo 会尝试将 some_fun
内的所有 torch/tensor 算子编译成一个单独的 FX 图,但可能无法将所有内容捕获到同一个图内。
某些图断点的原因对于 TorchDynamo 来说是不可克服的,并且无法轻松修复。—— 调用 torch 以外的 C 扩展对 torchdynamo 是不可见的,并且可以在 TorchDynamo 无法引入必要的 guard(参见 使 Dynamo 健全:Guard)的情况下执行任意操作,以确保编译后的程序可以安全地重用。如果生成的片段很小,图断点会阻碍性能。为了最大化性能,尽量减少图断点非常重要。
识别图断点的原因¶
要识别程序中的所有图断点及其相关原因,可以使用 torch._dynamo.explain
。此工具对提供的函数运行 TorchDynamo,并聚合遇到的图断点。以下是一个示例用法
import torch
import torch._dynamo as dynamo
def toy_example(a, b):
x = a / (torch.abs(a) + 1)
print("woo")
if b.sum() < 0:
b = b * -1
return x * b
explanation = dynamo.explain(toy_example)(torch.randn(10), torch.randn(10))
print(explanation_verbose)
"""
Graph Count: 3
Graph Break Count: 2
Op Count: 5
Break Reasons:
Break Reason 1:
Reason: builtin: print [<class 'torch._dynamo.variables.constant.ConstantVariable'>] False
User Stack:
<FrameSummary file foo.py, line 5 in toy_example>
Break Reason 2:
Reason: generic_jump TensorVariable()
User Stack:
<FrameSummary file foo.py, line 6 in torch_dynamo_resume_in_toy_example_at_5>
Ops per Graph:
...
Out Guards:
...
"""
输出包括
out_guards
- 一个列表的列表,其中每个子列表包含必须通过的 guard,以确保追踪的图有效。graphs
- 一个成功追踪的图模块列表。ops_per_graph
- 一个列表的列表,其中每个子列表包含在图表中运行的算子。
要在遇到的第一个图断点处引发错误,请使用 fullgraph
模式。此模式禁用 TorchDynamo 的 Python 回退,仅当整个程序可转换为单个图时才会成功。示例用法
def toy_example(a, b):
...
compiled_toy = torch.compile(toy_example, fullgraph=True, backend=<compiler>)(a, b)
过度重新编译¶
当 TorchDynamo 编译一个函数(或其一部分)时,它会做出关于局部变量和全局变量的某些假设,以便进行编译器优化,并将这些假设表示为在运行时检查特定值的 guard。如果这些 guard 中有任何一个失败,Dynamo 将重新编译该函数(或其一部分),最多 torch._dynamo.config.recompile_limit
次。如果您的程序达到了缓存限制,您首先需要确定哪个 guard 失败以及程序的哪一部分触发了它。
如果您的程序表现出有限的动态性,您可以通过调整 TorchDynamo 缓存限制来允许编译和缓存每个变体,但如果缓存限制设置得太高,您可能会发现重新编译的开销超过了任何优化收益。
torch._dynamo.config.recompile_limit = <your desired cache limit>
TorchDynamo 计划支持许多常见的动态张量形状场景,例如变化的批大小或序列长度。它不计划支持 rank-dynamism。在此期间,可以通过设置特定的缓存限制并结合 bucketing 技术,为某些动态模型实现可接受的重新编译次数。
精度调试¶
如果您设置环境变量 TORCHDYNAMO_REPRO_LEVEL=4
,也可以精简精度问题,它类似于 git bisect 模型,完整的可复现示例可能像 TORCHDYNAMO_REPRO_AFTER="aot" TORCHDYNAMO_REPRO_LEVEL=4
。我们需要这样做是因为下游编译器会生成代码,无论是 Triton 代码还是 C++ 后端,这些下游编译器产生的数值可能会有细微差异,但却对您的训练稳定性产生巨大影响。因此,精度调试器对于我们检测代码生成或后端编译器中的错误非常有用。
如果您想确保 torch 和 triton 之间的随机数生成是一致的,则可以启用 torch._inductor.config.fallback_random = True
扩展调试¶
可以通过使用以下实验性标志启用扩展调试。
TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED
- 如果 guard 的字符串表示与此标志值匹配,则提供扩展调试信息。例如,将其设置为“Ne(s0, 10)”以在 guard 发出时生成完整的 Python 和 C++ 回溯。TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL
- 在分配特定符号时提供扩展调试信息。例如,将其设置为“u2”以在此符号创建时生成完整的 Python 和 C++ 回溯。TORCHDYNAMO_EXTENDED_DEBUG_CPP
- 为所有扩展调试设置以及错误提供扩展调试信息(C++ 回溯)。例如,将其设置为“1”。C++ 回溯很慢且信息非常冗余,因此默认情况下不包含在扩展调试中。
冷启动计时和缓存损坏调试¶
为了测量冷启动编译时间或调试缓存损坏,可以传入 TORCHINDUCTOR_FORCE_DISABLE_CACHES=1
或设置 torch._inductor.config.force_disable_caches = True
,这将覆盖任何其他缓存配置选项并禁用所有编译时缓存。