Skip to content

Improve score_fusion_memory() - #127060

Closed
aorenste wants to merge 5 commits into
gh/aorenste/49/basefrom
gh/aorenste/49/head
Closed

aorenste wants to merge 5 commits into
gh/aorenste/49/basefrom
gh/aorenste/49/head

Conversation

@aorenste

@aorenste aorenste commented May 24, 2024 •

Copy link
Copy Markdown
Contributor

Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

score_fusion_memory is called O(n^2) times - so by moving the set union, has_unbacked_symbols check, and numbytes_hint out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:

time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2

Before this change: 12m33s
After this change: 10m15s

Stack from ghstack (oldest at bottom):

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @peterbell10 @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @ColinPeppler @amjames @desertfire @chauhang

Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s real
After this change: 10m15s real

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 24, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

@aorenste
aorenste marked this pull request as ready for review May 24, 2024 15:12
@aorenste
aorenste requested review from eellison and jansel May 24, 2024 15:12
Comment thread torch/_inductor/scheduler.py Resolved
Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

`score_fusion_memory` is called O(n^2) times - so by moving the set union, `has_unbacked_symbols` check, and `numbytes_hint` out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s
After this change: 10m15s



[ghstack-poisoned]
Comment thread torch/_inductor/scheduler.py Resolved
Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

`score_fusion_memory` is called O(n^2) times - so by moving the set union, `has_unbacked_symbols` check, and `numbytes_hint` out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s
After this change: 10m15s



[ghstack-poisoned]
aorenste added 2 commits May 24, 2024 13:30
Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

`score_fusion_memory` is called O(n^2) times - so by moving the set union, `has_unbacked_symbols` check, and `numbytes_hint` out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s
After this change: 10m15s



[ghstack-poisoned]
Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

`score_fusion_memory` is called O(n^2) times - so by moving the set union, `has_unbacked_symbols` check, and `numbytes_hint` out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s
After this change: 10m15s



[ghstack-poisoned]
@aorenste aorenste added the topic: not user facing topic category label May 25, 2024
pytorchmergebot pushed a commit that referenced this pull request May 25, 2024
Related to #98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This improves some of the perf of that checking.

`can_fuse_vertical` calls `fusable_read_and_write` on O(read deps * write deps) combinations - but only cares about write deps that are MemoryDeps - so do the isinstance check outside the inner loop to save O(read deps) when it won't matter anyway.

Also moves `fusable_read_and_write` to a instance method (instead of a closure) since it doesn't actually capture any variables.

I also tried pre-splitting the read deps into `StarDep` vs `MemoryDep` but that didn't actually make any perf difference.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```
Before this change: 10m15s
After this change: 9m31s

Related to #98467

Pull Request resolved: #127061
Approved by: https://github.com/peterbell10, https://github.com/jansel
ghstack dependencies: #127060
titaiwangms pushed a commit to titaiwangms/pytorch that referenced this pull request May 28, 2024
Related to pytorch#98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This
improves some of the perf of that checking.

`score_fusion_memory` is called O(n^2) times - so by moving the set union, `has_unbacked_symbols` check, and `numbytes_hint` out of the loop we call them O(n) times and the O(n^2) call gets cheaper.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```

Before this change: 12m33s
After this change: 10m15s

Pull Request resolved: pytorch#127060
Approved by: https://github.com/peterbell10, https://github.com/jansel
titaiwangms pushed a commit to titaiwangms/pytorch that referenced this pull request May 28, 2024
Related to pytorch#98467

The tacotron2 benchmark creates a lot of nodes which fusion then checks. This improves some of the perf of that checking.

`can_fuse_vertical` calls `fusable_read_and_write` on O(read deps * write deps) combinations - but only cares about write deps that are MemoryDeps - so do the isinstance check outside the inner loop to save O(read deps) when it won't matter anyway.

Also moves `fusable_read_and_write` to a instance method (instead of a closure) since it doesn't actually capture any variables.

I also tried pre-splitting the read deps into `StarDep` vs `MemoryDep` but that didn't actually make any perf difference.

Testing:
```
time python benchmarks/dynamo/torchbench.py --accuracy --inference --amp --backend inductor --disable-cudagraphs --device cuda --only tacotron2
```
Before this change: 10m15s
After this change: 9m31s

Related to pytorch#98467

Pull Request resolved: pytorch#127061
Approved by: https://github.com/peterbell10, https://github.com/jansel
ghstack dependencies: pytorch#127060
pytorchmergebot pushed a commit that referenced this pull request May 30, 2024
It seems that while #127060 improved the speed for tacotron2 it introduced a compilation_latency regression for some of the TIMM benchmarks.

The original change was to precompute the Dep metadata - but apparently some benchmarks have few enough overlaps that precomputing O(n) deps was slower than ignoring O(n^2) deps.  So change it to go back to computing the Dep metadata on demand but to then cache the result.

`dm_nfnet_f0` was a good example because on the dashboard it showed an increase from 140s -> 154s.

```
python benchmarks/dynamo/timm_models.py --performance --cold-start-latency --training --amp --backend inductor --dynamic-shapes --dynamic-batch-only --device cuda --total-partitions 5 --partition-id 1 --output timm-0.csv --only dm_nfnet_f0
```

Looking at the compilation_latency result.

On viable (d6e3e89):
172.777958
176.725071
177.907955

On viable with #127060 and #127061 fully backed out:
158.305166
158.688560
160.791187

On viable w/ this change:
160.094164
160.201845
161.752157

I think that's probably close enough considering the variance.

Pull Request resolved: #127326
Approved by: https://github.com/oulgen
@github-actions
github-actions Bot deleted the gh/aorenste/49/head branch June 25, 2024 01:57
anijain2305 added a commit that referenced this pull request Aug 25, 2026
…e pair

The fusion search asks O(pairs) questions, but three of the quantities it
consults depend only on a single buffer or a single node, and each was recomputed
from scratch on every pair:

- can_fusion_increase_peak_memory rescanned every read of both nodes looking for
  single-user buffers, then built each buffer's reuse key, which runs
  compute_required_storage_length and sympy_str.
- _score_fusion_memory_by_buffer_overlap summed read sizes over all deps of both
  nodes four separate times, hashing every Dep to reach the dep_size_hint cache.
- score_fusion_memory materialized `reads | writes` for both nodes. Fusion keeps
  merging nodes into larger ones, so paying O(deps) per pair to rebuild that
  union is what turned the search quadratic in practice.

Reuse keys are now memoized by buffer name on the Scheduler. Per-node read bytes
are memoized on the node, alongside the other read_writes-derived caches and
invalidated with them. The union is gone: the common-dep scan walks whichever
node has fewer deps and tests membership against the other node's raw read and
write sets, which preserves the de-duplication the union provided.

Only the key is memoized, not whether the buffer qualifies. `users` shrinks while
the fusion search runs - user-defined triton epilogue fusion drops one - so a
cached "has exactly one user" would go stale mid-search and this heuristic would
then reason from a buffer that is no longer reusable. That cannot produce wrong
tensors, but it can accept or reject a fusion it should not, which changes the
generated kernels. So eligibility is rechecked on every call and only the key, a
pure function of the buffer's layout, is kept. Rechecking costs nothing
measurable: 15.5s either way on the repro below.

The key survives the other way a name can go stale. Finalizing a multi-template
buffer swaps out the buffer a name refers to, but it copies the layout across,
and the key is a function of layout, device, dtype and name. Keying the cache on
the buffer object instead is not an option: an ir.MultiOutput is not hashable.

Reuse keys are keyed by buffer name rather than by scheduler node for a
performance reason too. Keying by node was tried first and was worse than doing
nothing, because every newly fused node then rebuilds keys for all of its reads
and the sharing across nodes that read the same buffer is lost.

On the earlier attempts in this area: #127060 eagerly precomputed every node's
dependency metadata and #127326 reverted it because sparse-overlap models
regressed. This computes its per-node data lazily, only for the nodes a candidate
pair actually names, so it is not that shape.

BaseSchedulerNode crossed the docstring linter's grandfathered size limit, so it
also gains the class docstring it was missing.

Measured against the parent commit. The repro is three foreach calls over a list
of N graph inputs - _foreach_norm(xs), then _foreach_div_(xs, norms) dividing in
place by that per-tensor norm list, then a second in-place mutation of the same
list - which is the shape of an internal optimizer graph that spends nearly all
of its compile in the fusion search. Cold compile, autotuning off, median of
three:

              parent    this change
    N=128     18.5s        8.0s
      fused_nodes  12.1s        1.8s
    N=275     57.5s       16.0s
      fused_nodes  46.8s        5.1s

The search is superlinear before and roughly linear after: 2.15x the inputs costs
3.1x the time on the parent and 2.0x with this change.

Test Plan:

```
python -m pytest -q -p no:randomly test/inductor/test_perf.py \
  test/inductor/test_memory.py test/inductor/test_inductor_scheduler.py \
  test/inductor/test_fusion_regions.py test/inductor/test_combo_kernels.py \
  test/inductor/test_foreach.py test/inductor/test_benchmark_fusion.py
# 922 passed, 5 failed

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
# 2532 passed, 55 failed

python -m pytest -q -p no:randomly test/inductor/test_triton_kernels.py \
  -k "epilogue or fusion"
# 16 passed
```

None of those failures are from this change. The four
TestOperatorReorderForPeakMemory ones fail identically with the change reverted.
test_benchmark_on_non_zero_device passes on its own and passes when its whole
file runs, so it is cross-file order dependence in that batch. For the 55,
running the same 55 tests as a set gives 49 failed and 6 passed both with this
change and on the parent, so the set is pre-existing and the difference in the
full-file run is ordering.

The triton_kernels epilogue and fusion tests are the ones that exercise the
mutable-users path described above.

This commit was authored with the assistance of an AI agent (Claude Code).

ghstack-source-id: 93732d8
Pull-Request: #194011
pytorchmergebot pushed a commit that referenced this pull request Aug 27, 2026
…e pair (#194011)

The fusion search asks O(pairs) questions, but three of the quantities it
consults depend only on a single buffer or a single node, and each was recomputed
from scratch on every pair:

- can_fusion_increase_peak_memory rescanned every read of both nodes looking for
  single-user buffers, then built each buffer's reuse key, which runs
  compute_required_storage_length and sympy_str.
- _score_fusion_memory_by_buffer_overlap summed read sizes over all deps of both
  nodes four separate times, hashing every Dep to reach the dep_size_hint cache.
- score_fusion_memory materialized `reads | writes` for both nodes. Fusion keeps
  merging nodes into larger ones, so paying O(deps) per pair to rebuild that
  union is what turned the search quadratic in practice.

Reuse keys are now memoized by buffer name on the Scheduler. Per-node read bytes
are memoized on the node, alongside the other read_writes-derived caches and
invalidated with them. The union is gone: the common-dep scan walks whichever
node has fewer deps and tests membership against the other node's raw read and
write sets, which preserves the de-duplication the union provided.

Only the key is memoized, not whether the buffer qualifies. `users` shrinks while
the fusion search runs - user-defined triton epilogue fusion drops one - so a
cached "has exactly one user" would go stale mid-search and this heuristic would
then reason from a buffer that is no longer reusable. That cannot produce wrong
tensors, but it can accept or reject a fusion it should not, which changes the
generated kernels. So eligibility is rechecked on every call and only the key, a
pure function of the buffer's layout, is kept. Rechecking costs nothing
measurable: 15.5s either way on the repro below.

The key survives the other way a name can go stale. Finalizing a multi-template
buffer swaps out the buffer a name refers to, but it copies the layout across,
and the key is a function of layout, device, dtype and name. Keying the cache on
the buffer object instead is not an option: an ir.MultiOutput is not hashable.

Reuse keys are keyed by buffer name rather than by scheduler node for a
performance reason too. Keying by node was tried first and was worse than doing
nothing, because every newly fused node then rebuilds keys for all of its reads
and the sharing across nodes that read the same buffer is lost.

On the earlier attempts in this area: #127060 eagerly precomputed every node's
dependency metadata and #127326 reverted it because sparse-overlap models
regressed. This computes its per-node data lazily, only for the nodes a candidate
pair actually names, so it is not that shape.

BaseSchedulerNode crossed the docstring linter's grandfathered size limit, so it
also gains the class docstring it was missing.

Measured against the parent commit. The repro is three foreach calls over a list
of N graph inputs - _foreach_norm(xs), then _foreach_div_(xs, norms) dividing in
place by that per-tensor norm list, then a second in-place mutation of the same
list - which is the shape of an internal optimizer graph that spends nearly all
of its compile in the fusion search. Cold compile, autotuning off, median of
three:

              parent    this change
    N=128     18.5s        8.0s
      fused_nodes  12.1s        1.8s
    N=275     57.5s       16.0s
      fused_nodes  46.8s        5.1s

The search is superlinear before and roughly linear after: 2.15x the inputs costs
3.1x the time on the parent and 2.0x with this change.

Test Plan:

```
python -m pytest -q -p no:randomly test/inductor/test_perf.py \
  test/inductor/test_memory.py test/inductor/test_inductor_scheduler.py \
  test/inductor/test_fusion_regions.py test/inductor/test_combo_kernels.py \
  test/inductor/test_foreach.py test/inductor/test_benchmark_fusion.py
# 922 passed, 5 failed

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
# 2532 passed, 55 failed

python -m pytest -q -p no:randomly test/inductor/test_triton_kernels.py \
  -k "epilogue or fusion"
# 16 passed
```

None of those failures are from this change. The four
TestOperatorReorderForPeakMemory ones fail identically with the change reverted.
test_benchmark_on_non_zero_device passes on its own and passes when its whole
file runs, so it is cross-file order dependence in that batch. For the 55,
running the same 55 tests as a set gives 49 failed and 6 passed both with this
change and on the parent, so the set is pre-existing and the difference in the
full-file run is ordering.

The triton_kernels epilogue and fusion tests are the ones that exercise the
mutable-users path described above.

This commit was authored with the assistance of an AI agent (Claude Code).

Pull Request resolved: #194011
Approved by: https://github.com/mlazos
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…e pair (pytorch#194011)

The fusion search asks O(pairs) questions, but three of the quantities it
consults depend only on a single buffer or a single node, and each was recomputed
from scratch on every pair:

- can_fusion_increase_peak_memory rescanned every read of both nodes looking for
  single-user buffers, then built each buffer's reuse key, which runs
  compute_required_storage_length and sympy_str.
- _score_fusion_memory_by_buffer_overlap summed read sizes over all deps of both
  nodes four separate times, hashing every Dep to reach the dep_size_hint cache.
- score_fusion_memory materialized `reads | writes` for both nodes. Fusion keeps
  merging nodes into larger ones, so paying O(deps) per pair to rebuild that
  union is what turned the search quadratic in practice.

Reuse keys are now memoized by buffer name on the Scheduler. Per-node read bytes
are memoized on the node, alongside the other read_writes-derived caches and
invalidated with them. The union is gone: the common-dep scan walks whichever
node has fewer deps and tests membership against the other node's raw read and
write sets, which preserves the de-duplication the union provided.

Only the key is memoized, not whether the buffer qualifies. `users` shrinks while
the fusion search runs - user-defined triton epilogue fusion drops one - so a
cached "has exactly one user" would go stale mid-search and this heuristic would
then reason from a buffer that is no longer reusable. That cannot produce wrong
tensors, but it can accept or reject a fusion it should not, which changes the
generated kernels. So eligibility is rechecked on every call and only the key, a
pure function of the buffer's layout, is kept. Rechecking costs nothing
measurable: 15.5s either way on the repro below.

The key survives the other way a name can go stale. Finalizing a multi-template
buffer swaps out the buffer a name refers to, but it copies the layout across,
and the key is a function of layout, device, dtype and name. Keying the cache on
the buffer object instead is not an option: an ir.MultiOutput is not hashable.

Reuse keys are keyed by buffer name rather than by scheduler node for a
performance reason too. Keying by node was tried first and was worse than doing
nothing, because every newly fused node then rebuilds keys for all of its reads
and the sharing across nodes that read the same buffer is lost.

On the earlier attempts in this area: pytorch#127060 eagerly precomputed every node's
dependency metadata and pytorch#127326 reverted it because sparse-overlap models
regressed. This computes its per-node data lazily, only for the nodes a candidate
pair actually names, so it is not that shape.

BaseSchedulerNode crossed the docstring linter's grandfathered size limit, so it
also gains the class docstring it was missing.

Measured against the parent commit. The repro is three foreach calls over a list
of N graph inputs - _foreach_norm(xs), then _foreach_div_(xs, norms) dividing in
place by that per-tensor norm list, then a second in-place mutation of the same
list - which is the shape of an internal optimizer graph that spends nearly all
of its compile in the fusion search. Cold compile, autotuning off, median of
three:

              parent    this change
    N=128     18.5s        8.0s
      fused_nodes  12.1s        1.8s
    N=275     57.5s       16.0s
      fused_nodes  46.8s        5.1s

The search is superlinear before and roughly linear after: 2.15x the inputs costs
3.1x the time on the parent and 2.0x with this change.

Test Plan:

```
python -m pytest -q -p no:randomly test/inductor/test_perf.py \
  test/inductor/test_memory.py test/inductor/test_inductor_scheduler.py \
  test/inductor/test_fusion_regions.py test/inductor/test_combo_kernels.py \
  test/inductor/test_foreach.py test/inductor/test_benchmark_fusion.py
# 922 passed, 5 failed

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
# 2532 passed, 55 failed

python -m pytest -q -p no:randomly test/inductor/test_triton_kernels.py \
  -k "epilogue or fusion"
# 16 passed
```

None of those failures are from this change. The four
TestOperatorReorderForPeakMemory ones fail identically with the change reverted.
test_benchmark_on_non_zero_device passes on its own and passes when its whole
file runs, so it is cross-file order dependence in that batch. For the 55,
running the same 55 tests as a set gives 49 failed and 6 passed both with this
change and on the parent, so the set is pre-existing and the difference in the
full-file run is ordering.

The triton_kernels epilogue and fusion tests are the ones that exercise the
mutable-users path described above.

This commit was authored with the assistance of an AI agent (Claude Code).

Pull Request resolved: pytorch#194011
Approved by: https://github.com/mlazos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants