Skip to content

Preserve FX graph cache guard provenance - #184193

Closed
jansel wants to merge 5 commits into
gh/jansel/789/basefrom
gh/jansel/789/head
Closed

jansel wants to merge 5 commits into
gh/jansel/789/basefrom
gh/jansel/789/head

Conversation

@jansel

@jansel jansel commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

Preserve source locations for Inductor guards that are saved in the FX graph cache, so a cache-hit recompile reason still points at the original guard producer instead of the cache replay site.

Fixes #141595
Generated by my agent

Root Cause

Without the FX graph cache, ShapeEnv records each ShapeGuard with the source location captured when Inductor creates the guard, for example can_use_32bit_indexing.

On an FX graph cache hit, Inductor only had CompiledFxGraph.guards_expr, a single combined Python expression string. Re-evaluating that string installs equivalent guards in the current ShapeEnv, but the new guards get the replay callsite as their source location. That is why recompile logs pointed at _lookup_graph, autograd_cache.py, or <string>:1 instead of the original Inductor guard.

Review Guide

  • torch/fx/experimental/symbolic_shapes.py: threads source locations alongside each produced guard expression, adds ShapeGuardExpression, and replays cached guards while temporarily using the stored source location for any ShapeGuard created by evaluation.
  • torch/_inductor/output_code.py: adds optional cached metadata fields for the per-guard expression/source list and the SymInt argument count used when saving it.
  • torch/_inductor/codecache.py: saves the new metadata, replays it on normal FX graph cache hits, and falls back to the existing combined-expression path for old cache entries, unsafe-skip mode, or AOTAutograd loads whose argument list differs.
  • Tests cover both the small ShapeEnv round trip and the original CUDA/flex-attention cache-hit failure mode.

Test Plan

  • PYTHONPATH=. python test/test_dynamic_shapes.py TestGuardsExpressions.test_guards_expression_source_info
  • PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_cache_hit_inductor_guard_preserves_source
  • PYTHONPATH=. python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_output_views_input_dynamic
  • lintrunner -a

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/184193

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:

✅ You can merge normally! (7 Unrelated Failures)

As of commit 40370b0 with merge base c004e2d (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: inductor release notes: fx release notes category labels May 18, 2026
@jansel

jansel commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 18, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 33s —— View job


Reviewing PR #184193: Preserve FX graph cache guard provenance

  • Gather context and read the diff
  • Review torch/fx/experimental/symbolic_shapes.py changes
  • Review torch/_inductor/codecache.py changes
  • Review torch/_inductor/output_code.py changes
  • Review test changes
  • Post review feedback

Review Summary

This PR preserves guard provenance (source locations) through the FX graph cache round-trip. When guards are reinstalled from a cache hit, they now carry the original source location (e.g., can_use_32bit_indexing) rather than a generic <string>:1 or _lookup_graph, which makes recompile reasons much more useful for debugging. The approach is clean and well-scoped.

Architecture

The design is solid:

  1. produce_guards_verbose now threads source_locations alongside exprs through all guard categories
  2. ShapeGuardExpression is a lightweight dataclass pairing each string expression with its SLoc
  3. On cache load, evaluate_guards_expression_with_source_info replays each guard individually, setting _evaluate_guards_source_location so that _evaluate_expr picks up the correct provenance
  4. Falls back gracefully to the existing evaluate_guards_expression codepath when source info is unavailable

Issues & Suggestions

1. Potential pickling issue with SLoc.framework_loc being FrameSummary (minor risk)

SLoc.framework_loc can be either str, None, or traceback.FrameSummary. When _get_sloc() is called during the original compilation, framework_loc is typically a FrameSummary object (see symbolic_shapes.py:7928). While FrameSummary should be picklable, it's worth noting that if this data is serialized (e.g., for remote FX graph cache), the FrameSummary fields (filename, lineno, name, line) need to survive the round-trip.

In practice, for the local cache path this is fine since the object stays in memory. For the remote cache, I'd verify that ShapeGuardExpression pickles correctly with a FrameSummary-typed SLoc. If this has already been tested, feel free to disregard.

2. getattr fallback for backwards compatibility (codecache.py:1857)

guards_expr_with_source = getattr(graph, "guards_expr_with_source", None)

This is necessary for loading old cache entries that don't have the new field — good defensive coding. However, it might be cleaner to add a comment explaining this is for backwards compatibility with cached graphs serialized before this change.

3. Performance: evaluating guards one-by-one vs. joined (symbolic_shapes.py:6847-6851)

The new evaluate_guards_expression_with_source_info evaluates each guard expression individually via eval(), whereas the old path evaluates them all in one eval(" and ".join(...)) call. This means N separate eval() calls instead of 1. For cache hits with many guards, this could have measurable overhead.

Potential mitigation: batch the guards that share the same sloc into a single eval() call, or at minimum note that this is intentionally trading performance for provenance accuracy. Given this only runs on cache hits (not the hot path), this is probably acceptable — but worth a note.

4. Context manager overhead for each guard (symbolic_shapes.py:6826-6835)

_evaluate_guards_with_source_location is a @contextmanager invoked per-guard. Each invocation allocates a generator + frame. For the same performance concern as above, a simpler pattern would be:

for guard in guards:
    self._evaluate_guards_source_location = guard.sloc
    result = eval(guard.expr, SYMPY_INTERP, locals_)
    if not bool(result):
        self._evaluate_guards_source_location = None
        return False
self._evaluate_guards_source_location = None
return True

This avoids the overhead and is arguably just as clear since there's no yield-back or exception that needs the finally. But the current implementation is correct and safe — this is a style/micro-optimization suggestion only.

5. Defensive length check (symbolic_shapes.py:6788-6791)

if len(produced_guards.source_locations) != len(produced_guards.exprs):
    source_locations: list[SLoc | None] = [None] * len(produced_guards.exprs)

Since source_locations and exprs are populated in lockstep in produce_guards_verbose, this condition should never be true. If it's truly unreachable, an assert would be more appropriate. If it's defensive against future code changes, a comment would help.

Correctness

  • The _copy_check exclusion for _evaluate_guards_source_location at line 4264 is correct — source locations are allowed to diverge between shape envs.
  • The guards comparison in map_value (line 4278-4280) already strips SLoc by only comparing .expr, so replayed guards with different provenance won't trigger copy-check failures.
  • The fallback to evaluate_guards_expression when guards_expr_with_source is None or unsafe_skip_cache_dynamic_shape_guards is set ensures backwards compatibility.

Tests

Both tests are well-targeted:

  • test_cache_hit_inductor_guard_preserves_source: End-to-end test verifying the recompile error message contains can_use_32bit_indexing (the real source) and not generic cache machinery paths.
  • test_guards_expression_source_info: Unit test for the round-trip through produce_guards_expression_with_source_info → evaluate_guards_expression_with_source_info, verifying sloc propagation.

Verdict

LGTM with minor suggestions. The core approach is correct, well-tested, and addresses a real pain point in debugging recompilations from cache hits. The main items to consider are the per-guard eval() overhead (acceptable for cache hits) and ensuring SLoc serializes correctly for remote cache scenarios.


[ghstack-poisoned]
jansel added a commit that referenced this pull request May 18, 2026
Store per-guard source locations with FX graph cache guard expressions and replay them when cache hits reinstall ShapeEnv guards, while preserving AOTAutograd's custom guard-check fallback when cached graph arguments differ.

Fixes #141595

Generated by my agent

ghstack-source-id: bb75077

Pull-Request: #184193
@jansel

jansel commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 18, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 6s —— View job


Reviewing PR #184193: Preserve FX graph cache guard provenance

  • Gather context and read the diff
  • Review torch/fx/experimental/symbolic_shapes.py changes
  • Review torch/_inductor/codecache.py changes
  • Review torch/_inductor/output_code.py changes
  • Review test changes
  • Post review feedback

Review Summary

Clean, well-scoped change. The core idea—thread SLoc alongside guard expressions through the cache round-trip so recompile reasons point to meaningful source locations instead of <string>:1—is correct and the implementation is straightforward.

Architecture

  1. _ShapeGuardsHelper gains a parallel source_locations list populated in lockstep with exprs during produce_guards_verbose
  2. ShapeGuardExpression pairs each expression string with its SLoc
  3. On cache load, evaluate_guards_expression_with_source_info replays guards one-by-one, setting _evaluate_guards_source_location so _evaluate_expr picks up the correct provenance
  4. Falls back to the joined evaluate_guards_expression path when source info is unavailable (old cache entries, arg count mismatch, unsafe_skip_cache_dynamic_shape_guards)

Issues

1. _evaluate_guards_source_location not reset on guard pass (correctness, minor)

symbolic_shapes.py:6838-6844 — If all guards pass and the function returns True, _evaluate_guards_source_location is correctly reset in the finally block. Good. But note: _evaluate_expr at line 8519 uses this field to override the sloc. If any other code path calls _evaluate_expr concurrently on the same ShapeEnv while this loop is running, it would pick up a stale sloc. This is safe today (single-threaded eval), but the field is mutable shared state on the ShapeEnv—worth noting if threading is ever introduced.

2. Per-guard eval() overhead (performance, acceptable)

The new path does N eval() calls instead of 1 joined expression. This only runs on cache hits and N is typically small (tens of guards, not thousands), so the overhead is negligible in practice. No action needed.

3. guards_expr_with_source_arg_count guards against arg count mismatch (design question)

codecache.py:1869 checks guards_expr_with_source_arg_count == len(symints). The comment mentions AOTAutograd can load with a different argument list. Is there a scenario where the arg count matches by coincidence but the meaning of the args differs? If so, the source info would be silently applied to the wrong guards. I suspect this can't happen in practice since the cache key already ensures the graph matches, but wanted to flag it.

4. Serialization of SLoc with FrameSummary (potential issue for remote cache)

SLoc.framework_loc can hold a traceback.FrameSummary. For local FX graph cache this is fine (pickle within the same process). For remote cache, FrameSummary should pickle correctly, but it pulls in the source line text which could be stale if code changes between serialization and deserialization. Not a correctness issue—just means the framework_loc.line field might be wrong on remote cache hits across code versions. Acceptable given the field is purely diagnostic.

Nits

  • The assertion at symbolic_shapes.py:6789-6791 can never fire since source_locations and exprs are appended in lockstep in the same loops. An assert might be lighter weight than raising, though I understand the preference for explicit AssertionError with a message in this codebase.

Tests

Both tests are well-targeted:

  • test_cache_hit_inductor_guard_preserves_source: End-to-end, verifies recompile error message shows can_use_32bit_indexing and not cache machinery paths.
  • test_guards_expression_source_info: Unit test for the round-trip, verifying sloc propagation into the new ShapeEnv.

Verdict

LGTM. The implementation is correct, well-tested, and handles backwards compatibility gracefully. The performance impact is negligible for the cache-hit path. Ship it.


@jansel
jansel marked this pull request as ready for review May 19, 2026 11:09
@jansel
jansel requested a review from laithsakka as a code owner May 19, 2026 11:09
@jansel
jansel requested review from BoyuanFeng and removed request for laithsakka May 19, 2026 11:09
@BoyuanFeng
BoyuanFeng requested review from laithsakka and removed request for BoyuanFeng May 20, 2026 03:47
@jansel
jansel requested a review from ezyang May 21, 2026 07:09
@ezyang

ezyang commented May 21, 2026

Copy link
Copy Markdown
Contributor

This PR is difficult to review

@jansel

jansel commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I updated the PR description to make the change easier to review: it now explains the cache-hit root cause, the file-by-file implementation, the fallback behavior, and the focused tests. No code changes were needed for this update; CI remains mergeable per Dr. CI.

@jansel
jansel requested a review from oulgen May 23, 2026 21:17
@ezyang

ezyang commented May 28, 2026

Copy link
Copy Markdown
Contributor

@laithsakka you prolly wanna read this change

@jansel

jansel commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 7, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorch-bot

pytorch-bot Bot commented Jun 17, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot revert: error: the following arguments are required: -c/--classification

usage: @pytorchbot revert -m MESSAGE -c
                          {nosignal,ignoredsignal,landrace,weird,ghfirst,autorevert}

Try @pytorchbot --help for more info.

@frgossen

Copy link
Copy Markdown
Contributor

@pytorchbot revert -m "This breaks vLLM - See #187484 for details" -c nosignal

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Reverting PR 184193 failed

Reason: Command git -C /home/runner/work/pytorch/pytorch revert --no-edit 060670aadfb5995aaf62aa31f2d7c23db24bd791 returned non-zero exit code 1

Auto-merging test/inductor/test_codecache.py
Auto-merging test/test_dynamic_shapes.py
Auto-merging torch/_inductor/codecache.py
CONFLICT (content): Merge conflict in torch/_inductor/codecache.py
Auto-merging torch/_inductor/output_code.py
Auto-merging torch/fx/experimental/symbolic_shapes.py
error: could not revert 060670aadfb... Preserve FX graph cache guard provenance (#184193)
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git revert --continue".
hint: You can instead skip this commit with "git revert --skip".
hint: To abort and get back to the state before "git revert",
hint: run "git revert --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Details for Dev Infra team Raised by workflow job

@frgossen

Copy link
Copy Markdown
Contributor

Reverting in #187581

frgossen added a commit that referenced this pull request Jun 17, 2026
This reverts commit 060670a.


ghstack-source-id: 7023e34
Pull-Request: #187581
@jansel jansel reopened this Jun 18, 2026
@datadog-pytorch-via-lf

Copy link
Copy Markdown

Pipelines

⚠️ Warnings

🚦 2 Pipeline jobs failed

Check mergeability of ghstack PR | ghstack-mergeability-check   View in Datadog   GitHub Actions

torchtitan-test | torchtitan-x-pytorch-test / test-osdc (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)   View in Datadog   GitHub Actions

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 3bdffb8 | Docs | Give us feedback!

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 20, 2026
FX graph cache hits replayed cached dynamic-shape guards from a single
combined Python expression. That reconstructed equivalent ShapeEnv guards,
but the guards inherited the cache replay callsite as their source location,
so recompile reasons pointed at cache machinery instead of the original
Inductor guard producer.

Store each cached guard expression with its original ShapeGuard source
location and replay those expressions with the saved provenance for ordinary
FX graph cache hits when the SymInt argument list matches. Keep the existing
combined-expression fallback for older cache entries and unsafe-skip mode.

The original fix was reverted after AOTAutograd cache hits in vLLM started
failing in FX graph cache guard replay. The root cause was that AOTAutograd
passes a custom exact-match guard evaluator and owns the cache-validity
contract for those loads, but the source-aware replay path bypassed that
custom evaluator when the argument count happened to match. Preserve custom
evaluate_guards callbacks in the post-load path instead of replaying source
locations for them. This keeps the provenance fix for normal FX graph cache
hits while avoiding incorrect AOTAutograd guard re-evaluation.

Keep the serialized guard-expression helper private so it does not become a
new public symbolic-shapes API.

Fixes #141595

Generated by my agent

Test Plan:
- PYTHONPATH=. python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
- PYTHONPATH=. python test/test_dynamic_shapes.py TestGuardsExpressions.test_guards_expression_source_info
- PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_custom_guard_evaluator_skips_source_replay
- PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_cache_hit_inductor_guard_preserves_source
- PYTHONPATH=. python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_output_views_input_dynamic
- PYTHONPATH=. python -m py_compile torch/fx/experimental/symbolic_shapes.py torch/_inductor/codecache.py torch/_inductor/output_code.py test/test_dynamic_shapes.py test/inductor/test_codecache.py test/dynamo/test_aot_autograd_cache.py
- lintrunner -a

ghstack-source-id: 278be7c

Pull-Request: #184193
@jansel

jansel commented Jun 20, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I rebased the PR onto current main after the revert and preserved the guard-provenance fix while addressing the vLLM/AOTAutograd regression. The update now only replays per-guard source locations for the default FX graph cache guard evaluator; custom evaluators such as AOTAutograd's exact-match checker keep using their own guard contract. I added a focused regression test and reran the public-bindings, symbolic-shapes, FX graph cache provenance, AOTAutograd cache, py_compile, and lintrunner checks locally.

@jansel

jansel commented Jun 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 20, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 20m 30s —— View job


Review: Preserve FX graph cache guard provenance (post-revert rebase)

  • Gather context and read the diff
  • Review torch/fx/experimental/symbolic_shapes.py
  • Review torch/_inductor/codecache.py & output_code.py
  • Review the vLLM/AOTAutograd regression fix
  • Review tests

This is the rebased version after the vLLM revert (#187484 / #187581). The diff is unchanged from the previously-approved version except for the regression fix, so I focused the review there and re-verified the surrounding logic.

The regression fix is correct

The vLLM breakage came from replaying per-guard source locations even when a custom guard evaluator owned the cache-validity contract (AOTAutograd's exact-match checker at autograd_cache.py:1213). The new gating in codecache.py:2183-2187 is the right fix:

can_replay_guards_with_source = (
    uses_default_guard_evaluator
    and guards_expr_with_source is not None
    and guards_expr_with_source_arg_count == len(symints)
)

uses_default_guard_evaluator = evaluate_guards is None (set before the unsafe_skip branch flips it to False, codecache.py:2131/2137) cleanly restricts the new path to ordinary Inductor FX-graph-cache hits. AOTAutograd and unsafe_skip_cache_dynamic_shape_guards both fall back to the joined evaluate_guards(graph.guards_expr, symints) path, exactly as before the original PR. Good — and test_custom_guard_evaluator_skips_source_replay pins this behavior by asserting evaluate_guards_expression_with_source_info is not invoked when a custom evaluator is supplied.

Correctness notes (all look sound)

  • _evaluate_guards_source_location lifecycle — evaluate_guards_expression_with_source_info (symbolic_shapes.py:7066-7085) now saves/restores via old_sloc in a try/finally, so re-entrancy and exception unwinding leave the field clean. It's also in the _copy_ exclusion list (symbolic_shapes.py:4354), correct since the override is transient and slocs are allowed to diverge between envs. This addresses the mutable-shared-state concern raised in the earlier reviews.
  • Short-circuit equivalence — the per-guard loop returns False on the first failing guard, matching the Python and short-circuit of the old joined eval. On a genuine cache hit all guards pass (already validated against hints in find_guarded_entry), so assert check is True holds and all guards get installed with their real slocs. Behaviorally consistent with the old path.
  • Backwards compat — getattr(graph, "guards_expr_with_source", None) handles old cache entries serialized before this field existed; they fall through to the joined path. Good.

Minor

  1. bound_sloc mislabel in the _simplified path (symbolic_shapes.py:6754-6758). bound_sloc is chosen as vr_sloc.lower whenever r.lower not in (-oo, -int_oo), but in _simplified mode the lower bound is omitted from bounds when r.lower == default (6740), so the emitted bound may contain only the upper bound while the sloc points at the lower. This is diagnostic-only and doesn't affect produce_guards_expression_with_source_info (which runs with _simplified=False), so it's harmless here — just noting it in case the helper is reused elsewhere.

  2. AssertionError vs assert for the lockstep check (symbolic_shapes.py:7035-7038). Same observation as prior reviews: exprs and source_locations are appended in lockstep, so this can't fire in practice. The explicit raise is fine; just confirming it's a true invariant guard, not reachable error handling.

  3. SLoc serialization for remote cache. SLoc.framework_loc can hold a traceback.FrameSummary (_guards.py:229), now pickled inside _ShapeGuardExpression for remote FX graph cache. FrameSummary pickles fine, but it carries the captured source line text, which could be stale across code versions on a remote hit. Purely diagnostic, acceptable — same conclusion as before.

Verdict

LGTM. The provenance machinery is unchanged from the version already approved by @oulgen, and the regression fix correctly scopes per-guard replay to the default FX-graph-cache evaluator so AOTAutograd's contract is untouched. The new test_custom_guard_evaluator_skips_source_replay directly guards against a recurrence of the vLLM breakage. Minor items above are non-blocking.

atalman pushed a commit that referenced this pull request Jun 22, 2026
@zou3519

zou3519 commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

janselbot, can you submit one PR with a minimum test case of the vLLM issue that we can check into the repository first before this PR goes in?

@jansel

jansel commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I split out a minimal test-only PR for the vLLM/AOTAutograd cache contract: #188050. It verifies FX graph cache hits replay the caller-supplied custom guard evaluator during post-load guard evaluation, which is the behavior the reverted version broke. I requested your review there.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 24, 2026
FX graph cache hits replayed cached dynamic-shape guards from a single
combined Python expression. That reconstructed equivalent ShapeEnv guards,
but the guards inherited the cache replay callsite as their source location,
so recompile reasons pointed at cache machinery instead of the original
Inductor guard producer.

Store each cached guard expression with its original ShapeGuard source
location and replay those expressions with the saved provenance for ordinary
FX graph cache hits when the SymInt argument list matches. Keep the existing
combined-expression fallback for older cache entries and unsafe-skip mode.

The original fix was reverted after AOTAutograd cache hits in vLLM started
failing in FX graph cache guard replay. The root cause was that AOTAutograd
passes a custom exact-match guard evaluator and owns the cache-validity
contract for those loads, but the source-aware replay path bypassed that
custom evaluator when the argument count happened to match. Preserve custom
evaluate_guards callbacks in the post-load path instead of replaying source
locations for them. This keeps the provenance fix for normal FX graph cache
hits while avoiding incorrect AOTAutograd guard re-evaluation.

Keep the serialized guard-expression helper private so it does not become a
new public symbolic-shapes API.

Fixes #141595

Generated by my agent

Test Plan:
- PYTHONPATH=. python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
- PYTHONPATH=. python test/test_dynamic_shapes.py TestGuardsExpressions.test_guards_expression_source_info
- PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_custom_guard_evaluator_skips_source_replay
- PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_cache_hit_inductor_guard_preserves_source
- PYTHONPATH=. python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_output_views_input_dynamic
- PYTHONPATH=. python -m py_compile torch/fx/experimental/symbolic_shapes.py torch/_inductor/codecache.py torch/_inductor/output_code.py test/test_dynamic_shapes.py test/inductor/test_codecache.py test/dynamo/test_aot_autograd_cache.py
- lintrunner -a

ghstack-source-id: 6e11288

Pull-Request: #184193
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
## Summary
Preserve source locations for Inductor guards that are saved in the FX graph cache, so a cache-hit recompile reason still points at the original guard producer instead of the cache replay site.

Fixes pytorch#141595
Generated by my agent

## Root Cause
Without the FX graph cache, `ShapeEnv` records each `ShapeGuard` with the source location captured when Inductor creates the guard, for example `can_use_32bit_indexing`.

On an FX graph cache hit, Inductor only had `CompiledFxGraph.guards_expr`, a single combined Python expression string. Re-evaluating that string installs equivalent guards in the current `ShapeEnv`, but the new guards get the replay callsite as their source location. That is why recompile logs pointed at `_lookup_graph`, `autograd_cache.py`, or `<string>:1` instead of the original Inductor guard.

## Review Guide
- `torch/fx/experimental/symbolic_shapes.py`: threads source locations alongside each produced guard expression, adds `ShapeGuardExpression`, and replays cached guards while temporarily using the stored source location for any `ShapeGuard` created by evaluation.
- `torch/_inductor/output_code.py`: adds optional cached metadata fields for the per-guard expression/source list and the SymInt argument count used when saving it.
- `torch/_inductor/codecache.py`: saves the new metadata, replays it on normal FX graph cache hits, and falls back to the existing combined-expression path for old cache entries, unsafe-skip mode, or AOTAutograd loads whose argument list differs.
- Tests cover both the small `ShapeEnv` round trip and the original CUDA/flex-attention cache-hit failure mode.

## Test Plan
- `PYTHONPATH=. python test/test_dynamic_shapes.py TestGuardsExpressions.test_guards_expression_source_info`
- `PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_cache_hit_inductor_guard_preserves_source`
- `PYTHONPATH=. python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_output_views_input_dynamic`
- `lintrunner -a`

Pull Request resolved: pytorch#184193
Approved by: https://github.com/oulgen
@jansel jansel closed this Jul 16, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
## Summary
Preserve source locations for Inductor guards that are saved in the FX graph cache, so a cache-hit recompile reason still points at the original guard producer instead of the cache replay site.

Fixes pytorch#141595
Generated by my agent

## Root Cause
Without the FX graph cache, `ShapeEnv` records each `ShapeGuard` with the source location captured when Inductor creates the guard, for example `can_use_32bit_indexing`.

On an FX graph cache hit, Inductor only had `CompiledFxGraph.guards_expr`, a single combined Python expression string. Re-evaluating that string installs equivalent guards in the current `ShapeEnv`, but the new guards get the replay callsite as their source location. That is why recompile logs pointed at `_lookup_graph`, `autograd_cache.py`, or `<string>:1` instead of the original Inductor guard.

## Review Guide
- `torch/fx/experimental/symbolic_shapes.py`: threads source locations alongside each produced guard expression, adds `ShapeGuardExpression`, and replays cached guards while temporarily using the stored source location for any `ShapeGuard` created by evaluation.
- `torch/_inductor/output_code.py`: adds optional cached metadata fields for the per-guard expression/source list and the SymInt argument count used when saving it.
- `torch/_inductor/codecache.py`: saves the new metadata, replays it on normal FX graph cache hits, and falls back to the existing combined-expression path for old cache entries, unsafe-skip mode, or AOTAutograd loads whose argument list differs.
- Tests cover both the small `ShapeEnv` round trip and the original CUDA/flex-attention cache-hit failure mode.

## Test Plan
- `PYTHONPATH=. python test/test_dynamic_shapes.py TestGuardsExpressions.test_guards_expression_source_info`
- `PYTHONPATH=. python test/inductor/test_codecache.py TestFxGraphCache.test_cache_hit_inductor_guard_preserves_source`
- `PYTHONPATH=. python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_output_views_input_dynamic`
- `lintrunner -a`

Pull Request resolved: pytorch#184193
Approved by: https://github.com/oulgen
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
@github-actions
github-actions Bot deleted the gh/jansel/789/head branch August 16, 2026 02:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic Created by an AI agent ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor release notes: fx release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants