Skip to content

[dynamo] Give CompilePackage an explicit capture mode, a serving mode and a serialization guard filter - #198087

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. A CompilePackage today has exactly one job: it is the ambient cache that caching_precompile fills behind the user's back, so the constructor takes a function, an optional cache entry and an inlined-sources switch and nothing else. Commit 4 below taught CheckFunctionManager to build a separately filtered copy of the guards for serialization and to build the live guards strictly for an explicit capture, but a package has no way to say which of those it wants, so convert_frame cannot ask it. Two further situations have no representation either: a package produced by torch.compiler.precompile that the caller saves itself, which must not be strict-or-lenient by accident and must not also leak into the ambient cache, and a package that serves a loaded artifact, which nothing will ever save again and whose uncovered frames should compile without being recorded.

Fix. CompilePackage.__init__ gains three keyword-only arguments, serialization_guard_filter_fn, explicit_capture and serving, stored on the instance and exposed through read-only properties of the same names, with the filter typed as a callable from a sequence of GuardFilterEntry to a sequence of booleans so it matches the guard_filter_fn hook. The commit is pure data: nothing in torch/ reads the properties yet. Commit 6 threads the filter and the capture flag into DynamoOutput.build_guards, commit 7 uses the capture flag to make the compile strict and to keep the package out of DynamoCache, and commit 8 uses the serving flag to stop recording. The new test pins that the three settings are independent and all off by default.

Summary. The design point is that a package now has three modes, and they are separate flags rather than one enum or one inferred bit. The ambient caching_precompile cache is the default with everything off; an explicit capture is a package the caller owns and saves, whose live guards stay strict and whose serialized copy may be filtered; a serving package holds a loaded artifact and only ever reads. The filter is deliberately not the capture flag: the code this was carved from originally inferred the capture mode from the filter being set, which made the filter double as a mode switch, so an ambient-cache user who only wanted to drop a guard from the saved state would silently also get strict errors and lose automatic persistence, while an explicit capture that wanted every guard saved had to pass a keep-all filter to be recognised. Keeping them independent lets commit 4's separate_save_build fire for a filter alone (a second build is needed whenever the saved guards differ from the live ones) without touching the strictness or persistence decisions that only the capture flag should make. The properties are read-only because the mode is fixed at construction and consulted on every frame; a package that could switch modes between frames would leave earlier entries recorded under one policy and later ones under another. Carved out of #195913.

The three settings are independent and off by default

from torch._dynamo.package import CompilePackage

def fn(x):
    return x + 1

def keep_all(entries):
    return [True] * len(entries)

ambient = CompilePackage(fn)
# parent: no such properties exist on the package
# now:    ambient.explicit_capture is False, ambient.serving is False,
#         ambient.serialization_guard_filter_fn is None

filtered = CompilePackage(fn, serialization_guard_filter_fn=keep_all)
# parent: TypeError, unexpected keyword argument
# now:    filtered.serialization_guard_filter_fn is keep_all and
#         filtered.explicit_capture is False (a filter is not a capture)

explicit = CompilePackage(fn, explicit_capture=True)
# now:    explicit.explicit_capture is True and
#         explicit.serialization_guard_filter_fn is None (a capture needs no filter)

serving = CompilePackage(fn, serving=True)
# now:    serving.serving is True, serving.explicit_capture is False

Pinned by test_explicit_capture_is_not_inferred_from_the_serialization_filter in test/dynamo/test_package.py. The snippet depends on nothing above this commit.

The flags are keyword-only and read-only

CompilePackage(fn, None, False, keep_all)
# now: TypeError: CompilePackage.__init__() takes from 2 to 4 positional arguments but 5 were given

explicit.explicit_capture = False
# now: AttributeError: property 'explicit_capture' of 'CompilePackage' object has no setter

The positional arguments of the parent constructor keep their positions, so existing callers are unaffected.

Test Plan:

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

The new test fails on the parent with a TypeError from the constructor 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/198087

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:

⏳ 54 Pending, 2 Unrelated Failures

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

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 9m 34s —— View job


PR Review: #198087

Pure-data plumbing that adds three construction-time modes to CompilePackage; the change is small and tested, but one inline comment contradicts the design the PR is establishing, nothing rejects the nonsensical flag combinations, and no in-tree caller sets serving yet.

Full review

PR Review: #198087

Summary

Adds three keyword-only constructor arguments to CompilePackage (serialization_guard_filter_fn, explicit_capture, serving) plus read-only properties, with no reader in torch/ yet. Found one contradictory comment, missing validation of mutually-exclusive combinations, an undocumented public interface addition, and two test gaps against the PR's own stated contract.

API Design

  • torch/_dynamo/package.py:1094 — the comment on _explicit_capture reads "A torch.compiler.precompile capture or serve, as opposed to the ambient caching_precompile cache". This directly contradicts the flag split this PR exists to create: the PR body states a serving package has explicit_capture is False, and serving is a separate flag precisely because serving is not a capture. As written, a future reader wiring up the serve path is told to set explicit_capture=True, which (per commits 6/7) would make the live guards strict and skip DynamoCache for an artifact that is only being read. Drop "or serve" and let the _serving comment below own that case. Fix this →

  • torch/_dynamo/package.py:1067-1073 — three independent flags give eight combinations, of which only three are meaningful, and nothing rejects the rest. serving=True, explicit_capture=True is self-contradictory under the comments as written (never-saved vs. saved-by-the-caller), and serving=True, serialization_guard_filter_fn=... silently ignores the filter because a serving package never serializes. The PR body argues well against collapsing these into one enum, and that argument holds — but independence is not the same as "any combination is legal". A constructor-time raise AssertionError for serving and explicit_capture and for serving and serialization_guard_filter_fn is not None costs two lines and turns a silently-ignored setting into a diagnosable one. The new test currently pins the permissiveness (assertTrue(CompilePackage(fn, serving=True).serving) with no combination coverage), so this is easier to settle now than after commits 6-8 depend on it.

  • torch/_dynamo/package.py:1682 and :1824 — both in-tree sites that build a package from a loaded _DynamoCacheEntry (DynamoStore.load_package, DynamoCache.load) still construct with CompilePackage(fn, entry.dynamo) and therefore get serving=False. After this commit serving has no setter anywhere in torch/. If commit 8 intends load_package to pass serving=True, that is the natural place to say so; if instead only a new torch.compiler.precompile serve path sets it, then these two existing load paths deliberately keep the record-and-re-save behavior and that distinction deserves a sentence in the _serving comment, because "serves a loaded artifact" describes both of them today.

Code Quality

  • torch/_dynamo/package.py:1050-1060 — the class docstring enumerates the package's interface as an explicit numbered list ("It has the following interface: 1. __init__ ... 2. save() ... 3. install()"). This PR adds three public properties to that interface and documents them only in constructor-body comments, so the docstring now under-describes the class. Since the modes are the load-bearing new concept, a one-line mention of the three modes under item 1 keeps the documented interface complete.

  • torch/_dynamo/package.py:1068-1070, 1116-1117 — Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] is now spelled out in nine places across torch/_dynamo/ (hooks.py:24, eval_frame.py:1810, guards.py:1376/5051/5059/5487, and the two added here). This PR is not obliged to fix the pre-existing duplication, but it is the second file to grow a copy; a GuardFilterFn alias next to GuardFilterEntry in torch/_dynamo/types.py would let this file import one name instead of repeating a three-line annotation for a parameter and its property.

Testing

  • test/dynamo/test_package.py:1564 — the PR body devotes a section to two properties of the new API that the test does not pin: that the flags are keyword-only (CompilePackage(fn, None, False, keep_all) must raise TypeError) and that the properties are read-only (explicit.explicit_capture = False must raise AttributeError). Both are claimed in the description as deliberate design choices — keyword-only so existing positional callers are unaffected, read-only so the mode cannot change between frames — and both are one assertRaises line each. Without them, a later refactor that adds a setter or reorders the signature passes the suite.

  • test/dynamo/test_package.py:1584 — self.assertTrue(CompilePackage(fn, serving=True).serving) is the only assertion about the serving package, so unlike ambient and filtered it is not checked for independence from the other two settings. The test's stated purpose is that the three settings are independent; asserting explicit_capture is False and serialization_guard_filter_fn is None on that instance completes the matrix the test name promises.

Recommendation

Approve

The comment at package.py:1094 is a must-fix before the stack lands, since commits 6-8 read these flags and the comment currently points a future reader at the wrong one. Everything else is either a cheap hardening of the contract the PR body already claims (flag-combination validation, the two missing assertions) or documentation upkeep. No correctness, BC, thread-safety, or performance concerns: nothing reads the properties yet, the positional parameters keep their positions so all four existing construction sites are unaffected, and storing a user callable on the instance is safe because only the derived _DynamoCacheEntry/PrecompileCacheEntry is ever pickled (package.py:1536-1546, :1750) and the class already holds _innermost_fn and _cached_backends.

Note: I reviewed statically and did not run python test/dynamo/test_package.py — no build was available in this checkout.
| Branch: gh/bobrenjc93/1424/head

[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/1424/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