Skip to content

Add an accurate Metal erfc for MPS (eager + inductor) - #189291

Closed
qflen wants to merge 2 commits into
pytorch:mainfrom
qflen:187806-metal-erfc
Closed

qflen wants to merge 2 commits into
pytorch:mainfrom
qflen:187806-metal-erfc

Conversation

@qflen

@qflen qflen commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Splits the MPS backend portion out of #189234 (gh-187806) per review.

Problem

c10::metal::erfc is 1.0 - erf(x): once erf saturates in fp32 (x ~ 3.9), erfc returns 0.0, i.e. 100% relative error over the entire upper tail. Everything consuming it on MPS inherits the flush:

Fix

  • Below erf's own branch threshold, keep 1 - erf(x): exact there.
  • Above it: erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a) with q = (a - 4)/(a + 4), p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via 2 - erfc(-x). The scaled-rational construction follows N. Juffa's vectorizable erfcf.
  • Both quotients use ::metal::fast::divide (per review): full-precision division made the branch compute-bound (gelu 1.3-1.7x slower on M2 Max, eager erfc 1.2-1.3x slower than erf on M5) and would tighten the max error only from ~5.6 to ~5.0 ulp.
  • "erfc" joins the Inductor MPS codegen op set so torch.compile on MPS uses the same implementation.

Verification (M5)

  • erfc accuracy, exhaustive enumeration of all 2^32 fp32 inputs vs float64 over the fp32-normal output range: max 5.6 ulp (4.0e-7 relative) on M5, 5.1 ulp on M2 Max (fast-math division rounding is GPU-dependent). Before: 100% relative error past x ~ 3.9.
  • Eager erfc runs at erf speed (was 1.2-1.3x slower with full-precision divides); Inductor output is bitwise identical to eager.
  • gammaincc(1200, x): tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.
  • New eager MPS tail tests for erfc and igammac, plus an Inductor regression test (test_mps_basic.py, test_erfc_tail_accuracy) that fails if the codegen op-set entry is dropped and compiled erfc falls back to 1 - erf.
  • Specials and the clamp branch pinned exactly in both erfc tests: erfc(0) = 1, erfc(+inf) = 0, erfc(-inf) = 2, nan propagates, erfc(+-10.5) = erfc(+-1e30) = exactly 0/2.

Base commit: 135435f.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

c10::metal::erfc was 1.0 - erf(x), which loses all precision once erf
saturates in fp32 (100% relative error past x ~ 3.9) and flushes the
upper tail to zero. Replace it: keep 1 - erf below erf's branch
threshold (exact there), and above it use
erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a) with q = (a - 4)/(a + 4),
where p is a degree-9 Remez fit against 60-digit mpmath references and
the squared exp argument is fma-compensated. Negative x uses
2 - erfc(-x), safe since erfc(-x) is small there. Measured max 4.6 ulp
over the fp32-normal output range. The scaled-rational construction
follows N. Juffa's vectorizable erfcf.

"erfc" joins the inductor MPS codegen op set so torch.compile on MPS
uses the same implementation. igammac improves for free: its large-a
asymptotic path evaluates 0.5 * erfc(...), so gammaincc(1200, x) now
tracks float64 to ~7e-5 relative down to values of 1e-33 instead of
flushing to zero below ~1e-8.

Split out of pytorch#189234 (pytorchgh-187806) per MPS-maintainer review; the gelu
rewrite there builds on this erfc and rebases on top.

Test Plan:

```
python test/test_mps.py -v -k tail_accuracy
python test/test_mps.py -k erfc
lintrunner test/test_mps.py c10/metal/special_math.h torch/_inductor/codegen/mps.py
```

On M5: the two new tail tests pass, the 23 existing erfc consistency
tests pass (1 pre-existing expected failure), lint clean. New tests are
dense sweeps vs float64 with bounds 1e-6 (erfc) and 5e-4 (igammac)
against measured 2.8e-7 and 6.6e-5.
@qflen
qflen requested a review from malfet as a code owner July 8, 2026 19:16
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Jul 8, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 625197b with merge base 135435f (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 commented Jul 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 8, 2026
@jansel

jansel commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 5m 27s —— View job


PR Review: #189291

Summary

Replaces the flush-to-zero 1 - erf(x) Metal erfc with an accurate scaled-rational implementation for |x| > 0.927734375, and wires erfc into the Inductor MPS codegen op set. The implementation is careful and the numerics verification is convincing; I found only minor points, none blocking.

Detailed review

Testing

  • The PR body claims special values are "preserved (erfc(0) = 1, erfc(+-inf) = 2/0, nan propagates)", but neither new test exercises them — test_erfc_tail_accuracy sweeps arange(-9, 9) (no inf/nan/zero-boundary), and test_igammac_tail_accuracy is unrelated. These special cases are the ones most likely to regress silently (the isnan early-out, the min(a, 10.5) clamp handling +inf, and the 2 - r path for -inf). If OpInfo test_output_match sample inputs don't already cover +-inf/nan for erfc on MPS, add explicit asserts:
    x = torch.tensor([0.0, float("inf"), float("-inf"), float("nan")], device="mps")
    self.assertEqual(torch.erfc(x).cpu(), torch.tensor([1.0, 0.0, 2.0, float("nan")]))

Code Quality

  • Nothing blocking. The comment at special_math.h:53-65 is unusually thorough and accurate (Sterbenz justification for the 1 - erf branch, the fma compensation of the squaring residual, the clamp rationale). No changes needed here.

API Design / Consistency

  • erfcx is not added to the MPS special-ops set, so Inductor still lowers it via the generic decomposition in codegen/common.py:947 (exp(square(x)) * erfc(x)). For large x that is inf * ~0 -> NaN, and this PR's accurate erfc does not fix it (eager MPS erfcx has its own erfcx_y100 kernel in UnaryKernel.mm, so eager and compiled diverge). This is pre-existing and out of scope, but worth a follow-up given this PR is already improving the erf-family accuracy story on MPS.

Correctness (verified, no action needed)

  • Special-value flow checks out: erfc(0) -> 1 - erf(0) = 1; +inf -> t=10.5, r~0, returns ~0; -inf -> 2 - r ~ 2; nan -> early return. The min discarding NaN is correctly guarded by the preceding isnan check.
  • Negative branch 2 - r has no catastrophic cancellation since r = erfc(a) < 0.19 for a > 0.927734375.

Recommendation

Approve — solid, well-documented numerics fix with CI green. Suggest confirming special-value (0/+-inf/nan) coverage exists (via OpInfo) or adding an explicit assert, and optionally filing a follow-up for the Inductor MPS erfcx decomposition gap.
· branch 187806-metal-erfc

@jhavukainen
jhavukainen self-requested a review July 9, 2026 16:22
@jhavukainen

Copy link
Copy Markdown
Collaborator

Thanks @qflen! Looks good in general. I'll need do some benchmarking to quantify what the effect of this will be on a few hardware. I assume the two additional full divisions this introduces will show up. But regardless the correctness should be priority, I just want to see if I can limit the blast radius to only cases requiring the more precise treatment.

@jhavukainen

Copy link
Copy Markdown
Collaborator

Ok so some findings here so far:

Yes the two divisions are significant. At least on some hardware. On M2 Max old gelu was 1.3-1.7x faster than the one with the new erfc. However I think there's a compromise that would give us almost the same accuracy and roughly retain the old performance. The accuracy of the polynomial approximator is not overly sensitive towards whether we use the full division or call into fast::divide for the two cases. Scanning across I'm seeing this replacement adds ~0.5 ulps to the max. divergence from the reference value in fp32 bringing it up 4.6 ulp->5.1 ulp. But the performance goes back up to essentially the bandwidth ceiling.

I'll need to think about the tradeoffs a little more but I'm leaning towards using the fast division unless there are strong counter arguments. It'll be a significant accuracy improvement with little cost. But that being said I'm not an expert on the high precision requiring use cases that warranted this investigation initially so I'll need to dig a bit deeper to understand if this'll would make it too inaccurate for real use cases.

Comment thread c10/metal/special_math.h Resolved
Comment thread c10/metal/special_math.h Resolved

@jhavukainen jhavukainen 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.

Could you verify if using fast division works on your setup as well. Locally I'm seeing it cut down the perf regression and make the erfc implementation essentially as fast as the 1+erf was while still getting within a hair's width of the accuracy.

It is possible the fast implementations are different between hardware generations, so it'd be great to verify your end. But I think this should work.

@jhavukainen

Copy link
Copy Markdown
Collaborator

For completeness the runtimes I saw on M2 Max using gelu as the sample op

  | gelu variant                  | tail accuracy            | gelu fwd (us/op) |
  |-------------------------------|--------------------------|-----------------:|
  | base (pre-PR, `1+erf`)        | catastrophic: 100% rel   | ~365             |
  |                               | err (tail flushed to 0)  |                  |
  | this PR (`erfc`, true divide) | 4.65 ulp (exhaustive)    | ~595             |
  | PR + `fast::divide`           | 5.10 ulp (exhaustive)    | ~361             |


@qflen

qflen commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for review! I'm on it.

Full-precision Metal division left erfc's rational branch compute-bound
in the -fno-fast-math metallib: jhavukainen measured gelu built on this
erfc 1.3-1.7x slower on M2 Max; on M5, eager fp32 erfc ran 1.1-1.3x
slower than erf and the fp16 kernel up to 2.2x slower than the pre-PR
1 - erf form. Both quotients now use ::metal::fast::divide (the final one
through a den local so clang-format keeps the line whole), restoring
eager erfc to erf speed on M5: 2139-2284us vs 2276us for erf over 2^25
fp32 elements across randn/uniform/tail input regimes, with fp16 up to
34% faster than before.

Accuracy cost, measured by exhaustive enumeration of all 2^32 fp32
inputs against float64 on M5: max error 4.985 -> 5.559 ulp and max
relative error 3.88e-7 -> 3.97e-7 over the fp32-normal output range
(the 4.6 ulp previously documented came from the dense 2^-10 sweep;
exhaustive enumeration of the unchanged true-divide code measures
4.985),
still 2.5x inside the tail test's 1e-6 bound, and far below igammac's
own ~7e-5 asymptotic error floor. The q = (t-4)/(t+4) quotient is
insensitive to the fast path; the final quotient accounts for the whole
delta. Specials are unchanged, the flush-to-zero region shows no
violations over 1.05e9 subnormal-output points, and inductor-MPS output
stays bitwise identical to eager. A Newton-refined reciprocal for the
final quotient would reproduce true-divide results bitwise at nearly
the same speed, but no consumer needs the extra 0.6 ulp, so the simpler
form the reviewer verified is enough.

Also adds a compiled-side tail test so inductor-MPS keeps lowering erfc
to c10::metal::erfc rather than a 1 - erf decomposition, and extends
both tail tests with exact special-value and clamp-branch checks
(0, +-inf, NaN, +-10.5, +-1e30), which the dense grid never reached;
those outputs are exactly 0/2 in fp32 on any GPU since exp(-110.25)
underflows even the subnormal range, so the asserts are bit-strict.

Test Plan:

```
python test/test_mps.py -k tail_accuracy -k erfc -k igammac
python test/inductor/test_mps_basic.py -k erfc
lintrunner c10/metal/special_math.h test/inductor/test_mps_basic.py
```

On M5: 30 tests OK (3 pre-existing expected failures: 1 erfc, 2
igammac), inductor tail test OK, lint clean. Exhaustive accuracy sweep
and eager/shader benchmarks run via torch.mps.compile_shader harness
(agent_space, not committed); eager torch.erfc verified bitwise equal
to the harness fast::divide variant after rebuild.
@qflen

qflen commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Verified on M5 and applied.

Checking every fp32 input against float64, the max error goes from 4.985 to 5.559 ulp here (max relative 3.9e-7 -> 4.0e-7), slightly wider than your 4.65 -> 5.10 on M2 Max, which matches your point that the fast implementations differ between hardware generations.

Special values and the flush-to-zero tail are unchanged, inductor output stays bitwise identical to eager, and there is still plenty of margin downstream: the tail tests bound relative error at 1e-6, and igammac's asymptotic path has its own ~7e-5 error floor, so the extra ~0.6 ulp is too small to matter for the use cases that motivated this.

Perf recovers on my end too, eager erfc is back at erf speed:

eager op, 2^25 elems (M5) true divide fast::divide
erfc fp32, uniform [-11, 11] 2968 us 2284 us
erfc fp16, uniform [-11, 11] 2318 us 1527 us
erf fp32 (unchanged reference) ~2276 us ~2276 us

One extra data point:
The whole accuracy difference comes from the final quotient (using fast division only for q never raises the max error), and a Newton-refined reciprocal restores the true-divide results bitwise at close to fast::divide speed, so we can tighten this later if a use case ever needs it.

@qflen

qflen commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Also added the compiled-path tail test. It and the eager test now pin the specials and the clamp branch exactly (erfc(0)=1, erfc(+-inf)=0/2, NaN propagates, erfc(+-10.5)=erfc(+-1e30)=0/2), which the dense grid never reached, and use assertEqual with rtol.

The second suggestion is applied through a den local only to keep clang-format from splitting the line.

@qflen
qflen requested a review from jhavukainen July 10, 2026 06:53

@jhavukainen jhavukainen 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.

Ok looks good to me both as a standalone addition, as well as how it'll work with the follow-up PR where the instances of 1+erf(x) move to calling erfc(x). There is little to no perf regression expected from that as far as I can tell now that the implementation uses fast division and the measurements show that the loss of accuracy from that is acceptable within the range the polynomial approximation is used.

I'll approve and kick off the tests but I think we'll need @malfet to chime in on this as well.

@jansel jansel added the topic: not user facing topic category label Jul 11, 2026
@malfet

malfet commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Thank you for your contributions, looks good to me!

@malfet

malfet commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator

@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

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
Splits the MPS backend portion out of pytorch#189234 (pytorchgh-187806) per review.

## Problem

`c10::metal::erfc` is `1.0 - erf(x)`: once erf saturates in fp32 (x ~ 3.9), erfc returns 0.0, i.e. 100% relative error over the entire upper tail. Everything consuming it on MPS inherits the flush:

- eager `torch.erfc` / `torch.special.erfc`
- `igammac` (`torch.special.gammaincc`), whose large-a asymptotic path evaluates `0.5 * erfc(...)`
- the gelu cancellation fix in pytorch#189234, which rewrites `1 + erf(u)` as `erfc(-u)` and needs an accurate erfc to build on

## Fix

- Below erf's own branch threshold, keep `1 - erf(x)`: exact there.
- Above it: `erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a)` with `q = (a - 4)/(a + 4)`, p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via `2 - erfc(-x)`. The scaled-rational construction follows N. Juffa's vectorizable erfcf.
- Both quotients use `::metal::fast::divide` (per review): full-precision division made the branch compute-bound (gelu 1.3-1.7x slower on M2 Max, eager erfc 1.2-1.3x slower than erf on M5) and would tighten the max error only from ~5.6 to ~5.0 ulp.
- `"erfc"` joins the Inductor MPS codegen op set so torch.compile on MPS uses the same implementation.

## Verification (M5)

- erfc accuracy, exhaustive enumeration of all 2^32 fp32 inputs vs float64 over the fp32-normal output range: max 5.6 ulp (4.0e-7 relative) on M5, 5.1 ulp on M2 Max (fast-math division rounding is GPU-dependent). Before: 100% relative error past x ~ 3.9.
- Eager erfc runs at erf speed (was 1.2-1.3x slower with full-precision divides); Inductor output is bitwise identical to eager.
- `gammaincc(1200, x)`: tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.
- New eager MPS tail tests for erfc and igammac, plus an Inductor regression test (`test_mps_basic.py`, `test_erfc_tail_accuracy`) that fails if the codegen op-set entry is dropped and compiled erfc falls back to `1 - erf`.
- Specials and the clamp branch pinned exactly in both erfc tests: `erfc(0) = 1`, `erfc(+inf) = 0`, `erfc(-inf) = 2`, nan propagates, `erfc(+-10.5) = erfc(+-1e30) =` exactly `0`/`2`.

Base commit: 135435f.

Pull Request resolved: pytorch#189291
Approved by: https://github.com/jhavukainen, https://github.com/malfet
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
Splits the MPS backend portion out of pytorch#189234 (pytorchgh-187806) per review.

## Problem

`c10::metal::erfc` is `1.0 - erf(x)`: once erf saturates in fp32 (x ~ 3.9), erfc returns 0.0, i.e. 100% relative error over the entire upper tail. Everything consuming it on MPS inherits the flush:

- eager `torch.erfc` / `torch.special.erfc`
- `igammac` (`torch.special.gammaincc`), whose large-a asymptotic path evaluates `0.5 * erfc(...)`
- the gelu cancellation fix in pytorch#189234, which rewrites `1 + erf(u)` as `erfc(-u)` and needs an accurate erfc to build on

## Fix

- Below erf's own branch threshold, keep `1 - erf(x)`: exact there.
- Above it: `erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a)` with `q = (a - 4)/(a + 4)`, p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via `2 - erfc(-x)`. The scaled-rational construction follows N. Juffa's vectorizable erfcf.
- Both quotients use `::metal::fast::divide` (per review): full-precision division made the branch compute-bound (gelu 1.3-1.7x slower on M2 Max, eager erfc 1.2-1.3x slower than erf on M5) and would tighten the max error only from ~5.6 to ~5.0 ulp.
- `"erfc"` joins the Inductor MPS codegen op set so torch.compile on MPS uses the same implementation.

## Verification (M5)

- erfc accuracy, exhaustive enumeration of all 2^32 fp32 inputs vs float64 over the fp32-normal output range: max 5.6 ulp (4.0e-7 relative) on M5, 5.1 ulp on M2 Max (fast-math division rounding is GPU-dependent). Before: 100% relative error past x ~ 3.9.
- Eager erfc runs at erf speed (was 1.2-1.3x slower with full-precision divides); Inductor output is bitwise identical to eager.
- `gammaincc(1200, x)`: tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.
- New eager MPS tail tests for erfc and igammac, plus an Inductor regression test (`test_mps_basic.py`, `test_erfc_tail_accuracy`) that fails if the codegen op-set entry is dropped and compiled erfc falls back to `1 - erf`.
- Specials and the clamp branch pinned exactly in both erfc tests: `erfc(0) = 1`, `erfc(+inf) = 0`, `erfc(-inf) = 2`, nan propagates, `erfc(+-10.5) = erfc(+-1e30) =` exactly `0`/`2`.

Base commit: 135435f.

Pull Request resolved: pytorch#189291
Approved by: https://github.com/jhavukainen, https://github.com/malfet
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
Splits the MPS backend portion out of pytorch#189234 (pytorchgh-187806) per review.

## Problem

`c10::metal::erfc` is `1.0 - erf(x)`: once erf saturates in fp32 (x ~ 3.9), erfc returns 0.0, i.e. 100% relative error over the entire upper tail. Everything consuming it on MPS inherits the flush:

- eager `torch.erfc` / `torch.special.erfc`
- `igammac` (`torch.special.gammaincc`), whose large-a asymptotic path evaluates `0.5 * erfc(...)`
- the gelu cancellation fix in pytorch#189234, which rewrites `1 + erf(u)` as `erfc(-u)` and needs an accurate erfc to build on

## Fix

- Below erf's own branch threshold, keep `1 - erf(x)`: exact there.
- Above it: `erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a)` with `q = (a - 4)/(a + 4)`, p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via `2 - erfc(-x)`. The scaled-rational construction follows N. Juffa's vectorizable erfcf.
- Both quotients use `::metal::fast::divide` (per review): full-precision division made the branch compute-bound (gelu 1.3-1.7x slower on M2 Max, eager erfc 1.2-1.3x slower than erf on M5) and would tighten the max error only from ~5.6 to ~5.0 ulp.
- `"erfc"` joins the Inductor MPS codegen op set so torch.compile on MPS uses the same implementation.

## Verification (M5)

- erfc accuracy, exhaustive enumeration of all 2^32 fp32 inputs vs float64 over the fp32-normal output range: max 5.6 ulp (4.0e-7 relative) on M5, 5.1 ulp on M2 Max (fast-math division rounding is GPU-dependent). Before: 100% relative error past x ~ 3.9.
- Eager erfc runs at erf speed (was 1.2-1.3x slower with full-precision divides); Inductor output is bitwise identical to eager.
- `gammaincc(1200, x)`: tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.
- New eager MPS tail tests for erfc and igammac, plus an Inductor regression test (`test_mps_basic.py`, `test_erfc_tail_accuracy`) that fails if the codegen op-set entry is dropped and compiled erfc falls back to `1 - erf`.
- Specials and the clamp branch pinned exactly in both erfc tests: `erfc(0) = 1`, `erfc(+inf) = 0`, `erfc(-inf) = 2`, nan propagates, `erfc(+-10.5) = erfc(+-1e30) =` exactly `0`/`2`.

Base commit: 135435f.

Pull Request resolved: pytorch#189291
Approved by: https://github.com/jhavukainen, https://github.com/malfet
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Splits the MPS backend portion out of pytorch#189234 (pytorchgh-187806) per review.

## Problem

`c10::metal::erfc` is `1.0 - erf(x)`: once erf saturates in fp32 (x ~ 3.9), erfc returns 0.0, i.e. 100% relative error over the entire upper tail. Everything consuming it on MPS inherits the flush:

- eager `torch.erfc` / `torch.special.erfc`
- `igammac` (`torch.special.gammaincc`), whose large-a asymptotic path evaluates `0.5 * erfc(...)`
- the gelu cancellation fix in pytorch#189234, which rewrites `1 + erf(u)` as `erfc(-u)` and needs an accurate erfc to build on

## Fix

- Below erf's own branch threshold, keep `1 - erf(x)`: exact there.
- Above it: `erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a)` with `q = (a - 4)/(a + 4)`, p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via `2 - erfc(-x)`. The scaled-rational construction follows N. Juffa's vectorizable erfcf.
- Both quotients use `::metal::fast::divide` (per review): full-precision division made the branch compute-bound (gelu 1.3-1.7x slower on M2 Max, eager erfc 1.2-1.3x slower than erf on M5) and would tighten the max error only from ~5.6 to ~5.0 ulp.
- `"erfc"` joins the Inductor MPS codegen op set so torch.compile on MPS uses the same implementation.

## Verification (M5)

- erfc accuracy, exhaustive enumeration of all 2^32 fp32 inputs vs float64 over the fp32-normal output range: max 5.6 ulp (4.0e-7 relative) on M5, 5.1 ulp on M2 Max (fast-math division rounding is GPU-dependent). Before: 100% relative error past x ~ 3.9.
- Eager erfc runs at erf speed (was 1.2-1.3x slower with full-precision divides); Inductor output is bitwise identical to eager.
- `gammaincc(1200, x)`: tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.
- New eager MPS tail tests for erfc and igammac, plus an Inductor regression test (`test_mps_basic.py`, `test_erfc_tail_accuracy`) that fails if the codegen op-set entry is dropped and compiled erfc falls back to `1 - erf`.
- Specials and the clamp branch pinned exactly in both erfc tests: `erfc(0) = 1`, `erfc(+inf) = 0`, `erfc(-inf) = 2`, nan propagates, `erfc(+-10.5) = erfc(+-1e30) =` exactly `0`/`2`.

Base commit: 135435f.

Pull Request resolved: pytorch#189291
Approved by: https://github.com/jhavukainen, https://github.com/malfet
qflen added a commit to qflen/pytorch that referenced this pull request Nov 23, 2026
Normal.cdf and special.ndtr compute 0.5 * (1 + erf(z / sqrt(2))). In the
lower tail erf(...) approaches -1 and the addition cancels: fp32 returns
exactly 0 below z ~ -6 (fp64 below z ~ -9), and the relative error is
already large well before that. Any log or ratio of the result then
breaks. The fix uses the identity 1 + erf(u) = erfc(-u), which every
backend already implements accurately (MPS since pytorch#189291).

The C++ calc_ndtr, the _refs ndtr and Normal.cdf change together so eager
and torch.compile agree. Since the decomposed graphs now contain
aten.erfc instead of aten.erf, three small follow-ons keep compile and
export working: aten.erfc is tagged core (as aten.erf already is) so core
decompositions keep it instead of lowering it back to 1 - erf; Triton-CPU,
whose libdevice has no erfc, gets 1 - erf, which also turns the stale
xfail on test_erfc into a pass; and the TorchScript ONNX exporter gets an
aten::erfc symbolic, since ONNX has no Erfc op.

This was split out of pytorch#189234, which also rewrote exact gelu the same
way. That part was dropped because it made eager CPU gelu 2-3x slower to
fix outputs below 1e-7 in magnitude.

Test Plan:

```
python test/test_unary_ufuncs.py -v -k test_special_ndtr_tail_accuracy
python test/distributions/test_distributions.py -v -k test_normal_cdf_tail_accuracy
python test/inductor/test_torchinductor.py -k test_erfc
```

The code changes are unchanged from pytorch#189234, where the touched suites
passed on CPU/MPS and on an A40. The new ndtr test and this split were
not run locally.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests Merged module: inductor open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants