Skip to content

[dynamo] Restore the TorchFunction TLS on scope exit in RootGuardManager - #198264

Closed
bobrenjc93 wants to merge 4 commits into
gh/bobrenjc93/1466/basefrom
gh/bobrenjc93/1466/head
Closed

bobrenjc93 wants to merge 4 commits into
gh/bobrenjc93/1466/basefrom
gh/bobrenjc93/1466/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. After #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 #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:

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

# parent (#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

// 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 #197049 column produced by monkeypatching the landed wrapper body back in:

benchmark #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 [dynamo] Restore the TorchFunction TLS after a guard tree throws #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]

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

🔗 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 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • Restructures exception safety on the core guard-evaluation path in RootGuardManager::check_nopybind_template and check_verbose_nopybind in torch/csrc/dynamo/guards.cpp
    • Removes the Python-side TLS restore in GuardManagerWrapper.check / check_verbose (torch/_dynamo/guards.py) in favor of a C++ c10::make_scope_exit
    • Fits no trivial class: a perf-motivated refactor of cleanup logic, not a single-cause bugfix or mechanical rename
  • Behavior change
    • _reset_relational_guard_state() now runs before the TLS restore, so reset_state() runs under ALL_DISABLED; the fix for that ordering is deferred to #​198269
  • Review signal
    • Earlier review rounds raised questions that changed the code (a stronger non-default-state test and a comment fix), so a human should confirm the final shape
  • Tests
    • Replaces GuardManagerWrapperTests with test_tensor_match_guard_throw_restores_torch_function, which covers both root paths under DisableTorchFunctionSubclass

reason: not_trivial
Reviewed commit: 64b88bc

Inference job

🐛 Report a wrong verdict

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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 22, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 45m 9s —— View job


Moving the TorchFunction TLS restore into a C++ scope_exit is the right call and strictly widens coverage over the Python wrapper, but the same non-RAII-exit bug the PR is fixing still applies to _reset_relational_guard_state() on the adjacent lines, and moving the TLS restore after it is a small behavior change worth a second look.

Full review

PR Review: #198264

Summary

Replaces the per-exit set_disabled_state(old_state) calls in RootGuardManager::check_nopybind_template / check_verbose_nopybind with a single c10::make_scope_exit, and reverts GuardManagerWrapper.check/check_verbose to plain delegation. The C++ restore is correct and covers strictly more than the Python wrapper did (the leaf guards at guards.cpp:4386 run before the TLS is touched, so nothing is lost, and run_root_guard_manager on the eval-frame path is now covered too). Three problems below.

Code Quality

_reset_relational_guard_state() is the same bug, left in place, and the PR's own test proves it is reachable.

torch/csrc/dynamo/guards.cpp:4548 is still called only from the eight returning exits (4387, 4407, 4414, 4419, 4457, 4474, 4484, 4492) — exactly the exits the PR just stopped relying on for the TLS. There is no entry-time reset (entry only does reset_dict_tag_recording_variables() at 4378, and check_verbose_nopybind does not even do that), _relational_guard_resetters (4611) is only ever appended to, and nothing invalidates or rebuilds the manager after a guard raise — lookup_in_list sets guard_error and returns (extra_state.cpp:225-240), guard_error_hook only prints. The same cache entry stays live with stale state. Two of the four reset_state() overrides are worse than a spurious recompile:

  • STORAGE_OVERLAPPING -> StorageOverlapChecker (1644-1691): add() does Py_INCREF (1660) and only reset() decrefs (1664-1670), so a skipped reset leaks a strong tensor ref. _expected_overlapping is fixed in the constructor (1649) and never recomputed, so the leftovers push _overlapping.size() past it and TORCH_CHECK(_expected_overlapping >= _overlapping.size()) (1679) throws on the next evaluation — after another add() has increfed again. That skips the reset again, so the entry is permanently poisoned: every later evaluation raises instead of answering, leaking one more ref each time.
  • SYMBOLIC_SHAPE_GUARD (2787-2890): _args_seen is zeroed only when it reaches _nargs (2837) or in reset_state() (2888). A throw after k of the leaves ran leaves _args_seen == k, so the next evaluation fires _guard_check_fn(_args_int.data(), _args_float.data()) (2839) after only _nargs - k fresh writes, with k slots still holding the previous round's values (or the constructor's zeros, 2813-2814). The guard can return true for shapes it was not compiled for, and the skew persists.

Reachability is the interleaving the new test already creates: these leaves are installed across many tensor guard managers (7412, 7436-7441), so one leaf running and then a different accessor's TENSOR_MATCH firing its TORCH_CHECK is exactly it.

The PR also reorders the two cleanups. Previously the TLS was restored before _reset_relational_guard_state(); now the explicit reset runs first and the scope_exit restores afterwards, so every reset_state() runs under ALL_DISABLED. Only StorageOverlapChecker::reset's Py_DECREF (1668) can run Python or free storage during reset, so this needs the guard to hold the last reference and is low risk — but it is a behavior change nobody asked for.

One edit fixes both: give the relational reset its own scope_exit declared before the TLS one, and drop the eight explicit calls. Reverse destruction order then restores the TLS first and resets afterwards — the pre-PR ordering — while also covering the throw path.

Fix this →

Dict-tag recording has the same shape, one line away from the diff. GuardManager::check_nopybind brackets start_recording_dict_pointers (3827) / stop_recording_dict_pointers (3847) with no RAII, so a throw leaves _is_recording_dict_pointers == true, a stale _current_tag_safe_root, and _recorded_tensor_metadata holding strong py::object refs (4597-4600). check_nopybind_template scrubs this at entry (4378); check_verbose_nopybind does not (compare 4441) — and verbose is precisely what runs next after a raise (extra_state.cpp:226-235, guards.py:5923, aot_compile.py:2248). Consequence is the stuck flag disabling the dict-tag fast path (5764) plus retained tensor refs, so perf/leak rather than wrongness, but it is a one-line fix to call the reset at verbose entry too.

The restored comment is inaccurate. torch/_dynamo/guards.py:780 and :784 now read "Only needed for debugging purposes." That is true of check_verbose only in the Dynamo sense; both are on the AOT-compile serving path — check via guard_check at aot_compile.py:754, called from __call__ at :1026, and check_verbose at :1028 and :2248. Since the PR is reintroducing this wording rather than inheriting it untouched, either drop the comment or say what it actually means (this wrapper is not the eval-frame hot path; that calls check_nopybind directly).

Testing

The replacement RootGuardManagerTorchFunctionTests covers only the TLS. Nothing exercises what the tree leaves behind after a throw for the state that is still not RAII — a test with a relational guard installed that throws mid-tree and then asserts the next check() answers correctly would have caught both items above, and is the regression test the fix in the first finding needs.

Recommendation

Needs 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 reset_state()-under-ALL_DISABLED ordering change this PR does introduce. Doing it here is cheaper than a follow-up; if you would rather split it, the ordering change should still be neutralized in this PR.

| Branch: `gh/bobrenjc93/1466/head`

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 22, 2026 19:51
@bobrenjc93
bobrenjc93 requested a review from frgossen September 22, 2026 19:53
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 22, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 23m 7s —— View job


The c10::make_scope_exit restore is correct and strictly widens coverage over the Python wrapper it replaces, and the new test is a genuine regression test; two follow-ups worth folding in are that reset_state() now runs while the TLS is ALL_DISABLED (an ordering change this PR introduces), and that the new test only exercises the default ENABLED state so it cannot distinguish restoring old_state from hardcoding ENABLED.

Full review

PR Review: #198264

Summary

Replaces the per-exit set_disabled_state(old_state) calls in RootGuardManager::check_nopybind_template and check_verbose_nopybind with a single c10::make_scope_exit, and reverts GuardManagerWrapper.check/check_verbose to plain delegation.

The core change is right. The scope_exit is declared after set_disabled_state(ALL_DISABLED) and before the first accessor call in both paths (guards.cpp:4402, :4466), so the leaf guards at 4386 / 4452 — which deliberately need the unmodified TorchFunction state for GLOBAL_STATE and the mode-stack guard — still run outside it. Nothing is lost relative to the Python wrapper, and run_root_guard_manager (guards.cpp:7565) on the eval-frame path is now covered too, which the wrapper never was. auto x = c10::make_scope_exit(...) matches every existing caller (torch/csrc/autograd/engine.cpp:1120, torch/csrc/autograd/profiler_python.cpp:1102), and the Engaged flag (c10/util/ScopeExit.h:14) rules out double-execution. The perf argument holds: the removed torch._C._get_torch_function_state() call returns a py::enum_ (torch/csrc/Module.cpp:3479-3486), so it allocated a Python enum instance per guard eval.

Three things below.

Code Quality

The cleanup order is inverted, and that is a behavior change this PR introduces. Before, each exit ran set_disabled_state(old_state) and then _reset_relational_guard_state(). Now the explicit reset runs first (4407, 4414, 4419, 4474, 4484, 4492) and the scope_exit restores the TLS afterwards, so every reset_state() override executes under ALL_DISABLED.

Three of the four overrides are pure C++ (OBJECT_ALIASING at 2684, NO_TENSOR_ALIASING at 2731, SYMBOLIC_SHAPE_GUARD at 2888). The fourth is not: STORAGE_OVERLAPPING::reset_state() (2771) delegates to StorageOverlapChecker::reset(), which Py_DECREFs every tensor it increfed (1664-1670). A Py_DECREF that drops the last reference can run a Python __del__, which would now see TorchFunction disabled. In practice the guard is holding inputs the caller's frame also references, so it almost never holds the last ref — low risk, but it is an unrequested change in an area the PR is otherwise careful about.

The cheap fix is to give the relational reset its own scope_exit declared before the TLS one and drop the eight explicit calls; reverse destruction order then restores the TLS first and resets afterwards, which is exactly the pre-PR ordering. Since #198269 is already going to add that scope_exit, the only thing that matters is that it is declared before restore_torch_function, not after — worth pinning down now so the ordering is restored rather than cemented.

Fix this →

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: StorageOverlapChecker::add() increfs (1660) and only reset() decrefs, _expected_overlapping is fixed in the constructor (1649) and never recomputed, and maybe_check() opens with TORCH_CHECK(_expected_overlapping >= _overlapping.size()) (1679). So a skipped reset leaves the vector over-full, the next evaluation throws out of the accessor tree at that TORCH_CHECK, which skips the reset again — self-perpetuating, with one leaked tensor ref per attempt. SYMBOLIC_SHAPE_GUARD is the soundness one: _args_seen is zeroed only at 2838 or in reset_state(), so a throw after k leaves fires _guard_check_fn (2839) with k slots still holding the previous round's values. The other two (OBJECT_ALIASING, NO_TENSOR_ALIASING) only ever fail conservatively.

Testing

The new test cannot distinguish "restores old_state" from "restores ENABLED". test_tensor_match_guard_throw_restores_torch_function (test/dynamo/test_guard_manager.py:526-556) snapshots _get_torch_function_state() at the default and compares after the raise. It does catch a missing restore — without the scope_exit the state would be ALL_DISABLED — but the captured-old_state half of 4398-4404 is the only thing distinguishing this from a hardcoded reset, and it is untested. Wrapping the two assertRaisesRegex blocks in torch._C.DisableTorchFunctionSubclass() (or setting _TorchFunctionState.SUBCLASSES_DISABLED) and asserting SUBCLASSES_DISABLED comes back covers it for two lines.

Fix this →

Two notes on what the deleted GuardManagerWrapperTests covered, neither of which is a real loss: the parametrize over check/check_verbose is now covered inline by the single test hitting both, and the KeyboardInterrupt case no longer has a distinct meaning, since scope_exit is exception-type-agnostic where the wrapper's except BaseException had to name it. The stub-root test going away is correct — it was testing the wrapper mechanism, which no longer exists.

The removed top-level imports (GuardManagerWrapper, parametrize, instantiate_parametrized_tests) are all genuinely unused now; the two remaining GuardManagerWrapper uses at :878 and :1532 are function-local imports.

Recommendation

Approve

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 scope_exit is declared before the TLS one, and the test strengthening is two lines. I would fold both in rather than leave them, but would not hold the PR on either.

| Branch: `gh/bobrenjc93/1466/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks. Dispositions against the current head 74fc3a1 (the review ran on the first head):

_reset_relational_guard_state() is the same bug, left in place -- Fixed in #198269, stacked directly on this PR: one c10::make_scope_exit per function, declared right after Py_BLOCK_THREADS so it also covers the leaf-guard early return, with the eight explicit calls dropped. Kept as its own PR because it is a separate behavior change (guard results on the next check, plus the STORAGE_OVERLAPPING leak) that deserves its own regression test rather than riding on the perf fix; this PR's description now says so. If you would rather see it folded in here, say so and I will.

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 ALL_DISABLED; the only reset that touches Python is StorageOverlapChecker::reset's Py_DECREF, and a tensor dealloc does not dispatch through __torch_function__, so it is harmless for the one commit it lasts. The description of #198269 spells this out.

Dict-tag recording has the same shape -- Declined for this stack. check_nopybind_template calls reset_dict_tag_recording_variables() on entry, so the stale _is_recording_dict_pointers / _current_tag_safe_root / _recorded_tensor_metadata last only until the next check of the same root, and check_verbose never records. It is a real third instance of the pattern, but it lives in GuardManager::check_nopybind, not in the two root exits these PRs touch. Happy to do it as a third PR if wanted.

The restored comment is inaccurate -- Fixed in 74fc3a1: the "Only needed for debugging purposes" comments are gone; check and check_verbose are bare delegations.

Testing: nothing exercises what the tree leaves behind after a throw -- Fixed in #198269: test_relational_guard_state_resets_after_the_tree_throws installs NO_TENSOR_ALIASING across two managers, throws out of the second one's TENSOR_MATCH, and asserts the throw repeats on the next check and check_verbose instead of the stale "Duplicate tensor found" failure. It fails with "RuntimeError not raised" on this PR alone.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

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 scope_exit right after Py_BLOCK_THREADS, before restore_torch_function, so reverse destruction runs the TLS restore first and the reset second, the pre-stack order. Not folded in here: doing so would be #198269's whole change. For the one commit where this PR stands alone, the only reset that touches Python is StorageOverlapChecker::reset's Py_DECREF, and a tensor dealloc does not go through __torch_function__, so the window is harmless.

Note for the follow-up: STORAGE_OVERLAPPING degrades worse than a spurious recompile -- Fixed in #198269: test_storage_overlapping_guard_state_resets_after_the_tree_throws pins exactly that mode. Against this PR alone it fails with the checker's own Expected _expected_overlapping >= _overlapping.size() to be true, confirmed on a build with the parent's guards.cpp swapped in.

The new test cannot distinguish "restores old_state" from "restores ENABLED" -- Fixed in 64b88bc: test_tensor_match_guard_throw_restores_torch_function now runs both throws inside torch._C.DisableTorchFunctionSubclass(), asserts the entry state is SUBCLASSES_DISABLED, and asserts that state is what comes back after each throw.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 1m 26s —— View job


The scope-exit restore is correct at head 64b88bc, the strengthened test now pins the captured old_state rather than a hardcoded ENABLED, and I found no new problems — the only thing still open is the cleanup-order inversion, which is genuinely #198269's change and is dispositioned.

Full review

PR Review: #198264

Summary

Moves the TorchFunction TLS restore in RootGuardManager into a c10::make_scope_exit and reverts GuardManagerWrapper.check/check_verbose to plain delegation. Re-reviewed at 64b88bc (previous rounds ran on c1954e1 and 74fc3a1). Verified against the current head:

  • Placement. Both scope exits are declared after set_disabled_state(ALL_DISABLED) and before the first accessor call (guards.cpp:4399-4402, :4461-4466), so the leaf guards — GLOBAL_STATE and the TorchFunction mode-stack guard, which need the unmodified state (:4449-4451) — still run outside the disabled window, as they did before. All six explicit set_disabled_state(old_state) calls that the scope exits subsume are gone, and no exit is left without a restore.
  • Safety during unwinding. The lambda is a single thread_local store, needs no GIL, cannot throw. lock_guard is declared earlier (:4373, :4437) so it still releases last; Py_BLOCK_THREADS has already run at both declaration points, so no Py_UNBLOCK_THREADS window is crossed.
  • Coverage. Strictly wider than the wrapper it replaces: run_root_guard_manager on the eval-frame path calls check_nopybind directly and was never covered by the Python try/except.

Verified dispositions

Comment accuracy — confirmed fixed: torch/_dynamo/guards.py:779-783 are bare one-line delegations with no "debugging purposes" wording.

Test strength — confirmed fixed at test/dynamo/test_guard_manager.py:549-560. Both throws now run inside torch._C.DisableTorchFunctionSubclass(), so old_state is SUBCLASSES_DISABLED and restoring the captured value is distinguishable from resetting to ENABLED. The assertEqual(state, SUBCLASSES_DISABLED) on entry is doing real work, since __enter__ only downgrades from ENABLED (torch/csrc/utils/disable_torch_function.cpp:56-59) — if an earlier test leaked ALL_DISABLED, the test fails loudly instead of silently reverting to the weaker assertion. The context manager restores on exit, so no TLS leaks to later tests.

Dict-tag recording, declined — the disposition checks out, so I withdraw that item for this stack. start_recording_dict_pointers / stop_recording_dict_pointers are only reached from GuardManager::check_nopybind (guards.cpp:3827, :3847); nothing on the verbose path records, so the missing reset at verbose entry cannot observe a stale flag set by verbose itself, and check_nopybind_template's entry reset (:4378) bounds the non-verbose case to the next check of the same root. Out of scope here.

Code Quality

The reset-under-ALL_DISABLED ordering change is the one thing this PR introduces and does not fix. _reset_relational_guard_state() (:4406, :4413, :4418, :4472, :4482, :4490) now runs before the scope exit rather than after the explicit restore, so StorageOverlapChecker::reset's Py_DECREF (:1668) can run a dealloc under ALL_DISABLED. Agreed this is harmless — tensor deallocation does not dispatch through __torch_function__ — and agreed that fixing it here would be #198269's whole diff. The only thing that matters is that #198269 declares the relational scope_exit before restore_torch_function, which the stated plan (right after Py_BLOCK_THREADS) does, giving back the pre-stack order under reverse destruction. Nothing to change in this PR.

Recommendation

Approve

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 py::enum_ allocation per eval (torch/csrc/Module.cpp:3479-3486). Land it with #198269 behind it.

| Branch: `gh/bobrenjc93/1466/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1466/head branch November 29, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants