Skip to content

[no-ci] [dynamo] Make an explicit capture strict and keep it out of the ambient cache - #198089

Closed
bobrenjc93 wants to merge 4 commits into
gh/bobrenjc93/1426/basefrom
gh/bobrenjc93/1426/head
Closed

bobrenjc93 wants to merge 4 commits into
gh/bobrenjc93/1426/basefrom
gh/bobrenjc93/1426/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. A CompilePackage built with explicit_capture=True (commit 5 of this stack) is a caller asking for exactly this frame, but _compile still treated it like the ambient cache in two places. When serialize_guards raised a PackageError (a guard the artifact cannot carry, such as a default argument whose __reduce__ fails), the catch in CheckFunctionManager consulted only torch._dynamo.config.strict_precompile, so with that flag off the explicit capture was silently bypassed: the compile ran, a "package bypass" warning was logged, and the entry the caller wanted came back with bypassed=True and no guarded code. Separately, under caching_precompile, ConvertFrameAssert.__call__ recorded every package into PrecompileContext through DynamoCache.record_package, so an explicit package whose caller will save it itself was also queued for the ambient cache's serialize/save path, where it would be written under its source_id as if it were a background cache entry.

Fix. _compile now passes strict_error=explicit_capture into DynamoOutput.build_guards, alongside the explicit_capture kwarg it already threads through. CheckFunctionManager already has the branch if strict_precompile or strict_error: raise e around serialize_guards, so an explicit capture re-raises the PackageError out of the compile instead of calling bypass_package, while a plain package keeps the existing bypass-with-warning behaviour. In ConvertFrameAssert.__call__, the record_package call is additionally gated on not self._package.explicit_capture, so the ambient caching_precompile recorder skips explicit packages. Two tests in test/dynamo/test_package.py pin each behaviour.

Summary. The two changes share one idea: an explicit capture has an owner, and the owner, not the ambient machinery, decides what happens to it. For strictness, the existing strict_error parameter was reused rather than adding a new flag, because aot_compile already passes strict_error=True for exactly this reason (a caller that asked for a specific frame should hear about a guard it cannot keep), and the two paths should agree; making explicit_capture imply strict_precompile globally was rejected because it would also change the behaviour of ambient packages in the same process. For recording, filtering at the ConvertFrameAssert call site rather than inside record_package keeps DynamoCache free of package-mode knowledge and leaves the ambient path byte-for-byte unchanged for non-explicit packages. Nothing else about the explicit package changes here: its guards are still built by commit 6's filtered save build and still land on pkg.cache_entry() via add_guarded_code, so the caller can save it. Commit 8 above narrows both gates further with record = package is not None and not package.serving, so a serving package neither raises nor records; a fresh explicit capture is never serving, so its behaviour is exactly what this commit introduces. Carved out of #195913.

An unpicklable guard raises for an explicit capture and bypasses for the ambient cache

import torch
from torch._dynamo.package import CompilePackage
from torch._dynamo.exc import PackageError

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(strict_precompile=False):
    ambient = CompilePackage(fn)
    torch._dynamo.optimize(backend="eager", package=ambient)(fn)(x)
    # parent: warns "Detected a package bypass: Guard evaluation failed: RuntimeError: config cannot pickle"
    # now:    same; the ambient cache still bypasses with a warning
    ambient.cache_entry().codes[0].bypassed   # True (both)

    torch._dynamo.reset()
    explicit = CompilePackage(fn, explicit_capture=True)
    torch._dynamo.optimize(backend="eager", package=explicit)(fn)(x)
    # parent: also bypassed with the same warning; strict_error defaulted to False here
    # now:    raises PackageError("RuntimeError: config cannot pickle") out of the compile

Pinned by test_explicit_capture_raises_where_the_ambient_cache_bypasses. The bypass_reason string visible on the ambient entry comes from commit 2 of this stack.

An explicit package is not queued for the caching_precompile cache

import torch
from torch._dynamo.package import CompilePackage
from torch._dynamo.precompile_context import PrecompileContext

def fn(x):
    return x + 1

with torch._dynamo.config.patch(caching_precompile=True):
    pkg = CompilePackage(fn, explicit_capture=True)
    torch._dynamo.optimize(backend="eager", package=pkg)(fn)(torch.randn(3))
    len(pkg.cache_entry().codes[0].guarded_codes)   # 1 (both): the capture itself is intact
    PrecompileContext._dynamo_cache_entries
    # parent: {pkg.source_id: <_DynamoCacheEntry>} via DynamoCache.record_package
    # now:    {}

    torch._dynamo.reset()
    ambient = CompilePackage(fn)
    torch._dynamo.optimize(backend="eager", package=ambient)(fn)(torch.randn(3))
    list(PrecompileContext._dynamo_cache_entries)   # [ambient.source_id] (both): ambient path unchanged

Pinned by test_explicit_capture_is_not_recorded_into_the_ambient_cache. Both snippets were run against the top of the stack, where commit 8 gates the same two lines on record; that gate is true for a package that is not serving, so the output is the same as at this commit.

Test Plan:

python test/dynamo/test_package.py -k test_explicit_capture_
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py

The two new tests fail on the parent (the explicit capture bypasses instead of raising, and the explicit package shows up in PrecompileContext._dynamo_cache_entries) 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/198089

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:

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@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/1426/head branch November 28, 2026 01:51
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