Skip to content

Do not memoize symbolic mod; key the op memo on resolved operands - #203252

Closed
laithsakka wants to merge 6 commits into
gh/laithsakka/544/basefrom
gh/laithsakka/544/head
Closed

laithsakka wants to merge 6 commits into
gh/laithsakka/544/basefrom
gh/laithsakka/544/head

Conversation

@laithsakka

@laithsakka laithsakka commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

The symbolic op memo in binary_magic_impl (added in #193219) was keyed on (op, lhs._expr, rhs._expr, _replacements_version_counter) and never cleared. This had three problems:

  • a % b picks Mod or PythonMod from bound_sympy, which reads var_to_range, but ranges weren't in the key. After the operands' ranges narrowed to non-negative, the memo kept returning PythonMod (same value, less simplified).
  • The key used the unresolved operands, but the result was computed from lhs.expr/rhs.expr, which go through replace()/_find and also depend on value ranges. After a range change let _find resolve further, the memo kept returning the less resolved result.
  • Each replacement change started a new set of keys, and entries from old versions stayed in the dict until the ShapeEnv was freed.

mod is no longer memoized. The key is now (op, lhs.expr, rhs.expr), the resolved operands, which SymNode.expr already caches on both the replacement and range counters, so a hit never depends on outdated replacements or ranges. ShapeEnv._get_symop_cache() empties the memo when replacements change, only to bound its size.

The add path passed each operand's _optimized_summation flag, which describes its unresolved _expr, together with the resolved expr. After a replacement such as s0 -> s1, s0 + s1 resolves to 2*s1 but keeps the flag, and adding s2 spliced it into Mul(2, s1)'s args, giving s1 + s2 + 2 instead of 2*s1 + s2. This predates the memo, but the resolved key would share that result with every node that resolves to 2*s1. The flag is now trusted only when expr is _expr.

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

Differential Revision: D129028772

Differential Revision: D129028772

[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: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR stops memoizing symbolic `mod`, keys the symbolic op memo on the resolved
operands `(op, lhs.expr, rhs.expr)`, clears the memo lazily when replacements
change, and trusts `_optimized_summation` only when `expr is _expr`.
Recommendation: Approve. Nothing blocks. The review marks every open point
non-blocking: two missing regression tests, the unmeasured hit-path cost,
operands being resolved twice, and comment/description wording.

Findings (5):

[minor] test/test_dynamic_shapes.py:7559
The right-operand flag gate (sym_node.py:1611) has no regression test
(non-blocking). Every new test puts the flagged, replaced operand on the left
(`p + s2`, `q + s2`, `t + s2`). Suppose :1611 went back to
`other._optimized_summation`. Then with `p = s0 + s1`, `s0 -> s1`, computing `s2
+ p` would call `_binary_search_insert_arg([2, s1], s2)` and return `s1 + s2 +
2` instead of `2*s1 + s2`. That is the same wrong-result bug this PR fixes, with
the operands swapped. The memo can't hide it, because the key `("add", s2,
2*s1)` is new. Fix: add `self.assertEqual((s2 + p).node.expr, 2 * s1.node.expr +
s2.node.expr)` to `test_optimized_summation_flag_after_replacement`.

[minor] test/test_dynamic_shapes.py:7548
The fetch-after-resolve ordering (sym_node.py:1565-1568) is untested
(non-blocking). In `test_range_change_refreshes_symop_memo`, the second
`node.add(one)` bumps the replacement counter while resolving `node.expr`. The
test asserts only `_expr`, which is the same under either ordering. Moving the
fetch back above the key would keep every test green; the only effect would be a
lost hit. Fix: install `_count_symop_hits` before the second add, assert `hits
== 0` after it, then run a third `node.add(one)` and assert `hits == 1`.

[minor] torch/fx/experimental/sym_node.py:1565
Operands are resolved twice (non-blocking). The key reads
`self.expr`/`other.expr`, and the computation (:1607-1611, :1623-1640,
:1642-1646) reads them again. Resolving one operand can call `_find` ->
`_set_replacement(..., "find")` (symbolic_shapes.py:8322), which bumps the range
and/or replacement version. The memo is fetched after the key is built, so an
entry can be stored under a less resolved key than its value. The value is still
correct, but the entry can never be hit, and the miss path makes extra
`replace()` calls. Fix: bind `lhs, rhs = self.expr, other.expr` once and use
them for the key, the computation and the gate (`lhs is self._expr`). This
carries over unchanged from the last review.

[minor] torch/fx/experimental/symbolic_shapes.py:4263
Comments and description don't match the code (non-blocking). :4263-4264 says
the memo "is also emptied when it changes", and the Note at :4274-4275 says
`_get_symop_cache` "empties the memo whenever replacements change". The clear
actually happens lazily, on the next `_get_symop_cache()` call (:4894-4896). The
comment at sym_node.py:1566-1567 already describes this correctly; use the same
wording. The PR description still says the memo is emptied "only to bound its
size". In fact the memo is an uncapped dict between replacement changes, and the
Note now gives a different reason. The resolution table says this was fixed, but
only the in-code comments were changed.

(1 more not shown, see the review run)

Reviewed commit: bd6673e

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit bd6673e with merge base e1c7456 (image):
💚 Looks good so far! There are no failures yet. 💚

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

  • Triviality
    • Not one root cause: drops mod memoization, rekeys the _symop_cache memo, and changes _optimized_add flag handling in binary_magic_impl
    • Changing a cache key's semantics in torch/fx/experimental/sym_node.py falls outside every trivial class
  • Correctness needs a human
    • New key (method, self.expr, other.expr) assumes resolved expr captures every range and replacement dependency; that is a design claim to verify
    • Flag gate self._optimized_summation and self.expr is self._expr turns off the fast path whenever an operand resolves to a different object
  • Review signal
    • The automated review on 2995e9e still requests changes and says test_optimized_summation_flag_survives_unrelated_replacement cannot fail
  • Scope
    • Adds ShapeEnv._get_symop_cache and _symop_cache_version, which clear the memo lazily on replacement-version changes in symbolic_shapes.py

reason: not_trivial
Reviewed commit: 2995e9e (NOT the current head bd6673e)

Inference job

🐛 Report a wrong verdict

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

github-actions[bot]

This comment was marked as outdated.

@laithsakka
laithsakka marked this pull request as draft November 3, 2026 20:05
[ghstack-poisoned]
[ghstack-poisoned]
@laithsakka

Copy link
Copy Markdown
Contributor Author

Automated review of 5885c17: changes requested before human review.

The PR keys the symbolic op memo in binary_magic_impl on the resolved operands, stops memoizing mod, empties the memo whenever replacements change, and trusts the _optimized_summation flag only when expr is _expr. The review found nothing that produces wrong results. Its recommendation is Request Changes: a lost summation fast path, a cache lookup-order issue, the unmemoized mod with no benchmarks, two inaccurate comments, and weak tests.

🔴 7 blocking findings are attached to the code below.

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.

Thread Resolution
self.expr is self._expr gate drops valid flags Kept is: replace() returns its input unchanged when no symbol is replaced, so is only misses when an equal sum was built separately in a different order and resolved first. Rare, and it only costs the fast path, never correctness.
Cache fetched before key operands are resolved Fixed: operands are resolved first, then _get_symop_cache() is fetched.
mod no longer memoized, no numbers Measured mod memoized on _var_to_range_version_counter vs not, on symint_sum, symint_sum_loop, update_hint, sum_floordiv, a mixed-stride elementwise chain, a broadcast chain and a dynamic=True cat/view chain. Symbolic % is rare (0–78 calls per compile), so the difference is within noise; kept mod unmemoized.
Counter comment contradicts the Note Fixed: both comments now say the memo is emptied on replacement changes only to drop entries keyed on old resolved forms, not for correctness.
Note's "never depends on outdated replacements" is too absolute Addressed in #203251: patch_source_specialization and _constrain_unify now bump _replacements_version_counter, and the export range write goes through _update_var_to_range. With every write bumping, counter 0 means no replacements, so the SymNode.expr short-circuit returns an already-resolved _expr.
test_replacement_change_clears_symop_memo only tests the getter Fixed: reads shape_env._symop_cache directly, asserts the exact ("add", a, 1) key, then runs a + 2 after _set_replacement and asserts only the new entry remains.
Missing coverage Added: (1) a repeated a * b is a memo hit under the new key; (2) after s0 -> s1, (s0 + s1) + s2 and (s1 * 2) + s2 share one entry, both 2*s1 + s2; (3) the summation flag survives an unrelated replacement.

@laithsakka
laithsakka marked this pull request as ready for review November 4, 2026 01:37
@laithsakka
laithsakka requested review from anijain2305 and ezyang and removed request for anijain2305 November 4, 2026 01:37
github-actions[bot]

This comment was marked as outdated.

@laithsakka

laithsakka commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Code Review Summary
Both reviewers finished on D129028772 (#203252) and found no issues.

this github actions reviewer must be a nerd or nit picker lol

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 4, 2026
[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 4, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]

@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 bd6673e: nothing blocking; ready for human review.

The PR stops memoizing symbolic mod, keys the symbolic op memo on the resolved operands (op, lhs.expr, rhs.expr), clears the memo lazily when replacements change, and trusts _optimized_summation only when expr is _expr. Recommendation: Approve. Nothing blocks. The review marks every open point non-blocking: two missing regression tests, the unmeasured hit-path cost, operands being resolved twice, and comment/description wording.

⚪ 5 non-blocking findings

def test_optimized_summation_flag_after_replacement(self):

The right-operand flag gate (sym_node.py:1611) has no regression test (non-blocking). Every new test puts the flagged, replaced operand on the left (p + s2, q + s2, t + s2). Suppose :1611 went back to other._optimized_summation. Then with p = s0 + s1, s0 -> s1, computing s2 + p would call _binary_search_insert_arg(\[2, s1\], s2) and return s1 + s2 + 2 instead of 2*s1 + s2. That is the same wrong-result bug this PR fixes, with the operands swapped. The memo can't hide it, because the key ("add", s2, 2*s1) is new. Fix: add self.assertEqual((s2 + p).node.expr, 2 * s1.node.expr + s2.node.expr) to test_optimized_summation_flag_after_replacement.

An earlier comment near this line has replies: #203252 (comment)


def test_range_change_refreshes_symop_memo(self):

The fetch-after-resolve ordering (sym_node.py:1565-1568) is untested (non-blocking). In test_range_change_refreshes_symop_memo, the second node.add(one) bumps the replacement counter while resolving node.expr. The test asserts only _expr, which is the same under either ordering. Moving the fetch back above the key would keep every test green; the only effect would be a lost hit. Fix: install _count_symop_hits before the second add, assert hits == 0 after it, then run a third node.add(one) and assert hits == 1.


cache_key = (method, self.expr, other.expr)

Operands are resolved twice (non-blocking). The key reads self.expr/other.expr, and the computation (:1607-1611, :1623-1640, :1642-1646) reads them again. Resolving one operand can call _find -> _set_replacement(..., "find") (symbolic_shapes.py:8322), which bumps the range and/or replacement version. The memo is fetched after the key is built, so an entry can be stored under a less resolved key than its value. The value is still correct, but the entry can never be hit, and the miss path makes extra replace() calls. Fix: bind lhs, rhs = self.expr, other.expr once and use them for the key, the computation and the gate (lhs is self._expr). This carries over unchanged from the last review.

An earlier comment near this line has replies: #203252 (comment)


# SymNode.expr. The symbolic op memo is also emptied when it changes,

Comments and description don't match the code (non-blocking). :4263-4264 says the memo "is also emptied when it changes", and the Note at :4274-4275 says _get_symop_cache "empties the memo whenever replacements change". The clear actually happens lazily, on the next _get_symop_cache() call (:4894-4896). The comment at sym_node.py:1566-1567 already describes this correctly; use the same wording. The PR description still says the memo is emptied "only to bound its size". In fact the memo is an uncapped dict between replacement changes, and the Note now gives a different reason. The resolution table says this was fixed, but only the in-code comments were changed.


cache_key = (method, self.expr, other.expr)

The hit path's extra cost is still not measured against the base (non-blocking). A memo hit used to key on the plain _expr attribute; it now calls the SymNode.expr property on both operands. Once the ShapeEnv has a replacement, that property calls replace() whenever either counter has moved or the node has never resolved. Nodes built on a hit start with _expr_cache=None (:132-134), so each link in a chain of hits pays one replace(). The posted numbers compare mod memoized vs. unmemoized on the stack top, not this PR vs. its base. symint_sum, sum_floordiv and update_hint_regression are mostly unbacked, so they barely reach this path. Ask: pr_time_benchmarks instruction counts, base vs. head, on backed-dynamic workloads such as diffusion_dit_hierarchical_dynamic or the add_loop dynamic variants. Low confidence, secondary: infer_size (torch/_prims_common/init.py:1034) also runs numel % newsize without going through a comparator, so the reply's reasoning for why % is rare is incomplete. The code comment at :1563 is accurate.

An earlier comment near this line has replies: #203252 (comment)

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

@github-actions
github-actions Bot dismissed stale reviews from themself November 13, 2026 00:50

Withdrawn: the automated review of bd6673e found nothing blocking.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 13, 2026
@laithsakka laithsakka added the topic: not user facing topic category label Nov 13, 2026
@laithsakka

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: fx release notes category topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants