Skip to content

Do not persist evaluate_expr fallback results across ShapeEnv changes - #203254

Closed
laithsakka wants to merge 7 commits into
gh/laithsakka/546/basefrom
gh/laithsakka/546/head
Closed

laithsakka wants to merge 7 commits into
gh/laithsakka/546/basefrom
gh/laithsakka/546/head

Conversation

@laithsakka

@laithsakka laithsakka commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

With fallback_value set (guard_or_true/guard_or_false), evaluate_expr returns the fallback when the expression is unknown. The outer lru_cache stored that answer permanently, so after new facts arrived (a guard, a range refinement) the same query kept returning the stale fallback instead of the now-provable result.

Split the cache in two:

  • _cached_evaluate_expr (lru_cache, persistent) stores only proven results. When the fallback is taken, _evaluate_expr returns the _USE_FALLBACK sentinel and this layer raises _FallbackTaken, which lru_cache does not store.
  • _cached_evaluate_expr_with_fallback (_lru_cache, cleared on _version_counter bumps) catches _FallbackTaken and returns fallback_value, so unknown answers live only until the next ShapeEnv change.

Calls without fallback_value go straight to the persistent layer, as before. The recorded _inner_evaluate_expr replaces its optional fallback_value parameter with a required allow_fallback: bool and returns the sentinel instead of raising, so ShapeEnv event recording and replay are unaffected.

Authored with an AI assistant.
@exported-using-ghexport

Differential Revision: D128538854

Differential Revision: D128538854

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor release notes: fx release notes category labels Nov 3, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

PR Status: draft

This PR is waiting for its author to mark it ready for review.

🟡 AUTOMATED REVIEW - OUTDATED (earlier commit) - Changes requested:

The PR splits evaluate_expr's cache so decided results persist across version
bumps while guard_or_true/guard_or_false fallback answers go in a
version-cleared _lru_cache that later facts can refine. The review finds no
correctness, replay or BC defects. It recommends Request Changes: the unguarded
_get_stack_summary call in _log_suppressed_dde needs fixing, and compile-time
evidence is needed that recomputing fallback queries after each bump is
acceptable.

Findings (9):

[major] torch/fx/experimental/symbolic_shapes.py:8911
Expensive, unguarded log call now runs far more often. `_log_suppressed_dde`
(8975-8983) calls `self._get_stack_summary(True)` before `log.info` even when
INFO is disabled. That walks user frames, calls `TracingContext.extract_stack()`
and runs `traceback.format_list` over the full user stack. Before this PR it ran
once per key until LRU eviction. Now it runs on every miss of the
version-cleared fallback cache, i.e. once per (query, `fallback_value`,
`_version_counter` value), and the same INFO line repeats after every bump. The
file already guards this pattern at 8716 (`if
self.log.isEnabledFor(logging.INFO):`). Apply that guard inside
`_log_suppressed_dde`.

[major] torch/fx/experimental/symbolic_shapes.py:8890
Fallback queries are now recomputed after every ShapeEnv version bump, and there
are no measurements. Before, an undecided `guard_or_*` query stayed in the
256-entry LRU until evicted; now it is never stored persistently.
`_update_version_counter` runs on every range refinement, replacement,
divisibility update, guard and deferred runtime assert, and each one empties the
fallback cache, so every unknown query re-runs the full `_inner_evaluate_expr`
`_evaluate_expr` path. The `_lru_cache` `prior_version` closure is shared across
ShapeEnvs, so alternating between two ShapeEnvs also empties it. In
unbacked-heavy traces, cost grows from about one evaluation per query to about
one per query per bump. With event recording on, each recomputation also records
a new `evaluate_expr` event with a tracked-fakes snapshot, which contradicts the
PR body's claim that event recording/replay are unaffected (replay itself is
still correct). Provide compile-time numbers on an unbacked-heavy workload (e.g.
pr_time_benchmarks) and correct that sentence in the PR description.

[minor] torch/fx/experimental/symbolic_shapes.py:4430
The new WARNING in `patch_source_specialization` is partly wrong and out of
scope. The technical claim holds: replacements/axioms change without
`_update_version_counter`. But "only used by mark_dynamic(...,
specialize_on=...)" is wrong, since `mark_unbacked` also takes `specialize_on`.
"No known users" is also wrong: the feature is documented in `mark_dynamic`'s
docstring and tested in test_torchinductor.py, test_aot_autograd_cache.py and
test_precompile.py. "We should probably deprecate it" is a policy statement
about a documented public API. And the leak predates this PR. Correct the facts
and turn the deprecation remark into a TODO with an issue link, or move it to
its own PR.

[minor] torch/fx/experimental/symbolic_shapes.py:8881
The NOTE says `_cached_evaluate_expr` "keeps decided results for the life of the
ShapeEnv". That is not true: it is the file's `lru_cache(256)` on the class
function, a single 256-entry LRU shared by every ShapeEnv and keyed on `self`,
so entries can be evicted. Say "until evicted from the shared 256-entry LRU;
never cleared by version bumps". The note also breaks the file's `# Note [...]`
naming convention (e.g. `# Note [guard_or_]`). The reference in the
`_cached_evaluate_expr` docstring (8926-8927) splits the title across two lines,
so grepping for it fails. Use `# Note [evaluate_expr caching with
fallback_value]` and keep each reference on one line.

(5 more not shown, see the review run)

Reviewed commit: 73fdfa1 (NOT the current head 65a96a0)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 New Failures

As of commit 65a96a0 with merge base 0522dc9 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Redesigns ShapeEnv.evaluate_expr caching into _cached_evaluate_expr plus _cached_evaluate_expr_with_fallback, using a _USE_FALLBACK sentinel and a _FallbackTaken exception
    • Changes the signature of the recorded _inner_evaluate_expr (fallback_value becomes a required allow_fallback), which shapes ShapeEnv event record and replay
    • Fits no trivial class: this is a cache-invalidation redesign on a hot core path, not a small local fix
  • User-facing behavior
    • guard_or_true/guard_or_false results can now change once guards or ranges are added later, which affects dynamic-shapes tracing outcomes
    • The _log_suppressed_dde call moves from _evaluate_expr to the fallback cache layer, so it now fires only on a cache miss
  • Reviewer questions
    • A reviewer should check the cache-correctness invariants and the cost of compile-time cache misses; the 3 new tests in test/test_dynamic_shapes.py cover only the basic cases
    • The new patch_source_specialization docstring names a known caching hole and proposes deprecating it, which a maintainer should weigh

reason: not_trivial
Reviewed commit: 73fdfa1 (NOT the current head 65a96a0)

Inference job

🐛 Report a wrong verdict

NEW FAILURES - The following jobs have failed:

  • BC Lint / bc_linter (gh)
    ##[error]API rate limit exceeded for installation. If you reach out to GitHub Support for help, please include the request ID A843:C3BDD:551FEC:10CA285:6AF749B4 and timestamp 2026-11-13 17:32:36 UTC. For more on scraping GitHub and how it may affect your rights, please review our Terms of Service (https://docs.github.com/en/site-policy/github-terms/github-terms-of-service) - https://docs.github.com/en/rest/using-the-rest-api/getting-started-with-the-rest-api#rate-limiting
  • pull / dynamo-cpython-test / test (dynamo_wrapped, 4, 7, mt-l-x86iavx512-8-64) (gh)
    test/test_dynamic_shapes.py::ShapeEnvAxiomCacheInvalidationTest::test_guard_updates_get_axioms_result

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review of 73fdfa1: changes requested before human review.

The PR splits evaluate_expr's cache so decided results persist across version bumps while guard_or_true/guard_or_false fallback answers go in a version-cleared _lru_cache that later facts can refine. The review finds no correctness, replay or BC defects. It recommends Request Changes: the unguarded _get_stack_summary call in _log_suppressed_dde needs fixing, and compile-time evidence is needed that recomputing fallback queries after each bump is acceptable.

🔴 2 blocking findings are attached to the code below.

⚪ 7 non-blocking findings

WARNING: Not safe with ShapeEnv caching. axioms and replacements are

The new WARNING in patch_source_specialization is partly wrong and out of scope. The technical claim holds: replacements/axioms change without _update_version_counter. But "only used by mark_dynamic(..., specialize_on=...)" is wrong, since mark_unbacked also takes specialize_on. "No known users" is also wrong: the feature is documented in mark_dynamic's docstring and tested in test_torchinductor.py, test_aot_autograd_cache.py and test_precompile.py. "We should probably deprecate it" is a policy statement about a documented public API. And the leak predates this PR. Correct the facts and turn the deprecation remark into a TODO with an issue link, or move it to its own PR.


# - _cached_evaluate_expr (plain lru_cache) keeps decided results for the

The NOTE says _cached_evaluate_expr "keeps decided results for the life of the ShapeEnv". That is not true: it is the file's lru_cache(256) on the class function, a single 256-entry LRU shared by every ShapeEnv and keyed on self, so entries can be evicted. Say "until evicted from the shared 256-entry LRU; never cleared by version bumps". The note also breaks the file's # Note \[...\] naming convention (e.g. # Note \[guard_or_\]). The reference in the _cached_evaluate_expr docstring (8926-8927) splits the title across two lines, so grepping for it fails. Use # Note \[evaluate_expr caching with fallback_value\] and keep each reference on one line.


_UseFallback has no docstring and no __repr__, and is now the return value of the recorded _inner_evaluate_expr. record_shapeenv_event's retlog (recording.py:298-300) logs that value to trace_shape_events. Those lines used to read -> False; they will now read -> <torch.fx.experimental.symbolic_shapes._UseFallback object at 0x...>. Its neighbours _ShapeEnvGuardError and _FallbackTaken both have docstrings. Add a one-line docstring and a __repr__ returning "_USE_FALLBACK".


def test_range_update_refines_fallback_result(self):

Tests only use fallback_value=False. _cached_evaluate_expr_with_fallback is now the only cache whose key includes fallback_value; _cached_evaluate_expr keys on allow_fallback=True for both directions. If a regression dropped fallback_value from the outer key, guard_or_true(u0 > 0) would return a cached False after guard_or_false(u0 > 0) in the same version, and no new test would fail. Also, the first assertFalse(...) in test_range_update_refines_fallback_result cannot tell "fallback taken" from "proved False". Add assertTrue(shape_env.evaluate_expr(query, fallback_value=True)) before refining; that covers both points.


torch.fx.experimental._config.aggressive_guard_free_semantics

Neither aggressive_guard_free_semantics branch is tested (9109-9119). The PR rewrote both: SKIP_RANGE_ANALYSIS now returns _USE_FALLBACK, and level 1 now maps _maybe_evaluate_range_only(...) is None to the sentinel. No file under test/ sets this config. Add a test under torch.fx.experimental._config.patch(aggressive_guard_free_semantics=...) for levels 1 and 2. Level 1 should check that a range-decidable unbacked query returns the proven value; level 2 should check that the fallback is returned and then refined after constrain_symbol_range.


except _FallbackTaken:

Nothing checks that _log_suppressed_dde still fires after it moved from three return sites in _evaluate_expr into the except _FallbackTaken handler (8910-8911). No test matches "could not evaluate ... due to data dependency". Add an assertLogs("torch.fx.experimental.symbolic_shapes", "INFO") check.


with mock.patch.object(

test_proven_fallback_query_survives_version_change uses mock.patch.object(..., wraps=...) and adds the file's only mock import (line 9). The sibling cache tests in this file assert cache_info().hits deltas instead. shape_env._cached_evaluate_expr.cache_info() is available, so assert a +1 hit there and drop the mock import.

Please address the findings and push; a new commit normally gets a fresh automated review.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

allow_fallback=True,
)
except _FallbackTaken:
self._log_suppressed_dde(orig_expr, fallback_value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Expensive, unguarded log call now runs far more often. _log_suppressed_dde (8975-8983) calls self._get_stack_summary(True) before log.info even when INFO is disabled. That walks user frames, calls TracingContext.extract_stack() and runs traceback.format_list over the full user stack. Before this PR it ran once per key until LRU eviction. Now it runs on every miss of the version-cleared fallback cache, i.e. once per (query, fallback_value, _version_counter value), and the same INFO line repeats after every bump. The file already guards this pattern at 8716 (if self.log.isEnabledFor(logging.INFO):). Apply that guard inside _log_suppressed_dde.

# catches _FallbackTaken and returns fallback_value, so an assumed answer
# is only reused until the ShapeEnv learns something new.
@functools.partial(_lru_cache, maxsize=256)
def _cached_evaluate_expr_with_fallback(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Fallback queries are now recomputed after every ShapeEnv version bump, and there are no measurements. Before, an undecided guard_or_* query stayed in the 256-entry LRU until evicted; now it is never stored persistently. _update_version_counter runs on every range refinement, replacement, divisibility update, guard and deferred runtime assert, and each one empties the fallback cache, so every unknown query re-runs the full _inner_evaluate_expr _evaluate_expr path. The _lru_cache prior_version closure is shared across ShapeEnvs, so alternating between two ShapeEnvs also empties it. In unbacked-heavy traces, cost grows from about one evaluation per query to about one per query per bump. With event recording on, each recomputation also records a new evaluate_expr event with a tracked-fakes snapshot, which contradicts the PR body's claim that event recording/replay are unaffected (replay itself is still correct). Provide compile-time numbers on an unbacked-heavy workload (e.g. pr_time_benchmarks) and correct that sentence in the PR description.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correctness>>> perf + pr time benchmarks already enabled.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Persistently caching an undecided fallback is incorrect once ShapeEnv learns new facts, so invalidation is intentional. PR-time benchmarks are already enabled; I’ll check their results for regressions. Agreed on the description: recording/replay correctness is preserved, but recomputation can produce additional recorded events—I’ll clarify that wording.

@laithsakka
laithsakka marked this pull request as draft November 3, 2026 20:05
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@laithsakka laithsakka closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor GL/human GreenLight marked as needing human review in progress PR is being worked on by the author, until the automated review accepts it release notes: fx release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants