Skip to content

[dynamo] Record why a compile was bypassed on the package entry - #198084

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. When a compile cannot be saved into its CompilePackage (most often because a guard's value cannot be pickled), OutputGraph.bypass_package logs a warning, emits a precompile_cache_bypass structured-trace artifact and marks the entry bypassed. The reason string exists only at that site: the package entry records a bare bypassed = True and nothing else. Anyone holding the package afterwards, in particular a writer that wants to name why a frame has nothing installable, can only say "bypassed" and send the user to tlparse, which a production job may not have. The reason is a fact about the entry and belongs on it.

Fix. _DynamoCodeCacheEntry gains bypass_reason: str | None = None, documented as item 11 of the class docstring. CompilePackage.bypass_current_compile takes an optional reason, truncates anything longer than _BYPASS_REASON_MAX_CHARS (2048) to that prefix plus " ... (truncated)", and stores it only when the entry ends up bypassed, storing None otherwise. add_guarded_code resets the reason alongside the flag it already resets. OutputGraph.bypass_package passes its reason argument through, so both existing bypass sites (guard serialization in CheckFunctionManager, and a graph with named parameters in compile_and_call_fx_graph) populate it with no further change.

Summary. The reason follows the flag exactly, because main's model is that an entry is bypassed only while it has no installable variant: a bypass on a code object that already recorded a guarded code leaves that variant installable and the entry not bypassed, so recording a reason there would describe a compile that did not cost the entry anything, and a later recorded compile clears the flag, so it clears the reason too. Storing the reason unconditionally was rejected for that mismatch, and a separate per-compile log was rejected because the artifact is what a later consumer has in hand. The cap exists because a reason can embed a repr of a user object (the guard-serialization message does) and the entry is pickled into the on-disk artifact, so an unbounded repr would bloat the file; 2048 characters keeps the exception text and drops the tail. The field has a default, so entries pickled before this commit load unchanged, and the artifact bytes of an entry that was never bypassed only gain a None. Nothing in torch/ reads the field yet; it is the ingredient a later stack's artifact builder needs to explain a refusal, and it sits above commit 1 (which fixed the bypass flag being set on a live entry) so that a copy carries its reason with it. Carved out of #195913.

The reason lives and dies with the bypassed flag

from torch._dynamo.package import CompilePackage

def fn(x):
    return x + 1

def region():
    return __compiled_fn_0_00000000_0000_0000_0000_000000000000()  # noqa: F821

pkg = CompilePackage(fn)
with pkg.code_context(fn.__code__):
    pkg.bypass_current_compile("x" * 3000)
entry = pkg.cache_entry().codes[0]
# parent: TypeError, bypass_current_compile() takes no arguments; the entry has no bypass_reason
# now:    entry.bypassed is True; len(entry.bypass_reason) == 2064 and it ends with " ... (truncated)"

with pkg.code_context(fn.__code__):
    pkg.add_guarded_code(b"", region.__code__)
# now:    entry.bypassed is False and entry.bypass_reason is None

with pkg.code_context(fn.__code__):
    pkg.bypass_current_compile("config cannot pickle")
# now:    entry.bypassed stays False (a variant is still installable) and entry.bypass_reason stays None

Pinned by test_bypass_reason_is_recorded_only_while_the_entry_is_bypassed.

The guard-serialization bypass names its cause on the entry

import torch
from torch._dynamo.precompile_context import PrecompileContext

class UnpicklableConfig:
    scale = 2.0
    def __reduce__(self):
        raise RuntimeError("config cannot pickle")

def fn(x, cfg=UnpicklableConfig()):
    return x.sin() * cfg.scale

x = torch.randn(3)
with torch._dynamo.config.patch(caching_precompile=True, strict_precompile=False):
    out = torch.compile(fn, backend="eager")(x)
# both: a warning "Detected a package bypass: Guard evaluation failed: RuntimeError: config cannot pickle"
#       and out == fn(x)
(entry,) = PrecompileContext._dynamo_cache_entries.values()
# parent: entry.codes[0].bypassed is True; nothing on the entry says why
# now:    entry.codes[0].bypass_reason == "Guard evaluation failed: RuntimeError: config cannot pickle"

Pinned by test_bypass_reason_names_the_guard_that_could_not_serialize. The existing test_bypassed_guards_keep_the_frames_earlier_variant keeps pinning that a bypass next to an installable variant does not bypass the entry.

Test Plan:

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

The two new tests fail on the parent (the reason argument and the field do not exist) and pass 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/198084

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 bb26af8 with merge base 618de55 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New behavior, not a class: adds field bypass_reason to the pickled _DynamoCodeCacheEntry at torch/_dynamo/package.py:649 plus a truncation cap at :654
    • Not a runtime no-op, doc, additive-test, annotation, mechanical-refactor, or single-cause-bugfix change; production logic in package.py and output_graph.py changes
  • Persisted artifact shape
    • The new field is pickled into the on-disk precompile artifact and from_cache_entry writes the string backend artifact {backend_id} missing at save time (package.py:990-994), a value outliving the call
    • PR body states a later stack's artifact builder will consume this field, so its wording and None-vs-set contract are a design decision a human should confirm
  • Signature and contract change
    • CompilePackage.bypass_current_compile gains a reason parameter (package.py:1273), and OutputGraph.bypass_package now forwards its reason (output_graph.py:2607)
    • Docstring item 11 (package.py:633-636) asserts the reason is None whenever not bypassed, while reason or None also stores None for an empty reason on a bypassed entry — a contract nuance worth a reviewer's read
  • Review record
    • Two prior automated review rounds in the PR raised four items and left open notes on docstring totality and a near-duplicate test, indicating a reviewer did learn something here

reason: not_trivial
Reviewed commit: bb26af8

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 19m 55s —— View job


This PR cleanly threads the existing bypass reason onto the package entry, but the new tests never exercise the save/load round trip that is the whole point of storing it, and the save-time bypass path is left without a reason on the same argument ("it's in the trace") that the PR rejects for the compile-time path.

Full review

PR Review: #198084

Summary

Adds bypass_reason: str | None to _DynamoCodeCacheEntry, populated from OutputGraph.bypass_package's existing reason through CompilePackage.bypass_current_compile. The mechanics are right — the reason follows bypassed exactly, add_guarded_code resets both, and the trailing default keeps old pickles loadable (the dataclass default is a real class attribute, so an entry unpickled from a pre-PR artifact reads None rather than raising). Three things to address: a testing gap on the persistence claim, an inconsistency in the save-time bypass path, and a misnamed cap constant.

Testing

  • test/dynamo/test_package.py:321-354 — neither new test touches the artifact. test_bypass_reason_is_recorded_only_while_the_entry_is_bypassed reads package.cache_entry().codes[0] (the live object), and test_bypass_reason_names_the_guard_that_could_not_serialize reads PrecompileContext._dynamo_cache_entries.values() (the live in-memory entry, before any pickling). The PR's stated motivation is that "a writer that wants to name why a frame has nothing installable" and holds the saved package can read the reason, so the round trip is the load-bearing claim and nothing pins it. It is also the fragile part: CompilePackage.initialize rebuilds a bypassed code with dataclasses.replace(code, guarded_codes=[], backend_ids=[], function_names=..., import_sources=...) at torch/_dynamo/package.py:1135, so bypass_reason survives a load only because it happens not to be in that argument list — a future edit there would drop it silently with every test still green. The adjacent test_bypassed_guards_keep_the_frames_earlier_variant already uses PrecompileContext.save_to_dynamo_cache() / DynamoCache.load(fn), so extending the second new test with save_to_dynamo_cache() + DynamoCache.load(fn) and asserting the reason on the reloaded codes[0] is a few lines. Fix this →

API Design

  • torch/_dynamo/package.py:986 — the save-time bypass (dataclasses.replace(code, bypassed=True) when a backend artifact is missing) leaves bypass_reason at None, which the new docstring item 11 justifies with "records its cause in the trace instead." That is exactly the argument the PR's own description rejects for the compile-time path ("send the user to tlparse, which a production job may not have"). The result is a field with three states, where a consumer seeing bypassed=True, bypass_reason=None has to infer "backend artifact was missing at save time" — and that consumer is the artifact builder this PR exists to feed. The site already has the cause in hand: it builds debug_str naming missing_backend two lines above. Setting a concrete reason there (e.g. dataclasses.replace(code, bypassed=True, bypass_reason=f"Backend artifact missing: {backend_id}")) makes the field total and removes the special case from the docstring. If that is deliberately deferred to a later commit in the stack, item 11 should say so rather than justify it by the trace. Fix this →

Code Quality

  • torch/_dynamo/package.py:654,1285-1286 — _BYPASS_REASON_MAX_CHARS = 2048 reads as a cap on the stored string, but the suffix is appended after the slice, so the field can hold 2064 characters. The tell is in the test, which has to spell the bound as 2048 + len(" ... (truncated)") (test/dynamo/test_package.py:331). Either slice to _BYPASS_REASON_MAX_CHARS - len(suffix) so the constant is the actual maximum, or name it for what it bounds (_BYPASS_REASON_MAX_PREFIX_CHARS). While there, have the test import the constant instead of hardcoding 2048 — the file already imports privates from the module (_collapse_device_types), and a hardcoded bound turns a future retune of the cap into a spurious test failure.
  • torch/_dynamo/output_graph.py:2584 — bypass_package's reason defaults to "" while bypass_current_compile takes str | None, so an omitted reason would store bypass_reason == "": bypassed, falsy, not None. No caller does this today (guards.py:5243 and output_graph.py:2932 both pass a string), but it is a free state to close — reason or None at the store in bypass_current_compile collapses it, and then a consumer's if entry.bypass_reason and is not None can never disagree.

Recommendation

Request Changes — only the round-trip test is a genuine blocker: the field's whole purpose is to be readable off a loaded artifact, and no test covers that path while the one line preserving it through initialize is incidental. The save-time-bypass inconsistency is worth resolving now or explicitly deferring in the docstring; the constant naming and the empty-string state are small.

· branch `gh/bobrenjc93/1421/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; all four folded (the fix is in bb26af8). Note this PR now sits at position 3 of the stack, above the CheckFunctionManager refactor #198085; its diff did not change by that move.

neither new test touches the artifact ... the round trip is the load-bearing claim and nothing pins it.

Fixed in bb26af8: test_bypass_reason_names_the_guard_that_could_not_serialize now saves through PrecompileContext.save_to_dynamo_cache(), reads back with DynamoCache.load(fn) and asserts the reason on the loaded entry, then builds a CompilePackage from that entry and asserts the reason on the package's own code entry (the initialize copy path).

the save-time bypass ... leaves bypass_reason at None ... a field with three states

Fixed in bb26af8: from_cache_entry now records backend artifact <id> missing at save time on the copy it bypasses, docstring item 11 says so, and test_save_time_bypass_names_the_missing_backend pins it (and that the live entry keeps None). bypassed=True now always comes with a reason.

_BYPASS_REASON_MAX_CHARS = 2048 reads as a cap on the stored string, but the suffix is appended after the slice

Fixed in bb26af8: the slice is _BYPASS_REASON_MAX_CHARS - len(suffix), so the constant is the actual maximum, and the test imports the constant instead of hardcoding 2048.

an omitted reason would store bypass_reason == ""

Fixed in bb26af8: bypass_current_compile stores reason or None; the first test now starts with an empty-string bypass and checks the field reads None.

@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 15m 33s —— View job


All four items from the previous round are genuinely fixed in bb26af8; what's left is one stale artifact (the PR description still documents the pre-fix behavior) and two small accuracy nits, none of which block.

Full re-review of bb26af8

Re-review: #198084

  • Read the updated diff
  • Verify the four folded fixes
  • Check for new issues introduced by the fixes
  • Post review

Verification of the four items

1. Round-trip coverage — fixed. test/dynamo/test_package.py:359-367 now goes save_to_dynamo_cache() → DynamoCache.load(fn) → CompilePackage(fn, loaded.dynamo), asserting the reason at each hop. That third hop is the one that matters: CompilePackage.initialize at torch/_dynamo/package.py:1143-1149 rebuilds a bypassed code with dataclasses.replace(code, guarded_codes=[], backend_ids=[], ...), and bypass_reason surviving that is incidental to the argument list. It is now pinned, so a future edit there fails a test instead of silently dropping the field. This was the blocker; it is closed.

2. Save-time bypass reason — fixed, and the state space is genuinely smaller. torch/_dynamo/package.py:990-994 now records backend artifact {backend_id} missing at save time on the copy it bypasses, docstring item 11 says so, and test_save_time_bypass_names_the_missing_backend (test/dynamo/test_package.py:369-381) pins both the saved reason and that the live entry keeps None. I checked the one way the two bypass paths could collide — a code that was already compile-time bypassed also picking up a save-time reason — and it cannot happen: bypassed=True implies guarded_codes == [], and bypass_current_compile (package.py:1288-1290) removes exactly the ids that compile added, so such a code has no backend_ids for the from_cache_entry loop to iterate. No overwrite.

3. Constant naming — fixed. package.py:1293-1295 slices to _BYPASS_REASON_MAX_CHARS - len(suffix), so the constant is the real maximum, and test_package.py:335 asserts len(...) == _BYPASS_REASON_MAX_CHARS against the imported constant rather than a hardcoded 2048. The import at test_package.py:24 matches the file's existing habit of pulling module privates (_collapse_device_types).

4. Empty-string state — fixed. reason or None at package.py:1296-1297 collapses "", and test_package.py:328-332 starts from an empty-string bypass and checks the field reads None.

Remaining

  • The PR description is now stale, and for a ghstack commit that is the artifact reviewers read. It still says the truncation yields 2064 characters ending in " ... (truncated)" (now 2048 total), still says "Nothing in torch/ reads the field yet" alongside a description that never mentions the save-time path, and the "The reason lives and dies with the bypassed flag" snippet does not show the empty-string-reads-None case the first test now opens with. Worth a ghstack -u with the body brought in line with bb26af8.
  • bypassed=True does not in fact always carry a reason — torch/_dynamo/package.py:1273 gives reason a None default, OutputGraph.bypass_package (output_graph.py:2584) defaults it to "", and reason or None maps both to None. Every real site passes a non-empty string (guards.py:5262, output_graph.py:2932), so this is unreachable in torch/ today, but the new tests at test_package.py:290,310,329 exercise it deliberately. Item 11 of the docstring (package.py:633-636) reads as if the reason is total over bypassed, which would mislead the later consumer this field exists for. Either drop the defaults so every caller must name a reason, or add half a sentence to item 11 saying a bypass site that gave no reason leaves it None. Fix this →
  • test_save_time_bypass_names_the_missing_backend is a near-duplicate of test_saving_does_not_bypass_the_live_entry (test_package.py:457-483): same fn, same _backend_artifacts_by_key.clear(), same create_cache_entries(), and the older test already asserts saved[key].dynamo.codes[0].bypassed / not live.codes[0].bypassed. The two new assertions are the reason-shaped counterparts of two the older test already makes; folding them in there would keep the save-time bypass contract in one place. Purely a tidiness call — leaving it as a separate, self-describing test is defensible.

Recommendation

Approve. The blocker is closed and the field is now well-covered on both bypass paths. Please refresh the PR description before landing, since the numbers and the scope in it no longer match the code.

· branch `gh/bobrenjc93/1421/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/1421/head branch November 28, 2026 01:50
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