Skip to content

[dynamo] Build the guard filter entries once in CheckFunctionManager - #198085

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. CheckFunctionManager applied the user's guard filter inline: when a filter was set it ran an extra unsaved build over the sorted guards, turned each guard into a GuardFilterEntry from that builder, called the filter, validated the result, and rebound the same local to the surviving list, which the runtime build, compile_check_fn and serialize_guards then all consumed. That shape supports exactly one filter. The next commit in this stack needs to apply a second filter (the package's serialization filter) to the same guards and keep both results, and inlining the build-entries-call-filter-validate sequence a second time would duplicate the extra build and the checks.

Fix. The constructor now sorts the guards into all_guards and defines two closures over them. build_filter_entries runs the inspection build at most once and caches the resulting GuardFilterEntry list; apply_filter takes a filter callable, forces the entries to exist, calls it, keeps the length and bool-type assertions from the old inline code, and returns the guards the filter kept. The list that the runtime build, compile_check_fn and serialize_guards receive is renamed runtime_guards and is either apply_filter(guard_filter_fn) or all_guards when no filter is set. No other function changes.

Summary. This is a pure refactor with no behaviour change: a filter is still called exactly once with the same entries, the inspection build still runs only when some filter exists, and a filter-less compile still does one build as before. Caching the entries rather than rebuilding per filter is sound because every build_guards call resets and repopulates code_list and guard_types on the guards it is given, so a single snapshot taken from the unsaved inspection build serves any number of filters over these guards; the comment in build_filter_entries records that. The alternative of hoisting this into a method on CheckFunctionManager was rejected because the closures only make sense over the constructor's locals (existing_diff_guard_sources, f_code, output_graph) and nothing outside the constructor needs them. The caching_precompile wrapper that rewrites guard_filter_fn is untouched and still applies to the runtime filter only. The commit above this one adds serialization_guard_filter_fn and calls apply_filter a second time for the guards that get pickled, which is why the runtime list gets its own name here. Carved out of #195913.

The filter still runs once over one set of entries

Run from the worktree root; the guard filter passed through compile options is the guard_filter_fn that CheckFunctionManager receives.

import torch
from torch._dynamo.types import GuardFilterEntry

calls = []

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

def fn(x):
    return x + 1

compiled = torch.compile(fn, backend="eager", options={"guard_filter_fn": record_filter})
compiled(torch.randn(3))
len(calls)                                  # parent: 1   now: 1
isinstance(calls[0][0], GuardFilterEntry)   # parent: True   now: True
any(e.guard_type == "TENSOR_MATCH" for e in calls[0])
# parent: True   now: True  (the entries cover all_guards, not the filtered list)
with torch.compiler.set_stance("fail_on_recompile"):
    compiled(torch.randn(3, dtype=torch.float64))
# parent: no recompile, TENSOR_MATCH was dropped   now: same

calls.clear()
torch.compile(fn, backend="eager")(torch.randn(3))
len(calls)                                  # parent: 0   now: 0 (no filter, no inspection build)

Inside the test helper the same path is exercised by constructing the manager directly, which is the shape the next commit extends:

CheckFunctionManager(f_code, tracer.output, guard_filter_fn=guard_filter_fn)
CheckFunctionManager(f_code, tracer.output, guard_filter_fn=guard_filter_fn, save_guards=True)

Pinned by test_global_state_guard_filter and test_torch_function_state_filter in test/dynamo/test_guard_serialization.py, and by every _test_serialization case in that file, which selects one guard type through guard_filter_fn and checks that the saved and rebuilt guard managers agree with the runtime one.

Test Plan:

python test/dynamo/test_guard_serialization.py -k guard_filter
python test/dynamo/test_guard_serialization.py

The file passes on the parent and passes here; no test changes because behaviour is unchanged.

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 added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 22, 2026
@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/198085

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

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • Restructures guard filtering in CheckFunctionManager.__init__ into two closures with memoized filter_entries (torch/_dynamo/guards.py:5118-5168).
    • That is new lazy-caching control flow in core guard construction, not a rename or move, so no trivial change class covers it.
    • The memoization pays off only for a second filter, and apply_filter has one caller in the tree (grep across ./pytorch hits only guards.py).
  • Reviewer questions sitting in the diff
    • if filter_entries is None: raise AssertionError(...) at guards.py:5152-5153 is unreachable: build_filter_entries always assigns a list before returning.
    • The assertion text at guards.py:5158 still reads sorted_guards length though the local is now all_guards.
  • Correctness
    • Behaviour looks preserved: one inspection build when a filter exists, and runtime_guards feeds build_guards, compile_check_fn, and serialize_guards (guards.py:5170-5257).
    • The caching rests on build_guards resetting guard.guard_types and guard.code_list per build (guards.py:5484-5485), a non-obvious invariant worth a human read.
  • Tests
    • No test added; test/dynamo/test_guard_serialization.py:4322 and :4340 apply a single guard_filter_fn, so they cannot distinguish the memoized build from the old per-filter build.

reason: not_trivial
Reviewed commit: ee9f978

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


PR #198085 review

Reviewed the 35/-16 refactor in torch/_dynamo/guards.py. The refactor is behaviour-preserving as claimed; two code-quality items are worth folding in, and one low-confidence lifetime note.

Full review

PR Review: #198085

Summary

Hoists the inline guard-filter application in CheckFunctionManager.__init__ into two closures (build_filter_entries / apply_filter) over a new all_guards local so the next commit in the stack can run a second filter over the same entries. The refactor is behaviour-preserving, but the two-closure split forces an unreachable assertion that should not exist, and one error message is now stale.

Code Quality

  • torch/_dynamo/guards.py:5152-5153 — if filter_entries is None: raise AssertionError("filter_entries must be built") is unreachable by construction; it exists only because mypy cannot narrow a nonlocal across a call to build_filter_entries(). The repo forbids silencing asserts but it equally does not want dead branches standing in for type narrowing. The split into two closures is what creates the problem: build_filter_entries has exactly one caller (apply_filter), so per CLAUDE.md ("Don't make trivial helper functions that are only used once unless it significantly improves code readability") it should be inlined, which narrows the type naturally and deletes the dead branch:

    filter_entries: list[GuardFilterEntry] | None = None
    
    def apply_filter(
        filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]],
    ) -> list[Guard]:
        nonlocal filter_entries
        if filter_entries is None:
            # Filtering depends on the builder's results, so the entries come
            # from an extra, unsaved build over every guard. Built at most
            # once: each build_guards call resets code_list and guard_types on
            # the guards it is given, so one snapshot serves every filter.
            inspection_builder, _ = self.build_guards(
                all_guards, existing_diff_guard_sources, f_code, output_graph, False
            )
            filter_entries = [
                make_guard_filter_entry(guard, inspection_builder)
                for guard in all_guards
            ]
        filter_results = filter_fn(filter_entries)
        ...

    This keeps the build-at-most-once semantics the next commit depends on and drops 6 lines. Fix this →

  • torch/_dynamo/guards.py:5158 — the assertion message still reads sorted_guards length ({len(all_guards)}) after the local was renamed to all_guards. A user hitting this from a bad guard_filter_fn gets pointed at a name that no longer exists in the file. Change the string to all_guards length.

Performance

  • torch/_dynamo/guards.py:5125 — low confidence, flagging for the author's judgement: caching filter_entries in a closure cell keeps the whole entry list, and therefore a strong reference to every guarded value (GuardFilterEntry.value from builder.get(guard)), alive for the remainder of __init__ — through compile_check_fn, the same-frame guard check, profile_guard_manager, and serialize_guards. On the parent the list was a temporary released immediately after the filter call. The cell dies when the constructor returns, and those values are reachable from output_graph.local_scope for the same window anyway, so this is probably a no-op — but this file goes to unusual lengths over lifetimes (cleanup_builder, self._weakrefs.clear(), self.output_graph = None, test_release_input_memory / test_release_scope_memory), so it is worth a conscious decision rather than an accident. If it matters, drop the cache after the last apply_filter call in the follow-up commit.

Notes on claims I verified

  • The caching-soundness argument in the description holds: build_guards assigns guard.guard_types = None / guard.code_list = None per guard at guards.py:5484-5485 (reset, not append), and GuardFilterEntry.code_parts is snapshotted as a tuple at construction (guards.py:4962), so a single inspection snapshot is stable across later builds.
  • The extra inspection build leaves no accumulated state on self for the real build: the three accumulating OrderedSets (used_builtin_vars, additional_used_local_vars, additional_used_global_vars) are only populated when save_guards=True, and the inspection build passes False. id_matched_objs lives on the per-build GuardManagerWrapper, not on self.
  • Under caching_precompile the wrapper at guards.py:5092 rebinds guard_filter_fn before all_guards is computed, so apply_filter(guard_filter_fn) receives the wrapper exactly as the parent did — the filter still runs exactly once per compile.
  • zip(all_guards, filter_results) without strict= is safe here because the length assertion precedes it.
  • No test changes are needed for a behaviour-preserving refactor; test/dynamo/test_guard_serialization.py already covers both the filtered and save_guards paths. I did not run the suite — this checkout has no built PyTorch, so test/dynamo/test_guard_serialization.py could not be executed from the review environment.

Recommendation

Approve — the refactor is correct and the stated invariants check out. The unreachable assertion and the stale sorted_guards string should be cleaned up before landing, ideally by the inline shown above, since the next commit in the stack will inherit whichever shape lands here.

· branch `gh/bobrenjc93/1422/head`

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