Repository navigation
[fx] Memoize the result expression of symbolic binary arithmetic - #193219
anijain2305 wants to merge 16 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193219
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (3 Unrelated Failures)As of commit 0a95fc4 with merge base 7418e12 ( UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Symbolic binary ops are overwhelmingly repeats. Counting every one in one
model's cold compile with dynamic=True: 333,741 calls producing only 1,937
distinct results, a 99.4% repeat rate. The hottest are not program semantics at
all:
19787x True and True
11616x s11 == 1
11106x s18 == 1
8686x s11 - 1
8661x s11 == 0
They come from tensor metadata. Every fake tensor created while tracing makes
c10 derive numel and contiguity, and those derivations are per-dimension loops
of SymInt operations (see _compute_contiguous_sym in c10/core/Contiguity.h: a
sym_eq, a mul, a sym_or and a sym_and per dimension, plus guard evaluations).
Each operation crosses into Python, builds a sympy expression and runs it
through ShapeEnv.replace. With counters added to SymbolicShapeMeta, one compile
does 9644 numel and 7126 is_contiguous derivations at ~40us and ~120us each;
the same model with dynamic=False does none of them, because C++ then takes the
int64_t path and never enters Python.
Cache the resulting expression on (op, lhs expr, rhs expr, replacement version).
The version is part of the key for the same reason SymNode.expr consults it: a
hit is only valid while replacements have not moved.
The cache deliberately holds the expression and pytype, never the SymNode.
Proxy slots are keyed on node identity, so returning one node to two call sites
gives the second the first's provenance in the graph being traced. That is not
theoretical: an earlier version of this patch cached nodes and broke
test_aot_autograd_symbolic_module_exhaustive_nn_CircularPad{1,2,3}d, where s49+2
was first built from a tangent, the forward then reused that node, and the
partitioner rejected the joint graph with "Node slice_scatter_2 was invalid, but
is output" because a forward output depended on a backward-only input. Guarding
the cache on proxy mode does not fix it either, since handle_sym_dispatch
computes the inner value with proxy modes disabled. Rebuilding a fresh node per
call site keeps provenance local and still skips the sympy work.
Total compile time, measured as the union of top-level chromium events, over
interleaved pairs:
pair 1: baseline 48.46s memo 46.46s
pair 2: baseline 47.93s memo 46.67s
pair 3: baseline 48.08s memo 46.01s
48.16s -> 46.38s, -3.7%, with no overlap between the two sets.
Test plan:
```
python test/test_proxy_tensor.py
python test/test_dynamic_shapes.py
python test/dynamo/test_misc.py
python test/functorch/test_aotdispatch.py
```
All produce failure sets identical to a run with the change stashed; this host
has pre-existing aarch64 CPU codegen failures, so the comparison is against a
stashed baseline rather than a clean run.
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: ccdfda7
Pull-Request: #193219
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
| # See Note [symbolic op memo] in symbolic_shapes.py. The cache holds the | ||
| # resulting expression, never the SymNode: proxy slots are keyed on node | ||
| # identity, so returning one node to two call sites would give the second | ||
| # the first's provenance in the graph being traced. |
There was a problem hiding this comment.
this part
proxy slots are keyed on node identity, so returning one node to two call sites would give the second the first's provenance in the graph being traced.
is not clear although i understand it. maybe rephrase it as
# See Note [symbolic op memo] in symbolic_shapes.py. The cache holds the
# result expression, never the SymNode. Given
# s1: a = x.size()[0] + 1
# s2: b = x.size()[0] + 1
# a and b must wrap different SymNodes, so that the two sites refer to
# different graph nodes as their producers. While tracing, the tracer keeps a
# table mapping each SymNode object to the graph node that produced it, and two
# SymNodes with the same expression are told apart only by object identity, so
# handing the same one to both sites makes s2 refer to the node created at s1
# as its producer:
There was a problem hiding this comment.
Thank you for a better comment.
| cached = cache.get(cache_key) | ||
| if cached is not None: | ||
| out, pytype, optimized_summation = cached | ||
| if ( |
There was a problem hiding this comment.
if (
pytype is not None
and out_hint is not _NO_HINT
and out_hint is not None
and not isinstance(out_hint, SymTypes)
):
out_hint = pytype(out_hint) # type: ignore[arg-type]
is replicted on cache hit and cache miss path, shall we put it in helper function
/
There was a problem hiding this comment.
in fact not only the out_hint compute but all between lines 1522 and 1540.
laithsakka
left a comment
There was a problem hiding this comment.
good overall small nits and suggestions
| # few hundred thousand ops were repeats of about two thousand distinct | ||
| # computations. Memoize on | ||
| # (op, lhs expr, rhs expr, replacement version); the version keeps a hit | ||
| # valid only while replacements have not moved. SymNode is immutable |
There was a problem hiding this comment.
"SymNode is immutable after construction, so sharing one between call sites is safe"
we do not share SymNode anyway? whats the value of the comment.
"Nodes built while proxy tracing are not cached at all - see the comment in SymNode's binary_magic_impl."
all nodes not cached we just cache sympy expression so this is also confusing
[ghstack-poisoned]
| # SymNode's binary_magic_impl for why two sites cannot share one. Under | ||
| # proxy tracing binary_magic_impl returns before it reaches this cache, | ||
| # so nothing being traced is served from here. | ||
| self._symop_cache: dict[Any, Any] = {} |
There was a problem hiding this comment.
do u think its concerning that this is unbounded? or meh
There was a problem hiding this comment.
I am not too concerned because its tied to single compile frame.
|
@pytorchbot merge |
Merge startedYour 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 |
…orch#193219) Symbolic binary ops are overwhelmingly repeats. Counting every one in one model's cold compile with dynamic=True: 333,741 calls producing only 1,937 distinct results, a 99.4% repeat rate. The hottest are not program semantics at all: 19787x True and True 11616x s11 == 1 11106x s18 == 1 8686x s11 - 1 8661x s11 == 0 They come from tensor metadata. Every fake tensor created while tracing makes c10 derive numel and contiguity, and those derivations are per-dimension loops of SymInt operations (see _compute_contiguous_sym in c10/core/Contiguity.h: a sym_eq, a mul, a sym_or and a sym_and per dimension, plus guard evaluations). Each operation crosses into Python, builds a sympy expression and runs it through ShapeEnv.replace. With counters added to SymbolicShapeMeta, one compile does 9644 numel and 7126 is_contiguous derivations at ~40us and ~120us each; the same model with dynamic=False does none of them, because C++ then takes the int64_t path and never enters Python. Cache the resulting expression on (op, lhs expr, rhs expr, replacement version). The version is part of the key for the same reason SymNode.expr consults it: a hit is only valid while replacements have not moved. The cache deliberately holds the expression and pytype, never the SymNode. Proxy slots are keyed on node identity, so returning one node to two call sites gives the second the first's provenance in the graph being traced. That is not theoretical: an earlier version of this patch cached nodes and broke test_aot_autograd_symbolic_module_exhaustive_nn_CircularPad{1,2,3}d, where s49+2 was first built from a tangent, the forward then reused that node, and the partitioner rejected the joint graph with "Node slice_scatter_2 was invalid, but is output" because a forward output depended on a backward-only input. Guarding the cache on proxy mode does not fix it either, since handle_sym_dispatch computes the inner value with proxy modes disabled. Rebuilding a fresh node per call site keeps provenance local and still skips the sympy work. Total compile time, measured as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 48.46s memo 46.46s pair 2: baseline 47.93s memo 46.67s pair 3: baseline 48.08s memo 46.01s 48.16s -> 46.38s, -3.7%, with no overlap between the two sets. Test plan: ``` python test/test_proxy_tensor.py python test/test_dynamic_shapes.py python test/dynamo/test_misc.py python test/functorch/test_aotdispatch.py ``` All produce failure sets identical to a run with the change stashed; this host has pre-existing aarch64 CPU codegen failures, so the comparison is against a stashed baseline rather than a clean run. This PR was authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#193219 Approved by: https://github.com/laithsakka
…03252) 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](https://our.internmc.facebook.com/intern/diff/D129028772/) Differential Revision: [D129028772](https://our.internmc.facebook.com/intern/diff/D129028772) Pull Request resolved: #203252 Approved by: https://github.com/anijain2305 ghstack dependencies: #203251
Stack from ghstack (oldest at bottom):
Symbolic binary ops are overwhelmingly repeats. Counting every one in one
model's cold compile with dynamic=True: 333,741 calls producing only 1,937
distinct results, a 99.4% repeat rate. The hottest are not program semantics at
all:
19787x True and True
11616x s11 == 1
11106x s18 == 1
8686x s11 - 1
8661x s11 == 0
They come from tensor metadata. Every fake tensor created while tracing makes
c10 derive numel and contiguity, and those derivations are per-dimension loops
of SymInt operations (see _compute_contiguous_sym in c10/core/Contiguity.h: a
sym_eq, a mul, a sym_or and a sym_and per dimension, plus guard evaluations).
Each operation crosses into Python, builds a sympy expression and runs it
through ShapeEnv.replace. With counters added to SymbolicShapeMeta, one compile
does 9644 numel and 7126 is_contiguous derivations at ~40us and ~120us each;
the same model with dynamic=False does none of them, because C++ then takes the
int64_t path and never enters Python.
Cache the resulting expression on (op, lhs expr, rhs expr, replacement version).
The version is part of the key for the same reason SymNode.expr consults it: a
hit is only valid while replacements have not moved.
The cache deliberately holds the expression and pytype, never the SymNode.
Proxy slots are keyed on node identity, so returning one node to two call sites
gives the second the first's provenance in the graph being traced. That is not
theoretical: an earlier version of this patch cached nodes and broke
test_aot_autograd_symbolic_module_exhaustive_nn_CircularPad{1,2,3}d, where s49+2
was first built from a tangent, the forward then reused that node, and the
partitioner rejected the joint graph with "Node slice_scatter_2 was invalid, but
is output" because a forward output depended on a backward-only input. Guarding
the cache on proxy mode does not fix it either, since handle_sym_dispatch
computes the inner value with proxy modes disabled. Rebuilding a fresh node per
call site keeps provenance local and still skips the sympy work.
Total compile time, measured as the union of top-level chromium events, over
interleaved pairs:
pair 1: baseline 48.46s memo 46.46s
pair 2: baseline 47.93s memo 46.67s
pair 3: baseline 48.08s memo 46.01s
48.16s -> 46.38s, -3.7%, with no overlap between the two sets.
Test plan:
All produce failure sets identical to a run with the change stashed; this host
has pre-existing aarch64 CPU codegen failures, so the comparison is against a
stashed baseline rather than a clean run.
This PR was authored with the assistance of an AI coding agent.