Skip to content

Fix compilation_latency regression caused by #127060 - #127326

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

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

Conversation

@aorenste

@aorenste aorenste commented May 28, 2024 •

Copy link
Copy Markdown
Contributor

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.

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

@pytorch-bot

pytorch-bot Bot commented May 28, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (3 Unrelated Failures)

As of commit bc21e88 with merge base 9a8e810 (image):

UNSTABLE - The following jobs failed but were likely due to flakiness present on trunk and has been marked as unstable:

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

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

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

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

[ghstack-poisoned]
aorenste added a commit that referenced this pull request May 28, 2024
ghstack-source-id: a5142a3
Pull Request resolved: #127326
@aorenste
aorenste requested review from anijain2305 and oulgen May 29, 2024 00:27
@aorenste
aorenste marked this pull request as ready for review May 29, 2024 00:27
@aorenste aorenste added the topic: not user facing topic category label May 29, 2024
@aorenste aorenste changed the title WIP: Fix compile time regression Fix compilation_latency regression caused by #127060 May 29, 2024
@aorenste

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 29, 2024
@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@aorenste

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@aorenste

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased gh/aorenste/51/orig onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via ghstack checkout https://github.com/pytorch/pytorch/pull/127326)

pytorchmergebot pushed a commit that referenced this pull request May 29, 2024
ghstack-source-id: 65813ff
Pull Request resolved: #127326
@aorenste

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

@github-actions
github-actions Bot deleted the gh/aorenste/51/head branch June 30, 2024 02:01
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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants