Repository navigation
Conversation
…hrows Composite (prim) backward nodes turn the global grad switch off before running and turn it back on afterwards. The set/restore pair was written by hand with no guard in between, so an exception thrown inside the composite implementation skipped the restore. The calling thread was then left with grad recording permanently disabled: every later forward silently stopped building the graph, with no error or warning. Add an RAII `egr::HasGradGuard` and use it in place of the manual pairs: - eager_gen.py: both composite branches, which fixes the 77 occurrences in the generated nodes.cc, covering all 26 ops in prim_white_list - multiply_node.cc: the hand-written multiply_grad / multiply_double_grad - py_layer_node.cc, eager_py_layer.cc, eager_utils.cc: the same pattern in PyLayer forward/backward and in the saved_tensors_hooks pack/unpack hooks, where PADDLE_ENFORCE_NOT_NULL and early `return Py_None` could also skip the restore Add a regression test asserting paddle.is_grad_enabled() is unchanged after a failing backward, for paddle.grad and Tensor.backward().
Paddle-Bot Review Board (review完成)
可维护性建议(总分 92 / 100,只给建议,不影响评审结论)
各维度得分(仅评本 PR 改动,点击展开)
Powered by Nyanpasu claude with Opus 5.5 默认推理级别, please check the suggestions carefully. |
| const Tensor& tensor) { | ||
| bool grad_tmp = egr::Controller::Instance().HasGrad(); | ||
| egr::Controller::Instance().SetHasGrad(false); | ||
| egr::HasGradGuard has_grad_guard(false); |
There was a problem hiding this comment.
这里修复的是一条用户可直接触发的泄漏路径:saved_tensors_hooks 的 pack hook 在 Python 中抛异常时,PyObject_Call 返回 NULL,旧代码在 PADDLE_ENFORCE_NOT_NULL(ret, ...) 处抛出而跳过 SetHasGrad(grad_tmp),此后线程内 grad 记录被关闭。新增测试只覆盖了 composite 反向(MatmulDoubleGradNode)路径,hook 这条路径没有回归覆盖。
建议在 test_grad_enabled_restore_on_backward_error.py 补一个用例:在 paddle.autograd.saved_tensors_hooks(pack_hook, unpack_hook) 中让 pack_hook 抛异常,执行 x * x(x.stop_gradient=False)并 assertRaises,之后断言 paddle.is_grad_enabled() 仍为 True 且新前向的 stop_gradient 为 False;unpack hook 抛异常的情况同理可选。
There was a problem hiding this comment.
已在 77214f6 中修复:新增 test_saved_tensors_pack_hook_error 与 test_saved_tensors_unpack_hook_error,分别覆盖 pack/unpack hook 抛异常后 grad 开关恢复。
There was a problem hiding this comment.
已补,感谢指出 —— 这条路径比我原先判断的更容易触发,实测确认是用户可直接触发的泄漏。
在 test_grad_enabled_restore_on_backward_error.py 中新增两个用例:
test_saved_tensors_pack_hook_error:pack hook 抛异常,覆盖PackHook::operator()test_saved_tensors_unpack_hook_error:unpack hook 在反向期间抛异常,覆盖UnPackHook::operator()
注意异常类型是 OSError(errors::External),不是 composite 路径的 ValueError,因此把 check_restored 改成接受期望的异常类型。
修复前后对比(同一份测试):未修复构建 5 failed / 1 passed,修复后 6 passed。两条新用例都在未修复构建上失败,确认有回归价值。
There was a problem hiding this comment.
已核对:两条新用例分别覆盖 PackHook 与 UnPackHook 的抛异常路径,期望 OSError 与 errors::External 的映射一致(paddle/fluid/pybind/exception.cc:73)。此问题已解决。
| // silently stops recording the computation graph. | ||
| class HasGradGuard { | ||
| public: | ||
| explicit HasGradGuard(bool value) |
There was a problem hiding this comment.
💡 可维护性建议(设计一致性,不阻塞合入):create_graph && egr::Controller::Instance().HasGrad() 在 eager_gen.py 两处模板、multiply_node.cc 两处和 py_layer_node.cc 中重复出现,其中 && HasGrad() 是承重项:若被“化简”为 HasGradGuard(create_graph),在外层 no_grad 下 create_graph=True 时会把 grad 重新打开。建议在 guard 上提供表达意图的入口(例如 explicit HasGradGuard(bool value) 之外增加 static 工厂或第二个构造参数,如“仅在 !create_graph 时关闭”),由 guard 内部计算 original_ && create_graph,调用点不再重复该组合。
There was a problem hiding this comment.
已在 77214f6 中处理:guard 内部计算 original_ && keep_grad,调用点统一传 create_graph,不会在 no_grad 下重新打开记录。
There was a problem hiding this comment.
已按建议改,并且采用了比加工厂函数更彻底的做法:把组合算进唯一的构造函数,参数语义从「目标值」改为「是否保留」。
explicit HasGradGuard(bool keep_grad)
: original_(Controller::Instance().HasGrad()) {
Controller::Instance().SetHasGrad(original_ && keep_grad);
}这样 original_ && keep_grad 永远不大于 original_,守卫在结构上就不可能把开关打开。调用点直接写 HasGradGuard(create_graph) 即为正确,你指出的「化简后在 no_grad 下重新打开 grad」从根上不存在了 —— 原来那个容易被误简化的写法,现在成了唯一写法。
所有调用点已去掉 && HasGrad();hook 处的 HasGradGuard(false) 语义不变(original_ && false 恒为 false)。
There was a problem hiding this comment.
已核对:构造时写入 original_ && keep_grad,guard 不会把记录重新打开;各调用点传 create_graph 或 false 的行为与原实现一致。此建议已解决。
| }; | ||
|
|
||
| // NOTE(yangyang): Temporarily switch the global grad switch to `value` and | ||
| // restore the previous one on scope exit. Composite backward implementations |
There was a problem hiding this comment.
💡 可维护性建议(契约一致性,不阻塞合入):注释把 guard 描述为 composite 反向专用(“Composite backward implementations ... have to turn grad recording off”),但本 PR 也把它用于 PyLayer forward/backward 和 saved_tensors_hooks / NodePostHook,且 create_graph=True 时并不关闭记录。建议注释只描述通用契约:作用域内把全局 grad 开关设为指定值,离开作用域(含异常)时恢复原值;composite 反向的背景放到调用点或去掉。
There was a problem hiding this comment.
同意,已改。注释现在只描述通用契约:作用域内按 keep_grad 设置开关、离开作用域(含异常展开)恢复原值,并显式写出「keep_grad 不会把记录重新打开」这条不变量 —— 这正是上一条里调用点可以直接传 create_graph 的依据。composite 反向的背景已从注释中移除。
There was a problem hiding this comment.
已在 77214f6 中处理:注释改为描述通用契约(作用域内按 keep_grad 关闭记录、退出含异常时恢复)。
There was a problem hiding this comment.
已核对:注释现在只描述通用契约(按 keep_grad 设置、退出作用域含异常时恢复),并写明 keep_grad 不会重新打开记录,与构造函数 original_ && keep_grad 一致。此建议已解决。
| public: | ||
| explicit HasGradGuard(bool value) | ||
| : original_(Controller::Instance().HasGrad()) { | ||
| if (value != original_) { |
There was a problem hiding this comment.
💡 可维护性建议(AI 生成债务,不阻塞合入):SetHasGrad 只是写一个 thread_local bool(tracer.cc:560),构造与析构中的 if (value != original_) / if (HasGrad() != original_) 判断不改变行为,反而让人误以为调用点的 create_graph && HasGrad() 依赖这个比较。建议与同文件的 EagerBackwardStateGuard 一致,构造时无条件 SetHasGrad(value),析构时无条件 SetHasGrad(original_)。
There was a problem hiding this comment.
同意,已去掉。构造和析构现在都是无条件写入,与同文件的 EagerBackwardStateGuard 保持一致。
There was a problem hiding this comment.
已在 77214f6 中处理:构造与析构改为无条件写入,与 EagerBackwardStateGuard 一致。
There was a problem hiding this comment.
已核对:构造与析构均为无条件 SetHasGrad,与 EagerBackwardStateGuard 写法一致。此建议已解决。
- HasGradGuard now takes `keep_grad` and sets `original_ && keep_grad`, so it can only turn grad recording off, never on. Call sites pass `create_graph` directly instead of repeating `create_graph && HasGrad()`, which removes the trap where "simplifying" to `HasGradGuard(create_graph)` would re-enable recording inside no_grad. - Drop the no-op comparisons in the constructor and destructor, matching EagerBackwardStateGuard. - Describe the generic contract in the comment instead of the composite backward background, since the guard is also used by PyLayer and the saved_tensors_hooks. - Add regression tests for a failing pack hook and a failing unpack hook. Both leak on an unfixed build (5 failed, 1 passed) and pass with the fix.
|
补充一处评审时可能会注意到的细节,供参考。 在
恢复发生在调用方拿到返回值之前,所以调用方观察到的开关状态是正确的。 对比 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #79923 +/- ##
===========================================
Coverage ? 100.00%
===========================================
Files ? 3
Lines ? 13
Branches ? 0
===========================================
Hits ? 13
Misses ? 0
Partials ? 0 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
PR Category
Execute Infrastructure
PR Types
Bug fixes
Description
背景
走 prim 组合路径的反向节点(
MatmulDoubleGradNode、`SiluDoubleGradNode 等)在执行期间必须把全局grad开关关掉,否则反向计算自身又会建图。因为它们的组合实现调用的是可微的前向 API(paddle/fluid/prim/api/composite_backward/composite_double_backward_api.h 中的 matmul、reshape、add)。这里对全局grad开关的关闭/恢复是在模版中手工实现的,中间没有任何守卫:
一旦组合实现内部抛出异常(形状校验、OOM、NaN 检查等),恢复那一行就被跳过。异常本身能正常传到 Python 层,但g_has_grad梯度开关在该线程剩余的生命周期内一直为 false,除非显示调用set_grad_enabled(True)。
如果grad开关一直被关,此后所有新的前向都静默停止记录计算图:输出带 stop_gradient=True,paddle.grad 找不到可求导路径,loss.backward() 不产生梯度,整个过程没有任何报错或警告。
任何捕获了反向异常后继续运行的代码都会受影响:
这个问题在一个单进程连续执行多个 case 的测试框架中被检测到:某个 case 反向报错之后,同一worker中后续所有 case 的反向都被静默跳过。
原始代码bug复现
paddle.grad(create_graph=False) 和 Tensor.backward() 都会泄漏;create_graph=True 不会,因为该分支根本不调用 SetHasGrad。不走 prim 路径的节点(AddDoubleGradNode、ScaleGradNode)抛出同样的 EnforceNotMet(InvalidArgument) 却不泄漏 —— 这说明决定因素是这对手工配对的置位/恢复,而不是异常类型。
作为对照,PyTorch 在 create_graph=False 下让 C++ 反向节点抛异常后,torch.is_grad_enabled() 保持为 True。
修复
在 paddle/fluid/eager/api/utils/global_utils.h 中新增 RAII 守卫 egr::HasGradGuard,守卫以 create_graph && HasGrad() 构造,完整保持原语义:create_graph 为真时目标值等于当前值,构造和析构都是空操作,与现有行为(该分支不动开关)一致,紧邻已有的 EagerBackwardStateGuard,并用它替换所有的手工关闭/恢复:
测试
新增 test/legacy_test/test_grad_enabled_restore_on_backward_error.py,断言反向报错后 paddle.is_grad_enabled() 与调用前一致,且一次无关的前向仍然建图;覆盖 paddle.grad(create_graph=False/True)与 Tensor.backward()。
在未修复的构建上实测:3 failed, 1 passed —— 三条泄漏路径失败、create_graph=True 通过,与上述分析完全吻合。修复后:4 passed。
另外重跑并全部通过:
并确认重新生成的 nodes.cc 中 has_grad_guard 出现 77 次、original_global_grad 为 0 次。
是否引起精度变化
否