Skip to content

[dynamo] Bypass only the compile whose guards failed to serialize, not the whole entry - #196505

Closed
bobrenjc93 wants to merge 7 commits into
gh/bobrenjc93/1147/basefrom
gh/bobrenjc93/1147/head
Closed

bobrenjc93 wants to merge 7 commits into
gh/bobrenjc93/1147/basefrom
gh/bobrenjc93/1147/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

A CompilePackage keeps one _DynamoCodeCacheEntry per code object, and
every compile of that code object -- the first and each later recompile for a
new guard variant -- appends its guarded code and backend id into that one
entry. When a compile could not be packaged, bypass_current_entry set
entry.bypassed = True and install() then skipped the WHOLE entry on
reload: variants of the same frame that had serialized fine were thrown away
with the one that had not, and a later serializable recompile could not
un-poison the entry.

There is no correctness reason for that granularity. Each variant's guards are
sound for its own bytecode, so installing the variants that serialized while
dropping the one that did not is safe: inputs that would have matched the
dropped variant miss every installed guard and are traced fresh in the loading
process, which is exactly what the whole frame did before. The whole-entry
flag came from #160902 and reflected the usual case (an unpicklable guarded
value is typically a default or closure that every variant guards on) plus the
fact that nothing attributed backend ids to the compile that registered them.

code_context now records the backend ids the compile inside it NEWLY added
to the entry, and bypass_current_compile (renamed from bypass_current_entry)
removes exactly those from the entry and from cached_backends; a backend an
earlier, installed variant still needs can never be stripped. Earlier variants
stay. Reading output.package also means a bypassed compile no longer updates
the package's device type (which used to run regardless) or records its inlined
sources (which the old add_inlined_source already skipped through its own
bypassed early return), and that a later successful compile of the same code
object records its inlined sources again, which the sticky per-entry flag used
to suppress. A poisoned entry loaded from disk is reset by the follow-up at the
top of this stack. Import sources and the resume function a bypassed compile registered
stay on the entry (both pre-existing and inert on load); only its backend ids
are dropped.

For the compile's own guarded code never to be recorded, _compile has to
consult the package on the OUTPUT GRAPH, which bypass_package clears, rather
than its local package variable. Reading the local also tripped an assertion
on the missing guards_state whenever guards themselves failed to serialize;
here it matters for a bypass raised before guards are built (a graph holding a
named parameter under prepare_freezing): with the old bypassed early
returns gone, the local-variable check would record the bypassed compile's
guarded code and re-derive a backend id nothing cached, and the save would
fail or drop the frame. So the output.package switch lands in this commit.

bypassed is kept but becomes derived state, "this entry currently has
nothing installable": set when a bypass leaves the entry with no guarded code,
cleared when a compile records one. It still has to exist because install()
treats an entry with zero guarded codes as a trivial function and skip_codes
it, which would stop the frame from ever being traced again after a reload.
The other writer, PrecompileCacheEntry.from_cache_entry (run by
PrecompileContext.create_cache_entries at SAVE time, on the live entries,
when a backend artifact is missing), is unchanged and still flags the whole
entry while keeping its stale guarded codes; making that path per-variant too
is a follow-up.

Test Plan:

python test/dynamo/test_package.py -k test_bypass_drops_only_the_current_compiles_backend -k test_bypass_of_every_compile_marks_the_entry_bypassed -k test_bypassed_guards_keep_the_frames_earlier_variant -k test_bypass_before_guards_keeps_the_frames_earlier_variant

Two end-to-end tests compile two variants of one frame, save, reload, and hit
the first variant under fail_on_recompile. In the first the second variant's
guards cannot be serialized (a guarded value whose __reduce__ raises
AttributeError, the one exception the pickler maps to PackageError at this
point in the stack); on main that compile crashes on the guards_state
assertion. In the second the bypass fires before guards are built (the
named-parameter path); without the convert_frame change the saved entry
carries a backend id nothing cached (the count assertion fails) and the
caching_precompile save then drops the whole frame.

Authored with an AI assistant.

FAQ

Q: from_cache_entry still sets code.bypassed = True on a missing backend
but leaves the id in backend_ids; now that add_guarded_code clears
bypassed, does a same-process recompile re-expose the stale id?

A: Yes, and the steady state is the same as before this change.
from_cache_entry runs at save time on the live entries, so a save after such
a recompile re-flags the entry before writing it (before this change it also
carried the new compile's id and stayed bypassed=True); the written entry
carries bypassed=True, and the next process's install() skips it before
the missing-backend RuntimeError, so the frame is never served from cache and
never crashes. Dropping
only the id at load is not a safe fix: the stale guarded codes whose bytecode
references that __compiled_fn would survive, be saved bypassed=False after
a recompile, and be installed with no backend in the next process, giving a
NameError on a guard hit. Making the load path per-variant means pruning
those guarded codes (via _backend_ids_from_code on the deserialized
bytecode) together with the id and deriving bypassed = not guarded_codes;
that is the follow-up the message names, kept out of this change to keep it
to the save side.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196505

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 32e06c3 with merge base 32d114b (image):
💚 Looks good so far! There are no failures yet. 💚

GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • bypass_current_compile (package.py:826-830) removes only ids in _current_backend_ids, which _add_backend_id appends solely inside the not in backend_ids branch (:856-858), so remove() cannot raise
    • convert_frame.py:1967-1980 now reads output.package, the same attribute bypass_package clears (output_graph.py:2607-2608), so a bypassed compile records no guarded code and the guards_state must not be None assertion is unreachable
    • code_context resets _current_backend_ids on both entry and exit (package.py:777, :783), so a bypass can never strip a backend id an earlier installed variant of the same code object registered
  • Preservation
    • The removed if self._current_entry.bypassed: return early returns in add_guarded_code/add_inlined_source are replaced by the upstream output.package is not None gate, and grep shows convert_frame.py:1978-1979 is their only non-test caller
    • bypassed is still set when an entry has no guarded code (package.py:830), keeping install()'s skip_code path at :979-982 from treating the frame as trivial
  • Testing
    • test_bypass_drops_only_the_current_compiles_backend and test_bypass_of_every_compile_marks_the_entry_bypassed (test_package.py:108-152) cover the bookkeeping and the flag being cleared by a later compile
    • test_bypassed_guards_keep_the_frames_earlier_variant and test_bypass_before_guards_keeps_the_frames_earlier_variant (:154-217) drive both real bypass sites (guards.py:4812, output_graph.py:2932) through compile, save and reload
  • Scope
    • Confined to dynamo precompile packaging; the bypass_current_entry rename has no stale callers, and the deferred from_cache_entry whole-entry granularity (package.py:561) is unchanged and signposted in the class docstring at :227-233

reason: clean
Reviewed commit: 32e06c3

Inference job

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 46m 43s —— View job


The core justification in bypass_current_compile's docstring — that "convert_frame skips add_guarded_code once bypass_package clears output.package" — does not hold for the output_graph.py:2932 bypass site, so removing the if self._current_entry.bypassed: return guard lets a bypassed compile record its guarded code and a backend id that has no artifact.

Full review

PR Review: #196505

Summary

Narrows a package bypass from the whole _DynamoCodeCacheEntry to just the compile that failed to serialize, making bypassed derived state. The refactor's premise is sound, but the specific safety argument for removing the add_guarded_code early return is incorrect for one of the two bypass call sites, and the load-time bypassed path was not updated for the new derived semantics.

Code Quality

torch/_dynamo/package.py:811-813 — the docstring's central claim is false, and the removed early return was what made it true.

The docstring states the bypassed compile's guarded code "is never recorded (convert_frame skips add_guarded_code once bypass_package clears output.package)". OutputGraph.bypass_package (output_graph.py:2607-2608) clears self.package, an OutputGraph attribute. But convert_frame.py:1966-1969 gates on the local package parameter (declared convert_frame.py:1708), which is never rebound inside _compile. Clearing output.package does not make convert_frame skip anything.

For the bypass_package at output_graph.py:2932 ("Graph contains named parameters due to static addresses") this is materially wrong. That site sits in compile_and_call_fx_graph (output_graph.py:2809), reached via compile_subgraph during tracing under compile_frame (convert_frame.py:1803) — strictly before build_guards (:1958) and add_guarded_code (:1969). And save=package is not None at :1962 is still True, so guards still serialize. Concretely, after this PR:

  1. Bypass fires at 2932, before add_backend_id at 3053 (gated by if self.package is not None: at 3052). So _current_backend_ids is empty — bypass_current_compile removes nothing — and the backend object never lands in _cached_backends. output_graph.py:2939-2940 also skips gm._backend_id = name, so AOTAutograd never records a BundledAOTAutogradCacheArtifact for it (aot_autograd.py:1027 reads gm._backend_id; autograd_cache.py:1541-1548 gates on precompile_backend_id).
  2. add_guarded_code then runs anyway: it appends the guarded code, sets bypassed = False, and _backend_ids_from_code(out_code) (package.py:158-164) re-adds the compiled-fn name — it is in out_code.co_names, since install_global_unsafe(name, ...) at 3136 plus cg.make_call_generated_code(name) at 3174 emit the global load.
  3. Result: an entry marked installable, carrying a backend id with no artifact. At save, PrecompileCacheEntry.from_cache_entry (package.py:540-560) logs "Backend not found" and sets code.bypassed = True for the whole code entry, dropping any variants that serialized fine — exactly the whole-entry granularity this PR set out to remove. (DynamoStore.save_cache_entry's RuntimeError at :1109-1111 is only reachable from save_package, which has no in-tree production caller, so this surfaces as a warning rather than a raise.)

Note the guards.py bypass site (guards.py:4813) avoids this by leaving guards_state = None, which trips the AssertionError at convert_frame.py:1967-1968 — i.e. it never reaches add_guarded_code by crashing, not by skipping. Neither site works the way the docstring describes.

Either keep a guard in add_guarded_code for the current compile (a per-compile "this compile was bypassed" flag rather than the entry-level one), or have bypass_package clear the reference convert_frame actually reads. Whichever you pick, the docstring needs to describe the real mechanism. Fix this →

torch/_dynamo/package.py:559 — the load-time bypassed = True path was not updated for the new derived semantics.

When a backend artifact is missing at load, from_cache_entry sets code.bypassed = True but leaves the missing id in code.backend_ids. Under the old semantics that flag was permanent, so install()'s if entry.bypassed: continue (:954-957) permanently shielded the entry from the RuntimeError at :962. Now add_guarded_code (:793) clears the flag on the next compile of that code object in the loading process while the unbacked id is still present, and bypass_current_compile's bypassed = not guarded_codes (:826) can likewise clear it whenever guarded_codes is non-empty — even though the flag was set for the unrelated "backend missing" reason that the new docstring at :227-231 explicitly folds into the same field. In practice install() is only called once per load (eval_frame.py:1001, package.py:1309), so this does not crash today; it silently poisons the re-serialized entry instead, since cache_entry() (:1024-1030) carries bypassed=False plus the stale id into the next process, where from_cache_entry bypasses the whole entry again. If bypassed is now derived from "has installable guarded codes", the load path should drop the missing backend id from code.backend_ids at :559 so the derivation stays true. Fix this →

Testing

test/dynamo/test_package.py:89-130 — both new tests drive CompilePackage internals directly and never go through a compile, which is why the incorrect premise above survived.

They call add_guarded_code(b"", ...), add_backend_id(...), and bypass_current_compile() by hand, so they assert the bookkeeping in isolation and cannot observe that a real bypass at output_graph.py:2932 is followed by an add_guarded_code that undoes it. The PR body defers the end-to-end reload test to the next commit, but the removal of the bypassed early return is a behavior change in this commit and needs at least one test that reaches bypass_current_compile through OutputGraph.bypass_package. Note the class-level @torch._dynamo.config.patch({"strict_precompile": True}) at test_package.py:43 turns any real bypass into a PackageError (output_graph.py:2590-2593), so such a test must patch that off — which is also why no existing test in this file covers the named-parameters path.

Recommendation

Request Changes

The refactor's premise (per-variant guards are sound for their own bytecode, so keep the variants that serialized) is right and the bypassed-as-derived-state framing is a genuine improvement. But the safety argument for dropping the add_guarded_code early return does not hold for the output_graph.py:2932 bypass, and no test exercises a real bypass, so please either restore a per-compile guard or make the mechanism match the docstring before landing.

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

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Updated. The review above ran against the previous head; findings 1 and 3 (convert_frame reading the local package, and no real-compile test) were already fixed in that update: _compile now reads output.package, and test_bypass_before_guards_keeps_the_frames_earlier_variant drives the named-parameter bypass through a real compile, save and reload. Finding 2 (the load-time from_cache_entry writer) is answered in the FAQ in the description: the steady state is unchanged from before, and dropping only the id at load would be unsafe; the per-variant load path is a named follow-up.

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 27m 34s —— View job


Confirmed: findings 1 and 3 are genuinely fixed at this head, and the FAQ's answer to finding 2 holds — the load-time writer is unchanged from before this PR and dropping only the id there would indeed be unsafe, so deferring it is the right call.

Re-review of the updated head

Verification of the claimed fixes

Finding 1 (convert_frame reading the local package) — fixed. convert_frame.py:1962 and :1970-1975 now read output.package, which is the same OutputGraph attribute bypass_package clears at output_graph.py:2608. I traced the identity: output is tracer_output.output_graph (convert_frame.py:1864), and the guards-path bypass reaches it via CheckFunctionManager.output_graph (guards.py:4635, set from the output_graph argument that _build_guards passes at :1056 from the same tracer_output.output_graph). So both bypass sites clear the object _compile reads. The docstring at package.py:813-815 is now accurate.

This also correctly fixes the pre-existing assertion problem: save=output.package is not None means the guards-path bypass leaves save=False on the next read, so the guards_state must not be None check at :1971 is no longer reachable after a guard-serialization bypass. Two secondary effects, both benign but worth confirming you intended them:

  • add_inlined_source / update_device_type are now also skipped for a bypassed compile. Skipping add_inlined_source is right (that compile's traced code isn't represented in any saved variant). Skipping update_device_type means _device_type retains whatever the last non-bypassed compile set; since it's a whole-package scalar used only for the GPU-availability check (package.py:451-473), a bypassed compile has nothing installable to check for, so leaving it is fine — arguably better than the old behavior, which let a dropped compile set it.
  • bypass_package's early if not self.package: return (output_graph.py:2588) makes a second bypass in the same compile a no-op, so bypass_current_compile can't double-run and backend_ids.remove can't raise ValueError. Good.

Finding 3 (no real-compile test) — fixed. test_bypass_before_guards_keeps_the_frames_earlier_variant (test_package.py:144-170) drives the output_graph.py:2932 named-parameter bypass through an actual torch.compile, and correctly patches strict_precompile=False at the method level to override the class-level True (test_package.py:55) that would otherwise turn the bypass into a PackageError. Setup checks out end to end: mark_static_address(guard=False) plus prepare_freezing=True makes make_graph_attribute true (builder.py:3013-3014), so register_attr_or_module puts w in the graph as a named parameter and next(gm.parameters(), None) fires the bypass — but only on the use_w=True variant, since the use_w=False graph never touches w. The len(entry["backend_ids"]) == 1 assertion is exactly the check that would have failed under the old local-package read (the bypassed compile would have re-derived its __compiled_fn id via _backend_ids_from_code, giving 2), and the _debug_get_precompile_entries + fail_on_recompile reload is the whole point of the PR. That's a well-targeted regression test.

Two small notes on the test, neither blocking:

  • setUp clears DynamoCache but the reload half depends on the on-disk cache written by save_to_dynamo_cache; torch._dynamo.reset() explicitly does not touch filesystem caches (torch/_dynamo/__init__.py:143), so this works, but it's the one test in the file that reads back from disk rather than through _save_and_reload. A one-line comment saying the reload is deliberately going through the real disk cache would help the next reader.
  • The comment at :150-153 explains the convert_frame coupling well. Consider also noting why the count is 1 and not 2 (the second compile's add_backend_id at output_graph.py:3053 never runs because the bypass at :2932 precedes it), since "1" otherwise reads as arbitrary.

Finding 2 (load-time from_cache_entry writer) — the FAQ is right; withdrawing the request. I verified the reasoning in the description:

  • Recompile-clears-the-flag is real but not new-in-kind: install() runs once per load (eval_frame.py:1001, package.py:1311), and the only consumer of the flag is that one call, so clearing it afterwards can't crash the loading process. The saved entry then carries the stale id with bypassed=False, and the next process's from_cache_entry re-bypasses the whole entry, so the frame is never served from cache. That is the same steady state as before: previously the entry was saved bypassed=True and also carried the new compile's id, so it was equally unusable. Not a regression.
  • The unsafety argument for the "just drop the id at load" fix checks out. install() skips the bypassed entry wholesale today, so the stale guarded codes are never inspected; drop only the id and those codes survive, get re-saved bypassed=False after any recompile, and are then installed in the next process with no __compiled_fn global — a NameError on a guard hit rather than a cache miss. Turning a silent miss into a crash would be strictly worse, so the correct per-variant fix does have to prune the guarded codes via _backend_ids_from_code on the deserialized bytecode, which is genuinely a separate change on the load side.

The docstring at package.py:227-232 already flags that the load-time writer keeps whole-entry granularity and points at from_cache_entry, which is the right amount of signposting for a named follow-up.

Remaining observations (non-blocking)

  • package.py:824-826 — backend_ids.remove(backend_id) would raise ValueError if an id in _current_backend_ids were somehow absent from entry.backend_ids. It can't happen today: _add_backend_id (:854-856) only appends to _current_backend_ids in the branch where it also appends to entry.backend_ids, nothing else removes from backend_ids, and code_context resets _current_backend_ids on both entry and exit (:775, :781) so it can never outlive its entry. Worth being aware of if anything later gains the ability to prune backend_ids mid-compile.
  • _current_backend_ids deliberately holds only ids this compile newly added — an id already on the entry from an earlier variant isn't re-appended, so a bypass won't strip a backend an earlier installed variant needs. That's the correct semantics and follows from the if backend_id not in ... backend_ids guard, but it's the subtlest part of the change and the field comment at :643-645 doesn't say it. One clause ("only ids this compile newly added, so a bypass never strips an earlier variant's backend") would make it explicit.
  • The restart path is fine: compile_frame retries inside one code_context (convert_frame.py:1634), and each attempt builds a fresh OutputGraph, so a bypass on a discarded attempt no longer poisons the successful one — a real improvement over the old sticky flag, since the discarded attempt's add_backend_id calls are the ones being removed.

Recommendation

Approve. The two substantive concerns from my prior review are resolved at this head, and the third is correctly deferred with a sound justification. The only suggestions left are comment/test-readability polish.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review follow-up: added test_bypassed_guards_keep_the_frames_earlier_variant, a real-compile test for the title path (a guarded value whose __reduce__ raises AttributeError), which on main tripped the guards_state assertion. The description now says where from_cache_entry actually runs: at save time on the live entries, via PrecompileContext.create_cache_entries, not at load.

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 54m 58s —— View job


Both round-2 follow-ups check out: the new test_bypassed_guards_keep_the_frames_earlier_variant really does drive the guards-serialization bypass through a live compile, and the description's correction is right — from_cache_entry runs only on the save path, mutating the live entry objects, never at load.

Round-3 review

Verification of the new test

test/dynamo/test_package.py:151-177 — the mechanism reaches the intended failure, and the assertions are self-validating.

I traced the path the test depends on:

  1. fn guards on cfg (a TYPE_MATCH on the UserDefinedObjectVariable, plus the cfg.scale read), so get_guard_manager_from_source records id(cfg) in guard_tree_values (guards.py:1714-1716). That matters: it keeps cfg out of missing_values in pickle_guards_state (guards.py:4584-4587), which would otherwise reduce it to _Missing and silently succeed.
  2. serialize_guards prunes local_scope to used_local_vars (guards.py:4942-4948); since a surviving guard originates from L['cfg'], cfg stays in the pickled state. The caching_precompile guard filter (guards.py:4659-4686) only drops ID_MATCH/CLOSURE_MATCH/WEAKREF_ALIVE/DICT_VERSION, so the TYPE_MATCH survives and keeps cfg reachable.
  3. ConfigThatCannotPickle is module-level, so type(obj).__qualname__ == type(obj).__name__ and it does not hit the local-scope PackageError at guards.py:4506-4511. reducer_override falls through to NotImplemented, pickle calls __reduce__, the AttributeError propagates, and guards.py:4604-4605 maps it to PackageError — the one exception that path converts, as the description says.
  4. CheckFunctionManager catches it at :4810 and calls self.output_graph.bypass_package(...). That output_graph is tracer_output.output_graph (threaded through _build_guards at convert_frame.py:1054-1056), the same object _compile reads as output at :1864, so clearing self.package at output_graph.py:2608 is what makes :1970 skip.

The assertions are the right ones and none of them can pass vacuously:

  • assertLogs + any("config cannot pickle" in line ...) pins that the bypass actually fired via the pickler, not some unrelated bypass. Without it the test would pass trivially if cfg got reduced to _Missing.
  • len(entry["backend_ids"]) == 1 is the per-compile claim. Unlike the named-parameter test, this bypass fires after add_backend_id (output_graph.py:3053), so _current_backend_ids is genuinely non-empty here and bypass_current_compile's backend_ids.remove is exercised for real. That's the complementary case to test_bypass_before_guards_..., where the list is empty — good that both are now covered.
  • On main this test would die on the guards_state must not be None assertion (convert_frame.py base, :1966-1968), since the old code read the local package, which is still non-None after the bypass. Confirmed against origin/gh/bobrenjc93/1147/base.
  • The trailing self.assertEqual(compiled(x, cfg), fn(x, cfg)) (outside the stance) is doing more work than it looks: it re-triggers the bypass in the loading process, against an entry that already has one installed guarded code. bypassed = not guarded_codes correctly stays False there, and backend_ids.remove succeeds because the post-reload compile appended the id itself. Worth a half-sentence comment saying that's deliberate, since it reads like a throwaway numerics check.

from_cache_entry runs at save time — confirmed, and the description is now accurate

record_package passes package.cache_entry() (package.py:1063), whose codes is list(self._codes.values()) (:1028) — the same _DynamoCodeCacheEntry objects the live package holds. PrecompileContext.record_dynamo_cache_entry just stores that dict (precompile_context.py:125), and create_cache_entries → from_cache_entry (:206-212) then mutates those live objects. The load path never touches it: load_cache_entry unpickles a PrecompileCacheEntry via read() (package.py:1152), so from_cache_entry is save-only. My round-1 framing of it as a "load-time writer" was wrong; the corrected docstring at package.py:229-232 matches the code.

This also means the FAQ's steady-state argument is right for a slightly stronger reason than stated: because the flag is set on the live entry, the same-process recompile the FAQ worries about is followed by a save that re-flags it before writing, and install() in the next process skips it before the missing-backend RuntimeError at :965. No new failure mode.

Two side effects of the output.package switch that are improvements, not regressions

Worth recording since neither is called out and both change behavior:

  • add_inlined_source was previously sticky. In the base, its early return read self._current_entry.bypassed, which survived across compiles — so once any compile of a frame bypassed, every later successful compile of that frame also skipped recording its inlined sources, leaving the saved package under-guarded against source edits. Gating on output.package per-compile fixes that: the bypassed compile skips (correct, its traced code backs no installed variant) and later ones do not.
  • Restart attempts no longer leak into the bypass accounting the wrong way. code_context wraps the whole retry loop (convert_frame.py:1997-2013, compile_frame at :1803), so _current_backend_ids spans all attempts. If a discarded attempt registered a backend id and a later attempt bypasses, both ids are now removed — which is what you want, since the discarded attempt's bytecode was thrown away. Previously both stayed on the entry under bypassed=True.

Remaining observations (all non-blocking)

  • Orphaned artifact is now in-memory only. After the guards bypass, gm._backend_id was already set, so AOTAutograd recorded a BundledAOTAutogradCacheArtifact for the dropped compile. Removing the id from entry.backend_ids means from_cache_entry no longer copies it into backend_content, so it is not written to disk — strictly better than before, where a bypassed entry carried both ids and both artifacts got serialized. It does linger in PrecompileContext._backend_artifacts_by_key until clear(). If you want to pin that contract, save_to_dynamo_cache()'s return already exposes it: len(debug_info["backends"]) == 2 alongside the existing len(entry["backend_ids"]) == 1 would document "recorded but not referenced, so not saved" in one line.
  • update_device_type is newly skipped for a bypassed compile (it never had a bypassed early return, so the base ran it even on bypass). Benign — _device_type is a whole-package scalar that the last non-bypassed compile sets, used only for the load-time GPU-availability check (package.py:451-473), and a bypassed compile has nothing installable to check for. Mentioning it only because it is not in the commit message's list of what the switch changes.
  • _current_backend_ids holds only ids this compile newly added. _add_backend_id appends to it inside the if backend_id not in ... backend_ids branch (:855-857), so a bypass can never strip a backend an earlier installed variant still needs. That is the correct semantics and the subtlest part of the change; the field comment at :645-647 says what the list is for but not this invariant. One clause would make it explicit.
  • OutputGraphCommon.bypass_package still raises NotImplementedError (output_graph.py:665-669). Not reachable: the only save_guards=True caller holding a plain OutputGraphCommon is aot_compile.py:435-437, which passes strict_error=True so the PackageError re-raises at guards.py:4811 before the bypass; functional_export.py:459 leaves save at its False default. Fine as-is, just confirming the new code path does not open it up.
  • Test-hygiene note carried over from round 2: these two end-to-end tests are the only ones in the file that read back through the real on-disk DynamoCache rather than _save_and_reload. That works — DiskDynamoCache.path_prefix() re-reads cache_dir() on each call (package.py:1315-1316), so it picks up the per-test fresh_cache() temp dir, and torch._dynamo.reset() does not clear filesystem caches. A one-line comment saying the disk round-trip is deliberate would save the next reader the trace.

Caveat

I reviewed statically; there is no built torch in this checkout, so I did not execute the four tests named in the test plan. The reasoning above is from reading the code paths, not from a run.

Recommendation

Approve. Both items from round 2 are genuinely addressed, the new test targets the exact assertion that fails on main, and the two bypass sites are now symmetrically covered (one before add_backend_id, one after). Everything left is comment and test-documentation polish.

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

@bobrenjc93
bobrenjc93 requested a review from aorenste September 10, 2026 03:00
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 10, 2026 03:00
… check, root-verdict caching, scope-first reduce tuple, load-bearing tests

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196481

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…an internal error (#196470)

Error-typing plumbing for the precompile stack above; it drops no guard and
makes nothing more serializable.

To precompile a frame, Dynamo pickles the values its guards read. Some of
those values cannot be pickled: a config object whose `__reduce__` raises, a
lock stored on a function, a `GradScaler` in the middle of an iteration, a
tensor subclass that asserts in `__tensor_flatten__`.

When that happens the frame cannot be precompiled. We do not drop the guard
that reads the value, because that would make the artifact accept inputs it
should not. Instead the failure is reported as a `PackageError`. In strict
mode (the explicit `torch.compiler.precompile` capture) the user gets that
error, carrying the value's own error message. In non-strict mode
(`caching_precompile`) the compile is left out of the artifact and the bypass
is logged.

Both behaviours depend on the pickling failure arriving as a `PackageError`,
and on main it did so for exactly one exception type. `pickle_guards_state` mapped
`AttributeError` (a function the pickler cannot look up by name); anything
else a user value raised while being pickled -- `RuntimeError` from
`__reduce__`, `TypeError` from an unpicklable handle, `AssertionError` from a
`__getstate__`, `RecursionError` from a deep graph or a `__reduce__` that never
memoizes -- escaped as an `InternalTorchDynamoError`: a compiler crash with an
internal traceback, invisible to the reporting above. Map everything that
`dump` raises to `PackageError` with the cause chained, re-raising a
`PackageError` from `reducer_override` unchanged. `RecursionError` gets its own
clause so the message names the limit that was hit instead of the
interpreter's "maximum recursion depth exceeded while calling a Python object";
reporting WHERE it overflowed is skipped deliberately, since walking the
object graph would recurse again off an already exhausted stack. The one
sibling check in `serialize_guards` that still raised a bare exception -- a
TYPE_MATCH on a class defined in local scope raised `TypeError` -- now raises
`PackageError` like the checks around it. Its message names only the type:
`repr(obj)` is user code that can raise, and that check runs outside the
mapped `dump`, so interpolating the object would have left a crash path on the
very case being closed (and printed multi-KB module reprs into the error).
To that end `TYPE_MATCH` and `FAKE_SCRIPT_TYPE_MATCH` record the offending
TYPE on the guard (`_unserializable` holds it instead of a bool), so
`serialize_guards` no longer re-fetches the value at all, and the duplicate
local-scope check inside `reducer_override` goes through the same helper.
`pickle_guards_state`'s `tree_leaves` walk over the local scope and its
portable-guard pruning block moved inside the mapped `try` as well: the walk
recurses into local values and a deep pytree could overflow there, and an
error in either is a bypass, not an internal error.

The commits above make the pickler traverse far more user data (rebuilt
functions carry their defaults, closures, attributes and module snapshots), so
every new category of value it reaches is a new way for a capture to crash
instead of reporting what could not be packaged; they all assume this mapping.

On the broad `except Exception`: it is the same policy `AOTAutogradCache`
applies, and in strict mode nothing is lost since the cause is chained. The
non-strict bypass branch does turn an internal reducer bug into a "package
bypass" warning (with the traceback in the tlparse artifact); the explicit
capture is strict and test_package.py runs with `strict_precompile=True`, so CI
still sees such a bug. If the non-strict ambient mode is retired, this commit
reduces to that re-typing alone.

Test Plan:

```
python test/dynamo/test_guard_serialization.py -k test_recursing_guarded_value_overflow_is_a_package_error -k test_unserializable_guarded_value_is_a_package_error -k test_type_match
python test/dynamo/test_package.py -k test_unserializable_guard_bypasses_the_package -k test_bypassed_guards_keep_the_frames_earlier_variant
```

The test_package test and the new `UnpicklableConfig` case of the parametrized
earlier-variant test (its `__reduce__` raises RuntimeError, where the existing
case raises AttributeError) error out on the previous commit: the RuntimeError
escapes the compile. They check that the frame still compiles and runs with a
"package bypass" warning, that the bypassed compile saved no backend, that
reloading installs nothing for a frame whose only variant was bypassed, and
that a variant of the same frame that serialized earlier is saved, installed
on reload and hit under `fail_on_recompile` while the bypassed inputs are
traced fresh and bypass again. In test_guard_serialization (strict), a
`RuntimeError` from a guarded default's `__reduce__` surfaces as a
`PackageError`, the recursion test fails on the previous commit on the
exception type (and with only the broad clause on the message), and the
local-class test now expects `PackageError`, and a local class whose
`__repr__` raises is pinned to produce that same `PackageError` (it escaped as
`RuntimeError` while the message interpolated the object).

Authored with an AI assistant.

FAQ

Q: Doesn't the broad `except Exception` hide a serializer-internal
`AssertionError` as a mere "package bypass" warning under the default
non-strict mode?

A: Yes, and that is the stated cost. It is the same policy `AOTAutogradCache`
applies (`except Exception` -> bypass, a strict flag to raise); the full
traceback goes to the `precompile_cache_bypass` tlparse artifact, and both
test_package.py and test_guard_serialization.py run with
`strict_precompile=True`, so an internal assertion is a hard CI failure.
Printing tracebacks in the default warning would spam production logs for the
common case of a user value that cannot pickle.

Q: `bypass_package` builds `PackageError("Detected a package bypass: %s",
reason)` with printf-style args, which renders as a tuple. Fix it here?

A: Pre-existing and not on this change's path: under `strict_precompile`,
`build_guards` re-raises the pickler's `PackageError` directly (the message is
`RuntimeError: config cannot pickle`) before `bypass_package` runs. It is a
separate one-line fix.

Q: Should the recursion message suggest `sys.setrecursionlimit` or a
`guard_filter_fn`?

A: The default path is a bypass, not an error, and a limit hit inside a user
`__reduce__` has no single remedy; the sibling messages in this function are
equally bare.

Q: The AOT pickler has no such mapping.

A: It has a different contract (it raises on its `errors` list) and is handled
separately.

Q: The `RecursionError` clause is only tested under strict mode.

A: Both modes share the clause; the only difference is what
`CheckFunctionManager` does with the resulting `PackageError`, and that
dispatch is exercised by the non-strict test_package tests for the broad
clause. A non-strict recursion test would drive ~1000 real frames at the
ambient limit for no additional coverage of this change.

Pull Request resolved: #196470
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
A pure move with no behavior change. At this commit the new base class has
exactly ONE subclass, `GuardsStatePickler`; the second user is
`AOTCompilePickler`, which #196685 (ten commits up this stack) moves onto the
base. The extraction happens here so the next five commits have one place to
add the by-value function reducers that both picklers will share.

`GuardsStatePickler` (guard state) and `AOTCompilePickler`
(torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild
objects that pickle cannot do by reference -- code objects, python modules,
bound methods -- and each carries its own copy of those reducers. This commit
moves `GuardsStatePickler`'s copies into a new `FunctionPicklerBase` in
package.py and makes `GuardsStatePickler` subclass it. Bodies are unchanged
(one parameter renamed, one return annotation tightened).

Until #196685, `AOTCompilePickler` keeps its own copies of these reducers,
including the same bugs the commits here fix in the guard pickler (an
unguarded `cell_contents` read and the old nested-function rebuild). #196685
changes its base to `FunctionPicklerBase`, deletes the duplicates and
rewrites its dispatch around the shared reducers; because the closure-cell,
bound-method and by-value function reducers that #196472-#196478 add already
live on the base, that commit adds no reducer bodies of its own.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
```

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

Pull Request resolved: #196471
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…196472)

When Dynamo serializes guard state it pickles some functions by value (every
`<locals>` function reached through a capture, and the wrapped functions the
commits above add), and pickling a function by value pickles every cell in its
`__closure__`. The old reducer read the cell's contents up front and passed
them as a constructor argument, `_unpickle_cell(cell.cell_contents)`. Two
ordinary shapes broke on that:

    def make(captured):
        def fn(x):
            if x is None:
                return unset  # never runs
            return x + captured

        if captured is None:
            unset = 1  # never runs, so the cell for `unset` stays EMPTY

        return fn

`fn` closes over `captured` (filled) and `unset` (never assigned, so its cell
is empty). Tracing a call to `fn` installs a TENSOR_MATCH on `captured`, and
serializing that guard state pickles `fn` with its closure. Reading
`cell_contents` on the empty cell raised `ValueError: Cell is empty` out of the
pickler: a `PackageError` under strict precompile (an internal error before the
previous commit), a bypass of a perfectly serializable frame otherwise.

    def outer():
        def fact(n):
            return 1 if n <= 1 else n * fact(n - 1)
        return fact

`fact`'s one cell contains `fact` itself. Pickling `fact` pickles its cell,
whose constructor argument was `fact`, which is not memoized yet because it is
still being pickled, so pickle started over: `RecursionError`, reported as
"exceeded the recursion limit while pickling guard state".

The fix rebuilds a cell in two steps, an empty `types.CellType()` that pickle
memoizes first and its contents assigned afterwards as pickle state. A cell
that refers back to its own function no longer recurses: the second time pickle
reaches the function it finds the CELL memoized, builds the inner copy of the
function and sets the cell's contents to it, and the outer `save_reduce` then
drops its duplicate through the recursive-object fallback because the object
is in the memo by then. A genuinely empty cell (reading
`cell_contents` raised `ValueError`) carries no state and is rebuilt empty,
and the contents are wrapped in a 1-tuple because pickle skips the state step
for a bare None, which would otherwise turn a cell holding None into an empty
one. The reducer lives on `FunctionPicklerBase` so the function-rebuilding
commits above share it; `AOTCompilePickler` keeps its own unguarded read until
#196454 moves it onto the base.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_empty_closure_cell_of_a_traced_local_function -k test_reduce_handles_an_empty_cell_reached_directly -k test_reduce_keeps_a_none_valued_cell -k test_reduce_preserves_a_self_referential_cell
```

On the previous commit the capture test and the direct-cell test error with
`ValueError: Cell is empty` and the self-referential one with `RecursionError`;
the capture test is the realistic trigger (a traced local function with an
empty sibling cell), the pickler-level one covers a raw cell, which no
serializable guard type can root at (CLOSURE_MATCH is unsupported). The new
`TestGuardsStatePickler` class drives the pickler directly.

Authored with an AI assistant.

FAQ

Q: Isn't the `keep_name_with_empty_cell` / `functools.wraps` / module-level
`EMPTY_CELL_WRAPPED` fixture more than this change needs? A local helper that
returns an empty cell would do.

A: At this commit only the empty cell is needed, but the fixture is shaped for
the by-value function commits above it: one pickles `EMPTY_CELL_WRAPPED`
itself as a rebuilt function with an empty sibling cell, and another renames
the wrapped function to prove the wrapper is rebuilt rather than resolved by
name. Defining it once here avoids reshaping it two commits later.

Q: The `FunctionPicklerBase` docstring claims a shared-fix invariant that
`AOTCompilePickler` violates.

A: The docstring states that `GuardsStatePickler` is the only subclass and
that `AOTCompilePickler` keeps its own copies until it is moved onto the base
separately; `prepare_f_locals` dereferences cells unconditionally there, so
that migration is a standalone change.

Pull Request resolved: #196472
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470, #196471

@aorenste aorenste left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Reviewed by me, assisted by AI)

[cleanup] My agent says:

In the commit message, "(both used to run regardless)" holds only for update_device_type. On the base ref add_inlined_source opens with its own if self._current_entry.bypassed: return, and the bypass has already set that flag by the time convert_frame calls it, so a bypassed compile did not record inlined sources pre-PR either. Instrumenting the named-parameter bypass on base prints add_inlined_source: bypassed=True n_sources=1 inlined 1->1 next to update_device_type: RAN; at the guards-serialization site neither runs, because base dies on the guards_state assertion first. The sentence's own later clause ("which the sticky per-entry flag used to suppress") depends on that early return existing.

Comment thread torch/_dynamo/package.py
dynamo_code=SerializedCode.from_code_object(dynamo_code),
)
self._current_entry.guarded_codes.append(guarded_code_entry)
self._current_entry.bypassed = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocker] My agent says:

This amplifies an existing leak by ~89x. An entry that from_cache_entry poisoned for a missing backend is skipped by install(), so the frame is traced fresh; that compile now reaches here, appends a full serialized guards state to the entry the reload deserialized, and clears the flag. The next save re-poisons it (the missing id is still first in backend_ids) and writes the bigger entry back over the same path, so the entry never becomes installable and never stops growing.

Measured end to end: real torch.compile under caching_precompile=True, one graph-break frame whose resume backend artifact is missing at save time, six reload+recompile+save cycles, size of the on-disk entry file:

base  33207 -> 33644 B  (+57 B/cycle)    guarded_codes 1 -> 1  backend_ids 1 -> 7
this  33207 -> 63745 B  (+5057 B/cycle)  guarded_codes 1 -> 7  backend_ids 1 -> 7

The backend-id half is pre-existing (output_graph.py:3053 was never gated on bypassed); the new half is one ~4 KB guards_state per run. So the FAQ's "the steady state is the same as before this change" is true for what gets served, not for what gets written.

Clearing a loaded bypassed entry's guarded_codes and backend_ids in initialize() bounds both and is strictly less than the per-variant load path the FAQ defers: install() cannot reach that entry anyway, and it lets the frame become cacheable again instead of staying poisoned forever.

scale = 2.0

def __reduce__(self):
raise AttributeError("config cannot pickle")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cleanup] My agent says:

AttributeError is load-bearing here, not incidental - pickle_guards_state maps only that one type to PackageError (guards.py:4603-4605). Swap it for TypeError and there is no bypass at all; the compile dies as InternalTorchDynamoError.

    def __reduce__(self):
        # AttributeError is the only exception pickle_guards_state converts to
        # PackageError, so it is the only one that reaches the bypass.
        raise AttributeError("config cannot pickle")

self.assertEqual(compiled(x), fn(x))
# Deliberate: re-triggers the bypass in the loading process against an
# entry that already holds one installed guarded code.
self.assertEqual(compiled(x, cfg), fn(x, cfg))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cleanup] My agent says:

The numerics match whether this was traced fresh or served by something that got installed, so nothing pins the claim the comment above makes. Every other caching_precompile test in the file brackets the reload with FRAME_COUNTER, and test_graph_break_partial_backend uses total_frames + 1 for exactly this shape:

self.assertEqual(compiled(x, cfg), fn(x, cfg))
self.assertEqual(torch._dynamo.convert_frame.FRAME_COUNTER, total_frames + 1)

with total_frames = torch._dynamo.convert_frame.FRAME_COUNTER captured before save_to_dynamo_cache().

bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
Follow-up to #196505, from its review. A resume frame whose backend artifact
is missing when the package is saved is written with `bypassed=True` by
`PrecompileCacheEntry.from_cache_entry`, and `install()` skips it, so the
next process traces that frame fresh:

```python
def fn(x):
    y = x.sin()
    torch._dynamo.graph_break()          # a resume frame with its own backend
    return x.sin() + y

torch.compile(fn)(x)
del PrecompileContext._backend_artifacts_by_key[resume_backend_id]
save()                                   # resume entry written bypassed
# next process
torch.compile(fn)(x)                     # resume frame traced fresh
save()
```

That fresh compile appended its guarded code to the stale one the reload had
deserialized, cleared the flag, and re-registered a backend id next to the
missing one still listed first. The next save found the missing id again,
re-poisoned the entry and wrote the bigger one back over the same path, so the
entry never became installable and never stopped growing:

```
base:    guarded_codes 1 -> 1  backend_ids 1 -> 7   (33 KB -> 34 KB over six cycles)
#196505: guarded_codes 1 -> 7  backend_ids 1 -> 7   (33 KB -> 64 KB)
```

(Byte sizes from the reviewer's environment; the counts reproduce exactly.)

The backend-id half predates #196505 (`OutputGraph` registers the id whether
or not the entry is bypassed); the guarded-code half is new there, since
`add_guarded_code` now appends and clears the flag on such an entry.

`CompilePackage.initialize` now drops a loaded bypassed entry's guarded codes
and backend ids. `install()` skips such an entry entirely, so nothing on it was
installable; the fresh compile's record is the whole entry and the next save
writes an installable one, so the third process hits without compiling
anything. The reset lives on the load side rather than in the save-time writer
because for an entry already on disk in the stale state the writer cannot tell
the missing id from the fresh compile's id listed beside it, so a writer-side
clear would discard the fresh code too and converge one save later. The
better endpoint, not taken here, is a per-guarded-code prune at write time
(drop only the guarded codes whose bytecode names the missing backend), which
would keep a multi-variant entry installable and never write the stale bytes.
The entry docstring says what the writer and the loader each do.

Two test cleanups from the same review: `ConfigThatCannotPickle` says why it
raises AttributeError specifically (the one exception the bypass mapped before
#196470 widened it), and the earlier-variant test pins that only the bypassed
inputs compiled after the reload. It counts `counters["frames"]["total"]`
rather than the `FRAME_COUNTER` bracket the file's other caching_precompile
tests use: `reset()` zeroes `FRAME_COUNTER` and installing a precompiled entry
consumes a compile id, so a `+ 1` there holds only by cancellation.

Test Plan:

```
python test/dynamo/test_package.py
python test/dynamo/test_package.py -k test_a_poisoned_entry_is_reset_on_load_instead_of_growing -k test_bypassed_guards_keep_the_frames_earlier_variant
```

The new test runs the cycle above through `PrecompileContext` and
`DynamoCache`: after the second save the resume entry has one guarded code and
one backend id and is not bypassed (on the previous commit it has two of each
and is bypassed again), and a third load serves both frames with
`counters["frames"]["total"]` unchanged under `fail_on_recompile`.

Authored with an AI assistant.

ghstack-source-id: cb4fb06
Pull-Request: #196756
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
Follow-up to #196505, from its review. A resume frame whose backend artifact
is missing when the package is saved is written with `bypassed=True` by
`PrecompileCacheEntry.from_cache_entry`, and `install()` skips it, so the
next process traces that frame fresh:

```python
def fn(x):
    y = x.sin()
    torch._dynamo.graph_break()          # a resume frame with its own backend
    return x.sin() + y

torch.compile(fn)(x)
del PrecompileContext._backend_artifacts_by_key[resume_backend_id]
save()                                   # resume entry written bypassed
# next process
torch.compile(fn)(x)                     # resume frame traced fresh
save()
```

That fresh compile appended its guarded code to the stale one the reload had
deserialized, cleared the flag, and re-registered a backend id next to the
missing one still listed first. The next save found the missing id again,
re-poisoned the entry and wrote the bigger one back over the same path, so the
entry never became installable and never stopped growing:

```
base:    guarded_codes 1 -> 1  backend_ids 1 -> 7   (33 KB -> 34 KB over six cycles)
#196505: guarded_codes 1 -> 7  backend_ids 1 -> 7   (33 KB -> 64 KB)
```

(Byte sizes from the reviewer's environment; the counts reproduce exactly.)

The backend-id half predates #196505 (`OutputGraph` registers the id whether
or not the entry is bypassed); the guarded-code half is new there, since
`add_guarded_code` now appends and clears the flag on such an entry.

`CompilePackage.initialize` now loads a bypassed entry without its guarded
codes and backend ids: the package's own map gets a `dataclasses.replace` copy,
and the caller's entry is untouched, since a store may hand out the object it
holds (`InMemoryDynamoStore` does). `install()` skips such an entry entirely,
so nothing on it was installable, every variant of that code object included
(`from_cache_entry` flags the whole entry on the first missing artifact); the
fresh compile's record is the whole entry and the next save writes an
installable one, so the third process hits without compiling anything. The reset lives on the load side rather than in the save-time writer
because for an entry already on disk in the stale state the writer cannot tell
the missing id from the fresh compile's id listed beside it, so a writer-side
clear would discard the fresh code too and converge one save later. The
better endpoint, not taken here, is a per-guarded-code prune at write time
(drop only the guarded codes whose bytecode names the missing backend), which
would keep a multi-variant entry installable and never write the stale bytes.
The entry docstring says what the writer and the loader each do.

Two test cleanups from the same review: `ConfigThatCannotPickle` says why it
raises AttributeError specifically (the one exception the bypass mapped before
#196470 widened it), and the earlier-variant test pins that only the bypassed
inputs compiled after the reload. It counts `counters["frames"]["total"]`
rather than the `FRAME_COUNTER` bracket the file's other caching_precompile
tests use: `reset()` zeroes `FRAME_COUNTER` and installing a precompiled entry
consumes a compile id, so a `+ 1` there holds only by cancellation.

Test Plan:

```
python test/dynamo/test_package.py
python test/dynamo/test_package.py -k test_a_poisoned_entry_is_reset_on_load_instead_of_growing -k test_bypassed_guards_keep_the_frames_earlier_variant
```

The new test runs the cycle above through `PrecompileContext` and
`DynamoCache`: after the second save the resume entry has one guarded code and
one backend id and is not bypassed (on the previous commit it has two of each
and is bypassed again), and a third load serves both frames with
`counters["frames"]["total"]` unchanged under `fail_on_recompile`. It also
builds a `CompilePackage` from a loaded entry and checks the entry it was
given still holds its guarded code while the package's `cache_entry()` does
not.

Authored with an AI assistant.

ghstack-source-id: 51ea561
Pull-Request: #196756
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
… getattr cannot resolve it (#196473)

A bound method (`obj.method`) is a pair: the function, and the object it was
fetched from -- the receiver, the `self` it will run against. Normally the pair
comes from a class attribute lookup, so it can be re-derived: `getattr(obj,
"method")` gives it back. Python also lets you build the pair by hand with
`types.MethodType(func, obj)`, in which case `obj`'s class may have no
attribute of that name at all. pickle's built-in rule for a bound method
stores the receiver and the NAME and does `getattr(receiver, name)` at load;
it never stores the function. The guard pickler therefore has an explicit
alternative that stores `(func, receiver)` -- the function by value (its code
object, rebuilt with `types.FunctionType`) and the receiver as the pickler
would store it anyway -- and rebuilds with `types.MethodType`.

Dynamo needs this whenever a compiled function receives a bound method:

    def on_step(state, x):
        return x + state.offset

    class State:
        offset = 1

    callback = types.MethodType(on_step, State())  # bind the state as `self`

    def fn(f, x):
        if callable(f):
            x = x + 1
        return f(x)

    torch.compile(fn)(callback, torch.randn(3))

`callable(f)` installs a TYPE_MATCH on `f`, and inlining `f(x)` adds an
ID_MATCH on `f.__func__.__code__` and a TYPE_MATCH on `f.__self__`. To
precompile, the bound method object is pickled with the guard state, and at
load those sources are re-walked against the reconstructed object, so it must
carry the same function and the same receiver.

The old code chose between pickle's rule and the explicit pair with a probe,
`getattr(receiver, func.__name__)`, taking the explicit pair only when the
probe did not return the same function. The probe was the bug:

- For `callback` it ran `getattr(State(), "on_step")`; `State` has no such
  attribute, and the AttributeError escaped the reducer: a PackageError under
  strict precompile, a bypass of a fine frame otherwise (an internal error
  before #196470 mapped every reducer exception to a PackageError). pickle's rule would have failed the same way at
  load, so the explicit pair is the only form that works here.
- A `functools.partial` as the method's function has no `__name__`, so the
  probe raised before looking anything up.
- A class holding the function as a `staticmethod` under that name makes the
  probe return the raw function, so `func is inner` held, pickle's rule ran,
  and the object loaded back as a plain function where a bound method was.
- Any receiver whose class defines `__getattr__` -- every nn.Module -- runs
  that user code in the probe, which can have side effects or recurse. And its
  answer means nothing for this pickler: a non-referenceable module is rebuilt
  as a bare `torch.nn.Module` placeholder at load, on which `getattr` would
  not find `forward`.

The nn.Module case also shows why the explicit pair, not the class, is what
makes the method reloadable. A module whose class is not a module-level name
cannot be pickled by reference, so the guard pickler stores its state and
rebuilds it as a plain `torch.nn.Module` with that state; the class is
forgotten. pickle's rule would then look `forward` up on the plain module and
find nn.Module's placeholder. With the explicit pair the loaded method is that
plain module with `forward`'s own code attached by `types.MethodType`, which is
all the guards read (the pickler-level test pins this; end to end this exact
shape is refused earlier by the local-class TYPE_MATCH check).

The fix moves the decision into `FunctionPicklerBase._reduce_bound_method`,
which stores the explicit pair unless it can PROVE pickle's rule will produce
the same bound method at load:

1. A receiver whose class defines `__getattr__` is never probed; the pair is
   stored without touching the instance. This is deliberately coarse; a false
   "store the pair" is still correct, and narrowing it per name with
   `getattr_static` at every guard build buys nothing but cost.
2. A name served per instance (in the instance `__dict__`, or a `__slots__`
   member) is stored as the pair: `getattr` at load hands back whatever the
   dict or slot holds -- a raw function or a method bound to another object --
   never a method over this pair (and in the self-cycle case the slot is not
   restored yet).
3. Otherwise probe, under a `try`: `getattr(receiver, name)` can raise anything
   through a `__getattribute__` override, a property or a metaclass
   `__getattr__`, and any exception falls back to the pair instead of escaping
   the reducer. A function without `__name__` skips the probe.
4. pickle's rule is taken only on proof: the probe must return a method bound
   to THIS receiver over THIS function (`inspect.ismethod(inner) and
   inner.__func__ is func and inner.__self__ is receiver`).

A method the class genuinely supplies to a plain instance still takes pickle's
compact rule, so ordinary bound methods pickle exactly as before.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method
```

Eight of the thirteen tests matched by the second command fail or error
against the previous commit's logic: seven new pickler-level tests (name self
lacks, slot, `__getattr__` proxy, raising probes, staticmethod name, a
`functools.partial` as `__func__`, the nn.Module method) and the one new
capture test. The fall-through test pins that plain methods and classmethods
keep pickle's compact `getattr` form (an always-explicit implementation fails
it); the four pre-existing `bound_method` capture tests pass on both. A known
gap closed by #196481: an nn.Module method whose `__func__` is fqn-mismatched
now reaches the `isfunction` branch and is pruned to `_Missing` unless a guard
registers the function, where pickle's name-based rule never needed the fqn.
The staticmethod case also fails against a plain `func is inner` check,
loading a function. The proxy test asserts the receiver's `__getattr__` was
never asked for the method name (pickle itself may probe protocol names on
the instance); the nn.Module test uses a function-local class so the receiver
is rebuilt as a bare `nn.Module`, where the default reconstruction would
resolve `forward` to the placeholder.

Authored with an AI assistant.

FAQ

Q: Should the `__getattr__` gate be narrowed with `getattr_static` so that
nn.Module methods stay on pickle's default path?

A: No. The default path rebuilds the method as `getattr(self, name)` on the
RELOADED receiver, and `GuardsStatePickler` rebuilds any nn.Module whose class
cannot be pickled by reference as a bare `torch.nn.Module`, on which `forward`
resolves to `_forward_unimplemented`. Empirically the narrowed gate loads that
placeholder and raises `NotImplementedError` on call; the coarse gate loads the
right function. A class-body lambda `forward` on a module-level class degrades
to `_Missing` under both gates, because the name a bound method reduces by is
`__func__.__name__`, i.e. `<lambda>`, not `forward` (on a function-local class
its qualname contains `<locals>`, so it is rebuilt from its code object and
loads fine); it raised `AttributeError` before this change, so it is not a
regression. The same fact covers the `functools.partial` case: pickle's own
`method.__reduce__` reads `__func__.__name__`, so a partial `__func__` is
unpicklable on the default path regardless of this reducer.

Q: Could the three receiver tests be one parametrized test?

A: Each asserts something different (the bound-method type for the
staticmethod case, `.func` of the partial, the receiver class for the module)
and documents a distinct failure mode; a shared body would need per-case
assertions.

Pull Request resolved: #196473
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…#196474)

Enabler for the precompile stack above this one.

pickle saves a function by NAME: it stores `__module__` and `__qualname__`,
and at load imports the module and walks the dotted name. That is the cheap,
exact default -- the loaded function IS the one the serving process has -- and
it works only if walking the name lands back on the same function.
`functools.wraps` breaks that: it copies the wrapped function's `__module__`,
`__qualname__`, `__name__`, `__doc__`, `__annotations__` (and `__type_params__`
on 3.12+) and `__dict__` onto the wrapper, so the
wrapper CLAIMS to be the original and the original's name now resolves to the
wrapper. A module-level lambda (qualname `<lambda>`), an `exec`-created
function, or a `__module__` of None have the same problem. Dynamo calls these
fqn mismatches, and until now the guard pickler replaced any such function
whose module was in `sys.modules` with a `_Missing("fqn mismatch")` sentinel,
which is right for a function nothing depends on; one whose module was not
(exec-created, or `__module__` None) fell through to pickle's by-reference rule
and failed the dump (a bypass).

    def keep_defaults(func):
        @functools.wraps(func)
        def wrapper(self, x):
            if len(func.__defaults__) == 2:
                x = x + 1
            return func(self, x)
        return wrapper

    class M(torch.nn.Module):
        @keep_defaults
        def forward(self, x, scale=2.0, shift=1.0):
            return x * scale + shift

    torch.compile(M())(torch.randn(3))

Dynamo inlines `wrapper` and reaches `func`, the undecorated `forward`,
through the closure. `func.__qualname__` is `M.forward`, but `M.forward` now
resolves to `wrapper`: an fqn mismatch. The `len(func.__defaults__) == 2`
check installs a SEQUENCE_LENGTH guard whose source walks through `func`.
Serialization stored `func` as the sentinel, so at load re-walking that source
hit `'_Missing' object has no attribute '__defaults__'` and the package failed
to load. A guard on `func.__module__` was worse: the sentinel happens to have
one, so the guard silently rebaked against `torch._dynamo.guards` and never
matched again. Every `functools.wraps` decorator that reads anything off the
function it wraps hits one of these.

The fix: a function whose name does not resolve back to it, and that some
guard is rooted at, is stored by value -- its code object, its `__module__`,
`__qualname__` and `__name__`, its closure cells, and its defaults -- and
rebuilt at load with `types.FunctionType`, using the imported module's dict as
globals (or an empty dict if the module cannot be imported; a guard reads
attributes off the function and never calls it). The three names are set
explicitly afterwards because `FunctionType` derives them from the code object
and `wraps` had changed them; a guard on `func.__name__` must see the value it
saw at trace time. Defaults travel as pickle state so a default that refers
back to the function does not recurse. Importing the module at load runs its
top-level code if it is not loaded yet (for a `wraps` wrapper that is the
wrapped function's module, almost always already imported); an import that
fails is logged at debug level before the empty scope is used. A `__module__`
that is not a str is restored as is: Dynamo's own trace rules cannot trace
such a function, but a decorator can leave one behind and the reducer must not
TypeError on it. The three names are restored unconditionally, None included,
so the result does not depend on the scope the caller happened to pass. A
`<locals>` function is rebuilt whether or not a guard is rooted at it, as
before; unlike a wraps wrapper it has no module-level neighbourhood to drag
along.

Two boundaries keep this narrow. An fqn-mismatched function that no guard
reads still becomes the sentinel, so rebuilding does not drag every wrapper's
neighbourhood into the artifact. And `<locals>` functions, which were already
rebuilt by value, now share this reducer; that fixes the old path passing
`__qualname__` as the function's NAME (`test_rebuilt_locals_function_keeps_its_name`
pins it: `__name__` was `outer.<locals>.f` before) and failing the load on an
unimportable module. Keyword-only defaults, the other attributes, and pruning of what no
guard reads land in the next commit; the Note in guards.py lists what the
rebuilt function carries so that gap is visible. `_apply_function_state` is a
classmethod like the other reducers embedded in an artifact, so the artifact
names the pickler subclass and resolves through its MRO.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k fqn_mismatch -k test_guard_rooted_at_a_none_valued_closure_cell -k test_rebuilt_function_keeps_an_empty_closure_cell -k test_reduce_restores_a_non_str_module -k test_rebuilt_functions_keep_a_shared_closure_cell_shared
```

The parametrized `test_guard_rooted_at_fqn_mismatched_function` cases each
mutate the restored attribute (`__defaults__`, `__name__`, `__qualname__`,
`__module__`) on the live function and assert the loaded guard REJECTS it,
since a reconstruction that pinned nothing passes the positive check alone.
Four of the six parametrized cases (`defaults_length`, `default_value`,
`renamed_name`, `qualname`) error on the previous commit with `'_Missing'
object has no attribute ...`, as do the module-gone-at-load, None-valued-cell
and empty-cell tests; the `module_name` case instead loads a guard pinned to
the sentinel's own `__module__` (`torch._dynamo.guards`) and never matches,
the silent form of the same failure; `none_module` fails the dump on the
previous commit, where pickle's by-reference rule cannot place a function
without a module. The `none_module` case covers a `__module__`
of None through the guard (Dynamo traces `func.__module__` as the scope's
`__name__`, a pre-existing divergence, so the guard's real-attribute round trip
is what it pins); the non-str case is pickler-level, since Dynamo cannot
trace such a function; and a function whose module was never in `sys.modules`
at dump time, which used to fail the dump by reference (a bypass), now rebuilds
and rejects a change like the others.

Authored with an AI assistant.

Pull Request resolved: #196474
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…ard reads (#196476)

`types.FunctionType(code, ...)` takes `__doc__` from the code object, leaves
`__annotations__` and `__type_params__` empty, and starts with an empty
`__dict__` and no `__kwdefaults__`.
`functools.wraps` overwrote all of these on the live function, and a guard
rooted at a wrapper reads them: an EQUALS_MATCH on `func.scale_flag`,
`func.__doc__` or `func.__kwdefaults__["scale"]`, an ID_MATCH on an annotation
value. Rebuilt from the code object alone those read None or empty, the guard
rebakes against that at load, and it fails forever with no load error (or the
load raises, for an attribute that is gone). So `__kwdefaults__`, `__dict__`,
`__doc__`, `__annotations__` and `__type_params__` now travel in the pickle
state next to the defaults, applied after memoization so `wrapper.me =
wrapper` terminates.

Carrying them verbatim would trade one failure for another: everything the
function holds comes along, and one unpicklable, unguarded neighbour -- a
`threading.Lock` a decorator stashed in `__dict__`, a local class in an
annotation, a `TypeVar` in the `__type_params__` that `wraps` copies off any
PEP 695 generic, an unrelated default -- fails the dump and silently bypasses
a package that never needed the value. Only values some guard tree node
references (`_keep`, identity in `guard_tree_values`) are carried; the rest
are replaced IN PLACE by a `_Missing` sentinel, one per reason, so the
signature's shape (defaults length, kwdefaults keys, `__dict__` key set)
survives for a guard that reads structure rather than values. Always-picklable
constants (None, bool/int/float/complex/str/bytes, Ellipsis, NotImplemented,
torch.dtype/device/layout/memory_format) are always carried: they cannot fail
the dump, and pruning them would make the rebuilt state depend on whether some
unrelated guard happened to register the interned value. That is deliberately
not dynamo's whole `common_constant_types`, which includes `torch.finfo` and
`torch.iinfo`, and those do not pickle. A registered CONTAINER (a guard on the `__defaults__` tuple
itself, as `bind_args` installs for any called function with a positional
default) is carried verbatim, since a whole-container EQUALS_MATCH rebakes its
constant from the reconstructed function at load; the follow-up that decides
per container whether a guard reads its values comes two commits up. Until
then any guard whose source walks THROUGH a container registers it -- an
unread positional default of a CALLED function (`bind_args` installs a length
guard on `__defaults__`), `f.__dict__["tag"]`, `f.__defaults__[0]`,
`f.__kwdefaults__["k"]`, `f.__annotations__["x"]` -- so an unpicklable sibling
in that container still fails the dump; only a plain attribute read
(`f.tag`) prunes. The `name_beside_unpicklable_default` subtest exercises the
pickler only because the test harness's guard filter drops the `bind_args`
guard. A cell whose contents are kept (or empty) passes through unchanged so
two functions closing over one variable still share it after reload; a
pruned cell is memoized by the original cell's identity for the same reason. `__dict__` is assigned before
`__type_params__`: on Python < 3.12 both live in `__dict__`, and the reducer's
pruned tuple has to win over the copy inside the carried dict.

Restore and prune land together because either alone regresses its parent:
verbatim restore fails the dump for every generic function and every local
function with an unpicklable attribute, and pruning needs the restore
plumbing. Annotations are read with `_read_raw_annotations`, which on 3.14+
asks for the FORWARDREF format so a TYPE_CHECKING-only name does not raise
during the dump; it returns a copy, with a proxy only for names that do not
resolve, and the copy is pruned per value like any other unkept container.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k prunes -k sentinels -k type_params -k kwdefaults -k attribute -k annotations -k reaches_itself -k copied_doc -k a_lambda -k name_beside -k with_an_empty_cell -k dict_key_set -k guarded_defaults_tuple -k package_error -k pruned -k reaching_itself
```

Sixteen of the twenty new tests matched by the second command fail or error on
the previous commit (the command also matches two pre-existing `package_error`
tests); the two that pass there pin that `_prune_cell` tolerates an empty cell
and that a kept default is carried rather than pruned. A manually assigned `__type_params__` round-trips on
every version, exercising the `__dict__`-before-`__type_params__` order on
3.10/3.11 where both hold it.

Authored with an AI assistant.

FAQ

Q: There is no test for the 3.14 `annotationlib` FORWARDREF branch of
`_read_raw_annotations`.

A: The 3.14 path differs only in how the annotations are READ; what comes
back is a fresh dict whose values go through the same version-independent
`_prune` as any other unguarded non-literal, which the unpicklable-annotation
test covers. On 3.14.7, FORWARDREF does not raise for a TYPE_CHECKING-only
name and returns a new dict each call, so the proxy can never be identity-kept
and is always sentinelled. There is no 3.14 torch build here to run a gated
test against, so it is deferred rather than shipped unverified.

Pull Request resolved: #196476
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
#196478)

Every function carries a pointer to the module dict it was defined in,
`fn.__globals__`, and its body looks up every non-local name there.
`functools.wraps` makes a wrapper lie about which dict that is:

```python
# decorators.py
SCALE = 2

def scaled(func):
    @functools.wraps(func)
    def wrapper(self, x):
        return func(self, x) * SCALE   # looked up in wrapper.__globals__
    return wrapper

# model.py
class M(torch.nn.Module):
    @scaled
    def forward(self, x):
        return x + 1

>>> M.forward.__module__
'model'          # copied from the wrapped function by wraps
>>> M.forward.__globals__ is sys.modules['decorators'].__dict__
True             # where wrapper was actually defined
```

The previous commit rebuilds such a function from its code object and, at
load, hands `types.FunctionType` the only scope it recorded:
`import_module(fn.__module__).__dict__`, here the `model` dict (#196684, above,
imports the compile scope instead, which removes this particular KeyError but
not the two reasons below). Tracing `wrapper` read `SCALE`, so Dynamo guards
through the function's globals:

```python
L['self'].forward.__func__.__globals__['SCALE'] == 2
```

Rebuilding the guard manager at load walks that path on the rebuilt function
and gets `model.__dict__['SCALE']`, a `KeyError`, so the whole package fails to
load. Two things an import can never provide even when it lands on the right
module: the guard must be baked from the value the compile SAW, not whatever
the live module dict holds in the loading process (an import would silently
accept a changed global), and a decorator module that only lived in
`sys.modules` at save has no dict to import at all.

When `fn.__globals__` is itself in `guard_tree_values` (some guard read
through it), carry a snapshot of the dict the function was actually defined
in instead of importing by name, pruned per value like the other containers:

```python
{"__name__": "decorators", "SCALE": 2, "scaled": _Missing(...), "functools": _Missing(...), "__builtins__": builtins}
```

The function is built directly over that dict at load, so
`wrapper.__globals__['SCALE']` is 2 and the guard bakes correctly. A function
whose globals no guard reads keeps the import fallback.

`__builtins__` cannot be a sentinel: `FunctionType` reads
`scope['__builtins__']` at creation to wire up `len`, `isinstance` and the
rest, so a pruned entry becomes the real `builtins` module (pickled by
reference) while a kept one, the builtins dict a guard read through, stays
verbatim; the key set is unchanged.

The snapshot is built once per module dict and memoized by identity, so two
wrappers from the same decorator file share ONE scope after load, as before
saving, and pickle records a reference rather than a copy for the second. It
travels as a reduce ARGUMENT, not as pickle state. A wrapper defined at module
scope is an entry in its own module dict, so pickle reaches it while the
snapshot is still being filled in; `fn.__globals__.update(snapshot)` applied
as state would copy whatever had loaded by then, an empty dict for that
function, and a guard through its globals would KeyError again. Passing the
dict to the constructor gives the function the one shared object and pickle
keeps filling it in afterwards, which is fine because a function reads
`__globals__` lazily at call time. The snapshot's entry for the function
itself closes the cycle through pickle's recursive-object fallback, the same
mechanism a cell closing over its own function relies on; the pure-Python
pickler applies the state on both passes (the C pickler drops the outer one
after the memo fetch), so every write in `_apply_function_state` is
idempotent. The one-`_Missing`-per-reason cache from the pruning commit keeps a
pruned module dict from carrying thousands of distinct sentinels.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_guard_through_globals_of_a_wrapper_from_another_module -k test_functions_sharing_a_module_dict_share_the_rebuilt_scope -k test_snapshot_globals_share_one_missing_sentinel -k fqn_mismatched_function_module
```

The two-module test wraps `torch._dynamo.testing.reset_rng_state` from this
test module and guards through the wrapper's `__globals__`; with the snapshot
replaced by the import fallback it errors with `KeyError` at load (at this
commit; #196684 above changes the fallback and this test then pins the
snapshot only through the save-time-value test). The save-time-value test
mutates the guarded global between dump and load and checks the rebuilt
wrapper still sees the saved value in a dict that is not the live one; with
the import fallback it sees the mutated value. The shared-scope test pickles
two module-scope wrappers with their module dict and requires both to load
over one complete scope; with the snapshot applied as state the nested one
loads with `{}`. The preserves-module test pickles that wrapper with its
globals and checks `__module__` is the wrappee's module while the scope's
`__name__` is this module's; without the `__module__` restore it comes back
None, since the wrapper is built while its own snapshot is still loading. The
shared-sentinel and built-once tests fail or error on the previous commit
(the latter reads an attribute this commit adds). The remaining snapshot tests
(preserved/rejected globals, module-scope wrappers) pass on the previous
commit too, since their fixtures live in one importable module.

Authored with an AI assistant.

FAQ

Q: The snapshot freezes the module dict's key set at save time, including the
names Dynamo installed into that dict during the compile (`__compiled_fn_N`,
`__builtins_dict___N`, ...). Can a guard on the dict's shape, such as
`len(func.__globals__)`, miss forever in another process?

A: A guard on a module dict's key set is fragile by construction, with or
without this change: Dynamo writes into module dicts, the names it writes
differ between the saving and the loading process, and `install()` reinstalls
only the ones the installed entries need. Before this change the constant was
rebaked from the live module dict at load, which already contained a different
set of installed names than at save. The snapshot does not make that shape
guard portable, and it is not meant to; it makes the VALUES a guard reads
through `__globals__` come back as they were saved, which is what the
motivating wrapper case needs. Filtering Dynamo's names out of the snapshot
would not help, since the live dict at check time contains them.

Q: No test loads a snapshot in a fresh process.

A: The pickler-level and harness tests pin the two properties the change owns
(the shared scope and the values it carries) and the on-disk round trip is
covered by test_package's reload tests for the package as a whole. A
cross-process test would only add the shape-guard question above, which is
answered by design rather than by this change.

Pull Request resolved: #196478
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…ard reads its values (#196479)

The pruning commit carries a rebuilt function's `__defaults__`,
`__kwdefaults__`, `__dict__` and `__annotations__` with every value a guard
did not read replaced by a `_Missing` sentinel:

```python
def scaled(func):
    @functools.wraps(func)
    def wrapper(self, x, scale=2.0, junk=threading.Lock()):
        return func(self, x) * scale
    wrapper.tag = "v1"
    wrapper._cache = threading.Lock()
    return wrapper

wrapper.__defaults__  ->  (2.0, _Missing)      # 2.0 is a literal, the Lock is not
wrapper.__dict__      ->  {"tag": "v1", "_cache": _Missing, "__wrapped__": ...}
```

The lock is never pickled, the shape survives, and a guard on `func.tag` or
`len(func.__defaults__)` bakes correctly at load.

It carved out one exception: a guard that compares a container as a whole,
`func.__defaults__ == (2.0, (1, 2))`, rebakes its constant from the
reconstructed function at load, so a tuple that came back as `(2.0, _Missing)`
would miss forever with no error. The commit therefore carried a container
verbatim whenever the container itself was in `guard_tree_values`. That is
the wrong signal, both ways.

Registration does not mean a value guard. The builder records every object a
source path walks through, and two very common guards register the tuple
without caring about its values:

```python
# 1. Calling any function with a positional default: bind_args installs a
#    SEQUENCE_LENGTH on __defaults__ so the parameter-to-default mapping holds.
mod.forward(x)              # len(L['mod'].forward.__func__.__defaults__) == 2

# 2. Reading one element: the source path passes through the tuple.
if wrapper.__defaults__[0] > 1.0: ...
```

Both survive per-value pruning, yet the old rule forced the whole tuple
verbatim, the dump tried to pickle the lock, and the package bypassed. A
CALLED function with an unread unpicklable default, the common shape, was
still broken end to end; the harness-level subtest passed only because
`_test_serialization`'s guard filter drops the `bind_args` guard.

The inverse rule fails too. A whole-tuple equality and a per-element guard
coexist in ordinary code:

```python
def forward(self, x, scale=2.0, shape=(1, 2)): ...
mod.forward(x)                                     # binds scale through the tuple
assert mod.forward.__defaults__ == (2.0, (1, 2))   # EQUALS_MATCH on the whole tuple
```

Prune here because an element is guarded through the tuple and the equality
guard rebakes against `(2.0, _Missing)`.

So record the decision where it is made. `EQUALS_MATCH` is the one guard whose
constant depends on every element (CONSTANT_MATCH lowers to it), so it now
records every plain tuple it reads whole, keyed by id and holding the value so
the id cannot be reused:

```python
def EQUALS_MATCH(self, guard, ...):
    val = self.get(guard)
    if self.save_guards and type(val) is tuple:
        self.value_guarded_containers[id(val)] = val
```

The pickler receives that map as a required argument (omitting it would
silently prune every container) and `_keep_container_verbatim` carries a plain
tuple whole only when it is in it:

| Guard installed on `__defaults__`        | Old rule                   | New rule                  |
|------------------------------------------|----------------------------|---------------------------|
| `len(...) == 2` from a call              | verbatim, Lock fails dump  | pruned, `(2.0, _Missing)` |
| `[0] > 1.0`                              | verbatim, Lock fails dump  | pruned, element kept      |
| `== (2.0, (1, 2))`                       | verbatim                   | verbatim                  |
| both of the last two                     | verbatim                   | verbatim                  |

The single path that installs such a guard is `wrap_listlike`'s CONSTANT_MATCH
on an all-literal tuple under an unspecialized nn.Module source, which also
leaves the elements sourceless, so it is exactly the shape with no
per-element registration to keep them. A plain dict is never carried
verbatim: a whole-dict comparison lowers to DICT_KEYS_MATCH plus per-value
guards, and EQUALS_MATCH's own allowlist rejects a plain dict, so the
recording is tuple-only. A dict/tuple subclass stays verbatim whenever kept,
since the guard reading that slot needs its type to survive and a subclass
instance cannot be rebuilt element by element. No per-source edge recording is
needed, so nothing here reads `__annotations__` off arbitrary objects (which
on 3.14 would force PEP 649 evaluation and NameError out of guard building).

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k prunes -k pruned_per_value -k stays_verbatim -k keeps_defaults_verbatim -k whole_defaults_equals
```

The compile-path tests go through `_roundtrip_through_precompile`: a real
`torch.compile` under `caching_precompile`, save, `torch._dynamo.reset`,
reload, and a hit under `fail_on_recompile`; the test base class now clears
`DynamoCache` and `PrecompileContext` in setUp and tearDown so those tests
leave no state behind. Seven of the thirteen tests
matched by the second command fail on the previous commit's rule (six with
`PackageError: cannot pickle '_thread.lock' object` / `unrelated default
cannot pickle`, the per-value unit test on its assertion). Of the other six,
the whole-defaults equality test passes there and fails against a rule that
prunes whenever an element is guarded through the tuple; the whole-tuple
verbatim and container-subclass tests pin the two carve-outs against a
prune-everything rule; and three are pre-existing tests swept in by `-k
prunes`.

Authored with an AI assistant.

Pull Request resolved: #196479
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476, #196478
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
… pruned (#196481)

A bound method is two objects, a function and a receiver, and a guard on it
can depend on the function without ever registering it:

```python
def target(self, x):
    return x

@functools.wraps(target)      # copies target's __module__ and __qualname__
def wrapper(self, x):
    return x * 3

class Recv:
    pass

class M(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.cb = types.MethodType(wrapper, Recv())

    def forward(self, x):
        if self.cb.__name__ == "target":
            x = x + 1
        return x * 2
```

Guards are not strings Dynamo evals. They are a tree of guard managers, one
node per value, and the edge from a parent node to a child is an ACCESSOR: the
one step that gets from the parent's value to the child's ("look up key `cb`",
"read attribute `__name__`"). The checks themselves (TYPE_MATCH, EQUALS_MATCH)
hang off the node whose value they test, and a check walks the tree top down:
fetch `self` from the frame's locals, take its `__dict__`, look up `cb` in it,
getattr `__name__`, compare. A method has no `__name__` of its own; Python
forwards `method.__name__` to `method.__func__.__name__`. The tree does not see
that hop, so the guard hangs directly off the method's node (TORCH_LOGS=guards):

```python
L['self']              accessed_by FrameLocalsGuardAccessor('self')  # the module
  L['self'].__dict__   accessed_by GetGenericDictGuardAccessor      # nn.Module attrs live here
    L['self'].cb       accessed_by DictGetItemGuardAccessor('cb')   # the bound method
      L['self'].cb.__name__  accessed_by GetAttrGuardAccessor(__name__)
        EQUALS_MATCH: == 'target'
```

Two earlier rules meet here. `_reduce_bound_method` saves a method whose name
does not resolve back on the receiver (`Recv` has no `cb`) explicitly as the
pair `(func, receiver)`, so pickle goes on to serialize `wrapper` as a value.
The fqn-mismatch rule then rebuilds a function from its code object if it is
in `guard_tree_values` and replaces it with `_Missing("fqn mismatch")` if not.
The builder registers the value of each node it builds through
`get_guard_manager_from_source` (the `__dict__` node is created inline by
`get_generic_dict_manager` and is not registered, which changes nothing here):

```python
L['self']              -> the module         registered
L['self'].__dict__     -> the module's dict  not registered (inline node)
L['self'].cb           -> the bound method   registered
L['self'].cb.__name__  -> 'target'           registered
wrapper                                      NOT registered
```

The function is consulted only by CPython's attribute forwarding while the
`GetAttrGuardAccessor(__name__)` accessor runs, never as a node's value. So the
function the guard depends on is exactly what the pruning rule sees as
untouched. At load the tree is rebuilt by walking the same four steps on the
reconstructed locals to re-derive each node's value, and the last step does:

```python
method = types.MethodType(_Missing("fqn mismatch"), Recv())
method.__name__     # AttributeError while the guard manager is rebuilt
```

The seed cannot live in the reducer. Pickle memoizes every object the first
time it meets it, and it walks the module `__dict__` in insertion order:

```python
self.other = wrapper                          # plain attribute, inserted first
self.cb = types.MethodType(wrapper, Recv())
```

Pickle reaches `wrapper` through `other`, writes the sentinel and memoizes
that by identity; when the reducer later sees `cb` and registers the function,
pickle only emits a back-reference to the sentinel already written. A seed in
`pickle_guards_state`'s leaf loop is no better, since a method inside an
attribute is not a leaf of the local scope.

Register the method's `__func__` where the method's own guard manager is
built, in `GuardBuilder.get_guard_manager_from_source`. Every method anywhere
in the guard tree passes there before anything is pickled, and guard state is
pickled exactly once per builder, so that single seed covers every path pickle
can take to the function:

```python
example_value = self.get(source)
self.guard_tree_values[id(example_value)] = example_value
if self.save_guards and inspect.ismethod(example_value):
    func = example_value.__func__
    if inspect.isfunction(func):
        self.guard_tree_values[id(func)] = func
```

Only a plain function is seeded: `MethodType` accepts any callable, and a
`functools.partial` or builtin `__func__` cannot be rebuilt by value, so
seeding it would just make `_prune` carry it verbatim wherever else it
appears.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`, then renames the function's `__name__` and checks
the reloaded guard rejects (a `fail_on_recompile` RuntimeError), so it pins
that the guard really reads the rebuilt function rather than that nothing
crashed.

Authored with an AI assistant.

Pull Request resolved: #196481
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476, #196478, #196479
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…196756)

Follow-up to #196505, from its review. A resume frame whose backend artifact
is missing when the package is saved is written with `bypassed=True` by
`PrecompileCacheEntry.from_cache_entry`, and `install()` skips it, so the
next process traces that frame fresh:

```python
def fn(x):
    y = x.sin()
    torch._dynamo.graph_break()          # a resume frame with its own backend
    return x.sin() + y

torch.compile(fn)(x)
del PrecompileContext._backend_artifacts_by_key[resume_backend_id]
save()                                   # resume entry written bypassed
# next process
torch.compile(fn)(x)                     # resume frame traced fresh
save()
```

That fresh compile appended its guarded code to the stale one the reload had
deserialized, cleared the flag, and re-registered a backend id next to the
missing one still listed first. The next save found the missing id again,
re-poisoned the entry and wrote the bigger one back over the same path, so the
entry never became installable and never stopped growing:

```
base:    guarded_codes 1 -> 1  backend_ids 1 -> 7   (33 KB -> 34 KB over six cycles)
#196505: guarded_codes 1 -> 7  backend_ids 1 -> 7   (33 KB -> 64 KB)
```

(Byte sizes from the reviewer's environment; the counts reproduce exactly.)

The backend-id half predates #196505 (`OutputGraph` registers the id whether
or not the entry is bypassed); the guarded-code half is new there, since
`add_guarded_code` now appends and clears the flag on such an entry.

`CompilePackage.initialize` now loads a bypassed entry without its guarded
codes and backend ids: the package's own map gets a `dataclasses.replace` copy,
and the caller's entry is untouched, since a store may hand out the object it
holds (`InMemoryDynamoStore` does); the containers the fresh compile writes to
(`import_sources`, `function_names`) are detached in the copy as well, since
`dataclasses.replace` is shallow. `install()` skips such an entry entirely,
so nothing on it was installable, every variant of that code object included
(`from_cache_entry` flags the whole entry on the first missing artifact); the
fresh compile's record is the whole entry and the next save writes an
installable one, so the third process hits without compiling anything. The reset lives on the load side rather than in the save-time writer
because for an entry already on disk in the stale state the writer cannot tell
the missing id from the fresh compile's id listed beside it, so a writer-side
clear would discard the fresh code too and converge one save later. The
better endpoint, not taken here, is a per-guarded-code prune at write time
(drop only the guarded codes whose bytecode names the missing backend), which
would keep a multi-variant entry installable and never write the stale bytes;
tracked in #196773.
The entry docstring says what the writer and the loader each do.

Two test cleanups from the same review: `ConfigThatCannotPickle` says why it
raises AttributeError specifically (the one exception the bypass mapped before
#196470 widened it), and the earlier-variant test pins that only the bypassed
inputs compiled after the reload. It counts `counters["frames"]["total"]`
rather than the `FRAME_COUNTER` bracket the file's other caching_precompile
tests use: `reset()` zeroes `FRAME_COUNTER` and installing a precompiled entry
consumes a compile id, so a `+ 1` there holds only by cancellation.

Test Plan:

```
python test/dynamo/test_package.py
python test/dynamo/test_package.py -k test_a_poisoned_entry_is_reset_on_load_instead_of_growing -k test_bypassed_guards_keep_the_frames_earlier_variant
```

The new test runs the cycle above through `PrecompileContext` and
`DynamoCache`: after the second save the resume entry has one guarded code and
one backend id and is not bypassed (on the previous commit it has two of each
and is bypassed again), and a third load serves both frames with
`counters["frames"]["total"]` unchanged under `fail_on_recompile`. It also
builds a `CompilePackage` from a loaded entry and checks the entry it was
given still holds its guarded code while the package's `cache_entry()` does
not.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196756
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1147/head branch November 18, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants