Repository navigation
[dynamo] Restore the TorchFunction TLS on scope exit in RootGuardManager - #198264
bobrenjc93 wants to merge 4 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198264
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit 64b88bc with merge base a49c2df ( 🟡 GREEN LIGHT - PR requires human review:
reason: UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Claude finished @bobrenjc93's task in 45m 9s —— View job Moving the TorchFunction TLS restore into a C++ Full reviewPR Review: #198264SummaryReplaces the per-exit Code Quality
Reachability is the interleaving the new test already creates: these leaves are installed across many tensor guard managers ( The PR also reorders the two cleanups. Previously the TLS was restored before One edit fixes both: give the relational reset its own Dict-tag recording has the same shape, one line away from the diff. The restored comment is inaccurate. TestingThe replacement RecommendationNeeds Discussion The TLS change itself is correct and the perf argument is sound. What needs a decision is the relational-guard reset: it is pre-existing rather than introduced here, but the PR is editing exactly those exits, the fix is three lines, and folding it in also erases the |
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 23m 7s —— View job The Full reviewPR Review: #198264SummaryReplaces the per-exit The core change is right. The Three things below. Code QualityThe cleanup order is inverted, and that is a behavior change this PR introduces. Before, each exit ran Three of the four overrides are pure C++ ( The cheap fix is to give the relational reset its own Note for the follow-up, since this PR chose to split it. Deferring the relational reset to #198269 is a defensible split, but one of the four leaves degrades worse than a spurious recompile, so it should not slip: TestingThe new test cannot distinguish "restores Two notes on what the deleted The removed top-level imports ( RecommendationApprove The TLS change is correct, it is a strict coverage improvement, it has a regression test that fails without it, and the instruction-count win is real. Neither finding blocks: the ordering inversion is low-risk and disappears when #198269 lands provided the relational |
[ghstack-poisoned]
|
Thanks. Dispositions against the current head 74fc3a1 (the review ran on the first head):
The PR reorders the two cleanups -- Fixed in #198269. With both cleanups on scope exits, reverse destruction order is TLS restore, then relational reset, then unlock, which is the pre-stack order on main. In this PR alone the reset runs under Dict-tag recording has the same shape -- Declined for this stack. The restored comment is inaccurate -- Fixed in 74fc3a1: the "Only needed for debugging purposes" comments are gone; Testing: nothing exercises what the tree leaves behind after a throw -- Fixed in #198269: |
[ghstack-poisoned]
|
Dispositions against head 64b88bc (the review ran on 74fc3a1): The cleanup order is inverted, and that is a behavior change this PR introduces -- Fixed in #198269, which declares the relational Note for the follow-up: STORAGE_OVERLAPPING degrades worse than a spurious recompile -- Fixed in #198269: The new test cannot distinguish "restores old_state" from "restores ENABLED" -- Fixed in 64b88bc: |
|
Claude finished @bobrenjc93's task in 1m 26s —— View job The scope-exit restore is correct at head Full reviewPR Review: #198264SummaryMoves the TorchFunction TLS restore in
Verified dispositionsComment accuracy — confirmed fixed: Test strength — confirmed fixed at Dict-tag recording, declined — the disposition checks out, so I withdraw that item for this stack. Code QualityThe reset-under- RecommendationApprove Correct, a strict coverage improvement over the wrapper, regression-tested including the non-default-state case, and the ~2,700-instruction win is the removal of a genuine |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…ger (pytorch#198264) **Problem.** After pytorch#197049, every guard evaluation through `GuardManagerWrapper.check` pays for a Python-side TorchFunction state read that exists only to clean up after a C++ throw, and that read costs about 2,600 instructions per evaluation because it returns a pybind enum. **Fix.** Restore the TorchFunction TLS with a `c10::make_scope_exit` inside `RootGuardManager` itself, so a throw is handled where it happens, and put the Python wrapper back to a one-line delegation. **Summary.** `RootGuardManager::check_nopybind_template` and `check_verbose_nopybind` set the TorchFunction TLS to `ALL_DISABLED` while the accessors run and wrote the old value back on every returning exit but not on a C++ throw, so pytorch#197049 added a save and restore around the delegation in `GuardManagerWrapper.check` / `check_verbose`. frgossen then flagged on that PR that `nn_module_guard_eval / instruction_count` stepped 72,881 -> ~75,600 (+4.8%, about +2,700 instructions per eval) the day it landed, and the whole step is the one `torch._C._get_torch_function_state()` call the wrapper added, whose pybind `py::enum_` return allocates, registers and frees a Python enum instance on every call. This PR moves the restore into C++ as a scope exit declared right after `set_disabled_state(ALL_DISABLED)` in both root check paths, drops the explicit restores on the returning exits, and returns the wrapper to `return self.root.check(x)`. The scope exit costs nothing per eval and covers every C++ exception type that can leave the tree, including the `py::error_already_set` that the eval_frame path catches in `lookup_in_list` (a `TORCH_CHECK` on that path is not caught anywhere and would terminate regardless, so the TLS is moot there). Nothing about what a guard tree returns or raises changes; only the state a throw leaves behind, and the per-eval cost, differ. ## The leak, before and after The tree the tests use: a `TENSOR_MATCH` on a strided nested tensor, whose stride read fires a `TORCH_CHECK` from inside an accessor while the TLS is disabled. From `test_tensor_match_guard_throw_restores_torch_function` in `test/dynamo/test_guard_manager.py`: ```python nested = torch.nested.nested_tensor( [torch.randn(2, 3), torch.randn(3, 3)], layout=torch.strided ) root = RootGuardManager() manager = root.dict_getitem_manager("x", "L['x']", nested, default_mgr_enum) manager.add_tensor_match_guard( nested, [None] * 3, [None] * 3, "x", ["check_tensor(x)"], None, type(nested), torch._C._dispatch_keys(nested), ) err = "NestedTensorImpl doesn't support" with torch._C.DisableTorchFunctionSubclass(): state = torch._C._get_torch_function_state() # SUBCLASSES_DISABLED, asserted with self.assertRaisesRegex(RuntimeError, err): root.check({"x": nested}) # throws out of the accessor torch._C._get_torch_function_state() # parent, calling the root directly: ALL_DISABLED -- the thread is stuck, and # a __torch_function__ subclass on it silently stops dispatching from here on # now: SUBCLASSES_DISABLED -- equal to `state` ``` The guard is built from explicit `[None] * 3` size and stride lists because building it from the tensor would read the same strides, and the accessor is the root's own so nothing else can reject the input first. `check_verbose` throws from the sizes read instead of the strides read and is asserted the same way in the same test. Both throws run under `DisableTorchFunctionSubclass`, a non-default state, so that restoring the captured state is told apart from resetting to ENABLED: a restore that hardcoded ENABLED would fail the equality against `state`. ## The wrapper, before and after ```python # parent (pytorch#197049), torch/_dynamo/guards.py def check(self, x): torch_function_state = torch._C._get_torch_function_state() # pybind py::enum_ return try: return self.root.check(x) except BaseException: torch._C._set_torch_function_state(torch_function_state) raise # now def check(self, x): return self.root.check(x) ``` The `try`/`except` itself is free; the enum read is the cost. `_get_torch_function_state` is a pybind lambda returning `at::impl::TorchFunctionDisabledState`, bound as a `py::enum_`, so each call pays pybind dispatch plus allocating, registering and freeing a Python enum instance. Measured with the benchmark's own `torch._C._instruction_counter`, that call alone is about 2,600 instructions; the TLS read behind it is trivial. The old "only needed for debugging" comment is not restored, since `AOTCompiledModel` dispatch calls `check` and `check_verbose` on its serving path. ## The C++ restore ```cpp // RootGuardManager::check_nopybind_template, torch/csrc/dynamo/guards.cpp const auto old_state = at::impl::PythonTorchFunctionTLS::get_disabled_state(); at::impl::PythonTorchFunctionTLS::set_disabled_state(ALL_DISABLED); auto restore_torch_function = c10::make_scope_exit([old_state] { at::impl::PythonTorchFunctionTLS::set_disabled_state(old_state); // every exit, throws included }); if (!GuardManager::check_accessors_nopybind(value)) { // parent: set_disabled_state(old_state); here and on the two exits below _reset_relational_guard_state(); return false; } ``` `check_verbose_nopybind` gets the same scope exit at the same point. The destructor is a single store into a C++ `thread_local`, needs no GIL and cannot throw, so it is safe during unwinding; the mutex `lock_guard` is declared earlier and still releases last. The sibling `_reset_relational_guard_state()` calls have the same non-RAII exit and are made RAII in the next PR of this stack, with their own regression test; this PR is only the TLS restore. ## Numbers Same build and same process, `torch._C._instruction_counter` min over 300 evals of the benchmark's guard manager, with the pytorch#197049 column produced by monkeypatching the landed wrapper body back in: | benchmark | pytorch#197049 wrapper | this PR | delta | |---|---|---|---| | nn_module_guard_eval | 80,968 | 78,297 | -2,671 (-3.30%) | | nn_module_guard_eval_dynamic | 111,751 | 109,093 | -2,658 (-2.38%) | Absolute counts differ from CI's machine; the delta is the point, and it matches the ~2,700 frgossen reported. ## Tests - `test_tensor_match_guard_throw_restores_torch_function` (`test/dynamo/test_guard_manager.py`, in `GuardManagerTests`): the tree above, `check` then `check_verbose` called on the root directly under `DisableTorchFunctionSubclass`, TLS asserted equal to the captured `SUBCLASSES_DISABLED` state after each throw. It replaces the stub-root test from pytorch#197049, which exercised the wrapper's `try`/`except` and goes with it. - `test_aot_compile_module_restores_torch_function_after_a_throw` and `test_aot_compile_function_restores_torch_function_after_a_throw` (`test/dynamo/test_aot_compile.py`): the public callers, `AOTCompiledModel.__call__` and `torch.compiler.load_compiled_function`, on the same nested-tensor throw. Their bodies are unchanged apart from their comments and still pass against the C++ restore. Test Plan: ``` python test/dynamo/test_guard_manager.py # 89 tests OK python test/dynamo/test_aot_compile.py -k restores_torch_function python benchmarks/dynamo/pr_time_benchmarks/benchmarks/nn_module_guard_eval.py /tmp/bench.csv lintrunner -a test/dynamo/test_guard_manager.py test/dynamo/test_aot_compile.py torch/_dynamo/guards.py torch/csrc/dynamo/guards.cpp ``` Authored with an AI assistant (Claude Fable 5.1). Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: pytorch#198264 Approved by: https://github.com/williamwen42
Stack from ghstack (oldest at bottom):
Problem. After #197049, every guard evaluation through
GuardManagerWrapper.checkpays for a Python-side TorchFunction state read that exists only to clean up after a C++ throw, and that read costs about 2,600 instructions per evaluation because it returns a pybind enum.Fix. Restore the TorchFunction TLS with a
c10::make_scope_exitinsideRootGuardManageritself, so a throw is handled where it happens, and put the Python wrapper back to a one-line delegation.Summary.
RootGuardManager::check_nopybind_templateandcheck_verbose_nopybindset the TorchFunction TLS toALL_DISABLEDwhile the accessors run and wrote the old value back on every returning exit but not on a C++ throw, so #197049 added a save and restore around the delegation inGuardManagerWrapper.check/check_verbose. frgossen then flagged on that PR thatnn_module_guard_eval / instruction_countstepped 72,881 -> ~75,600 (+4.8%, about +2,700 instructions per eval) the day it landed, and the whole step is the onetorch._C._get_torch_function_state()call the wrapper added, whose pybindpy::enum_return allocates, registers and frees a Python enum instance on every call. This PR moves the restore into C++ as a scope exit declared right afterset_disabled_state(ALL_DISABLED)in both root check paths, drops the explicit restores on the returning exits, and returns the wrapper toreturn self.root.check(x). The scope exit costs nothing per eval and covers every C++ exception type that can leave the tree, including thepy::error_already_setthat the eval_frame path catches inlookup_in_list(aTORCH_CHECKon that path is not caught anywhere and would terminate regardless, so the TLS is moot there). Nothing about what a guard tree returns or raises changes; only the state a throw leaves behind, and the per-eval cost, differ.The leak, before and after
The tree the tests use: a
TENSOR_MATCHon a strided nested tensor, whose stride read fires aTORCH_CHECKfrom inside an accessor while the TLS is disabled. Fromtest_tensor_match_guard_throw_restores_torch_functionintest/dynamo/test_guard_manager.py:The guard is built from explicit
[None] * 3size and stride lists because building it from the tensor would read the same strides, and the accessor is the root's own so nothing else can reject the input first.check_verbosethrows from the sizes read instead of the strides read and is asserted the same way in the same test. Both throws run underDisableTorchFunctionSubclass, a non-default state, so that restoring the captured state is told apart from resetting to ENABLED: a restore that hardcoded ENABLED would fail the equality againststate.The wrapper, before and after
The
try/exceptitself is free; the enum read is the cost._get_torch_function_stateis a pybind lambda returningat::impl::TorchFunctionDisabledState, bound as apy::enum_, so each call pays pybind dispatch plus allocating, registering and freeing a Python enum instance. Measured with the benchmark's owntorch._C._instruction_counter, that call alone is about 2,600 instructions; the TLS read behind it is trivial. The old "only needed for debugging" comment is not restored, sinceAOTCompiledModeldispatch callscheckandcheck_verboseon its serving path.The C++ restore
check_verbose_nopybindgets the same scope exit at the same point. The destructor is a single store into a C++thread_local, needs no GIL and cannot throw, so it is safe during unwinding; the mutexlock_guardis declared earlier and still releases last.The sibling
_reset_relational_guard_state()calls have the same non-RAII exit and are made RAII in the next PR of this stack, with their own regression test; this PR is only the TLS restore.Numbers
Same build and same process,
torch._C._instruction_countermin over 300 evals of the benchmark's guard manager, with the #197049 column produced by monkeypatching the landed wrapper body back in:Absolute counts differ from CI's machine; the delta is the point, and it matches the ~2,700 frgossen reported.
Tests
test_tensor_match_guard_throw_restores_torch_function(test/dynamo/test_guard_manager.py, inGuardManagerTests): the tree above,checkthencheck_verbosecalled on the root directly underDisableTorchFunctionSubclass, TLS asserted equal to the capturedSUBCLASSES_DISABLEDstate after each throw. It replaces the stub-root test from [dynamo] Restore the TorchFunction TLS after a guard tree throws #197049, which exercised the wrapper'stry/exceptand goes with it.test_aot_compile_module_restores_torch_function_after_a_throwandtest_aot_compile_function_restores_torch_function_after_a_throw(test/dynamo/test_aot_compile.py): the public callers,AOTCompiledModel.__call__andtorch.compiler.load_compiled_function, on the same nested-tensor throw. Their bodies are unchanged apart from their comments and still pass against the C++ restore.Test Plan:
Authored with an AI assistant (Claude Fable 5.1).
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98