Skip to content

[dynamo] Serialize a separately built, separately filtered copy of a package's guards - #198086

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. CheckFunctionManager runs one guard build and hands its result to two consumers: the guard manager installed in the frame's live cache, and, under save_guards, the pickled state a package records for a later process. Those two cannot share a build once a package captures on purpose. A save build is weaker than a live one: GuardBuilder consults save_guards in several places and, when it is set, replaces a guard the artifact cannot carry with a portable but looser one (the pytree SUPPORTED_NODES guard is demoted from an O(1) DICT_VERSION check to a keys-match expansion, and SHAPE_ENV guards are captured as code parts rather than a ShapeEnv), so with a single build the live cache also runs the weaker guards. A package that has to leave a non-portable guard out of its artifact had only guard_filter_fn, which also removes the guard from the live cache, so a later capture example that differs only in the dropped guard reuses the wrong graph instead of triggering the variant the package needs to record. And under caching_precompile the constructor rewrites guard_filter_fn to drop ID_MATCH, CLOSURE_MATCH, WEAKREF_ALIVE and DICT_VERSION from every build, live guards included.

Fix. CheckFunctionManager takes two keyword-only arguments, serialization_guard_filter_fn and explicit_capture. When guards are being saved and either is set, separate_save_build is on: build_guards runs for the runtime guards with save_guards=False, so the installed manager is the strict live build, and a second build_guards runs with save_guards=True over the serialization-filtered guard list; serialize_guards pickles from that second builder and that list. Both filters read the one snapshot of filter entries that build_filter_entries produces, and the inspection build is still skipped when no filter exists. After compile_check_fn returns, the serialization builder's guard_tree_values is seeded with the runtime builder's, so a guard dropped from the saved copy never prunes the value it named. The caching_precompile rewrite of guard_filter_fn is skipped when explicit_capture is set. The test helper _test_serialization forwards _explicit_capture and _serialization_guard_filter_fn to the manager it saves from.

Summary. The saved state has to come from a builder that ran with saving on over exactly the guards being pickled, because saving changes what the builder emits (the keys-match demotion, the shape code parts, used_builtin_vars, the extra locals DUPLICATE_INPUT records), while the live manager has to come from a builder that ran with saving off; filtering the pickled guard list after one build cannot satisfy both, so a second build is the only shape that works, and it is paid only when the two copies can differ. An explicit capture always splits even without a filter, because the save build is weaker than the live one regardless of filtering; an ambient caching-precompile package (no flag, no filter) keeps the single save build it has today, so nothing changes for it. The tree-values merge exists because pickle_guards_state prunes any local the guard tree does not reach into a placeholder, and a dropped guard would otherwise prune a tensor the rest of the state still refers to (it comes back with no dtype and the loaded check misfires); it runs after compile_check_fn because DuplicateInputs and StorageOverlap fetch their managers through get_guard_manager_from_source in there, which is what registers those tensors, and test_duplicate_input_survives_separate_save_build pins that order. Skipping the ambient rewrite for an explicit capture means such a package says what its artifact omits through its own filter; without one, a non-portable guard reaches the serializer and is refused as a PackageError rather than silently dropped. The commit below builds the shared filter entries this relies on; the commits above give CompilePackage the two flags and thread them through _compile. Carved out of #195913.

The filter applies to the saved copy, not to the live guards

Driven through CheckFunctionManager directly, the way test/dynamo/test_guard_serialization.py does it:

def drop_tensor_match(entries):
    return [e.guard_type != "TENSOR_MATCH" for e in entries]

mgr = CheckFunctionManager(
    f_code, tracer.output, guard_filter_fn=keep_tensor_match, save_guards=True,
    serialization_guard_filter_fn=drop_tensor_match,
)
loaded = load_guard_manager(load_guards_state(mgr.guards_state), f_code, f_globals)
x_int = torch.randint(0, 5, (3,))
ref.check({"x": x_int})     # live build:  False (TENSOR_MATCH still enforced)
loaded.check({"x": x_int})  # saved copy:  True  (TENSOR_MATCH filtered out)
# parent: no serialization_guard_filter_fn; the only filter is guard_filter_fn,
#         which removes a guard from the live manager and the saved copy alike
# now:    the live manager rejects the int tensor, the loaded copy accepts it

Pinned by test_serialization_filter_applies_to_the_saved_copy_only.

An explicit capture keeps the live guards strict

End to end, which needs the commits above (they carry the flags from CompilePackage into _compile); run from a file, since the package records source lines:

def fn(x):
    return pytree.tree_leaves(x)[0] + 1

def keep_portable(entries):  # by guard_type, so the SUPPORTED_NODES keys-match guard stays
    return [e.guard_type not in ("MODULE_MATCH", "ID_MATCH", "CLOSURE_MATCH") for e in entries]

pkg = CompilePackage(fn, explicit_capture=True, serialization_guard_filter_fn=keep_portable)
opt = torch._dynamo.optimize(backend="eager", package=pkg)(fn)
opt({"t": torch.randn(3)})
live = str(_debug_get_cache_entry_list(fn.__code__)[0].guard_manager)
state = load_guards_state(pkg._codes[fn.__code__].guarded_codes[0].guards_state)
loaded = str(load_guard_manager(state, fn.__code__, fn.__globals__))
"___dict_version(" in live    # True: DICT_VERSION on SUPPORTED_NODES, 4 KeyManagers
"___dict_version(" in loaded  # False: keys-match expansion, 99 KeyManagers
any(g._force_dict_keys_match for g in state.output_graph.guards)  # True
# parent: one build with save_guards=True, so the live manager also carried the
#         keys-match demotion and lost the O(1) dict-version check
# now:    the live manager is the strict save_guards=False build; only the saved
#         copy is demoted

The saved-side behaviour is pinned by test_supported_nodes_dict_keys_match; the explicit split is exercised by test_duplicate_input_survives_separate_save_build. A filter keyed on derived guard types would drop this guard instead: the entries come from the unsaved inspection build, where it still reads as DICT_VERSION.

Dropping a guard does not drop the value it named

The merge is load-bearing when a saved guard names a value that only compile_check_fn registers. Under use_lamba_guard_for_object_aliasing, DUPLICATE_INPUT names its second input through additional_used_local_vars without registering it in the builder's guard tree, and an aotautograd DuplicateInputs registers its tensors inside compile_check_fn, on the runtime builder:

def fn(x, x_):
    return x + x_

def inject(output):  # what AOTAutograd records for two aliased inputs
    output.tracing_context.guards_context.aotautograd_guards.append(
        DuplicateInputs(LocalSource("x"), LocalSource("x_"))
    )

with torch._dynamo.config.patch(use_lamba_guard_for_object_aliasing=True):
    x = torch.randn(3, 2)
    ref, loaded = self._test_serialization(
        "DUPLICATE_INPUT", fn, x, x, _explicit_capture=True, _post_trace=inject
    )
state = load_guards_state(self._cached_guards_state)
state.output_graph.local_scope["x_"]
# without the merge, or with it before compile_check_fn: _Missing(missing values)
# now: a tensor; the serialization builder inherits the runtime builder's
#      guard_tree_values after compile_check_fn, so the duplicated input
#      the saved guard names is pickled
ref.check({"x": x, "x_": x}), loaded.check({"x": x, "x_": x})  # (True, True)
ref.check({"x": x, "x_": torch.randn(3, 2)}), loaded.check(...)  # (False, False)

Pinned by test_duplicate_input_survives_separate_save_build, which fails with the merge removed and with the merge moved ahead of compile_check_fn. Under the default aliasing guard DUPLICATE_INPUT registers both tensors itself during the build, so the merge is a conservative superset there.

The caching_precompile rewrite leaves an explicit capture alone

End to end at the top of the stack:

def h(x):
    return x + id(x)

def drop_id_match(entries):
    return [e.guard_type != "ID_MATCH" for e in entries]

with torch._dynamo.config.patch(caching_precompile=True):
    pkg = CompilePackage(h, explicit_capture=True, serialization_guard_filter_fn=drop_id_match)
    torch._dynamo.optimize(backend="eager", package=pkg)(h)(x)
    live = _debug_get_cache_entry_list(h.__code__)[0].guard_manager
    "___check_obj_id" in str(live), live.check({"x": other})   # (True, False)
    state = load_guards_state(pkg._codes[h.__code__].guarded_codes[0].guards_state)
    loaded = load_guard_manager(state, h.__code__, h.__globals__)
    "___check_obj_id" in str(loaded), loaded.check({"x": other})  # (False, True)
    # ambient CompilePackage(h): live has no ID_MATCH and accepts `other`
# parent: the rewrite ran for every build, so the explicit package's live guards
#         lost ID_MATCH too
# now:    the live cache keeps ID_MATCH; the artifact omits it through the
#         package's own filter

The ambient behaviour is pinned by the unchanged test_id_match_with_config. An explicit capture with no filter lets ID_MATCH reach the serializer, which refuses it (ID_MATCH guard cannot be serialized); here that is a bypass, and the commit above that makes explicit captures strict turns it into a raise.

Test Plan:

python test/dynamo/test_guard_serialization.py -k separate_save_build
python test/dynamo/test_guard_serialization.py -k saved_copy_only
python test/dynamo/test_guard_serialization.py

The two new tests fail on the parent, which does not accept the new keyword arguments, and pass here; the rest of the file behaves as before.

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/198086

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, 3 Unrelated Failures

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

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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 39m 51s —— View job


Reviewed — the two-build split is the right shape, but the guard_tree_values blanket merge and the fact that serialization-filtered guards bypass the same-frame sanity check are worth addressing before landing, and the caching_precompile skip is untested.

Full review

PR Review: #198086

Summary

Splits CheckFunctionManager into a strict save_guards=False runtime build plus a separate save_guards=True serialization build, gated on a new serialization_guard_filter_fn / explicit_capture pair. The two-build shape is well motivated and the reasoning in the PR body holds up, but three things need attention: guards that only the serialization filter keeps are never same-frame validated, the guard_tree_values merge is broader than the problem it solves (and its comment misdescribes what it does), and the caching_precompile behavior change has no test at this level.

API Design

  • torch/_dynamo/guards.py:5210-5222 — guards kept only by serialization_guard_filter_fn are never sanity-checked. The comment at 5181-5187 states the serialization filter "is applied to every guard, not composed with the runtime filter." Since the two filters read the same filter_entries independently, serialized_guards can contain a guard that guard_filter_fn excluded from runtime_guards. The same-frame sanity check at guards.py:5267 only runs self.guard_manager — the runtime manager — so any guard present only in the serialization set is pickled without ever being validated against the capturing frame. Before this PR the two lists were identical, so the check covered everything that got saved; now it doesn't.

    The new test exercises exactly this shape: the helper's default guard_filter_fn keeps only TENSOR_MATCH, while drop_tensor_match keeps everything except TENSOR_MATCH, so the serialized set and the runtime set are disjoint. Either check the serialization manager against output_graph.local_scope too (the serialization build's GuardManagerWrapper is currently discarded at 5215, so it's available), or document that non-composed filters are unsupported and assert set(serialized_guards) <= set(runtime_guards). Fix this →

Code Quality

  • torch/_dynamo/guards.py:5226-5238 — the guard_tree_values merge is broader than the gap it fixes, and defeats one of the feature's stated uses. The test pins a real problem: DuplicateInputs / StorageOverlap register tensors on the runtime builder inside compile_check_fn, so the serialization builder never sees them. But the fix inherits the runtime builder's entire tree, not just what compile_check_fn added.

    guard_tree_values membership is the prune gate in three places — pickle_guards_state (4992, controls whether a leaf lands in missing_values), reducer_override's tensor branch (4684-4685) and module branch (4746-4747). Post-merge, any object the runtime guards reach is treated as guarded by the serializer even when the serialization filter deliberately dropped the guard naming it. So dropping a guard no longer drops the value, and reducer_override will attempt to pickle an object that was omitted precisely because it isn't portable — turning a deliberate omission into a PackageError → bypass_package. That undercuts the motivating use case ("a package may need to omit a non-portable identity guard").

    The narrow fix is to snapshot set(builder.guard_tree_values) immediately before compile_check_fn and merge only the delta, so the serialization builder inherits what compile_check_fn registered and nothing else.

    Relatedly, the comment at 5231 says "So prune against the unfiltered tree." The runtime builder is not unfiltered — it is built over runtime_guards, which guard_filter_fn already filtered (5198-5199). The comment should say what the code does. Fix this →

  • torch/_dynamo/guards.py:5097 vs 5178-5180 — inconsistent save_guards gating of the two new arguments. serialization_guard_filter_fn is silently dropped when save_guards is false (5178-5180), and explicit_capture is likewise ignored for the build split (5188-5190) — but explicit_capture still suppresses the caching_precompile filter rewrite at 5097 regardless of save_guards. So CheckFunctionManager(..., explicit_capture=True) with save_guards=False under caching_precompile keeps ID_MATCH / DICT_VERSION in the live guards while producing no artifact at all. Either gate 5097 on save_guards too, or raise when explicit_capture / serialization_guard_filter_fn are passed without save_guards rather than silently no-opping them.

Testing

  • No test for the caching_precompile and not explicit_capture change at guards.py:5097. This is a one-token condition that changes which guards land in the live cache — the change most likely to silently regress, and the only one in the diff with no coverage. The PR body has a worked example but defers it to commits higher in the stack; it is testable here without CompilePackage, by calling CheckFunctionManager directly under torch._dynamo.config.patch(caching_precompile=True) with explicit_capture=True and asserting ___check_obj_id survives in the live manager. The existing test_id_match_with_config (test_guard_serialization.py:3545) covers only the ambient path.

  • No test for explicit_capture=True with no serialization filter. The PR body states this path lets a non-portable guard reach the serializer and be refused as a PackageError bypass, and calls that out as a bypass rather than a raise. It's a new reachable state (separate_save_build is true with serialized_guards is runtime_guards) and nothing in the diff exercises it — test_duplicate_input_survives_separate_save_build passes _explicit_capture=True but the helper always installs a guard_filter_fn, and no test passes _explicit_capture=True without a serialization filter to observe the bypass.

  • No test for the inverse of the merge. test_duplicate_input_survives_separate_save_build pins that a dropped guard doesn't prune its value, but nothing pins the other direction — that a value reached only by a guard the serialization filter dropped is still prunable. Given the finding above, that's the assertion that would have caught the over-broad merge.

Performance

  • torch/_dynamo/guards.py:5188-5222 — an explicit capture with no filter goes from one guard build to two. With explicit_capture=True and both filters absent, build_filter_entries() is skipped (5195) but separate_save_build is still true, so build_guards runs twice over an identical guard list. That doubles the SHAPE_ENV path, including a second produce_guards_verbose call — a known compile-time hotspot — on a ShapeEnv the first build already froze (3590). It appears safe (produce_guards_verbose reads accumulated state rather than calling evaluate_expr), but the cost is real and unmeasured. The PR body claims the second build "is paid only when the two copies can differ"; with no filter the two lists are identical by construction, so what differs is only save_guards. Worth confirming the compile-time delta on a model-sized capture, or noting it explicitly as accepted.

Recommendation

Request Changes

The design is sound and the tests that exist are well-targeted. Blocking items: the unvalidated serialization-only guards (API Design), the over-broad guard_tree_values merge plus its incorrect comment (Code Quality), and a test for the caching_precompile skip — a behavior change to live guards with no coverage in this PR.

• Branch: `gh/bobrenjc93/1423/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; two of these changed the code, two changed the tests, and I am declining two with reasons below. The fixes are in 865e0d8.

guards kept only by serialization_guard_filter_fn are never sanity-checked.

Fixed in 865e0d8: the save build's GuardManagerWrapper is kept and gets the same same-frame check against output_graph.local_scope, raising its own "Serialized guard failed on the same frame it was created" if a guard the live manager does not hold fails on the frame that produced it.

the guard_tree_values merge is broader than the gap it fixes ... The narrow fix is to snapshot set(builder.guard_tree_values) immediately before compile_check_fn and merge only the delta

Fixed in 865e0d8: the runtime builder's keys are snapshotted before compile_check_fn and only the entries it added (the DuplicateInputs/StorageOverlap registrations) are handed to the serialization builder; the comment now says exactly that instead of "prune against the unfiltered tree". test_value_reached_only_by_a_dropped_guard_is_pruned pins the inverse you asked for: with every guard on an unpicklable dict value dropped from the saved copy, the value is pruned to _Missing instead of being pickled (the whole-tree merge tried to pickle the lock and bypassed).

inconsistent save_guards gating of the two new arguments.

Declined: this is the intended asymmetry. explicit_capture describes the package, not this compile: an explicit package's live guards are never rewritten by the ambient filter, including on a compile that saves nothing (a serving package, or a compile that was bypassed before the guards were built), while a serialization filter has nothing to act on unless something is saved. The comment at the rewrite now says "whether or not this compile saves them".

No test for the caching_precompile and not explicit_capture change

Fixed in 865e0d8: test_explicit_capture_keeps_id_match_live_under_caching_precompile builds through CheckFunctionManager directly under caching_precompile=True and checks that the ambient manager accepts another tensor (ID_MATCH rewritten away), the explicit capture's live manager rejects it, and the loaded copy accepts it because the package's own filter omitted the guard.

No test for explicit_capture=True with no serialization filter.

Declined here: that path is only reachable from a package, and the two commits above that wire it exercise it end to end (#198088 saves TENSOR_MATCH unfiltered from a bare explicit package, #198089 pins the raise on a guard the artifact cannot carry); the bypass leg is the pre-existing PackageError handling in this constructor.

an explicit capture with no filter goes from one guard build to two.

Acknowledged as the cost of the design rather than fixed: the live guards of an explicit capture are the strict save_guards=False build and the artifact is the save_guards=True build, and those differ in what they emit (the keys-match demotion, the shape code parts), so one build cannot serve both. The ambient path already pays two builds whenever a guard_filter_fn is installed; the description now states the second build as accepted.

@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 36m 4s —— View job


Re-reviewed 865e0d8/6592598: the two accepted fixes landed correctly and both declines are reasonable, but the new serialization same-frame check has an ordering/diagnostics problem and the narrowed guard_tree_values delta leaves aotautograd-named values order-dependent.

Full review

Verification of the four changes

Item Status
Same-frame check on the saved copy Landed at guards.py:5274-5281 — the save build's GuardManagerWrapper is kept and checked. See findings 1-2.
Narrow the guard_tree_values merge Landed at guards.py:5226-5245; comment rewritten. Confirmed test_value_reached_only_by_a_dropped_guard_is_pruned genuinely distinguishes delta-merge from whole-tree merge (the whole-tree version reaches id(lock) via values_before_check, tries to pickle it, and the helper's assertIsNotNone(guards_state) fails on the bypass). See finding 3.
caching_precompile skip test Landed. test_explicit_capture_keeps_id_match_live_under_caching_precompile builds ref without explicit_capture (so the ambient rewrite applies) and the saving manager with it — that does pin the one-token condition at 5098.
save_guards gating asymmetry Declined. Accepted: "explicit_capture describes the package, not this compile" is coherent, and I verified the load path (package.load_guard_manager, save_guards=False, no explicit_capture) is unaffected in practice because every guard type the rewrite drops is already in UNSUPPORTED_SERIALIZATION_GUARD_TYPES and so cannot appear in a loaded artifact.
explicit_capture with no filter, untested here Declined. Accepted — that path needs CompilePackage, which arrives higher in the stack.
Two builds for a filterless explicit capture Acknowledged in the description. Accepted.

New findings

  • guards.py:5274-5292 — the serialization check runs first and raises with no fail reason, so it degrades diagnostics for pre-existing failures. When a guard fails on its own frame, the runtime check at 5282 reports which guard failed via get_guard_fail_reason_helper. The new check is placed ahead of it, and a guard present in both sets (the common case, since the filters usually overlap heavily) will fail on the serialization manager first — so what used to be "Guard failed... Guard fail reason: <reasons>" is now a bare "Serialized guard failed..." with nothing to go on. Two changes: run the runtime check first so the informative message wins, and give the new one a reason of its own. get_guard_fail_reason_helper can't be reused (it asserts guard_manager.global_scope is not None, and the serialization manager never goes through compile_check_fn), but serialization_guard_manager.check_verbose(output_graph.local_scope).verbose_code_parts works and needs no extra state. Fix this →

  • guards.py:5274-5281 — the check's coverage is narrower than the comment suggests, and specifically excludes the guard the merge below exists for. The serialization manager never goes through compile_check_fn, so three families of guards are absent from it: the no-tensor-aliasing guard (5658), the use_lamba_guard_for_object_aliasing epilogue lambda (5681), and the aotautograd DuplicateInputs/StorageOverlap guards (5692-5726). serialization_builder.object_aliasing_guard_codes and .no_tensor_aliasing_names are simply discarded. Functionally that's fine — loading rebuilds through a fresh CheckFunctionManager which does run compile_check_fn — but it means the check validates leaf and accessor guards only, and DUPLICATE_INPUT (the case the merge twelve lines down is entirely about) is not among them. Worth saying so in the comment at 5274, since "the saved copy ... gets the same-frame check of its own" reads as full parity.

  • guards.py:5226-5245 — the delta makes inheritance of aotautograd-named values depend on unrelated guards. The narrowing is right for the case the review asked about, but values_before_check is a blanket "the runtime builder already had this" exclusion, and aotautograd_guards are subject to neither filter — they're installed unconditionally in compile_check_fn and rebuilt unconditionally from output_graph._aotautograd_guards on load. So: if the serialization filter drops the TENSOR_MATCH on a tensor that an aotautograd DuplicateInputs names, the runtime build registers id(t) during its own build, id(t) lands in values_before_check, the delta excludes it, the serialization builder never registers it, and pickle_guards_state prunes it to _Missing — while the loaded build reinstalls an object-aliasing guard rooted at that source. The new test can't see this: its guard_filter_fn keeps only DUPLICATE_INPUT, so no TENSOR_MATCH ever registers x pre-compile_check_fn and id(x) is legitimately in the delta.

    The predicate you actually want isn't "added during compile_check_fn" but "named by something in the serialized guard set". Since the aotautograd guards are exactly the unfilterable part, the direct form is to walk output_graph.aotautograd_guards and call serialization_builder.get_guard_manager_from_source(...) for their sources, instead of inferring them from a runtime-build delta. That removes the order dependence and the values_before_check snapshot entirely. If you'd rather keep the delta, a test that keeps TENSOR_MATCH in the runtime filter and drops it in the serialization filter, with an injected DuplicateInputs, would pin whichever behaviour you intend. Fix this →

  • test_guard_serialization.py:3796 — drop_guards_on_b can pass vacuously. The helper's own guard_filter_fn asserts any(ret) so a guard-type rename can't silently neuter a test; the custom filters here don't. If d['b'] ever stops receiving a guard, scope["d"]["b"] is _Missing for the ordinary unguarded-value reason and the test still passes while testing nothing. self.assertTrue(any(e.name == "d['b']" for e in entries)) inside the filter restores that property. Same applies to drop_tensor_match and drop_id_match.

  • guards.py:5192-5197 — the eager build_filter_entries() is a no-op and its comment claims a guarantee the call order already provides. filter_entries is memoised, so both filters see one snapshot whenever it is built; and in every branch that needs it, apply_filter builds it before the save build at 5217 anyway (the guard_filter_fn is None, serialization_filter is not None case builds it at 5216). I checked what the inspection build's reset of guard.guard_types/code_list could clobber: only the runtime build's export info, which nothing reads (compile_check_fn walks builder.code, and serialize_guards runs after the save build). Either drop the call or reword the comment to say it's defensive.

Recommendation

Comment — nothing here blocks the two-build split, which is now in good shape. Finding 1 is a small, mechanical reordering worth doing before landing since it touches an existing error path; findings 2-3 are about the new code's comments matching its actual reach, with 3 carrying a concrete reachability argument I'd want either closed or pinned by a test.

I could not run test/dynamo/test_guard_serialization.py — no built PyTorch in this checkout — so all of the above is from reading, not execution.

• Branch: `gh/bobrenjc93/1423/head`

[ghstack-poisoned]
@bobrenjc93

bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks; the two mechanical items and the vacuous-filter item are folded, and finding 3 is answered by moving the aotautograd hand-off into a PR of its own with the direct form you suggested. The fixes are in 533f1fa.

the serialization check runs first and raises with no fail reason

Fixed in 533f1fa: the live manager's check runs first, so a guard both hold still fails with the named reason, and the saved copy's check now uses check_verbose and reports its verbose_code_parts.

the check's coverage is narrower than the comment suggests

Fixed in 533f1fa: the comment now says the check covers the leaf and accessor guards of the saved copy only, that the saved copy never ran compile_check_fn, and that load rebuilds those guards through a fresh CheckFunctionManager.

the delta makes inheritance of aotautograd-named values depend on unrelated guards ... the direct form is to walk output_graph.aotautograd_guards and call serialization_builder.get_guard_manager_from_source(...) for their sources

Split out: this PR no longer inherits anything from the runtime builder's tree (so a value only the live guards reach is pruned, pinned by test_value_reached_only_by_a_dropped_guard_is_pruned), and the direct form lives in #198125, "Register the sources of aotautograd guards on a package's saved guards", two positions up. Its test is the one you described: runtime keeps TENSOR_MATCH, the serialization filter drops it, a DuplicateInputs is injected after tracing, and the aliased input is still a tensor in the saved copy; it fails on this PR with _Missing.

drop_guards_on_b can pass vacuously

Fixed in 533f1fa: the three custom filters assert the guard they drop is present (drop_tensor_match, drop_id_match, drop_guards_on_b).

the eager build_filter_entries() is a no-op

Fixed in 533f1fa: the call and its comment are gone; the memoised snapshot is built by the first apply_filter in every branch that needs it.

Size after the split: this PR is 136 inserted lines (was 185), the new PR 59.

@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 37m 42s —— View job


Re-reviewed 533f1fa: the two diagnostics fixes from round 2 landed cleanly, but removing the guard_tree_values merge outright (rather than narrowing it) reopened the AOTAutograd pruning gap the deleted test was pinning.

Full review

PR Review: #198086

Summary

Splits CheckFunctionManager into a strict save_guards=False runtime build plus a separate save_guards=True serialization build, gated on serialization_guard_filter_fn / explicit_capture. Round 2's two findings about the same-frame check are fixed correctly; the third — narrowing the guard_tree_values merge — was addressed by deleting the merge entirely, which is a different change than the one requested and reintroduces the defect the now-deleted test_duplicate_input_survives_separate_save_build covered.

Verification of round-2 items

Round-2 finding Status in 533f1fa
Serialization check ran first, with no fail reason Fixed. Runtime check is now first (guards.py:5248), save check second (5264), and the new AssertionError carries info.verbose_code_parts from check_verbose. I verified the save manager is safe to check_verbose without compile_check_fn: add_python_lambda_leaf_guard_to_root binds guard_fn at build time (2262-2263), GuardManagerWrapper.closure_vars is read only by get_guard_fail_reason_helper (5992) and the debug path (6224), never by RootGuardManager::check_verbose_nopybind, and the two RootGuardManagers have independent _fail_count / _recorded_dict_pointers / relational state.
Comment overstated the check's coverage Fixed. 5259-5263 now names the three families the save manager lacks.
guard_tree_values merge too broad Not fixed as requested — see finding 1.
Vacuous custom filters Fixed. All three filters now assert the guard they drop was present.
Eager build_filter_entries() no-op Fixed by deletion.

Code Quality

  • guards.py:5204-5219 — deleting the merge outright reopens the AOTAutograd pruning gap; the request was to narrow it, not remove it. Round 2 asked to replace the whole-tree merge with a targeted registration (walk output_graph.aotautograd_guards and register their sources on the serialization builder). 533f1fa instead removed the merge and deleted the test. The gap is unchanged from what the merge existed to close:

    serialization_builder is constructed at 5210, before compile_check_fn(builder, ...) at 5219, and compile_check_fn only ever receives the runtime builder. The AOTAutograd loop at 5670-5705 calls builder.get_guard_manager_from_source(...) for DuplicateInputs.input_source_a/b and StorageOverlap.overlapping_sources / non_overlapping_sources — that call is what populates guard_tree_values[id(tensor)] (1755). So a tensor named only by an AOTAutograd aliasing guard is absent from serialization_builder.guard_tree_values, and pickle_guards_state (4973) prunes it to _Missing via the tensor branch at 4684-4685.

    I checked this against the parent (git show origin/gh/bobrenjc93/1423/base:torch/_dynamo/guards.py): there is one builder, it is the one compile_check_fn gets, and serialize_guards is called with it — so the AOTAutograd-named tensor is in guard_tree_values there. This is a regression introduced by the two-build split, not a pre-existing hole.

    aotautograd_guards are neither filterable nor optional: they are installed unconditionally in compile_check_fn, they travel into the artifact (output_graph.py:461, 498), and load reinstalls them through a fresh CheckFunctionManager. So the loaded build calls get_guard_manager_from_source on a source whose value is now a _Missing, and installs an object-aliasing guard rooted at the sentinel.

    Reachability needs the serialization filter to drop every guard that would otherwise register the tensor, which is exactly what the feature is for. Under the default use_lamba_guard_for_object_aliasing=False (config.py:453) Dynamo's own DUPLICATE_INPUT registers both tensors during the build, so a surviving DUPLICATE_INPUT masks it; under use_lamba_guard_for_object_aliasing=True it records a code part instead (3322-3328) and does not register the second input, which is the configuration the deleted test used.

    The targeted form avoids the order dependence round 2 raised and closes the gap — register the AOTAutograd sources directly on serialization_builder rather than inferring them from the runtime builder. Fix this →

Testing

  • test/dynamo/test_guard_serialization.py — the only coverage of the save build's interaction with aotautograd_guards was deleted, along with the _post_trace hook that made it expressible. 533f1fa removed test_duplicate_input_survives_separate_save_build, the _post_trace kwarg from _test_serialization, and the DuplicateInputs import. Nothing in test/dynamo/ now exercises aotautograd_guards together with save_guards, so the finding above is unpinned in either direction. Restoring the test alongside the targeted registration would pin it; if instead you intend the pruning to be correct behaviour, a test asserting the _Missing and the load-time outcome is what documents that.

  • test_value_reached_only_by_a_dropped_guard_is_pruned (3744) does not distinguish the fix from the deletion. It pins that a value reached only by dropped guards is pruned — true under the narrow merge and under no merge alike, since its d['b'] is never touched by compile_check_fn. That is the inverse assertion round 2 asked for and it is a good test, but it is not evidence that removing the merge was safe.

Performance

  • guards.py:5264-5270 — the save-manager check adds a second full guard evaluation on every saving compile. check_verbose_nopybind (guards.cpp:4428) runs every leaf and accessor guard, and unlike check_nopybind it takes no early-exit-and-sort shortcut and allocates a GuardDebugInfo per guard (4103-4140). It is the right check to have and the cost is bounded, but it lands on the compile path, not a diagnostic path, for every explicit capture. Using check() and only re-running check_verbose() to build the message on failure would keep the diagnostics and drop the steady-state cost.

Recommendation

Request Changes

Finding 1 is a behaviour regression against the parent with its only test deleted in the same commit. The rest of the round-2 feedback is resolved and the two-build split itself reads correctly.

I could not run test/dynamo/test_guard_serialization.py — there is no built PyTorch in this checkout — so all of the above is from reading, not execution.

• Branch: `gh/bobrenjc93/1423/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/1423/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