Repository navigation
[dynamo] Reset a bypassed cache entry on load instead of growing it - #196756
bobrenjc93 wants to merge 8 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196756
Note: Links to docs will display an error until the docs builds have been completed. ❌ You can merge normally! (1 Unrelated Failure), 1 Unclassified FailureAs of commit 0baa088 with merge base 0929b23 ( GREEN LIGHT - PR approved to be merged without human review:
reason: UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Claude finished @bobrenjc93's task in 20m 52s —— View job PR Review: #196756Two findings worth addressing before merge (one real correctness edge, one unreadable comment); the core fix and the new regression test look sound to me. Full reviewSummary
Code Quality
Testing
Backward Compatibility
RecommendationRequest Changes The comment at |
[ghstack-poisoned]
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
…, docstring, test asserts the input entry is untouched [ghstack-poisoned]
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
|
Claude finished @bobrenjc93's task in 20m 35s —— View job Re-reviewed after the two fold commits: both findings from the previous round are addressed, and the one thing left is that Full reviewPR Review: #196756Summary
I verified separately that the reassign-during- Code Quality
RecommendationApprove The diagnosis, the fix, and the regression test are correct, and the earlier findings are folded. The remaining item is a one-line copy-depth (or comment-scope) correction plus the matching assertion; worth doing before merge but it doesn't put the change at risk. |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: Check mergeability of ghstack PR / ghstack-mergeability-check, inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…y, pin the dict-served case (#196764) Follow-up to the reviews of #196473 and #196474. `_reduce_bound_method` read `func.__name__` before its `try`. `getattr` with a default swallows only AttributeError, and `__func__` is an arbitrary callable by the reducer's own premise, so a proxy that raises anything else escaped the reducer while the receiver-side probe two lines down was already guarded: ```python class ProxyFunc: def __getattr__(self, name): raise RuntimeError(f"proxy has no {name}") pickler._reduce_bound_method(types.MethodType(ProxyFunc(), Plain())) # before: RuntimeError: proxy has no __name__ # now: (_unpickle_bound_method, (ProxyFunc(), Plain())) ``` The read moves inside the `try`, after the `__getattr__` gate (which takes the pair without probing `func` at all), where `explicit` is already built for the `except` to return. The `__dict__` half of the per-instance condition had no test: `SlottedByName` has no instance dict, so the slot test lands on the `getattr_static` half, and ablating the `__dict__` clause left the suite green while the shape it exists for broke at load: ```python obj = Plain() obj.global_add = types.MethodType(global_add, obj) # with the clause: loads back as MethodType(global_add, Plain) # without the clause: AttributeError: 'Plain' object has no attribute 'global_add' ``` Pinned now, and the comment says which receivers reach that clause: one that HAS an instance dict, which a pure-slots receiver does not (a slotted subclass of a non-slotted base has both, and either clause gives the same answer), and a class defining `__getattr__` (every nn.Module) takes the pair before it either way. Two tests from #196474 were not pinning what they said. The shared-closure-cell test used a `<locals>` pair, whose branch returns before the `guard_tree_values` gate, so the dict it built was inert and the test passed on the parent; it now uses two module-level `functools.wraps` wrappers sharing one cell, which only the gate carries. The module-method test's comment described the `<locals>` rebuild bug from the commit that fixed it; the comment is gone and the test asserts the rebuilt function's `__name__` is `forward`, which is a record of what the rebuild carries rather than a regression guard (the name path is pinned by `test_rebuilt_locals_function_keeps_its_name`), so the comment now points at the call as the assertion that catches the placeholder. Type nits from the same reviews: `object` instead of `Any` for the resolution walk and both rebuilt scopes; the bound-method reducer returns its real shape, `tuple[Callable[..., Any], tuple[Any, ...]] | None`; the state tuple stays `Any`, since its elements are assigned to typed function slots and the checker rejects `object` there. One #196474 comment is not a code change here: at that commit the by-value payload carried every closure cell and default unconditionally, so a `wraps` wrapper capturing a lock no guard read failed the dump. #196476, two commits above it, prunes each cell and default through the same `guard_tree_values` test, and that is where the prune lives in this stack. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k bound_method -k shared_closure_cell python test/dynamo/test_aot_compile.py -k Pickler ``` The proxy test fails on the previous commit with the RuntimeError above. Its second case pins the ORDERING rather than the `try`: the receiver is a proxy whose class defines `__getattr__`, so the gate takes the pair and the name is never asked for, which the fixture records; moving the read back above the gate fails that assertion while the rest of the test stays green. The monkeypatched-method test fails against the `__dict__` clause ablated. The shared-cell test fails when the fqn-mismatched pair is not in `guard_tree_values` (both prune to `_Missing`), which the old `<locals>` pair could not show. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196764 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693, #196756
Stack from ghstack (oldest at bottom):
Follow-up to #196505, from its review. A resume frame whose backend artifact
is missing when the package is saved is written with
bypassed=TruebyPrecompileCacheEntry.from_cache_entry, andinstall()skips it, so thenext process traces that frame fresh:
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:
(Byte sizes from the reviewer's environment; the counts reproduce exactly.)
The backend-id half predates #196505 (
OutputGraphregisters the id whetheror not the entry is bypassed); the guarded-code half is new there, since
add_guarded_codenow appends and clears the flag on such an entry.CompilePackage.initializenow loads a bypassed entry without its guardedcodes and backend ids: the package's own map gets a
dataclasses.replacecopy,and the caller's entry is untouched, since a store may hand out the object it
holds (
InMemoryDynamoStoredoes); the containers the fresh compile writes to(
import_sources,function_names) are detached in the copy as well, sincedataclasses.replaceis shallow.install()skips such an entry entirely,so nothing on it was installable, every variant of that code object included
(
from_cache_entryflags the whole entry on the first missing artifact); thefresh 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:
ConfigThatCannotPicklesays why itraises 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_COUNTERbracket the file's other caching_precompiletests use:
reset()zeroesFRAME_COUNTERand installing a precompiled entryconsumes a compile id, so a
+ 1there holds only by cancellation.Test Plan:
The new test runs the cycle above through
PrecompileContextandDynamoCache: after the second save the resume entry has one guarded code andone 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 underfail_on_recompile. It alsobuilds a
CompilePackagefrom a loaded entry and checks the entry it wasgiven still holds its guarded code while the package's
cache_entry()doesnot.
Authored with an AI assistant.
🤖 Generated with Claude Code
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98