Repository navigation
[inductor] Stop re-asking sympy the same symbolic questions - #193489
anijain2305 wants to merge 15 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193489
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit c833258 with merge base 557649f ( 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. |
This PR needs a
|
[ghstack-poisoned]
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these is a pure query - it reads the shape env but never guards on it -
so the answer can be memoized. Where staleness is possible it is safe in one
direction only: ranges only ever narrow, so a provable fact stays provable and a
stale negative merely forgoes an optimization. The sizevars caches use the
existing _lru_cache idiom already used by _optimization_hint_cache, which drops
everything whenever replacements change - exactly when an answer could differ.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on FairChem UMA with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series (energy -3755.467, force_sum
~1.55).
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: a5f3d54
Pull-Request: #193489
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these is a pure query - it reads the shape env but never guards on it -
so the answer can be memoized. Where staleness is possible it is safe in one
direction only: ranges only ever narrow, so a provable fact stays provable and a
stale negative merely forgoes an optimization. The sizevars caches use the
existing _lru_cache idiom already used by _optimization_hint_cache, which drops
everything whenever replacements change - exactly when an answer could differ.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on FairChem UMA with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series (energy -3755.467, force_sum
~1.55).
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: a5f3d54
Pull-Request: #193489
[ghstack-poisoned]
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these is a pure query - it reads the shape env but never guards on it -
so the answer can be memoized. Where staleness is possible it is safe in one
direction only: ranges only ever narrow, so a provable fact stays provable and a
stale negative merely forgoes an optimization. The sizevars caches use the
existing _lru_cache idiom already used by _optimization_hint_cache, which drops
everything whenever replacements change - exactly when an answer could differ.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on FairChem UMA with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series (energy -3755.467, force_sum
~1.55).
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: bf3bf5d
Pull-Request: #193489
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these is a pure query - it reads the shape env but never guards on it -
so the answer can be memoized. Where staleness is possible it is safe in one
direction only: ranges only ever narrow, so a provable fact stays provable and a
stale negative merely forgoes an optimization. The sizevars caches use the
existing _lru_cache idiom already used by _optimization_hint_cache, which drops
everything whenever replacements change - exactly when an answer could differ.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on FairChem UMA with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series (energy -3755.467, force_sum
~1.55).
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: bf3bf5d
Pull-Request: #193489
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these is a pure query - it reads the shape env but never guards on it -
so the answer can be memoized. Where staleness is possible it is safe in one
direction only: ranges only ever narrow, so a provable fact stays provable and a
stale negative merely forgoes an optimization. The sizevars caches use the
existing _lru_cache idiom already used by _optimization_hint_cache, which drops
everything whenever replacements change - exactly when an answer could differ.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on FairChem UMA with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series (energy -3755.467, force_sum
~1.55).
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: bf3bf5d
Pull-Request: #193489
[ghstack-poisoned]
[ghstack-poisoned]
|
|
||
|
|
||
| @functools.lru_cache(maxsize=4096) | ||
| def _intersect_value_ranges(self: Any, other: Any) -> Any: |
There was a problem hiding this comment.
This can def have typing improved here.
[ghstack-poisoned]
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these reads the shape env but never guards on it, so the answer can be
memoized - but what invalidates it depends on what kind of question it is, and
getting that wrong is a correctness bug rather than a slowdown:
- A substitution (simplify) or a heuristic (optimization_hint) depends only on
replacements, so the existing _lru_cache idiom - already used by
_optimization_hint_cache - is enough.
- A "is this provably true" query depends on everything the ShapeEnv knows.
ShapeEnv._version_counter summarises replacements, divisible and deferred
runtime asserts, but deliberately not axioms, because ShapeEnv's own caches
take axioms as an explicit lru key argument instead. A cache sitting above
that layer therefore has to watch axioms itself; otherwise adding one would
not make a newly provable fact visible, and _add_axioms popping what it
pushed would leave behind an answer that was only true inside that scope.
So the soundness-sensitive caches go through _deduction_lru_cache, which clears
whenever (version counter, number of axioms) moves. That costs almost nothing in
practice: the ShapeEnv settles early, so over a whole compile these clear 36-53
times and still hit 84-97%. An earlier revision of this commit used the
replacements-only rule everywhere, which broke
test_config_of_sizearg_with_check_constraint: it adds an axiom and then expects
statically_known_multiple_of to see it.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on one model with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series.
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: 41710e7
Pull-Request: #193489
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
| shape_env = self.shape_env | ||
| return (shape_env._version_counter, len(shape_env.axioms)) | ||
|
|
||
| def _deduction_lru_cache(self, fn, maxsize=None): |
There was a problem hiding this comment.
Add Callable /ParamSpec typing here, otherwise this erases the typing of the callable it goes through.
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
mhmm reading the summary its not True, that optimization_hint is actually only invalidated when replacement changes (I know this is already landed as part of #192817). consider u0 and u3+1 Another situation that also shall invalidate the cache, is that there are APIs to update individual optimization hints of symbol, such as torch._dynamo.override_optimization_hint() those can also be called from the traced code. then can be scoped ..etc |
Ok. I am ok to table this if there are unknowns that can make caching wrong. I m also ok reverting #192817 if that was premature merge. |
[ghstack-poisoned]
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these reads the shape env but never guards on it, so the answer can be
memoized - but what invalidates it depends on what kind of question it is, and
getting that wrong is a correctness bug rather than a slowdown:
- A substitution (simplify) or a heuristic (optimization_hint) depends only on
replacements, so the existing _lru_cache idiom - already used by
_optimization_hint_cache - is enough.
- A "is this provably true" query depends on everything the ShapeEnv knows.
ShapeEnv._version_counter summarises replacements, divisible and deferred
runtime asserts, but deliberately not axioms, because ShapeEnv's own caches
take axioms as an explicit lru key argument instead. A cache sitting above
that layer therefore has to watch axioms itself; otherwise adding one would
not make a newly provable fact visible, and _add_axioms popping what it
pushed would leave behind an answer that was only true inside that scope.
So the soundness-sensitive caches go through _deduction_lru_cache, which clears
whenever (version counter, number of axioms) moves. That costs almost nothing in
practice: the ShapeEnv settles early, so over a whole compile these clear 36-53
times and still hit 84-97%. An earlier revision of this commit used the
replacements-only rule everywhere, which broke
test_config_of_sizearg_with_check_constraint: it adds an axiom and then expects
statically_known_multiple_of to see it.
Seven changes, in rough order of how much they matter:
- statically_known_equals: 30,901 calls covering a few hundred distinct pairs, a
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
- sizevars.simplify: 82% of its 93,690 inputs are a bare Integer (44,458) or a
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
- _is_multiple_of: asked repeatedly about the same pair while splitting
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
- expr_fits_within_32bit and statically_known_true: 92.6% and 97.3% hit rates
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
- ValueRanges intersection: 4,835 calls covering 68 distinct pairs, ~72us each,
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
- statically_known_{equals,leq,geq,lt,gt} on two concrete ints: 16,795 of 30,903
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
*before* the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is `type(x) is int` rather than isinstance,
deliberately: sympy.Integer and bool must keep taking the general path.
- The cache comments in __init__ are grouped into one note, with each call-count
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on one model with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/inductor/test_torchinductor.py -k GPU
python test/test_dynamic_shapes.py
python test/test_sympy_utils.py
```
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series.
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: ebe4a93
Pull-Request: #193489
mm if it had big wins, we can cache on version counter++ potentially, no need to revet folllow up is fine, its not dangerous. |
| """State that a "is this provably true" answer depends on. | ||
|
|
||
| ShapeEnv._version_counter summarises replacements, divisible and | ||
| deferred runtime asserts. It deliberately excludes axioms, because |
There was a problem hiding this comment.
The comment says the version counter deliberately excludes axioms because ShapeEnv's own caches take axioms as an explicit lru key argument. I don't think that's true for most calls though? _maybe_evaluate_static is usually called with axioms=None, and then it just reads self.axioms (~7380), so axioms aren't part of the key on that path. So I'm not sure the "explicit key argument" justification actually holds here.
And since axioms are always derived from guards + runtime asserts, I'm not clear on why we key on axioms rather than guards. num_deferred_runtime_asserts is already in _get_key() but len(self.guards) isn't — feels like that's the thing that's really missing, and len(axioms) is standing in for it indirectly.
Which makes me suspect something is off in _version_counter generally, not just here. I also noticed _refine_ranges manually clears _maybe_evaluate_static LRU cache -- but no other cache lol--, which seems odd — simplify reads self.var_to_range too and doesn't get cleared.
But If refining ranges changes what's statically provable, and ranges are in neither the version counter nor this new key, what's covering that in this PR? Maybe it works out because refinement only ever happens alongside a guard being added?
|
Note that those caches cache the intermediate work in between the top level call and the inner to _maybe_evaluate_static _inner_evaluate_expr, |
|
i feel like version counter shall track len(guards) and thats it we shall remove the adhoc cleanup of the static evaluation cache and then we shall use version counter |
|
Isn't what we want a version counter, with respect to the axioms / bounds for the symbols in the expr? We could just start with len(guards) though. |
in principal, version counter shall be that .. but its not with hacks around that issue now. |
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
laithsakka
left a comment
There was a problem hiding this comment.
lets file an issue to
Stack from ghstack (oldest at bottom):
Lowering and scheduling interrogate sympy constantly, and almost none of it is
new information: the same expression is simplified, the same pair compared, the
same divisibility checked, thousands of times per compile. sympy caches none of
this, and every miss is expensive because merely constructing a relational
evaluates it and drags in assumption queries.
Each of these reads the shape env but never guards on it, so the answer can be
memoized - but what invalidates it depends on what kind of question it is, and
getting that wrong is a correctness bug rather than a slowdown:
replacements, so the existing _lru_cache idiom - already used by
_optimization_hint_cache - is enough.
ShapeEnv._version_counter summarises replacements, divisible and deferred
runtime asserts, but deliberately not axioms, because ShapeEnv's own caches
take axioms as an explicit lru key argument instead. A cache sitting above
that layer therefore has to watch axioms itself; otherwise adding one would
not make a newly provable fact visible, and _add_axioms popping what it
pushed would leave behind an answer that was only true inside that scope.
So the soundness-sensitive caches go through _deduction_lru_cache, which clears
whenever (version counter, number of axioms) moves. That costs almost nothing in
practice: the ShapeEnv settles early, so over a whole compile these clear 36-53
times and still hit 84-97%. An earlier revision of this commit used the
replacements-only rule everywhere, which broke
test_config_of_sizearg_with_check_constraint: it adds an axiom and then expects
statically_known_multiple_of to see it.
Seven changes, in rough order of how much they matter:
quarter of all time in GraphLowering.run. 0.67s -> 0.18s. This one is worth
explaining, because the obvious placement does not work: caching
statically_known_true instead achieves nothing here, since by the time it is
reached the caller has already built the sympy.Eq and construction is the
expensive part. The cache has to sit one level up, on (left, right).
bare Symbol (32,393), neither of which needs expand+xreplace at all. The rest
go through a cache over 1,373 distinct expressions. 0.43s -> 0.23s.
iteration ranges, at ~67us each because the structural walk falls back to
building sympy.Eq(Mod(...), 0). 9,954 calls -> 314. 0.67s -> 0.18s.
with zero cache clears over a whole compile. 0.42s -> 0.21s and 0.35s -> 0.23s.
(Caching statically_known_true is worthwhile for its own direct callers; it is
only the equality path above that it cannot help.)
nearly all of it building sympy Max and Min. ValueRanges is a frozen hashable
value object and the intersection consults no shape env at all, so this one is
cacheable outright with no invalidation to reason about; it lives on a bounded
module-level lru_cache. 72us -> 0.53us per repeat. (tighten is just
self & other, so its 4,727 calls are the same work.)
equality queries and 5,645 of 7,238 greater-than queries compare sizes that
are already integers. For leq/geq/lt/gt the sympy relational was built
before the cache was consulted, so the cache could never save that cost.
5.8us -> 0.065us. The guard is
type(x) is intrather than isinstance,deliberately: sympy.Integer and bool must keep taking the general path.
figure next to the cache it describes.
One alternative was tried and rejected: peepholing common sympy patterns (1*x,
True and True) instead of caching was worth only ~0.1s, because the cost is in
construction and evaluation rather than in any one simplification.
Together these are worth about 4.4s of a 42.4s cold compile on one model with
dynamic=True. Two members were individually resolvable by interleaved A/B; the
statically_known_equals cache measured
pair 1: baseline 41.06s cached 40.08s
pair 2: baseline 40.34s cached 39.93s
pair 3: baseline 40.72s cached 40.21s
for 40.71s -> 40.07s. The rest are at or under this machine's ~1s noise floor,
so the group figure is the trustworthy one, and the two microbenchmark-only
numbers above (the int comparisons, ~0.12s, and the ValueRanges memo) are
reported from call counts times per-call cost rather than wall clock, because
per-call instrumentation overhead now exceeds what is being measured.
Test plan:
test_sympy_utils passes clean. The inductor and dynamic-shapes suites have
pre-existing failures on this aarch64 host, where inductor emits -march=armv9-a
and the local gcc accepts only up to armv8.6-a. These are unrelated, and rather
than assume so the failing sets were compared directly with and without the
change: identical, 78 names for test_torchinductor_dynamic_shapes and 55 for
test_dynamic_shapes.
Model numerics are unchanged across the series.
This PR was authored with the assistance of an AI coding agent.
cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01 @voznesenskym @penguinwu @EikanWang @Guobing-Chen @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo