Skip to content

[MPS] Migrate log_sigmoid forward/backward from MPSGraph to Metal - #187228

Closed
malfet wants to merge 2 commits into
gh/malfet/953/basefrom
gh/malfet/953/head
Closed

malfet wants to merge 2 commits into
gh/malfet/953/basefrom
gh/malfet/953/head

Conversation

@malfet

@malfet malfet commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Replace the MPSGraph-based log_sigmoid_forward_*_mps / log_sigmoid_backward_mps* with native Metal kernels in ActivationKernel.metal using unary iterator.
Forward numerically stable formula is $min(0, x) - \log1p(e^{-|x|})$. Backward uses the
observation that $\frac{d}{dx} log(sigmoid(x)) = sigmoid(-x)$, which lets us
write the gradient as (in<0) ? (1-t) : t with $t = \frac{z}{1+z}$, $z = e~{-|in|}$.

Replace fail in LogSigmoid float16 OpInfo test_forward with xfail to a toleranceOverride(atol=5e-3, rtol=1e-3).

Microbenchmark (us per call, A/B from the same script with only the impl swapped):

shape|dtype                      fwd mpsg   fwd metal  fwd_x   bwd mpsg  bwd metal  bwd_x
1024|float32                        10.68       6.61   1.62x      30.00      15.94   1.88x
1024|float16                        10.85       6.77   1.60x      27.46      17.95   1.53x
1024|bfloat16                       11.83       6.70   1.77x      26.64      14.22   1.87x
1024x1024|float32                   36.35      20.64   1.76x      30.05      41.84   0.72x
1024x1024|float16                   14.68      11.92   1.23x      29.53      27.60   1.07x
8x1024x1024|float32                267.45     252.40   1.06x     378.48     380.34   1.00x
32x1024x1024|float32              1012.71     987.62   1.03x    1499.97    1481.34   1.01x

Co-Authored-By: Claude Opus 4.7 [email protected]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

✅ No Failures

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

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

@pytorch-bot pytorch-bot Bot added ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels Jun 13, 2026
# loses precision as sigmoid(x) saturates near 1 for moderate x.
# log_sigmoid uses the stable `min(0,x) - log1p(exp(-|x|))`
# in fp32, so it can differ from the naive reference by up to
# ~1 ULP of sigmoid(x) (~4e-3 for x in fp16's mid-range).

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.

No way to improve this with precise::math stuff?

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.

It's not about precise math, but the fact that we test fused op against decomposed one, and fused is more accurate. I'll propose a separate PR to upcast to fp32

const float in = float(self);
const float z = ::metal::precise::exp(-::metal::abs(in));
const float t = z / (1.0f + z);
return static_cast<T>(float(grad_output) * (in < 0.0f ? 1.0f - t : t));

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.

No need for any precise mul etc math helpers?

[ghstack-poisoned]
@malfet
malfet requested a review from mruberry as a code owner June 14, 2026 01:39
malfet added a commit that referenced this pull request Jun 14, 2026
Replace the MPSGraph-based `log_sigmoid_forward_*_mps` /
`log_sigmoid_backward_mps*` with native Metal kernels in
`ActivationKernel.metal` / `ActivationKernel.mm`. Forward uses the
numerically stable `min(0, x) - log1p(exp(-|x|))`. Backward uses the
observation that `d/dx log(sigmoid(x)) = sigmoid(-x)`, which lets us
write the gradient as `(in<0) ? (1-t) : t` with `t = z/(1+z)`,
`z = exp(-|in|)` -- one mul and one add cheaper than the
max_deriv/sign formulation CUDA carries.

The new kernels register only `float/half/bfloat`, matching CUDA's
`AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, ...)`. The old
MPSGraph path auto-promoted integer inputs, so the logsigmoid and
multilabel_soft_margin_loss OpInfos carried `dtypesIfMPS` lists with
int8/uint8/int16/int32 -- and the consistency test had matching
xfail entries. Drop both: with CUDA-aligned dtype support, those
samples are no longer generated.

Also relax the LogSigmoid float16 `test_forward` xfail to a
`toleranceOverride(atol=5e-3, rtol=1e-3)`. The test's reference function
`i.sigmoid().log()` is the naive composition that loses precision in fp16
(sigmoid saturates near 1.0 for moderate `x`, then log of a value 1 ULP
below 1.0 differs from the stable formula by up to ~4e-3); the new
tolerance covers that gap.

Microbenchmark (us per call, A/B from the same script with only the impl
swapped):

```
shape|dtype                      fwd mpsg   fwd metal  fwd_x   bwd mpsg  bwd metal  bwd_x
1024|float32                        10.68       6.61   1.62x      30.00      15.94   1.88x
1024|float16                        10.85       6.77   1.60x      27.46      17.95   1.53x
1024|bfloat16                       11.83       6.70   1.77x      26.64      14.22   1.87x
1024x1024|float32                   36.35      20.64   1.76x      30.05      41.84   0.72x
1024x1024|float16                   14.68      11.92   1.23x      29.53      27.60   1.07x
8x1024x1024|float32                267.45     252.40   1.06x     378.48     380.34   1.00x
32x1024x1024|float32              1012.71     987.62   1.03x    1499.97    1481.34   1.01x
```

Metal wins on dispatch overhead at small sizes; parity at large sizes
where the op is memory-bandwidth bound. The one regression at
1024x1024 fp32 backward is consistent across reruns -- MPSGraph appears
to fuse the sub/mul chain particularly well at that shape -- but the
gap closes at both smaller and larger sizes.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
ghstack-source-id: 262112b
Pull-Request: #187228
@malfet

malfet commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint + MPS are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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/malfet/953/head branch July 15, 2026 02:22
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…torch#187228)

Replace the MPSGraph-based `log_sigmoid_forward_*_mps` / `log_sigmoid_backward_mps*` with native Metal kernels in `ActivationKernel.metal` using unary iterator.
Forward  numerically stable formula is $min(0, x) - \log1p(e^{-|x|})$. Backward uses the
observation that $\frac{d}{dx} log(sigmoid(x)) = sigmoid(-x)$, which lets us
write the gradient as `(in<0) ? (1-t) : t` with $t = \frac{z}{1+z}$, $z = e~{-|in|}$.

Replace fail in LogSigmoid float16 OpInfo `test_forward` with xfail to a `toleranceOverride(atol=5e-3, rtol=1e-3)`.

Microbenchmark (us per call, A/B from the same script with only the impl swapped):

```
shape|dtype                      fwd mpsg   fwd metal  fwd_x   bwd mpsg  bwd metal  bwd_x
1024|float32                        10.68       6.61   1.62x      30.00      15.94   1.88x
1024|float16                        10.85       6.77   1.60x      27.46      17.95   1.53x
1024|bfloat16                       11.83       6.70   1.77x      26.64      14.22   1.87x
1024x1024|float32                   36.35      20.64   1.76x      30.05      41.84   0.72x
1024x1024|float16                   14.68      11.92   1.23x      29.53      27.60   1.07x
8x1024x1024|float32                267.45     252.40   1.06x     378.48     380.34   1.00x
32x1024x1024|float32              1012.71     987.62   1.03x    1499.97    1481.34   1.01x
```

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pull Request resolved: pytorch#187228
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#187151
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…torch#187228)

Replace the MPSGraph-based `log_sigmoid_forward_*_mps` / `log_sigmoid_backward_mps*` with native Metal kernels in `ActivationKernel.metal` using unary iterator.
Forward  numerically stable formula is $min(0, x) - \log1p(e^{-|x|})$. Backward uses the
observation that $\frac{d}{dx} log(sigmoid(x)) = sigmoid(-x)$, which lets us
write the gradient as `(in<0) ? (1-t) : t` with $t = \frac{z}{1+z}$, $z = e~{-|in|}$.

Replace fail in LogSigmoid float16 OpInfo `test_forward` with xfail to a `toleranceOverride(atol=5e-3, rtol=1e-3)`.

Microbenchmark (us per call, A/B from the same script with only the impl swapped):

```
shape|dtype                      fwd mpsg   fwd metal  fwd_x   bwd mpsg  bwd metal  bwd_x
1024|float32                        10.68       6.61   1.62x      30.00      15.94   1.88x
1024|float16                        10.85       6.77   1.60x      27.46      17.95   1.53x
1024|bfloat16                       11.83       6.70   1.77x      26.64      14.22   1.87x
1024x1024|float32                   36.35      20.64   1.76x      30.05      41.84   0.72x
1024x1024|float16                   14.68      11.92   1.23x      29.53      27.60   1.07x
8x1024x1024|float32                267.45     252.40   1.06x     378.48     380.34   1.00x
32x1024x1024|float32              1012.71     987.62   1.03x    1499.97    1481.34   1.01x
```

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pull Request resolved: pytorch#187228
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#187151
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) Merged release notes: mps Release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants