Skip to content

[dynamo] Bypass a code whose backend is missing on a copy of the cache entry - #198083

Closed
bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1420/basefrom
gh/bobrenjc93/1420/head
Closed

bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1420/basefrom
gh/bobrenjc93/1420/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. When PrecompileContext.create_cache_entries stitches a saved entry together, PrecompileCacheEntry.from_cache_entry marks every code whose backend artifact it cannot find as bypassed, so that a later load skips that code instead of installing a graph it does not have. It did this by writing bypassed = True straight onto the code entry it was handed. That entry is not a snapshot: PrecompileContext._dynamo_cache_entries holds the _DynamoCacheEntry that CompilePackage.cache_entry built with the package's own _DynamoCodeCacheEntry objects, the ones still serving this process. So a save that came up short on one backend flipped the live package to bypassed as a side effect, and since nothing in the save path ever writes bypassed = False, the flag stuck until the next recorded compile of that frame cleared it; every save in between wrote a bypassed entry even if the artifact had come back. Separately, fn_first_lineno was annotated as str | None although it is always assigned co_firstlineno, an int.

Fix. from_cache_entry no longer mutates its input. It walks the codes, and for a code whose backend is missing it appends dataclasses.replace(code, bypassed=True) instead of the original; codes with all their backends present are appended as they are. It then returns a PrecompileCacheEntry built around dataclasses.replace(cache_entry, codes=codes), so neither the entry nor its codes list is the live object. The fn_first_lineno annotation becomes int | None. A new test in test_package.py compiles under caching_precompile, clears the recorded backend artifacts, saves, and checks that the saved copy is bypassed while the live entry is not.

Summary. The save path is a reader of the package's state and should not be able to change what the package does next; bypassing on a copy is the smallest change that gives it that property. A shallow dataclasses.replace is enough because the function only ever rewrites the bypassed flag and the codes list; the guarded codes and import sources inside each code entry are shared with the live entry but are not written here, matching what the load path already does when it copies a bypassed code before re-tracing. The alternative of having the caller deep-copy the whole _DynamoCacheEntry before handing it in was rejected as much more expensive (the guards state is large) and as leaving the trap in place for any other caller. The observable output of a save is unchanged: the same codes are bypassed, the same dynamo_cache_bypass artifact is emitted, and backend_content holds the same artifacts. This is the bottom of the stack and later commits build on the live entry staying trustworthy: commit 2 records a bypass reason on the entry only while it is bypassed, and commit 11 derives a package's uncovered frames from which entries are not bypassed, both of which would misreport a package that a save had silently flipped. Carved out of #195913.

A save whose backend is gone no longer flips the live package

import torch
from torch._dynamo.precompile_context import PrecompileContext

def fn(x):
    return x.sin()

x = torch.randn(3)
with torch._dynamo.config.patch(caching_precompile=True):
    torch.compile(fn)(x)
    ((key, live),) = PrecompileContext._dynamo_cache_entries.items()
    live.codes[0].backend_ids              # ['__compiled_fn_1_...']
    PrecompileContext._backend_artifacts_by_key.clear()   # the artifact is gone at save time
    saved, _ = PrecompileContext.create_cache_entries()
    saved[key].dynamo.codes[0].bypassed    # True: the saved copy skips this code on load
    saved[key].backends                    # {}
    live.codes[0].bypassed
    # parent: True, the live entry was written to in place and stayed bypassed
    #         until the next recorded compile of fn
    # now:    False, the live entry is untouched
    saved[key].dynamo is live              # now: False (a replaced copy)

Pinned by test_saving_does_not_bypass_the_live_entry in test/dynamo/test_package.py.

The copy stops at the flag; a code with its backend passes through unchanged

import torch
from torch._dynamo.package import CompilePackage, PrecompileCacheEntry

def fn(x):
    return x.sin()

pkg = CompilePackage(fn)
torch._dynamo.optimize(backend="eager", package=pkg)(fn)(torch.randn(3))
live = pkg.cache_entry()
type(live.fn_first_lineno)                          # int (co_firstlineno), matching the new annotation
live.codes[0] is pkg._codes[fn.__code__]            # True: the entry shares the package's own code objects

saved = PrecompileCacheEntry.from_cache_entry(live, {})   # no backend content at all
saved.dynamo.codes[0].bypassed                      # True
live.codes[0].bypassed, pkg._codes[fn.__code__].bypassed
# parent: (True, True), the package serving this process was bypassed too
# now:    (False, False)
saved.dynamo.codes is live.codes                    # now: False, a new list on a replaced entry

backends = {b: object() for b in live.codes[0].backend_ids}
saved2 = PrecompileCacheEntry.from_cache_entry(live, backends)
saved2.dynamo.codes[0] is live.codes[0]             # True: nothing to bypass, so the code is not copied
saved2.dynamo.codes[0].bypassed                     # False

The pass-through and the shared-object claims follow from cache_entry building codes=list(self._codes.values()) and from the loop only replacing a code on the missing-backend branch; the bypass side is pinned by the same test as above.

Test Plan:

python test/dynamo/test_package.py -k test_saving_does_not_bypass_the_live_entry
python test/dynamo/test_package.py

The new test fails on the parent, where the live entry comes back bypassed, and passes here.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 [email protected]

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ 6 Pending, 2 Unrelated Failures

As of commit d49d488 with merge base 618de55 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Save-path behavior moves
    • torch/_dynamo/package.py:980-986 swaps code.bypassed = True for dataclasses.replace, so a later save writes an installable entry where it wrote a bypassed one
    • The diff's own new assertion in test/dynamo/test_package.py pins that second save as not bypassed, a change in what DynamoCache receives
    • bypassed feeds _summarize at precompile_package.py:1561-1568, building PrecompileSummary.bypassed, uncovered_frames, and backend_graphs
  • Stated invariant is incomplete
    • dataclasses.replace(cache_entry, codes=codes) also shares source_info, whose inlined_sources set is mutated in place by SourceInfo.add_code (package.py:591)
    • The new comment at package.py:956-959 names only guarded_codes, backend_ids, import_sources, function_names, so "non-mutating" reads stronger than the copy is
  • Mixed concerns and prior review churn
    • The fn_first_lineno retype to int | None at package.py:897 is a separate fix the PR body introduces with "Separately"
    • Three review findings already changed this revision per the PR comments, evidence a reviewer learns something here

reason: not_trivial
Reviewed commit: d49d488

Inference job

🐛 Report a wrong verdict

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 13m 48s —— View job


The change is correct and no existing test or production caller depended on the old in-place mutation, but the new test pins the in-process object invariant rather than the repeated-save consequence the PR description leads with.

Full review

PR Review: #198083

Summary

Makes PrecompileCacheEntry.from_cache_entry bypass a backend-less code on a copy instead of writing bypassed = True onto the live _DynamoCodeCacheEntry the running CompilePackage is still serving, and corrects the fn_first_lineno annotation to int | None. The core change is right; the test coverage does not reach the failure the description motivates it with.

Testing

test_saving_does_not_bypass_the_live_entry (test/dynamo/test_package.py:395-412) does not cover the repeated-save failure the PR is motivated by. The description's headline consequence is: "nothing in the save path ever writes bypassed = False, so the flag stuck until the next recorded compile of that frame cleared it; every save in between wrote a bypassed entry even if the artifact had come back." That is the user-visible bug — a second save writes an entry that install() will refuse to use even though every artifact is present — and the test does not exercise it. It performs exactly one create_cache_entries() call and asserts on in-process object identity and flags (lines 410-412). Everything after "the flag stuck" is untested.

The scenario is reachable, not hypothetical. PrecompileContext._dynamo_cache_entries and _backend_artifacts_by_key are process-lifetime class state (torch/_dynamo/precompile_context.py:92,96) and no production code calls PrecompileContext.clear(), while torch.compiler.save_cache_artifacts() is a public API (torch/compiler/init.py:757,771) that can be called more than once. Backend artifacts are recorded lazily — try_save_cache_entry fires at backward-compile time (torch/_functorch/_aot_autograd/runtime_wrappers.py:2926-2927) — so a save taken before the first backward legitimately misses an artifact that is present by the next save. Add a case that saves, re-records the missing artifact into _backend_artifacts_by_key, saves again, and asserts the second saved entry is not bypassed. That assertion fails on the parent for the reason the description gives, and it is the one that protects the property users care about.

The pass-through branch is unverified. The description claims saved2.dynamo.codes[0] is live.codes[0] when all backends are present, and concedes it only "follows from" reading the loop. Since the whole point of the change is which objects the returned entry holds, assert it: with backends fully populated, the returned codes entry should be the same object and bypassed should be False. One extra from_cache_entry call in the same test covers it.

Code Quality

The stated invariant is only partly achieved, and the gap is worth a sentence in the comment. The new comment at torch/_dynamo/package.py:954-955 asserts the function is "non-mutating," and the description generalizes that to "the save path is a reader of the package's state." The copy is shallow by design, so the returned entry's guarded_codes and backend_ids lists, import_sources dict, and function_names list are the live package's own containers — including on the dataclasses.replace(code, bypassed=True) copy. Notably, the load path at torch/_dynamo/package.py:1125-1131 does detach those containers when it copies a bypassed code, with a comment explaining why, so the two sides of the same concern are now handled differently.

This is not a live bug: the only caller of from_cache_entry is create_cache_entries (torch/_dynamo/precompile_context.py:208), whose result is pickled almost immediately by DiskDynamoStore.write (torch/_dynamo/package.py:1697), which snapshots by value. But it does mean the returned entry is not safe to hold across further compilation in-process, and save_cache_artifacts() does not take compile_lock even though the PrecompileContext class state is documented as "Protected by the compile_lock" (torch/_dynamo/precompile_context.py:89). That locking gap is pre-existing and out of scope here; the ask is narrower — since the PR is establishing an invariant that a later commit in the stack relies on, say in the comment what the copy does and does not detach, so the next reader does not take "non-mutating" as stronger than it is.

Verified, no action needed

  • No subclasses of _DynamoCacheEntry or _DynamoCodeCacheEntry exist, and neither has init=False fields or a __post_init__, so dataclasses.replace re-invoking __init__ is safe.
  • No existing test or production caller reads .bypassed off the live entry after a save. The assertions at test/dynamo/test_package.py:311,317 come from bypass_current_compile (unaffected); those at 1304,1321 read entries round-tripped through DynamoCache.load, which still see the bypass.
  • fn_first_lineno is assigned co_firstlineno at torch/_dynamo/package.py:1492 and only JSON-dumped in debug_info(); int | None is correct and not a BC concern for existing pickles.
  • The partial backend_content write for a code whose Nth backend is missing (ids 0..N-1 are already recorded before the break) is pre-existing and unchanged — it is the behavior documented at test/dynamo/test_precompile_package.py:2303-2304.
  • Replacing the else: branch with an unconditional statement after the break is semantically identical.

Recommendation

Request Changes — only for the missing repeated-save regression test. The production change is correct and I would approve it as-is otherwise; the new test just does not assert the property that the description says broke, and that property is reachable from a public API.

I was not able to run python test/dynamo/test_package.py -k test_saving_does_not_bypass_the_live_entry — this checkout has no built PyTorch and no .venv, so the test-plan claim that it fails on the parent and passes here is unverified by me.

· branch `gh/bobrenjc93/1420/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; both test asks are folded, and the comment now says what the copy does and does not detach. Replies per finding (the fix is in d49d488):

Add a case that saves, re-records the missing artifact into _backend_artifacts_by_key, saves again, and asserts the second saved entry is not bypassed.

Fixed in d49d488: test_saving_does_not_bypass_the_live_entry now snapshots the recorded artifacts before clearing them, saves (bypassed copy, live entry untouched), restores the artifacts and saves again, asserting the second saved entry is not bypassed. On the parent the second assertion fails: the first save had flipped the live entry in place, so the second save wrote a bypassed entry although every artifact was present.

The pass-through branch is unverified.

Fixed in d49d488: the same second save asserts saved[key].dynamo.codes[0] is live.codes[0].

The stated invariant is only partly achieved, and the gap is worth a sentence in the comment.

Fixed in d49d488: the comment in from_cache_entry now states that the copy is shallow (the returned entry shares guarded_codes, backend_ids, import_sources and function_names with the live entry), that this suits the one caller, which pickles it at once, and that detaching those containers is the load path's job in CompilePackage.initialize.

Also since your review: the pure refactor of CheckFunctionManager (#198085) now sits directly above this PR, ahead of #198084, so the two commits that stand on their own are at the bottom of the stack; no diff changed by that move.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

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


All three review findings are addressed in d49d488 and I have no further blocking comments; the second-save assertion is the one that would fail on the parent, which is exactly the gap I flagged.

Follow-up review of d49d488

Verification of the three findings

1. Repeated-save regression test — fixed, and it does fail on the parent. test_saving_does_not_bypass_the_live_entry (test/dynamo/test_package.py:395-421) now snapshots _backend_artifacts_by_key before clearing it, saves, restores, and saves again. I traced both revisions:

  • On the parent, the first create_cache_entries() writes code.bypassed = True onto live.codes[0]. The second save finds every backend present, so it never touches bypassed, and the already-set flag rides through into the written entry — assertFalse(saved[key].dynamo.codes[0].bypassed) at line 420 fails. That is the "flag stuck / every save in between wrote a bypassed entry" consequence the description leads with, now pinned. assertIsNot(saved[key].dynamo, live) at line 411 also fails on the parent.
  • On this revision the first save's dataclasses.replace(code, bypassed=True) leaves live alone (line 413), and the second save's code passes through unbypassed.

The premise the test rests on holds: the live _DynamoCacheEntry in _dynamo_cache_entries is built by cache_entry() with codes=list(self._codes.values()) (torch/_dynamo/package.py:1493), so live.codes[0] is the package's own _DynamoCodeCacheEntry, and a single forward compile under caching_precompile does record a backend artifact before the save (the same invariant test_precompile_context.py:44 already asserts), so the restore in line 418 is not vacuous.

2. Pass-through branch — fixed. assertIs(saved[key].dynamo.codes[0], live.codes[0]) at line 421 covers it. The object-identity claim is what the from_cache_entry loop actually guarantees (the code is only rebound on the missing-backend branch, torch/_dynamo/package.py:980), so asserting identity rather than just bypassed is False is the right strength here.

3. Shallow-copy caveat in the comment — fixed. torch/_dynamo/package.py:954-959 now says the copy is shallow, names the shared containers, says why that suits the single caller (pickles at once), and points at CompilePackage.initialize as the place that detaches them — which lines up with the load-path comment at package.py:1120-1131. The docstring at package.py:626-628 is updated consistently ("flags a saved copy ... the live entry keeps serving this process").

One optional nit

The comment enumerates the shared containers as guarded_codes, backend_ids, import_sources, function_names — all per-code. dataclasses.replace(cache_entry, codes=codes) also carries the live source_info through by reference, and SourceInfo.inlined_sources is a set that a later compile mutates in place via _source_info.add_code (package.py:591,1250). Same conclusion as the rest (the one caller pickles immediately, so nothing observes it), but since the comment is an enumeration, adding source_info to the list would make it complete. Not worth a respin on its own.

Also checked, no action needed

  • dataclasses.replace is safe on both classes: neither _DynamoCodeCacheEntry (package.py:602-644) nor _DynamoCacheEntry (package.py:890-897) has init=False fields or a __post_init__, and there are no subclasses.
  • The other write path, DiskDynamoStore.save_cache_entry (package.py:1563-1585), builds PrecompileCacheEntry(cache_entry, backend_content) around the live entry directly and raises on a missing backend rather than bypassing. It never wrote bypassed, so it is unaffected; its own hold-across-compile caveat is pre-existing and out of scope.
  • fn_first_lineno: int | None matches the sole assignment (co_firstlineno, package.py:1496) and its only read is the JSON debug_info() dump.
  • The else: → unconditional backend_content[backend_id] = ... after the break is semantically identical, and an empty backend_ids still appends the code untouched.
  • Lint-relevant details are fine: ASCII-only comments, and the # noqa: UNSPECIFIED_BACKEND on line 405 is the code the repo's linter expects.

Recommendation

Approve. I could not execute python test/dynamo/test_package.py -k test_saving_does_not_bypass_the_live_entry — this checkout has no built PyTorch and no .venv — so the pass/fail claims above are from reading the two revisions, not from a run. Worth confirming the new assertions locally against the parent before merging, since that is the part I cannot verify.

· branch `gh/bobrenjc93/1420/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Abandoning this stack for now; it may be reopened later.

@bobrenjc93 bobrenjc93 closed this Sep 22, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1420/head branch November 28, 2026 01:48
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 module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant