Repository navigation
[precompile] Precompile summary types and the guard-drop policy vocabulary - #195917
Closed
bobrenjc93 wants to merge 57 commits into
Closed
bobrenjc93 wants to merge 57 commits into
bobrenjc93 wants to merge 57 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195917
Note: Links to docs will display an error until the docs builds have been completed. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 3, 2026
Closed
Closed
Closed
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93
added a commit
that referenced
this pull request
Sep 9, 2026
ExtraState's cache had no lock, and lookup() walks it while evaluating guards, which run Python, so the GIL can drop mid-iteration and another thread can clear the list being walked. Once precompile artifacts are installed and unloaded on live code objects at runtime this is no longer survivable. ExtraState now has a recursive cache_mutex taken through CacheLock, which try-locks first and releases the GIL only when it must wait, so a waiter holding the GIL cannot wedge the owner that needs it. lookup() and try_lookup_without_guard_eval() hand back a new reference to the cached code and copy trace_annotation out under the lock, and the frame evaluator holds that reference before anything that can drop the GIL. Evictions that arrive under a live lookup park instead of splicing the list being walked: invalidate() (reached from weakref.finalize) never blocks and re-locates its entry by guard-manager identity, so its binding no longer takes the raw CacheEntry pointer, and reset_code and the region/precompile resets park on the state when cache_python_depth is non-zero, applied by the next depth-zero holder. reset_code empties the state in place (clear_in_place) rather than destroying a mutex another thread may be parked on. The default exec strategy moves into a lock-free std::atomic with a generation token behind get/set_with_token/compare_and_set bindings, the current isolate_recompiles_id becomes thread-local, precompile entries carry a region and an owner token, and get_backend honours a backend's _torchdynamo_cache_key behind a one-way gate. The Python side of the region/owner bindings follows in the next commit; guards.py only adopts the new invalidate() signature. Every path that hands cache state out does so under the lock: create_cache_entry fills the new entry's code (owned) and trace annotation for its caller before releasing, so the frame evaluator never dereferences the entry once a concurrent clear could destroy it; _load_precompile_entry builds its PrecompileEntry (which runs Python) before taking the lock and drains parked evictions before appending, so a parked CLEAR_ALL cannot eat the install; and _debug_get_precompile_entries raises the Python depth around its casts, so a package finalizer reached from GC parks its eviction instead of splicing the list being walked. remove_from_cache takes compile_lock like torch._dynamo.reset(), which is the contract reset_extra_state's header states. Test Plan: This is the C++ locking change; it carries no tests of its own. Its concurrency/contract coverage is added one commit up in #196120 (see the FAQ), which adds ~787 lines to test/dynamo/test_recompile_ux.py. Verified at the stack head by: ``` python test/dynamo/test_recompile_ux.py python test/dynamo/test_package.py python test/test_precompile.py ``` Authored with an AI assistant. FAQ Q: update_diff_guard_root_manager is a Python-reachable mutator that reassigns diff_guard_root_mgr as a raw pointer, and the lock-free lookup() window dereferences that field. Isn't that an unlocked write racing a lock-free read? A: Reachable only under skip_guard_eval_unsafe with two threads recompiling one code object concurrently, and it predates this PR -- base lookup() held no lock at all. The lock added here reasons about node lifetime during guard evaluation, not about this field's stability under concurrent recompile; closing that window means taking cache_mutex in the binding (it runs at compile time, so the cost is irrelevant) and is tracked as a follow-up. The comment scope is narrowed to say so rather than implying the field mutation is already covered. Q: Six sites still hold cache_mutex across arbitrary Python (create_cache_entry's py::cast, the debug enumerators, drain_pending_invalidations), so the lock-ordering invariant the header claims holds only for guard evaluation. Isn't the header over-claiming? A: The mitigation this commit lands does cover the hot path -- guard evaluation under lookup() -- with one named residual on the frame-eval path: the parked-invalidation drain lookup() runs at cache_python_depth 0, whose decrefs of the old guard_manager can fire a user __del__ under the lock (extra_state.h says exactly this); every other Python-under-cache_mutex site runs only at compile/debug time. Rather than the full snapshot-release/park treatment of all six (which needs care around user __del__ and backend __eq__), the header claim is narrowed to state the mitigation covers guard evaluation and to name the knowingly-exempt sites. Q: This locking commit ships no tests of its own. Where is the coverage? A: Added in the sibling commit, not missing. This ghstack splits the C++ locking change from its concurrency/contract suite so each reviews on its own; the 14 tests (~787 lines) are added in "[dynamo] Concurrency and contract tests for the ExtraState lock" (#196120), later on this same stack, in test/dynamo/test_recompile_ux.py. This commit's own diff touches no test files; the stack head has the full coverage. The deterministic (single-threaded) pin a reviewer would want for the park/drain path is there too: test_region_clear_from_inside_a_lookup_is_parked drives a CLEAR_ALL from inside a live lookup via a backend __eq__ hook and asserts the next depth-zero lookup drains the parked clear before it scans candidates, with no TORCH_CHECK fired; and the drain-before-read contract on _get_total_cache_entry_count / _debug_get_cache_entry_list is asserted across that suite. Q: The region/ownership bindings this commit adds (14 of them, plus _torchdynamo_cache_key / _torchdynamo_force_callback_on_cache_miss) have no caller anywhere. Why add dead surface? A: The consumers are higher in this stack, in the commits the reslice split these bindings away from. Concretely, _get_cache_entry_count_for_region is imported and called in convert_frame.py by #195913's capture/serve accounting (total_count -= _get_cache_entry_count_for_region(code, region_id)), and the region/owner install bindings by the precompile install/package layer above that. The reslice deliberately keeps the C++ bindings with the locking change they belong to rather than splitting a binding from its lock, and the stack merges atomically, so no released commit ships a binding with no consumer. They read as unused only in this PR's isolated diff. Q: get_backend treats _torchdynamo_force_callback_on_cache_miss = False as still forcing, because it only tests presence. Isn't False surprising? A: Presence-only is intended and matches the hasattr convention these markers use; the attribute is set to opt in and absent to opt out, and its value is not read. Documented as presence-only. Q: reset_code now empties the state in place instead of nulling the extra pointer, so the run-only empty-cache fast path is gone on every reset. Isn't that a permanent hot-path regression? A: The null-out is unsafe once the mutex must outlive parked waiters: freeing the extra state (and its mutex) under a thread parked on that mutex is a use-after-free, so reset drains and clears in place instead. The lost fast path is narrow (an empty cache after reset) and the correctness of not destroying a mutex another thread holds is not negotiable. Correcting the cost characterization from an earlier draft: it is per-frame and permanent, not per-reset. The husk stays attached, so callback.is(Py_False) && extra == nullptr never fires again for that code object; every subsequent run-only frame pays the region-id lookup, the strategy read, get_backend, the callback set, and a CacheLock acquire in try_lookup_without_guard_eval. Measured on this checkout that is ~88 ns/frame over a NULL-extra-state frame (run-only, trivial body, best of 7 x 200k). Small, and it does not outweigh refusing to free a mutex under a parked waiter -- but a pr_time benchmark measures compile time and will never see it, so tracking it needs a run-only-after-reset runtime benchmark, not pr_time. Q: Every intercepted frame with a guarded cache entry now pays two full cache snapshots and two cache_mutex acquisitions (try_lookup_without_guard_eval then lookup, each snapshotting every entry in both buckets) where base held no lock and allocated nothing. Bound the snapshot to the first backend match, and skip building it when a precompile candidate was found. A: The doubled snapshot+acquire on the guarded-hit path is real and structural (distinct from the ~88 ns run-only-after-reset figure above, which does not cover this path). The bounded-prefix half of the suggestion is unsound as stated: backend_match runs lock-free after cache_mutex releases (that release before guard/backend evaluation is the whole point of the snapshot), so the code cannot know which entry is the first backend match while still holding the lock -- it must capture a complete, stable snapshot and decide hit-vs-fallback afterward. Stopping the snapshot loop early would require running backend_match under cache_mutex, reintroducing exactly the Python-under-the-lock the design removes. The precompile-skip half is a valid micro-optimization (the precompile branch returns before cache_candidates is read), but both narrowings are subsumed by the deferred RAII snapshot refactor tracked for this locking work, which collapses the two acquisitions into one and is where the snapshot's shape should be tuned with a runtime benchmark -- not guessed at here, since this checkout cannot build to measure it. Q: The per-region frame_state split changes CompileId.frame_id numbering -- each region now allocates its own frame id for the same code object, shifting tlparse/TORCH_LOGS labels and graph_id_filter's frame_id matching -- and the old comment justified the split by dynamic-shape generalization, which frame_state no longer drives. Why is it here, untested, in a locking commit? A: The comment was stale and is corrected in this pass: the ExtraState frame_state holds only "_id" (the frame-id counter); dynamic-shape generalization moved to PGO's process-global code state, so the split does not touch it. The split is kept deliberately -- an isolated region must number its compiles independently so its tlparse/TORCH_LOGS labels stay coherent instead of interleaving with the default scope. The renumbering is the intended observable; a dedicated test for per-region numbering is worth adding and is tracked, but the behavior is label/id bookkeeping, not guard or cache correctness. Q: When reset() races a lookup on another thread, it parks a CLEAR_ALL (because that lookup holds cache_python_depth > 0) and returns with the cache entries still present and servable. Doesn't that break reset()'s clean-slate contract? A: Yes, reset() becomes asynchronous under this specific race, and this is new with releasing cache_mutex during guard evaluation (the old recursive mutex would have blocked the peer instead). The window is bounded: every reader that matters (lookup, _get_total_cache_entry_count, _debug_get_cache_entry_list) drains parked evictions before it reads, so the first depth-zero holder wipes the entries and the stale state is never observable from Python afterward. This is documented on clear_in_place where the park happens. Q: `apply_pending_evictions` has a thirteen-fold preamble -- all 13 call sites repeat the same four lines declaring `reaped_precompile`/`reaped_cache`/ `reaped_evictions` before taking `CacheLock`, and `lookup()` now layers a fourth ordering constraint (`reaped_*` before `python_depth`) enforced only by declaration order, which a reformat could break silently. Why not an RAII holder? A: An RAII holder owning the three containers and the lock, draining in its destructor after unlocking, is the right structural fix and would replace the comment-repeated-thirteen-times invariant with something the compiler enforces. It is deferred deliberately: it touches all 13 sites and the drain ordering is subtle enough that folding it into this locking commit would enlarge the diff and the review surface without changing behavior. It is tracked as a follow-up refactor; the current declaration-order discipline is correct, just not structural. Q: `torch/_dynamo/CLAUDE.md:274` still describes `ExtraState` as holding "`frame_state` (dynamic shapes detection)", the same stale claim fixed in `extra_state.h`. Why leave the doc twin stale? A: Out of scope for this commit for a mechanical reason: a `.md` file under `torch/_dynamo/` cannot be included in a commit here without crashing the IMPORT_LINTER CI lint, so the doc twin cannot be touched from this stack. It is noted so a maintainer can correct it in a separate, lint-safe change; the load-bearing description in `extra_state.h` is already fixed. Q: The region-exact lookup has no fallback to the default -1 bucket. Isn't that a lost entry? A: The region-exact lookup is the target end-state; the region-owned install that passes a real id lands one PR up (#195911). At this commit every install still passes the default id -1 (the region-owned install is #195911, higher in this stack), so the common precompile path is unaffected. The one honest gap is transitional and not covered by "the stack merges atomically": because ghstack lands PRs one at a time, in the window between this PR and #195911 a frame under torch.compile(..., isolate_recompiles=True) gets a region id >= 0 and a loaded CompilePackage on that code object matches nothing, so it falls through to a normal compile (or is rejected under a serving stance that forbids recompiles). This is deliberate -- keeping a -1 fallback here only to delete it in #195911 would churn the exact bytes this PR establishes -- and in that window (TORCH_CACHING_PRECOMPILE=1 plus isolate_recompiles=True, both public knobs, so the combination IS reachable) the consequence is a recompile instead of a served entry, or a fail_on_recompile error -- whose message, until this round, listed precompiled guards the region-exact lookup never evaluated. That message now filters the entries it prints by the frame's region (the filter #195915 lands, pulled forward), so it blames the miss on nothing; rejecting the combination outright was rejected because a hard error where base worked is worse than a recompile. #195911 closes the window by installing into the context's region. A permanent test cannot pin the miss, since by the stack head the same frame is a hit. Q: drain_pending_invalidations does a Py_INCREF on orig_code. Can that resurrect a freed code object? A: No. drain runs only at cache_python_depth 0, and every caller holds orig_code alive for the duration -- the intercepted frame or the pybind handle owns a reference -- so the INCREF always sees a live object. The invariant is documented above drain_pending_invalidations. Q: The cache counter (and use_lru) is a plain integer/bool, not an atomic. Isn't that a race? A: No, though the earlier phrasing of this answer overreached. It holds for total_cache_entry_count, which is only ever touched under cache_mutex. use_lru is looser: its setter takes no lock while the reads (create_cache_entry, both move_to_front sites) are under cache_mutex. It is still safe -- a tearing-free bool set once from a config knob -- so a plain type is correct, but the justification is "benign unsynchronized publish of a config flag", not "always under the lock". Q: eval_frame_cpp.cpp does not check the PyUnicode intern for NULL. Bug? A: It degrades safe: a NULL intern falls back to the slow lookup rather than crashing, so it is a nit, not a correctness hazard. Q: The PyThread_tss_set return value is ignored. A: Intentional. The only failure mode is TSS-key-not-created, which cannot happen after module init creates the key, and there is no meaningful recovery on a per-frame hot path. Q: compare_and_set_code_exec_strategy returns False when the code object has no ExtraState, but get_code_exec_strategy_token reports generation 0 for an absent state and set_code_exec_strategy_with_token creates one on demand. Can't a read-then-CAS sequence then never succeed on a code object Dynamo has not intercepted yet? A: In the abstract yes, but no real caller hits it, and auto-creating the state inside the CAS is worse. Every installer establishes state through set_code_exec_strategy_with_token (which bumps the generation above 0) BEFORE it ever calls compare_and_set, so the token it reads is never the absent-state 0. Making the CAS create-on-absent was tried and reverted: init_and_set_extra_state aborts if state already exists (a TOCTOU under concurrent first-touch), and creating an ExtraState during a CAS resurrects state on a code object mid- teardown. The absent-state case is genuinely "nothing to compare against", so returning False -- caller re-reads, sees generation 0, and installs via set_code_exec_strategy_with_token -- is the correct contract, not a lost race. Q: The deferred-drain caveat's FAQ scopes the freed-snapshot window to "a third thread", but ConvertFrameAssert.__call__ reaches it with the compiling thread itself doing the freeing: it calls _get_cache_entries_for_region (twice, in the isolate_recompiles_id >= 0 branch) and _get_total_cache_entry_count back to back, each running apply_pending_evictions, while holding non-owning py::cast wrappers from the first call; a parked CLEAR_ALL applied by the second call at depth 0 then frees the nodes behind those wrappers, and compute_cache_size reads a freed node. compile_lock does not cover this prologue. A: Correct, and the self-inflicted variant sharpens the caveat: the freeing thread is the caller, not a third one, and the isolate_recompiles_id >= 0 branch is the shortest path because it puts two drain-on-read calls in one statement with the first result still live. The durable fix is the one the header already names -- hand back owning references from _get_cache_entries_for_region the way lookup()/create_cache_entry now do -- which closes both the third-thread and the self-inflicted forms; short of that, draining once per __call__ or raising cache_python_depth across the whole prologue removes the self-inflicted variant. The finding is latent (no in-tree caller drives concurrent region reads against a parked CLEAR_ALL yet) and the fix is C++ on the cache-lifetime path, which cannot be authored or validated without a build here, so the caveat text is corrected to drop the "third thread" scoping and the owning-reference fix is tracked as follow-up. Q: install() can finish with zero precompile entries: it drains then pushes, so if a concurrent lookup holds cache_python_depth raised, install()'s own uninstall parks a PRECOMPILE_ALL that the drain cannot apply, the pushed entry lands behind it, and the next depth-zero holder splices it away -- the package installs and serves nothing. The install-park comment also pointed at a PR FAQ that did not exist. A: Real. The comment is corrected to describe it precisely (install defeating its own install under a concurrent lookup) and to drop the dead FAQ pointer. It is the same non-owning / deferred-drain class as the caveats below: the durable fix is C++ on the cache-lifetime path -- park the install behind the parked eviction, or stamp installs with a sequence so a drained PRECOMPILE_ALL only removes entries older than itself -- and cannot be authored or validated without a build here. Latent: no in-tree caller drives a concurrent lookup against a self-parked PRECOMPILE_ALL yet. Tracked with the owning-reference follow-up, #196394. Q: Parked evictions get no candidate-side filter. drop_pending_invalidated_candidates keeps a parked invalidation from serving, but there is no equivalent for parked evictions, so _reset_precompile_entries / _clear_cache_entries_for_region can return having removed nothing while in-flight lookups keep serving -- and since uninstall() pops the installed globals first, a stale serve LOAD_GLOBALs a name that is gone (NameError). A: Real, and not a regression (base cleared the list under the iterating thread, a UAF). The symmetric one-line candidate-side eviction filter is the right fix and is the same C++ cache-lifetime change deferred above. The uninstall() global-pop ordering is separately addressed on the Python side by resetting entries before popping globals (see #195911's teardown-loop swap). Deferred here because the only observable consequence is unreproduced and the filter cannot be built or validated in this environment. Tracked with #196394. Q: extract_cache_entry is the one remaining borrowed-CacheEntry* handout: it returns &it->second.front() after the reaped_* locals (whose destructors run Python) go out of scope, and dynamo__custom_eval_frame hands that pointer to dynamo_call_callback, which ConvertFrameAssert.__call__ carries through the whole _compile at depth 0 with cache_mutex unheld. The header caveat and the FAQ name only _get_cache_entries_for_region. A: Correct -- same shape, same fix. The extra_state.h caveat now names extract_cache_entry alongside _get_cache_entries_for_region as needing owning references. The fix is C++ on the cache-lifetime path and is deferred with the rest of that class; it cannot be authored or validated without a build here. Tracked with #196394. Q: _has_precompile_entries is the one region-taking binding without a `region_id >= -1` TORCH_CHECK_VALUE, while every sibling got one -- and it runs on every served call. Isn't it the odd one out? A: Yes, and the omission is benign. An out-of-range id (say -5) simply fails the `entry.isolate_recompiles_id ==` comparison and the function returns false, the same result as any valid id with no matching entry -- there is no buffer indexing or negative-index hazard behind it, unlike the paths that guard. Adding the check to match the sibling sweep is correct and belongs with the other C++ range-check hardening tracked in #196394 (this stack cannot build C++ to verify a behavioral C++ change in isolation); it is a consistency nit, not a correctness gap, and the hot-path comment already notes the function does no Python and takes no lock. Q: `_load_precompile_entry`'s comment calls the install-defeats-itself race "a tracked follow-up" with no link, and it reproduces: under a concurrent lookup a raw `_reset_precompile_entries` + `_load_precompile_entry` sequence parks a PRECOMPILE_ALL that the pushed entry then lands behind, so the install serves nothing. A: Real at this commit for that raw sequence, and closed for the only production caller one PR up: #195911 keys `CompilePackage.uninstall()`'s eviction by owner token and mints a fresh token per install, so the parked owner eviction cannot eat the reinstall (`test_reinstall_survives_an_eviction_parked_by_uninstall` in #196120 pins it). The raw sequence still loses and is now listed in #196394 (sequence-stamping evictions is a C++ change that needs a build to verify); the comment now says both. Q: This diff introduces a parked-eviction state machine, a GIL-releasing recursive cache lock, thread-local region ids, per-region frame state and 12 new bindings, and its only test change is a docstring. Nothing here exercises any of it. A: The coverage is one PR up, in #196120, one test per bullet of the ask: eviction parked behind a live lookup then applied by the next depth-zero holder (`test_region_clear_from_inside_a_lookup_is_parked`, `test_precompile_reset_from_inside_a_lookup_is_parked`); reset_code from Python run by a guard (`test_reset_code_from_python_run_by_lookup_is_safe`, plus the skipped racing variant tracked in #196394); invalidate mid-lookup (`test_invalidation_racing_an_in_flight_lookup_parks_and_drains`, `test_invalidate_targets_the_entry_by_guard_manager_identity`); install after a parked reset (`test_reinstall_survives_an_eviction_parked_by_uninstall`); the thread-local id (`test_isolate_recompiles_id_is_thread_local`); and the CAS's stale generation across reset_code (`test_exec_strategy_token_and_compare_and_set`). They live in the next PR so this one stays a reviewable C++ change under the size gate. Q: `torch._dynamo.reset()` now returns with a code object's cache entries still present and servable whenever any thread is inside a lookup on it. That changes a public API's contract; it should be an explicit decision, not only a C++ comment. A: Agreed, and now stated where users read it: `torch._dynamo.reset()`'s docstring carries an NB describing the asynchronous clear under a concurrent lookup and pointing at `clear_in_place`. Making the clear synchronous (wait for depth zero, or gate the Python-side clear on the C++ clear having applied) stays deferred in #196394. Q: Per-region `frame_state` makes the `frame_compile_id >= accumulated_recompile_limit` fallback per-region, removing the only backstop for non-growing recompiles (invalidated guard managers), and grows `FRAME_COUNTER` / `FRAME_COMPILE_COUNTER` per (code object, region) -- measured +20/+20 for 20 `isolate_recompiles=True` wrappers of one function. A: Correct, and the header comment says so verbatim. The growing case stays capped globally by `total_cache_entries_all_regions`; the escape is exactly region-minting loop plus invalidated guard managers. A per-code-object limit counter kept separate from the per-region display id is the fix; it is filed as #196495 and cited from the comment rather than folded into this locking change. Q: `_torchdynamo_force_callback_on_cache_miss`, `_torchdynamo_cache_key` and `_enable_precompile_cache_keys` have no producer at this commit, so the marker lookup, the run_only override and the recursive_callback demotion skip on the per-frame hot path are unreachable here. A: Their producers are higher in the stack: `_torchdynamo_force_callback_on_cache_miss` is set by `eval_frame.py`'s fail_callback under the serving stance (#195915); `_enable_precompile_cache_keys()` and `_torchdynamo_cache_key` are set by `precompile_package.py` (#195917); and #196120 pins them (`test_force_callback_on_cache_miss_marker_overrides_run_only`, `..._reaches_a_recursive_frame`, `test_cache_key_lookup_is_off_until_a_cache_key_backend_exists`). The C++ lands first so each consumer is a Python-only change. Q: The `compile_lock` requirement is enforced on one of three spellings of `reset_code`: the raw `torch._C._dynamo.eval_frame.reset_code` and `torch._dynamo.decorators.reset_code` (re-exported by the `dir()` loop) bypass it. A: Fixed for the trap that mattered: `decorators.py` no longer re-exports the raw binding (its TYPE_CHECKING import is gone and the loop skips the name), so `torch._dynamo.reset_code` -- the wrapper that takes the lock -- is the one Python-level spelling. Renaming the C binding to `_reset_code_unlocked` is the structural version and touches init.cpp/.pyi; nothing in-tree calls the raw spelling, so it is left for a build-verified follow-up. Q: `_reset_precompile_entries_for_owner` uses `PyCode_Check` "matching the sibling bindings added in this commit", but `_clear_cache_entries_for_region` and `_reset_precompile_entries_for_region`, added in the same commit, use the `py::module::import("types")` form. A: Fixed: both now use `PyCode_Check`, and the comment says the pre-existing bindings keep the import form (converting them would add lines for no behavior). Q: The `drop_pending_invalidated_candidates` comment reads as if it closes the wrong-graph hazard, but an `invalidate()` that arrives after `lookup()` releases `cache_mutex` parks and the in-flight lookup can still serve the entry it named. A: Comment fixed to say exactly that: the filter covers invalidations parked BEFORE the snapshot; a later one rides to the next lookup. Q: `lookup_optional`'s NULL-name branch returns without `PyErr_Clear()` although a failed `PyUnicode_InternFromString` leaves a MemoryError set, breaking the "WITHOUT raising" contract, and its comment says the statics are initialized "at module init" when they are function-local. A: Both fixed: the branch clears the error and the comment says "on its first call". Q: `CacheCandidate` is defined twice (`lookup` and `try_lookup_without_guard_eval`); `fullgraph_compiled_frame_count` is consulted per frame with no comment on its process-global scope; three readers skip the parked-invalidation filter. A: The duplicate struct is a mechanical hoist that changes no behavior; it is left for the owning-reference follow-up (#196394) that reworks the same two functions, since C++ cannot be compiled here. The frame-count comment is a one-line nit left as is. The three readers (`_get_cache_entries_for_region`, `_get_total_cache_entry_count`, `_debug_get_cache_entry_list`) feed recompile reporting, accounting and the collective gate, never serving, so a parked invalidation cannot make them serve a wrong graph. Q: pr-sanity-checks is red -- this commit is 2027 lines. A: Trimmed under the gate by condensing the longest added comment blocks (same facts, fewer lines) and by the `PyCode_Check` conversion above, while absorbing the reset() docstring, the decorators.py fix and the two comment additions this round asked for. Q: Once `_enable_precompile_cache_keys()` fires, `get_backend()` returns the cache key, so `CacheEntry::backend` holds the key while Python's `innermost_backend` only follows `_torchdynamo_orig_backend`; `get_guard_fail_reason_helper` then reports "different backend callables. Cached backend: str ..." with functools.partial advice. A lying diagnostic? A: Yes, for the description only: the classification is right (a key mismatch IS a backend mismatch) and the C++ `backend_match` compares key-to-key, so no wrong graph is served. Fixed here at the site named: `describe_backend` renders a non-callable cached side as its `_torchdynamo_cache_key`, the reason says "backend cache keys" instead of "callables", and `_CacheEntry.backend` is typed `object` in the .pyi to match the header's "must not assume callable". Rendering the NEW side as a key needs the un-unwrapped callback chain (a Python twin of `get_backend`), which lands with the only producer, `_PrecompileBackend` in #195917, together with a recompiles-log test; it has no producer at this commit. Q: The `_has_precompile_entries` comment says no Python runs and the CacheLock wait is the only place the GIL can drop, but the drained nodes' destructors (`~CacheEntry` sets `guard_manager.cache_entry`, `~PrecompileEntry` drops three py::objects) run Python once the lock releases, and the read-looking predicate drains a parked CLEAR_ALL as a side effect on every served call. A: Comment corrected on both counts: no Python UNDER the lock; the call drains parked evictions first (a parked CLEAR_ALL empties the cache there, the drain-before-read contract every reader follows) and the reaped nodes die after the lock releases, where their destructors can run arbitrary Python. Q: `drain_pending_invalidations` destroys its drained py::objects under `cache_mutex` (a parked entry's old guard_manager can be the last reference, so arbitrary user `__del__` runs under the lock), unlike its two siblings that hand their records out to die after the lock. Unintentional asymmetry? A: The hazard is the one the lock-ordering comment in extra_state.h already names and accepts (a hot-path drain is rare); the asymmetry is real and the `dead_invalidations` out-param at the eight call sites is the right symmetric fix -- it belongs with the RAII reaper-holder rework tracked in #196394 (C++ that cannot be built or verified here). A `CachePythonDepth` spanning `pending` would not fix the ABBA (Python still runs under the lock); it only turns a re-entrant reset from apply into park, unnecessary at depth 0 with no live iteration. Q: On the guard-error returns, `e.restore()` runs before the `reaped_*` containers die, so their Python destructors run with an exception set. A: Real and latent (it needs a parked region/precompile eviction drained in the same lookup plus a raising guard in a surviving bucket). The mechanism differs from the review's: `cache_entry`/`extra_state` are plain instance attributes of `GuardManagerWrapper`, not pybind setters, so nothing terminates; the risk is that a generic setattr's `_PyType_Lookup` can clear the pending exception on a method-cache miss, so `lookup()` returns NULL without an exception set and the frame raises SystemError instead of the guard's error. The fix (restore after the reaped nodes die, or clear them before `e.restore()`) is C++ and is tracked in #196394; the comment above the declarations now records it. Q: `id + 2` in `int64_t` is signed-overflow UB for `INT64_MAX`, reachable through the private binding; the ASAN job builds with `-fno-sanitize-recover`. A: Fixed on both sides of the TSS round trip with unsigned arithmetic (`(uint64_t)id + 2` on the write, `(uint64_t)(uintptr_t)value - 2` on the read); cast-only C99, unreachable from torch.compile. ghstack-source-id: 971bf56 Pull-Request: #195355
[ghstack-poisoned]
[ghstack-poisoned]
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Stack from ghstack (oldest at bottom):
The pure-function half of the multi-graph capture, ahead of the session that
drives it. torch/compiler/_precompile_types.py holds the public dataclasses:
ExampleInput (one capture call with keywords), GuardFact, FrameInvariants and
PrecompileSummary, whose
completealso checks that at least one backendgraph was compiled, since allow_empty_graphs lets a frame that compiled nothing
count as one guarded code.
torch/_dynamo/precompile_package.py starts with everything the session will
consult but that is testable on its own. The default serialization filter
drops only the identity guards that cannot be serialized, and a caller's filter
composes with it rather than replacing it. The risky-drop lint decides whether
losing an identity guard can plausibly change results by intersecting the
binding SITE with who owns the value: a read off a namespace torch or the
stdlib owns, a builtin read the ordinary way, or a def bound to its own name
in its own file is waived; instance attributes, closure cells, aliased imports
and registry lookups are not. Ownership is decided by where a module RESOLVES
to, not by its name, because stdlib names are a collision away from a third
party. The guard-type classification splits GuardBuilder's methods into four
disjoint sets -- shape-bearing and semantic guards that are never dropped,
unmodelled state that is never compared, no-op markers, and the only types the
invariance policy may drop -- and
varying_guard_slotsfinds the slotsthat actually discriminate between captured variants. Guard facts are rendered
with addresses and Dynamo's per-process counters normalized away so a report
diffs clean across runs.
Test Plan:
Authored with an AI assistant.
[no ci]