Newshot

Dynamo 导出测试时好时坏之谜

Translation(model translation, not the source's own text)

Dynamo 导出测试的不稳定案例

不断追问为什么。

连续几个月来,Dynamo 导出测试时不时地失败,报错为“AssertionError: whole graph export entails exactly one call”。无法复现的不稳定测试很难调试,因为你无法轻易地做出更改并查看它是否解决了问题。所以当我注意到本地 pytest 运行总是以类似方式失败时(如此可靠,以至于起初我认为它们是确定性失败),我觉得应该停下手中的事情,彻底查明问题,因为否则似乎不太可能有其他人能弄清楚。

在调试棘手问题时,减少实验迭代时间是有益的。在我的情况下,运行完整测试套件需要几分钟:我希望在前几次运行中触发这个不稳定测试。最初我想通过按固定顺序运行所有测试,然后使用 delta debugging 移除运行测试,直到不稳定性消失。但事实证明,pytest 并没有真正内置的方法来做到这一点;内置的 unittest 有,但事实上,当你不用 unittest 运行时,测试就不再失败了(对于那些在家猜测的人来说,这是一个重要线索!)然而,pytest 确实支持 -k 参数标志中的布尔运算符,例如,你可以说 -k foo and bar 来选择名称中只包含 foo 和 bar 的测试。所以我用这个来逐步缩减测试到可以在几秒钟内运行的程度:PYTHONUNBUFFERED=1 pytest test/dynamo/test_dynamic_shapes.py -k 'Unspec and export and not dupes and not reorder' -v -x -s。很好。

接下来,我想更好地理解失败时到底发生了什么。一个好的开始是打开 DEBUG 日志并查看日志。不幸的是,打开日志也会让 bug 消失。所以只能回到老式的打印调试。经过一番三角定位,我终于确定,在有 bug 的情况下,我们到达了这段代码:


        on_enter()
            prior = set_eval_frame(callback)
            backend_ctx = backend_ctx_ctor()
            backend_ctx.__enter__()
            dynamic_ctx = enable_dynamic(self.dynamic, self.export)
            dynamic_ctx.__enter__()
            try:
                return

      

} else if (result != Py_None) { DEBUG_TRACE("create cache %s", name(frame)); extra = create_cache_entry(extra, result); Py_DECREF(result); set_extra(frame->f_code, extra); // Re-enable custom behavior eval_frame_callback_set(callback); return eval_custom_code(tstate, frame, extra->code, throw_flag);


        
将内部异常回调改为重置 Dynamo 回调,确实“修复”了测试失败。但还有一些未解之谜。为什么回调内部会报错?为什么这会非确定性地失败?有没有可能是我们有意在出错时保持回调禁用?

继续追问为什么。

我决定要弄清楚这个测试为什么会非确定性地失败。这个测试与另一个测试有什么不同?下面是一个成功测试的示例:

      

TRACE[_custom_eval_frame:650] begin __init__ /home/ezyang/local/a/pytorch-env/lib/python3.9/contextlib.py 86 -1 0 0 TRACE[_custom_eval_frame:679] skip __init__ TRACE[_custom_eval_frame:650] begin __enter__ /home/ezyang/local/a/pytorch-env/lib/python3.9/contextlib.py 114 -1 0 0 TRACE[_custom_eval_frame:679] skip __enter__ TRACE[_custom_eval_frame:650] begin enable_dynamic /data/users/ezyang/a/pytorch/torch/_dynamo/eval_frame.py 162 -1 0 0 TRACE[_custom_eval_frame:679] skip enable_dynamic TRACE[_custom_eval_frame:650] begin func /data/users/ezyang/a/pytorch/test/dynamo/test_export.py 83 -1 0 0 TRACE[_custom_eval_frame:752] create cache func


        
每条 begin 日志行都告诉我们 Dynamo 的自定义帧处理器在何时被调用。我们看到一些上下文管理器相关的内容、一次对 enable_dynamic 的调用,然后是对实际要跟踪的函数的调用。函数之前的所有内容都被跳过,而函数本身会创建一个缓存条目。这一切都说得通,我们可以将每条日志条目与 eval frame 设置之后实际正在执行的 Python 代码对应起来。

那失败的情况呢?

      

TRACE[_custom_eval_frame:650] begin enable_dynamic /data/users/ezyang/a/pytorch/torch/_dynamo/eval_frame.py 162 -1 0 0 TRACE[_custom_eval_frame:679] skip enable_dynamic TRACE[_custom_eval_frame:650] begin __call__ /home/ezyang/local/a/pytorch-env/lib/python3.9/weakref.py 586 -1 0 0 TRACE[_custom_eval_frame:760] create skip __call__ TRACE[_custom_eval_frame:650] begin del_ten /data/users/ezyang/a/pytorch/torch/_subclasses/meta_utils.py 118 -1 0 0 TRACE[_custom_eval_frame:760] create skip del_ten TRACE[_custom_eval_frame:650] begin __del__ /data/users/ezyang/a/pytorch/torch/multiprocessing/reductions.py 37 -1 0 0 TRACE[_custom_eval_frame:760] create skip __del__ TRACE[_custom_eval_frame:650] begin _free_weak_ref /data/users/ezyang/a/pytorch/torch/storage.py 766 -1 0 0 TRACE[_custom_eval_frame:760] create skip _free_weak_ref TRACE[_custom_eval_frame:650] begin <lambda> /data/users/ezyang/a/pytorch/torch/_dynamo/utils.py 329 -1 0 0 TRACE[_custom_eval_frame:760] create skip <lambda> TRACE[_custom_eval_frame:650] begin _remove_id /data/users/ezyang/a/pytorch/torch/_dynamo/utils.py 332 -1 0 0 TRACE[_custom_eval_frame:760] create skip _remove_id TRACE[_custom_eval_frame:650] begin <lambda> /data/users/ezyang/a/pytorch/torch/_dynamo/utils.py 329 -1 0 0 TRACE[_custom_eval_frame:679] skip <lambda> TRACE[_custom_eval_frame:650] begin _remove_id /data/users/ezyang/a/pytorch/torch/_dynamo/utils.py 332 -1 0 0 TRACE[_custom_eval_frame:679] skip _remove_id TRACE[_custom_eval_frame:650] begin __del__ /data/users/ezyang/a/pytorch/torch/multiprocessing/reductions.py 37 -1 0 0 TRACE[_custom_eval_frame:679] skip __del__ TRACE[_custom_eval_frame:650] begin _free_weak_ref /data/users/ezyang/a/pytorch/torch/storage.py 766 -1 0 0 TRACE[_custom_eval_frame:679] skip _free_weak_ref TRACE[_custom_eval_frame:650] begin <genexpr> /data/users/ezyang/a/pytorch/torch/_dynamo/eval_frame.py 733 14 0 0 TRACE[set_eval_frame_py:831] python enabled=0 and is run_only=0


        
文章标题:Dynamo 导出测试偶发失败的案例

正文:
我们看到一些熟悉的面孔:这段 trace 仍然调用了 enable_dynamic。但接着,有一堆随机的 frame,似乎与正在执行的 Python 代码完全不对应。它是从哪来的?有一些线索:有很多线索指向 __del__,它负责对象终结。还有这个 <genexpr>,它到底是从哪来的?

![image](https://canada1.discourse-cdn.com/flex036/uploads/pytorch1/original/1X/5fdb06218ad11b3a65ec2b66c11c131cca6d05b9.png)

是 GC!我迅速用 pytest-gc 检查了禁用 GC 会发生什么,果然,这也解决了问题。非确定性的谜团解开了:失败之所以非确定性地发生,是因为 GC 何时触发是非确定性的;而且你必须足够倒霉,恰好在 Dynamo 的 frame handler 安装之后、但还没真正到达相关 frame 之前触发了 GC。我们也可以通过在处理上下文管理器之后安装 frame handler 来确认这一点。这也解释了为什么这个错误在 pytest 中更容易复现:pytest 的实现中有一些引用环,导致 GC 运行得频繁得多。

所以,我们有多种方式可以修复这个问题。看起来在 GC 期间不运行 Dynamo 也许是个好主意?cpython - How to detect if frame evaluation is occurring during GC in Python - Stack Overflow 不过,我读了一些 CPython 的代码,似乎这并不可行。但这是否意味着调试结束了?

继续问为什么。

为什么在 Dynamo frame handler 已安装的情况下运行 GC 会是个问题?虽然这很奇怪,但 frame handler 似乎仍应被正常调用。可实际上,callback 却以内部错误失败了。但如果我们实际上从未调用过 callback,它又怎么会以内部错误失败呢?

我们可以强制 CPython 打印出被抛出的异常是什么,然后再恢复该异常,使其继续正常传播,使用以下技巧:

      

PyObject ptype, pvalue, *ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); Py_XINCREF(ptype); Py_XINCREF(pvalue); Py_XINCREF(ptraceback); PyErr_Restore(ptype, pvalue, ptraceback); PyErr_Print(); PyErr_Restore(ptype, pvalue, ptraceback);


        
(使用 Py_XINCREF 很重要,因为 ptype/pvalue/ptraceback 可能是 NULL)。

打印出的 backtrace 显示,我们在 callback handler 的第一行就失败了。我甚至都无法打印:在 print 运行之前,我就立刻失败了。会不会是……当我进入 eval frame 时,已经有一个处于活动状态的 Python 错误?在 callback 之前快速检查一下 PyErr_Occurred() 就证实了这一点!

为什么会有处于活动状态的 Python 错误?我不太确定,但我想起了 CPython 的一个小知识:当一个生成器耗尽时,它通过抛出 GeneratorExit 异常来结束。所以也许事情发生时,我们正处于展开一个生成器的过程中?

我提交了第一个补丁,然后去睡觉了。

      

diff --git a/torch/csrc/dynamo/eval_frame.c b/torch/csrc/dynamo/eval_frame.c index 4a5ca5b6abdb7..1e588f5dcdfd6 100644 --- a/torch/csrc/dynamo/eval_frame.c +++ b/torch/csrc/dynamo/eval_frame.c @@ -646,6 +646,17 @@ static PyObject* _custom_eval_frame( frame->f_lasti, frame->f_iblock, frame->f_executing); +

  • // In obscure situations, we can enter the eval frame with an exception
  • // already set (the most common situation this when we hit a generator
  • // expression which is exiting with GeneratorExit). In this case, there
  • // isn't really any chance that Dynamo will be able to successfully handle
  • // it. Immediately propagate it out.
  • if (PyErr_Occurred() != NULL) {
  • DEBUG_TRACE("propagate error %s", name(frame));
  • return NULL;
  • }

+ CacheEntry* extra = get_extra(frame->f_code); if (extra == SKIP_CODE || (callback == Py_False && extra == NULL)) { DEBUG_TRACE("skip %s", name(frame));


        
Dynamo 导出测试不稳定的案例

早上,常规测试套件全部通过……但在 `dynamo` 配置下运行的一些测试却失败了。有时候,修复 Dynamo 中的 bug 会导致原本通过的测试开始失败,原因是潜在的 bug。我本可以跳过那些测试,继续过自己的日子。

不断追问为什么。

我决定至少要先说服自己,这些新的失败不是我的错。幸运的是,这些失败是确定性的。奇怪的是,相关测试被标记为 xfail,但现在我们不知怎么跳过了 xfail 处理,仍然因异常而报错。我用 pdb 单步跟踪栈展开过程,确认:是的,不知怎么我们就是没有进入 finally 处理器。幸运的是,事实证明,仅仅抛出一个异常并配上一个非平凡的处理器,就足以复现问题。

      

import torch import contextlib import torch._dynamo

import logging torch._dynamo.config.log_level = logging.DEBUG torch._dynamo.config.output_code = True

@contextlib.contextmanager def ctx(): try: yield except RuntimeError: print("out")

@torch._dynamo.optimize("eager") def f(): with ctx(): h()

def h(): raise RuntimeError("boof")

f()


        
我仔细检查了 Dynamo 重写后的字节码,确认:是的,字节码仍然正确设置了上下文管理器。看起来是我的补丁有问题。我能想到几种可能可行的替代写法……

不断追问为什么。

Alban 这时已经被我拉进这桩糟心事里,他想弄明白为什么在帧入口处会有活跃的错误。Alban 阅读了 _PyEval_EvalFrameDefault 的源代码,注意到两件事:

- 你本不应该在错误已设置的情况下调用 eval frame,有一个调试断言在防止这种情况!cpython/ceval.c at 53dceb53ade15587b9cfd30c0a0942232517dee9 · python/cpython · GitHub

- 但生成器退出是特殊情况,当 throwflag 为 true 时会进入退出展开。cpython/ceval.c at 53dceb53ade15587b9cfd30c0a0942232517dee9 · python/cpython · GitHub

这与我们目前看到的一切都一致:出问题的帧无一例外都是 `<genexpr>` 帧,我快速做了个测试,确认我们到达这里时 throwflag 确实为 true。同样清楚的是,返回 NULL 与展开不同,因为展开会导致一堆额外的终结代码运行。这引出了我们最终的补丁:

      

diff --git a/torch/csrc/dynamo/eval_frame.c b/torch/csrc/dynamo/eval_frame.c index 4a5ca5b6abdb7..39a8226704919 100644 --- a/torch/csrc/dynamo/eval_frame.c +++ b/torch/csrc/dynamo/eval_frame.c @@ -646,6 +646,32 @@ static PyObject* _custom_eval_frame( frame->f_lasti, frame->f_iblock, frame->f_executing); +

  • if (throw_flag) {
  • // When unwinding generators, eval frame is called with throw_flag ==
  • // true. Frame evaluation is supposed to continue unwinding by propagating
  • // the exception. Dynamo doesn't really know how to do this, nor does it
  • // really want to do this, because there's unlikely any code to capture
  • // (you're going to immediately quit out of the frame, perhaps running
  • // some unwinding logic along the way). So we just run the default
  • // handler in this case.
  • //
  • // NB: A previous version of this patch returned NULL. This is wrong,
  • // because returning NULL is different from unwinding an exception.
  • // In particular, you will not execute things like context manager
  • // __exit__ if you just return NULL.
  • //
  • // NB: It's /conceivable/ that you might want to actually still call the
  • // Dynamo callback when throw_flag == TRUE, to give Dynamo a chance to
  • // do any stack unwinding code. But this is not really useful because
  • // (1) Dynamo doesn't actually know how to do stack unwinding, so it would
  • // immediately skip the frame, and (2) even if it did, this would only
  • // be profitable if there was tensor code in the unwinding code. Seems
  • // unlikely.
  • DEBUG_TRACE("throw %s", name(frame));
  • return eval_frame_default(tstate, frame, throw_flag);
  • }

+ CacheEntry* extra = get_extra(frame->f_code); if (extra == SKIP_CODE || (callback == Py_False && extra == NULL)) { DEBUG_TRACE("skip %s", name(frame));

我们的调试故事到此结束。没有放过任何细节:我们成功解释了原始问题中观察到的每一种行为。通过不断追问为什么,我们避免合入一个错误的修复,这个修复本会掩盖最初的问题,却让我们暴露于一个更隐蔽、更少触发的 bug。这个故事的寓意是什么?

不断追问为什么。

最终 PR:Fix flaky Dynamo export tests by ezyang · Pull Request #96488 · pytorch/pytorch · GitHub

本着追问为什么的精神——你(或者我们的 CI?)为什么没有运行 Python 的调试版本?

我没有运行调试版 Python,因为配置起来很麻烦(我必须启动一个全新的 Python 环境并从源码构建 Python。)至于 CI,我们可能应该有一个使用调试版 Python 运行的 CI 版本。

挑战在于 PyTorch 测试套件的总执行规模,调试构建完成它需要长 3-5 倍的时间。但可以按需/定期执行。或者可以选择一部分测试来运行。

我不认为那是真的?Greg 提到的是 CPython 的调试版本,不是 PyTorch。我在本地运行 CPython 的调试版本,据我所见它并没有明显变慢。

天才!忍不住再问一个为什么?为什么 Python 把异常机制用作流程控制方法?虽然这有点超出范围,而且可能是条死胡同,我还是选择发问,因为我看到这种反模式不知怎么地在 Python 世界里变成了相当流行的模式。又痛苦了。

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗