Repository navigation
[Bug Fix] Restore global grad switch when a composite backward node throws #79923
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
omoYang
wants to merge
2
commits into
PaddlePaddle:develop
from
omoYang:fix-prim-grad-stop-gradient-restore
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
test/legacy_test/test_grad_enabled_restore_on_backward_error.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| import paddle | ||
|
|
||
|
|
||
| def build_failing_graph(): | ||
| """Build a graph whose second order backward is doomed to fail. | ||
|
|
||
| ``dout`` has an illegal shape (it should be [4, 0]): matmul_grad itself | ||
| succeeds because of the 0-size fast return, but taking grad of its output | ||
| runs MatmulDoubleGradNode, whose composite implementation calls the matmul | ||
| forward api and fails the K dimension check in InferMeta. | ||
| """ | ||
| x = paddle.randn([4, 8]) | ||
| y = paddle.randn([8, 0]) | ||
| dout = paddle.randn([4, 3]) | ||
| for tensor in (x, y, dout): | ||
| tensor.stop_gradient = False | ||
| dx, _ = paddle._C_ops.matmul_grad(x, y, dout, False, False) | ||
| return [x, y, dout], dx | ||
|
|
||
|
|
||
| class TestGradEnabledRestoreOnBackwardError(unittest.TestCase): | ||
| """Raising from a backward node must not leak the global grad switch. | ||
|
|
||
| Composite (prim) backward nodes and the saved_tensors_hooks turn grad | ||
| recording off before running and turn it back on afterwards. When the code | ||
| in between throws, the restore must still happen, otherwise the whole | ||
| thread silently stops recording the computation graph. | ||
| """ | ||
|
|
||
| def check_restored(self, action, expected_error=ValueError): | ||
| paddle.set_grad_enabled(True) | ||
|
|
||
| with self.assertRaises(expected_error): | ||
| action() | ||
|
|
||
| self.assertTrue(paddle.is_grad_enabled()) | ||
| probe = paddle.randn([2, 2]) | ||
| probe.stop_gradient = False | ||
| self.assertFalse((probe * 2).stop_gradient) | ||
|
|
||
| def test_paddle_grad_without_create_graph(self): | ||
| def action(): | ||
| inputs, dx = build_failing_graph() | ||
| paddle.grad( | ||
| [dx], | ||
| inputs, | ||
| grad_outputs=[paddle.randn(dx.shape)], | ||
| create_graph=False, | ||
| allow_unused=True, | ||
| ) | ||
|
|
||
| self.check_restored(action) | ||
|
|
||
| def test_paddle_grad_with_create_graph(self): | ||
| def action(): | ||
| inputs, dx = build_failing_graph() | ||
| paddle.grad( | ||
| [dx], | ||
| inputs, | ||
| grad_outputs=[paddle.randn(dx.shape)], | ||
| create_graph=True, | ||
| allow_unused=True, | ||
| ) | ||
|
|
||
| self.check_restored(action) | ||
|
|
||
| def test_tensor_backward(self): | ||
| def action(): | ||
| _, dx = build_failing_graph() | ||
| dx.backward(paddle.randn(dx.shape)) | ||
|
|
||
| self.check_restored(action) | ||
|
|
||
| def test_tensor_backward_with_retain_graph(self): | ||
| def action(): | ||
| _, dx = build_failing_graph() | ||
| dx.backward(paddle.randn(dx.shape), retain_graph=True) | ||
|
|
||
| self.check_restored(action) | ||
|
|
||
| def test_saved_tensors_pack_hook_error(self): | ||
| """The pack hook runs in forward and reports failure by returning NULL.""" | ||
|
|
||
| def pack_hook(tensor): | ||
| raise RuntimeError("pack hook fails on purpose") | ||
|
|
||
| def unpack_hook(value): | ||
| return value | ||
|
|
||
| def action(): | ||
| x = paddle.randn([2, 2]) | ||
| x.stop_gradient = False | ||
| with paddle.autograd.saved_tensors_hooks(pack_hook, unpack_hook): | ||
| return x * x | ||
|
|
||
| self.check_restored(action, OSError) | ||
|
|
||
| def test_saved_tensors_unpack_hook_error(self): | ||
| """The unpack hook runs while the backward graph is being walked.""" | ||
|
|
||
| def pack_hook(tensor): | ||
| return tensor | ||
|
|
||
| def unpack_hook(value): | ||
| raise RuntimeError("unpack hook fails on purpose") | ||
|
|
||
| def action(): | ||
| x = paddle.randn([2, 2]) | ||
| x.stop_gradient = False | ||
| with paddle.autograd.saved_tensors_hooks(pack_hook, unpack_hook): | ||
| out = (x * x).sum() | ||
| out.backward() | ||
|
|
||
| self.check_restored(action, OSError) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这里修复的是一条用户可直接触发的泄漏路径:
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
已在 77214f6 中修复:新增
test_saved_tensors_pack_hook_error与test_saved_tensors_unpack_hook_error,分别覆盖 pack/unpack hook 抛异常后 grad 开关恢复。There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
已补,感谢指出 —— 这条路径比我原先判断的更容易触发,实测确认是用户可直接触发的泄漏。
在
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
已核对:两条新用例分别覆盖
PackHook与UnPackHook的抛异常路径,期望OSError与errors::External的映射一致(paddle/fluid/pybind/exception.cc:73)。此问题已解决。