Repository navigation
[dynamo] Region-owned precompile install and the concurrency stress suite - #195911
bobrenjc93 wants to merge 54 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195911
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. |
|
@claude /pr-review |
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 41m 10s —— View job Re-reviewed at Full review of #195911 (twentieth pass)PR Review: #195911SummaryAdds a per-install owner token, per-package resume-global renaming, Verified fixedRecorded so they are not re-litigated. I re-derived each rather than taking the summary.
Code Quality
Testing
RecommendationRequest Changes — narrowly, for one line. Everything else in this round holds up under checking: the fallback teardown is correct and cannot itself raise, the warm-load fallback test is well-targeted, the reinstall test's hook gate closes a real vacuity, and CI at Previously investigated and dismissedRecorded so they need not be re-litigated: the stale-finalizer window on reinstall ( |
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
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
Test Plan:
```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```
The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (The C++ guard tree never propagates --
`check_nopybind` clears and returns false -- so today's raisers are Python-side,
`prepare_f_locals` / `bind_locals`, which would fail the call for the same input
anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
ghstack-source-id: 6fed4ac
Pull-Request: #195354
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
Test Plan:
```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```
The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.
A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.
Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.
A: The user guide now says both: the attribute is read off the callable handed to
`torch.compile` or that callable's `compiler_fn` (so for `aot_autograd(fw_compiler=
...)` it goes on the returned object), only the literal False counts, and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.
Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.
A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.
Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.
A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".
Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.
A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.
Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.
A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.
Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.
A: `cached[:4]` now.
Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.
A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.
Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.
A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.
Q: No test where an opted-out result's guard evaluation raises.
A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.
Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.
A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.
ghstack-source-id: 2b8291a
Pull-Request: #195354
[ghstack-poisoned]
|
@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description). |
|
Claude finished @bobrenjc93's task in 21m 34s —— View job Re-reviewed at Full review of #195911 (twenty-first pass)PR Review: #195911SummaryAdds a per-install owner token, per-package resume-global renaming, Verified fixedRecorded so they are not re-litigated. The interdiff against last round is small (six content hunks), so I re-derived each claim rather than restating.
Testing
Code Quality
RecommendationRequest Changes — narrowly, for the test. The fix itself is right, and I verified it rather than taking the summary: the What blocks is that a bug fix arrived without an effective regression test: CI at Previously investigated and dismissedRecorded so they need not be re-litigated: the stale-finalizer window on reinstall ( |
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
Test Plan:
```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```
The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. The two branches now use predicates fitted to their
inputs: the raising branch tests `kind == "KeyError" and "G['" in detail` (a raised
KeyError stringifies to the bare `"G['NAME']"`, so the verbose-report text
`"KeyError on G["` can never appear there) and the non-raising branch keeps
`"KeyError on G["` over the verbose parts. They are intentionally different, not
drift.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.
A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.
Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.
A: The user guide now says both: the attribute is read off the object passed as
`backend=` to `torch.compile` (a registered name resolves to its function first),
so for `aot_autograd(fw_compiler=...)` it goes on the returned `AotAutograd`
object and not on `fw_compiler`; only the literal False counts; and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.
Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.
A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.
Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.
A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".
Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.
A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.
Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.
A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.
Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.
A: `cached[:4]` now.
Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.
A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.
Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.
A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.
Q: No test where an opted-out result's guard evaluation raises.
A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.
Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.
A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.
Q: The docs say the attribute is read "off that callable's compiler_fn when it
is a wrapper", but `aot_autograd()` returns an `AotAutograd` whose `__name__` is
"compiler_fn" and which has no `compiler_fn` attribute. Which wrapper is meant?
A: Only torch.compile's own `_TorchCompileWrapper`, which stores the user's
backend as `.compiler_fn`; the one-hop getattr exists to see through it.
`AotAutograd` is never unwrapped (it IS the wrapper's compiler_fn), so the docs
now state the rule without naming an internal: set it on the object passed as
`backend=`. One limit for the record: `torch._dynamo.optimize("name")` with a
registered NAME string never resolves the name before classifying, so a
declaration on the registered function is honoured only through
`torch.compile`; the string path falls back to the name blacklist (fail-closed,
native).
Q: The mismatch RuntimeError prints the full six-tuple, so a 256-vs-None
simdlen/march tail can read as the cause while the remedy names cpp.simdlen.
A: The tail is diagnostic on purpose (`_cpu_codegen_target_problem`'s docstring:
simdlen and march stay in the recorded tuple for diagnostics but do not gate),
and the `problem` sentence appended to the same error names the exact gating
component (machine, or ISA/width/macros) with both values, so the cause is
stated next to the tuple. Labelling the two trailing fields is a wording
refinement left for follow-up.
Q: Neither shipped store reload path is exercised for the package flag.
A: The kwarg threading through `DynamoStore.load_package` /
`load_and_install_package` lands in #195913, which owns that seam; the test
belongs there (noted for that PR's next round), not in this commit whose reload
sites are unchanged.
ghstack-source-id: bdfdf3539edd4d29fcd1a3b27d39bde4cc837bad
Pull-Request: https://github.com/pytorch/pytorch/pull/195354
[ghstack-poisoned]
|
@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ). |
|
Claude finished @bobrenjc93's task in 55m 54s —— View job Re-reviewed at Full review of #195911 (twenty-second pass)PR Review: #195911SummaryStamps every precompile install with a per-install owner token and renames resume globals per package so two packages loaded from one artifact coexist on a shared code object, plumbs This round's deltaThis PR's own contribution moved by exactly 21 content lines across three hunks (interdiff of
Base update Also fixed in the base, and worth recording since it was an open inline thread: the Verified fixedRecorded so they are not re-litigated. I fact-checked the test rather than taking the summary, because it was vacuous once already.
Code Quality
Testing
RecommendationApprove. The blocker from my last pass is closed, and I verified it rather than accepting the claim: the rewritten test now installs onto the shared The three carried residuals — CI at Previously investigated and dismissedRecorded so they need not be re-litigated: the stale-finalizer window on reinstall ( |
Stack from ghstack (oldest at bottom):
Put the region/owner bindings from the previous commit to work from Python.
CompilePackage stamps every precompile entry it installs with a fresh
per-install _install_owner token and renames the artifact's resume functions
to per-package token-suffixed names (_resume_name_token,
_resume_global_renames, _rename_globals, which rewrites co_names recursively
through co_consts). A __resume_at name carries only a per-capture counter that
restarts every process, so two artifacts collide on it; the rename makes it
unique to the loaded package. The __compiled_fn backend globals already carry a
per-capture uuid and are left as-is. So two packages loaded from one artifact
coexist on a shared frame -- their precompile entries told apart by owner, their
resume functions by per-package name -- and unload in either order for
everything scoped that way. Before,
init and install() both called uninstall(), which reset EVERY precompile
entry on the code object, a neighbouring package's included, and the
fixed-name resume globals were overwritten by the next load. Neither reset
happens now: install() registers a weakref.finalize
(_uninstall_abandoned_package, atexit=False) before it installs anything, so a
failed install is torn down too; it pops only globals still
holding the dead package's own values and tears entries down through
_reset_precompile_entries_for_owner, which parks rather than blocks since
finalize can fire mid-guard-evaluation. An explicit uninstall() applies the
same identity check, so a name the user rebound keeps the user's value.
install() and DynamoCache.load_and_install_package take a keyword-only
isolate_recompiles_id, and _TorchDynamoContext installs the cached package
into its own region, since precompile entries match their region exactly.
Known limit at this commit, closed higher in the stack (#195915): a global two
loads genuinely share -- a __compiled_fn both install under its per-capture uuid,
an import alias bound to the same module object, or a resume/backend global
shared between a loaded package and a plain torch.compile of a different function
in the same module (not only the two-loads-of-one-artifact case) -- is popped by
whichever unloads first here, and "unload" includes GC: no explicit uninstall()
is needed. On the default caching_precompile path a transient torch.compile
wrapper being garbage-collected strips a name a still-live wrapper's installed
bytecode LOAD_GLOBALs, and the live one then raises NameError from inside user
code at an arbitrary later call. #195915 adds the owner-counted teardown that
pops a shared name only with its last owner, which is what makes the default
path safe -- so this commit must not land as the stack tip without #195915.
Test Plan:
test_recompile_ux.py adds the package-driven parking tests: a reinstall
surviving an eviction parked by uninstall, and a precompile reset run from
inside a lookup (the binding-only concurrency cases live with the previous
commit). test_package.py pins the finalizer, the co_consts recursion, two
loads of one artifact coexisting and unloading in either order, the
identity-checked uninstall (reading the installed name from the package's
bookkeeping, since a free-threaded build may not have popped the capture-time
global yet), and caching_precompile serving an isolate_recompiles context.
Authored with an AI assistant.
FAQ
Q: The shared _compiled_fn* backend globals are not part of the per-install
renames, so if two packages load from one artifact and the one loaded second
uninstalls first, it pops a name the live package still reads and NameErrors it.
Shouldn't those globals be renamed or ref-counted?
A: Correct that they are not renamed here -- only the resume functions are. A
_compiled_fn* name already carries the uuid minted when its graph was
captured; a _resume_at* name carries only a per-capture counter that restarts
every process, so the resume names alone get a per-package token suffix (
{name}_{_resume_name_token}, the uuid minted once in__init__).The hazard you describe -- two loads of one artifact sharing a _compiled_fn*
name, the second-loaded uninstalling first -- is real at this commit, and it is
addressed by ref-counting rather than more renaming. #195915, higher in this
stack, adds a per-module registry (_GLOBAL_BINDINGS) that keeps, per name, a
stack of value-keyed bindings each owning a WeakSet[CompilePackage]; a binding
is popped only when its last owner uninstalls, and the binding beneath it is
restored, so a second-loaded package uninstalling first cannot strip a name the
first still owns. That same registry subsumes the import-alias case this message
lists as a known limit. At this commit uninstall is identity-checked -- a
package removes a name only while it still holds the value it wrote -- which
keeps a user's rebind and non-overlapping installs correct; the cross-package
ref-counting for shared names is what #195915 adds.
Q: test_two_packages_from_one_artifact_coexist serves both packages while both
are live but never serves pkg_b AFTER pkg_a.uninstall(). Wouldn't serving it
then be a stronger test?
A: It would, but it cannot pass at this commit -- it is the known limitation
above. pkg_a.uninstall() pops the import-alias and __compiled_fn globals both
loads share, so serving pkg_b afterwards NameErrors on a stripped global. That
is exactly the behaviour the in-test note and #195915 describe; the test serves
both while co-installed (the coverage this commit does deliver) and documents
that after-unload serving is #195915's to add.
Q: DynamoCache.load_and_install_package's new isolate_recompiles_id keyword is
only ever called with its default in the tests. Why not cover a non-default
region through the wrapper?
A: The region-scoped path IS covered, through the production entry point that
motivates it: _TorchDynamoContext calls package.install(isolate_recompiles_id=...)
directly (eval_frame.py), which
test_automatic_dynamo_serves_an_isolate_recompiles_context exercises under
fail_on_recompile for both the default and isolated context. The public wrapper
forwards the keyword to that same install(), so a separate non-default call
through it would re-test the forward, not new behaviour.
Q: The tests call uninstall() without a try/finally or addCleanup, so a
mid-test failure leaves per-install globals and entries behind for the next
test.
A: The suite's base class (torch._inductor.test_case.TestCase) runs
torch._dynamo.reset() and clears DynamoCache/PrecompileContext in setUp, and the
per-test path() is unique, so leaked cache state does not cross into another
test. addCleanup would tidy the module dict sooner but changes no outcome; the
one place it matters -- a user rebinding that must survive -- already uses it.
Q: test_abandoned_package_uninstalls_on_gc relies on a single gc.collect()
firing the finalizer promptly, which a free-threaded build may defer. Shouldn't
it retry the collection?
A: On refcounted CPython the del drops the last reference and the collection is
synchronous, which is what CI runs today. A bounded gc retry is the right
hardening for a free-threaded build and is worth adding when that build gates
these tests; it is orthogonal to what this commit changes and is deferred rather
than pre-empted here.
Q: install() now scopes its precompile entries to isolate_recompiles_id, but the
len(guarded_codes) == 0 skip (a trivial entry compiles to an empty graph) calls
skip_code unconditionally: it writes the code object's GLOBAL exec strategy via
set_code_exec_strategy for EVERY install, region-scoped or not, and isolated
regions inherit that SKIP per field when they hold no entry of their own. So one
package installing a trivial entry turns dynamo off for that code in every
region, including an install into an isolate_recompiles region -- not just the
-1 default bucket.
A: Correct, and an earlier draft of this answer claimed mitigations that do not
exist at this commit. To set the record straight: skip_code is the plain, un-
refcounted set_code_exec_strategy (there is no _SKIP_INSTALLERS registry); the
branch has no region-scoped path, so an isolate_recompiles_id >= 0 install writes
the global strategy just like the default bucket; and the comment there is the
generic "Dynamo generates empty graph for trivial functions" note, not a scoping
caveat. It is not a regression in that the skip_code CALL was already unconditional
before this commit, and pre-commit install() wiped every entry anyway -- but what
making install() region-aware newly introduces is the REACH: a region-N install of
a trivial entry now writes a GLOBAL SKIP that every other region (the -1 default
included) inherits, so on the success path a later torch.compile of the same
function in the default region silently becomes a no-op until torch._dynamo.reset().
So it is not a new call, but it is a newly cross-region effect. The honest fix is to
route the id >= 0 case through set_code_region_exec_strategy (the same shape as the
precompile-entry handling this commit adds, so uninstall's region reset also drops
the skip) and record which codes were skipped so uninstall() can restore them; that
is genuine follow-up work, not yet done here; #195915 lands the region-scoped
branch (set_code_region_exec_strategy for id >= 0) and the record-and-restore
bookkeeping (_SKIP_INSTALLERS refcount, compare_and_set on uninstall), leaving
only the default bucket's write global there, refcounted so the prior strategy is
restored once.
Q: The RuntimeError fallback calls initialize(fn, None), which does not reset the
package, so the "fresh" package keeps the failed load's _codes/_device_types; the
next compile appends onto those stale entries and save_to_dynamo_cache() writes
the merged result, so the on-disk artifact grows one duplicate guarded code +
backend id per install failure, forever. This is NOT covered by
reset_after_failed_install() (which only handles _initialized); the growth comes
from _codes surviving.
A: Real at this commit, and the reproduction is correct: here the handler pokes
_initialized = False and re-initializes, and at this commit initialize() does not
clear _codes/_device_types, so the load-derived entries survive and the artifact
grows across warm serves. It is fixed higher in this same stack at #195915, and
-- as the finding correctly points out -- not by reset_after_failed_install()
alone. #195915 does two things together: it replaces the cross-module
_initialized poke with self._package.reset_after_failed_install() (assert nothing
installed, then _initialized = False), AND it makes initialize() reset the
load-derived fields up front -- self._codes = {} and self._device_types = set()
with a comment that "every field a load writes has to be reset here rather than
trusted to still hold its init value." So in the shipped stack the handler's
reset_after_failed_install() followed by initialize(fn, None) clears _codes and
_device_types, and the artifact does not grow. Because the stack merges
atomically, main never sees this commit as tip without #195915's reset; the
field-clearing lands next to the fields it has to know about, which is the shape
this finding recommends.
Correction: the consequence is worse than benign growth. Once _codes survives
and the load-derived resume entry is re-appended, function_names carries a
duplicate name, and on the next load _resume_global_renames raises on it. Until
this revision that raise was an AssertionError, which escapes the
except RuntimeError fallback this stack adds in eval_frame.py -- so one transient
failed install could poison the artifact into a hard crash at torch.compile()
decoration time, not merely grow it. This commit closes that off at the source:
_add_function now skips a function_name already in code.function_names (so the
failed-install path never re-appends the same code's name), install() reserves
the counter values behind a loaded artifact's
__resume_at_<offset>_<n>names soa compile in this process cannot mint one of them for a different code object
(the cross-entry collision
_resume_global_renamesrejects), and_resume_global_renames raises RuntimeError rather than AssertionError so any
residual duplicate from a corrupt on-disk artifact is caught by the failed-install
fallback and degrades to a cold compile instead of taking working user code down.
the two fixes here make the failure mode recoverable regardless of route.
One more mechanism worth naming, since it decides how urgent #195915's reset is:
create_cache_entries stores the surviving _codes entries BY REFERENCE
(PrecompileContext.record_dynamo_cache_entry, unlike the deepcopying
record_artifact) and sets code.bypassed = True on them, after which
add_guarded_code / _add_backend_id / add_import_source all early-return on bypassed
-- so the affected frame is permanently dropped from every future load and cannot
be re-captured. That unrecoverable bypassed write, not per-load growth, is the real
harm: the carried-over set is the artifact's own entries, so it does not grow one
duplicate per install as the Q frames it; #195915's up-front _codes reset is what
prevents the bypassed write from ever happening.
Q: Dropping the wholesale _reset_precompile_entries lets precompile entries on a
shared code object grow with the number of live compiled callables on the
automatic caching_precompile path: N retained wrappers over one code object each
hold a full copy of the artifact's entries in region -1 under their own owner
(measured 1,2,3,4 vs a parent's 1,1,1,1). Isn't that unbounded growth?
A: It is bounded by the number of LIVE wrappers, and the duplication is intended,
not a leak. Each retained callable owns its own region -1 entries because each is
an independent install with its own owner token; a lookup must find the entry
belonging to the wrapper it is dispatching, so collapsing them across owners would
be wrong. The dedup in install() (_installed_precompile_codes keyed by id) is
per-package by design -- it stops one package re-installing the same code twice,
not two packages sharing a code object. Transient wrappers are GC-collected and
their entries torn down by the weakref finalizer (_uninstall_abandoned_package), so
the count tracks live instances rather than growing without bound. The growth is
O(live callables), the correct accounting for per-owner region entries;
test_two_packages_from_one_artifact_coexist pins the co-installed count, and a
dedicated per-owner count assertion would document the same intended
1-per-live-owner shape.
Q: In _uninstall(), the pop-globals loop runs unconditionally, but entry teardown
(_reset_precompile_entries_for_owner) can park when the cache lock is unavailable
or cache_python_depth > 0. So an entry can stay matchable after its
_resume_at/_compiled_fn globals are gone -- a served entry would NameError.
Shouldn't the two halves land atomically?
A: The asymmetry is real; the earlier version of this answer defended it with two
mitigations that do not exist at this commit, and both were wrong. There is one
shared teardown, _uninstall_abandoned_package, used by both uninstall() and the
weakref.finalize registration -- it did NOT reset entries first, it popped
globals first and reset entries three lines down, so the window was on the GC path
too. And there is no _PACKAGE_INSTALL_LOCK held across it (grep finds none); two
threads calling install() both run the teardown and both rebind the install owner.
This commit fixes the non-parked window on both paths at once by swapping the two
loops so the precompile entries are reset FIRST and the globals are popped after.
The remaining parked sub-case (reset defers to a later depth-zero drain while the
globals are already gone) needs the pops attached to the parked eviction so both
halves drain together -- the same "accepted parked residual" class the
extra_state.h lock-ordering note documents for the C++ side, tracked with
#196394. That both-halves-atomic change is deferred rather than
done blind here because its only observable consequence is unreproduced, but the
swap is strictly better than the status quo whether or not it lands.
Q: The finalizer teardown loop does module.dict.get(name) is value then
del module.dict[name] -- not atomic. From a weakref.finalize callback (which
GC can fire at any bytecode boundary) a concurrent removal between the check and
the del raises KeyError, CPython swallows it as an unraisable, and the rest of
the loop is abandoned, leaking every remaining global this package installed.
Shouldn't it be module.dict.pop(name, None)?
A: Real at this commit, and closed by #195915 higher in the same stack: that
commit rewrites this teardown -- uninstall() gets its own global-popping loop and
the finalizer defers to a _DEAD_PACKAGES drain -- and every removal there is
module.dict.pop(name, None), which has no check-then-del window. Because the
stack merges atomically, main never runs this commit's del; the pop-based
teardown lands with it. The one-line del->pop here would be strictly correct too,
but it is superseded by #195915's rewrite of the whole function, so it is not
applied to this intermediate in isolation.
Q: _uninstall_abandoned_package is the shared teardown for both paths at this
commit -- uninstall() calls it directly -- but its name and its comment's first
line describe only the weakref.finalize/GC path, so a reader greps it to
understand uninstall() and has to unlearn the name.
A: Accurate at this commit, and resolved higher in the stack rather than renamed
here. #195915 gives uninstall() its own teardown loop and leaves
_uninstall_abandoned_package registered only as the weakref.finalize callback,
so at the landed tip the name and comment describe exactly what the function
does. Renaming it to something path-neutral here would be inaccurate at the
endpoint, where it really is the abandoned-package (GC) callback again, so the
naming is left to track the endpoint shape.
Q: _resume_global_renames's RuntimeError branch (and the _add_function dedup
that removes its trigger) is load-bearing -- eval_frame.py's fallback only
catches RuntimeError, so a refactor back to AssertionError silently restores a
hard crash at torch.compile() decoration -- yet neither has a test in this
commit's diff.
A: The type IS pinned, so a refactor back to AssertionError fails CI:
test_resume_global_renames_rejects_duplicate_name asserts _resume_global_renames
raises RuntimeError("duplicate resume-function name") on two install_to_global
entries sharing a name, and test_add_function_dedups_function_name asserts
function_names stays length 1 after a double _add_function. Both live in #195913,
higher in the stack, co-located with the package-lifecycle tests their fixtures
share, rather than in this commit's diff; because the stack lands atomically, the
anti-poisoning contract is regression-protected in CI. The end-to-end fallback
(a corrupt artifact degrading to a cold compile through the except RuntimeError
handler) is exercised by the failed-install tests rather than pinned as its own
case.
Q: Dropping
self.uninstall()from__init__regresses a CAPTURING packageconstructed while another package is installed on the same code object: lookup is
region-exact but not owner-exact, so the new package is served the installed
entry, records nothing, and
save_packagethen overwrites the good artifact withone that has zero guarded codes -- whose install
skip_code()s the frame, makinga later
torch.compileof that function a silent no-op untilreset().A: Confirmed (backend never invoked, zero guarded codes, poisoned artifact) and
fixed on the capture side:
_TorchDynamoContext.__call__now refuses up frontwhen its package does not own the precompile entries already serving the frame in
its region (
CompilePackage.owns_install_on+_has_precompile_entries), with anerror naming the function and the two ways out (uninstall first, or
isolate_recompiles=True). Refusing rather than auto-minting a region keepsoptimize(package=)'s recompile accounting unchanged for users who did not askfor isolation. The refusal fires only for a USER-SUPPLIED package (a
CompilePackage(fn)arrives initialized; the transparent cache hands
_optimizean uninitializedfn=Nonepackage) that has RECORDED NOTHING for the frame(
has_guarded_codes_for): a package that already holds guarded code for it saves avalid artifact, and being served by a neighbour is then legitimate -- the manual
DynamoCacheflow (test_dynamo_cache_manual_load) calls an old wrapper whosepackage captured earlier while a freshly loaded package serves. The transparent
package is exempt because a cache hit installs its own entries and a miss records
and writes nothing. The check runs at decoration AND on every call of the wrapper,
so the neighbour can arrive in either order, and it is bound to the frame Dynamo
intercepts (resolved after
wrap_inlinemay have reboundfn; for an nn.Module,forwardrather than the skipfile_wrapped_call_implthat OptimizedModule handsthe context). Cost: nothing without a user package; once the package has recorded
the frame the Python check short-circuits before the C++ scan.
test_capturing_package_refuses_a_frame_another_package_servespins both orders(including decoration alone) under both configs, that the installed package keeps
serving, and that an isolated region captures normally; the module variant pins
the nn.Module path.
Q: The warm-load fallback handler in
_TorchDynamoContext.__call__(except RuntimeError->uninstall()-> re-init) is not exercised by any test; deletingthe
uninstall()line leaves a per-install resume global and a live region entrybehind and nothing fails.
A: Added
test_failed_warm_load_is_torn_down_before_the_cold_fallback: acaching_precompile warm serve whose SECOND entry's
load_guards_stateraises, sothe first entry's precompile entry and renamed resume global are bound when the
handler runs; it asserts the cold compile returns the right answer, the warning is
logged, no precompile entry survives and no token-suffixed
__resume_at_*globalis left. Injecting on the second
load_guards_statecall (rather than wrappinginstall()to raise after completing) keeps the test valid at #195915, whereinstall()rolls back its own partial state and a post-install raise would leavenothing partial.
Q:
_installed_globalsnow holds the installed VALUE, so a package whose name alater load displaced pins its dead backend wrapper for its whole lifetime.
Shouldn't it hold a
weakref.ref?A: At this commit a weakref would work and the pin is bounded (one displaced set
per live package that was overwritten;
uninstall()drops it). But #195915 makesthe strong reference load-bearing: its per-name binding stack REBINDS a name to
the surviving owner's value when the top owner unloads -- two loads of one
artifact, second-loaded unloading first, put the first package's
__compiled_fn_*wrapper back so it keeps serving (measured: after the second package's
uninstall()the module holds the first package's original object and it servesunder
fail_on_recompile). A weakref to the displaced value is dead exactly whenthat rebind needs it. The registry also records globals a compile inside the
region installs (
claim_region_global), whose values are not all weakref-able. Sothe value is held strongly by design at the endpoint; the retention it costs is
O(live displaced packages).
Q: The finalizer's identity check is only tested through
uninstall(), never onthe GC path; and
test_reinstall_survives_an_eviction_parked_by_uninstallpasseseven if its backend
__eq__hook never fires.A: Both fixed:
test_finalizer_leaves_a_users_rebinding_alonedrops the package,collects, drives an unrelated install/uninstall (so a finalizer that defers its
pop to the next install, as #195915's does, has run) and asserts the user's
rebinding is intact; the eviction test now asserts the hook list is empty after
the second call.
Q:
test_failed_install_is_torn_down_when_the_package_diesdeletes a backend byhand, but on a disk load
from_cache_entrypre-marks missing backendsbypassed,so
after_deserializationis the real source of a mid-install RuntimeError.A: The by-hand deletion is deliberate: it is the one failure that fires AFTER
earlier entries are bound at both this commit and #195915 (where
after_deserializationmoves before any install and so can no longer produce apartial install). The test pins teardown of a PARTIAL install, not the loader's
bypass path; production-shaped coverage of a failing rebuild is the new
fallback-handler test above.
Q: The
extra_state.cppcomment "(every install at this commit still passes thedefault id -1)" becomes false once this commit lands.
A: That comment is #195355's; it is reworded there to name #195911 as the commit
that registers each region under its own id, so it stays true at every point in
the stack.
Q: The refusal gates on
not config.caching_precompile, but that is a globalconfig, not "this package came from the transparent cache": a user-supplied
CompilePackage(fn)with the config on is not refused and reproduces the fullpoisoning chain -- a regression against the parent on the config this stack
targets.
A: Confirmed and fixed: the gate is now "the package is user-supplied" (a
CompilePackage(fn)is initialized at construction; the transparent cache'spackage is built with
fn=Noneand initialized later by the context), so theconfig no longer matters. Both measurements in the comment hold: on a hit the
context's own install makes
owns_install_ontrue, and on a miss with aneighbour installed the auto package records nothing and
save_to_dynamo_cache()writes no dynamo entry. The test is parametrized over the config.
Q: The check runs at decoration, so decorate -> neighbour installs -> call slips
through and poisons the same way (pre-existing, but the refusal is then a partial
fix, and
@optimize(package=)at import time is exactly the missed order).A: Fixed: the check is a closure bound to the code object, run at decoration and
again at the top of every call of the wrapper (before the enter/exit hooks, inside
the try that restores eval-frame state). It costs nothing when no user package is
set; for a serving package the Python-side
owns_install_onshort-circuits beforethe C++
_has_precompile_entriesscan, so only a capturing user package pays onelock-scoped scan per call. The test now exercises the reverse order too.
Q:
test_two_packages_region_scoped_serves_its_own_entriesasserts onlyresume_b; ifresume_awere empty the poison loop would be vacuous.A: Added
self.assertTrue(resume_a)alongside it.Q:
linux-jammy-py3.14t-clang21is red on this PR and every PR above it.A: One test,
test_finalizer_leaves_a_users_rebinding_alone, found the installed__compiled_fn_Nname by diffing the module dict; under free-threading thecapture-time CleanupHook pops the previous compile's name late (deferred
refcounting), so the install rebinds a key already present and the diff is empty.
It now reads the name from the package's own bookkeeping, as the sibling uninstall
test already did (and #195915 adapts it to its
_InstalledGloballist the sameway it adapted the sibling).
Q: The per-call refusal breaks
test_dynamo_cache_manual_load: the documentedmanual DynamoCache flow decorates with a capture-time
CompilePackage(fn)and isthen served by a separately loaded package, which the check calls "another
package".
A: Fixed: the refusal now requires that the user package has recorded nothing for
the frame. The old wrapper's package holds a guarded code for
fn(it capturedbefore the save), so it is served without complaint; a fresh package that never
saw Dynamo run on the frame is still refused, which is the only shape that can
poison an artifact. This also bounds the cost the review measured: the C++ scan
runs only until the first compile of the frame.
Q:
TestCase.enterContextis 3.11+, but the project supports 3.10 and CI runsit; both parametrizations hard-error there.
A: Fixed: the test body runs under
with torch._dynamo.config.patch(...).Q: The refusal is dead on the nn.Module path (
getattr(fn, "__code__")is Nonefor a module; OptimizedModule then re-enters with the bound
__call__, askipfile, so the closure checks a code object Dynamo never intercepts), and
codewas captured before
wrap_inlinerebindsfn. Also, thatgetattrprobe runs auser
nn.Module.__getattr__(CI:test_custom_getattr_hasattr_no_recursion).A: Fixed: the frame code is resolved once
fnis final, without a getattr probe(
isinstance(fn, (FunctionType, MethodType))), and a module's bound__call__resolves to
innermost_fn(module.forward).__code__, where the entries live.test_capturing_package_refuses_a_module_frame_another_package_servespins it,including that an isolated region still captures the module normally.
Q:
install()records_installed_precompile_codes[id(code)]before thezero-guarded check, so a skipped frame is "owned" although no entry was installed,
contradicting
owns_install_on's docstring.A: Fixed: the code is recorded only when the entry has guarded codes; a
zero-guarded entry writes the skip and owns nothing.
Q: The dedup in
_add_functionis within one entry; the collision_resume_global_renamesrejects is across entries (two code objects claiming one__resume_at_<offset>_<n>after a reload plus a branch-divergent recompile, sincethe counter restarts per process), and a re-record persists the duplicate.
A: Correct, and the commit message wording is fixed.
install()now reserves thecounter values behind every loaded
__resume_at_<offset>_<n>name(
_reserve_unique_id_through, moved down from #195915 where it reserved thebuiltins-dict index), so a compile in this process cannot mint a loaded name for a
different code object; the rejection becomes unreachable by construction rather
than by the builtins-index coincidence.
Q: Two threads calling
install()on one package both passuninstall()and bothregister a finalizer; only the last is detachable, so a stale finalizer survives
and fires at package death.
A: Real at this commit and closed by #195915, whose
install()holds_PACKAGE_INSTALL_LOCKacross the uninstall and the finalizer registration, so thedetach-then-register pair is atomic and exactly one finalizer is live per package.
ghstack lands PRs individually, so that window exists on main between the two
merges; two concurrent installs of one package are a data race on every other
field too, so the window changes nothing a correct program observes.
Q: The decoration-time check site is not covered (both test cases decorate and
call in one expression); the region half of
owns_install_onis untested; thefinalizer test's
entries == 0assertion is self-fulfilling because_save_eager_packageends withtorch._dynamo.reset().A: All three fixed: the refusal test now decorates after the neighbour installs
and asserts the raise before any call; the region-scoped test asserts
owns_install_onfor both packages in both regions; the finalizer test saves theunrelated package up front so no reset runs after the install (verified that the
assertion now fails with the finalizer neutered). The
-1sentinel is the samedefault-region id the C++ side uses (
set_eval_frame_isolate_recompiles_id), so itis kept rather than switched to None.
Q: The install docstring says "dropping it undoes these updates", but the
skip_codea zero-guarded entry writes is never undone byuninstall()or thefinalizer at this commit.
A: Docstring now carries the caveat until #195915's record-and-restore
bookkeeping lands.
Q:
refuse_if_another_package_servesrunshas_guarded_codes_for(a dict walk)on every call of the compiled function.
A: Latched: once the package has recorded on the frame it is the server there,
and the closure stores that in a nonlocal bool, so the steady state is one bool
read per call.
Q:
refusal_codeis not unique to the callable being decorated: everywrap_inline'd frame in the process shares oneinnercode object, so apackage serving one built-in nn.Module makes decorating a second built-in module
with another package refuse at decoration.
A: Real; fixed.
_refusal_frame_codereturns None forwrap_inline's sharedinnercode (_WRAP_INLINE_INNER_CODE), since entries on that frame aremulti-owner by design and say nothing about who serves a particular module.
test_two_packages_share_a_built_in_modules_wrap_inline_framesaves a barenn.Linearpackage, loads it andinstall()s it (which is what puts a precompileentry on the shared
innercode; a package that merely records undercaching_precompile installs nothing), then decorates a bare
nn.ReLUwith a freshpackage and checks it is not refused and records its own entry. With the
innerexemption removed the test raises the refusal at decoration. The mirror half (a
second package on the same shared frame is not refused when it perhaps should be)
cannot be decided per owner on a shared frame: lookup is by guard, so a second
module whose guards match the first package's entry (a same-shape Linear) is
served by it and records nothing, exactly as a second
torch.compile(Linear)shares the first's cache entry today, and one whose guards miss records its own.
Q: The
__resume_atcounter reservation has no unit test at this commit, theprefix is spelled twice (
symbolic_convert.pyand the install regex), andnothing shows
install()actually moving the counter past a loaded artifact'snames.
A:
test_reserve_unique_id_through_skips_past_a_loaded_artifacts_countermoveddown from #195915 (it depends only on
bytecode_transformation);RESUME_FN_PREFIXis now the one spelling (precedent:COMPILED_FN_PREFIX), usedby the resume-function minting and the install regex; and
test_install_moves_the_counter_past_a_loaded_artifacts_resume_namesloads anartifact with a graph break, resets the counter to simulate a fresh serving
process, installs, and checks the next minted id is past every loaded name.
Q:
test_resume_function_with_freevars_reinstalls_its_closurehas one resumeentry, so the per-iteration default-argument capture in
_make_fnis unpinned.A: The closure now graph-breaks twice, so two resume functions are rebuilt
through the factory and a late-binding regression would fail the numeric check.
Q:
test_two_packages_share_a_built_in_modules_wrap_inline_framecannot failwith the
_WRAP_INLINE_INNER_CODEfix reverted.A: Confirmed and fixed.
CompilePackage(lin.forward)is initialized atconstruction, so the first package only RECORDED an entry on
innerand neverinstalled one;
_has_precompile_entries(inner, -1)stayed False and the refusalshort-circuited regardless of the fix. The test now saves, loads and installs the
first package (verified: passes with the fix, raises the refusal at decoration
without it).
Q: The
_WRAP_INLINE_INNER_CODEcomment understates the blast radius: more thanbuilt-in modules route through
wrap_inline.A: Comment now lists them: skipfile functions and built-in module forwards,
top-level in-graph and polyfilled functions, and any module under
config.wrap_top_frame(thedebug_force_nested_callsroute.replace()s thecode, so it is not shared and the refusal still applies there).
Q: The
extra_state.cppcomment "every install at this commit still passes thedefault" is falsified by this commit.
A: That text no longer exists: #195355 (which owns the line) reworded it to
"Installs below #195911 in this stack pass the default id -1; that commit's
region-owned install registers each region under its id" (extra_state.cpp:759-760
on this PR's base branch). The quote is from an earlier round.
[no ci]