Skip to content

[inductor] Improve stability of scaled softmax - #124119

Closed
peterbell10 wants to merge 9 commits into
gh/peterbell10/721/basefrom
gh/peterbell10/721/head
Closed

peterbell10 wants to merge 9 commits into
gh/peterbell10/721/basefrom
gh/peterbell10/721/head

Conversation

@peterbell10

@peterbell10 peterbell10 commented Apr 15, 2024 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

This adds a pattern which replaces:

   scale(x) - scale(x).amax(dim, keepdim=True)

with

   scale(x - x.amax(dim, keepdim=True))

where scale can be either multiplication or division by a scalar,
or a tensor that is broadcast in the dim dimension.

We can find this pattern inside of the decomposed graph of:

F.softmax(scale(x), dim=dim)

This has the effect of both reducing the chance of hitting the fma
issue and also means we avoid recomputing scale(x) inside and outside
the reduction which may be significant if we can remove an extra division.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 15, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 3445a33 with merge base 8bf9e99 (image):
💚 Looks good so far! There are no failures yet. 💚

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

peterbell10 added a commit that referenced this pull request Apr 15, 2024
This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

ghstack-source-id: d36b83d
Pull Request resolved: #124119
@Chillee

Chillee commented Apr 16, 2024

Copy link
Copy Markdown
Collaborator

Curious - do you think the right place to apply this is at the graph level or perhaps lower inside Inductor?

@lezcano

lezcano commented Apr 16, 2024

Copy link
Copy Markdown
Collaborator

Note that the general pattern here would be a*x - F(a*x) = a*(x-F(x)) for F linear, as the same thing may happen for any function F that's linear and that it happens to be the identity at some point (advanced indexing, diag + unsqueeze...). Detecting this may be possible if we look at the auto_linear tag in the derivatives file (if this is accessible). If it's not, we could always list the functions, but it may very well be overkill. If you think it is, just having this simpler pattern for starters looks reasonable to me.

@peterbell10

Copy link
Copy Markdown
Collaborator Author

Curious - do you think the right place to apply this is at the graph level or perhaps lower inside Inductor?

I think this has to be done at the graph level as reductions are always realized, so the pattern would be split across two computed buffers. One buffer does y = amax(scale(x)) and the other does scale(x) - y.

Note that the general pattern here would be a*x - F(a*x) = a*(x-F(x)) for F linear

While that pattern does make mathematical sense, I don't think it works here as amax isn't actually linear.

This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

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

[ghstack-poisoned]
peterbell10 added a commit that referenced this pull request Apr 16, 2024
This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

ghstack-source-id: 9d7c6e2
Pull Request resolved: #124119
@peterbell10
peterbell10 marked this pull request as ready for review April 16, 2024 19:45
@lezcano

lezcano commented Apr 17, 2024 •

Copy link
Copy Markdown
Collaborator

yeah, the more general pattern just asks for F to be 1-homogeneous, but we don't have a good way of marking which ops are 1-homogeneous. (I realised of this after writing this but I don't currently have much access to internet lol).

We could write a small tool that uses OpInfos to figure out which ops are 1-homogeneous (or, in general, have any property that is stable under compositions (i.e. it's functorial in some sense)). Of course this is well outside this PR, but I may pitch this problem to someone, as I think it would be quite useful to write mathematically sound transformations.

Comment thread test/inductor/test_pattern_matcher.py Resolved
[ghstack-poisoned]
peterbell10 added a commit that referenced this pull request Apr 18, 2024
This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

ghstack-source-id: 467a400
Pull Request resolved: #124119

@lezcano lezcano left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Just one question. What happens to the other PRs after this one? Are still relevant? Do we still want to disable fma at large?

#
# which is more stable as we only compute the scaling once.
#
# NOTE: This pattern must come after fused attention matching!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we test this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the existing fused attention tests are sufficient. If this pattern is applied first then the attention patterns wouldn't match any more.

@peterbell10

Copy link
Copy Markdown
Collaborator Author

What happens to the other PRs after this one? Are still relevant? Do we still want to disable fma at large?

This is a tough question. On the stack disabling fma I'm seeing more accuracy failures after already fixing a handful. Given that the goal is ostensibly to improve accuracy, this isn't a great sign.

I think it might be worth exploring an fx graph level fma insertion. That fixes potential discrepancies between the same value being recomputed in different places, while still preserving the accuracy improvements from fma. However, there's still the issue that many of these operations aren't visible at the fx graph level. Once we reach inductor IR it's too late though as we don't know if an intermediate has multiple users.

@peterbell10

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 18, 2024
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR needs a release notes: label
If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Details for Dev Infra team Raised by workflow job

[ghstack-poisoned]
peterbell10 added a commit that referenced this pull request Apr 19, 2024
This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

ghstack-source-id: 995ca2e
Pull Request resolved: #124119
Comment on lines +429 to +430
one = torch.scalar_tensor(1, dtype=inp.dtype, device=inp.device)
sign = torch.where(other >= 0, one, -one)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit. you can even

Suggested change
one = torch.scalar_tensor(1, dtype=inp.dtype, device=inp.device)
sign = torch.where(other >= 0, one, -one)
sign = torch.where(other >= 0, 1, -1)

@peterbell10 peterbell10 Apr 22, 2024 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need these to be tensors so where returns the correct dtype.

@lezcano

lezcano commented Apr 22, 2024

Copy link
Copy Markdown
Collaborator

Why did the last commit fixes a perf regression?

@peterbell10

Copy link
Copy Markdown
Collaborator Author

Why did the last commit fixes a perf regression?

Basically where(other >= 0, inp, -inp) was being saved for backwards, which resulted in additional buffers and writes, even if other was a scalar. On the other hand if I do inp * where(other >= 0, one, -one) then the multiplication can be recomputed in the backward pass from inp. Also changing other.abs() to sign * other allows better constant folding.

[ghstack-poisoned]
[ghstack-poisoned]
peterbell10 added a commit to peterbell10/pytorch that referenced this pull request May 10, 2024
This adds a pattern which replaces:
```python
   scale(x) - scale(x).amax(dim, keepdim=True)
```
with
```python
   scale(x - x.amax(dim, keepdim=True))
```
where `scale` can be either multiplication or division by a scalar,
or a tensor that is broadcast in the `dim` dimension.

We can find this pattern inside of the decomposed graph of:
```python
F.softmax(scale(x), dim=dim)
```

This has the effect of both reducing the chance of hitting the `fma`
issue and also means we avoid recomputing `scale(x)` inside and outside
the reduction which may be significant if we can remove an extra division.

ghstack-source-id: 877abaa
Pull Request resolved: pytorch#124119
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebased gh/peterbell10/722/orig onto refs/remotes/origin/viable/strict because #124616 was rebased, please pull locally before adding more changes (for example, via ghstack checkout https://github.com/pytorch/pytorch/pull/124119)

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.

5 participants