Skip to content

Fix 1+erf catastrophic cancellation in gelu, Normal.cdf, and ndtr - #189234

Closed
qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:187806-mps
Closed

qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:187806-mps

Conversation

@qflen

@qflen qflen commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #187806.

Builds on #189291 (accurate Metal erfc), now merged. This PR consumes that erfc; the shared Metal files that briefly lived in both PRs are dropped here after rebasing onto it.

Root cause

Exact gelu computed 0.5 * x * (1 + erf(x / sqrt(2))). For negative x, erf(...) approaches -1 and the addition cancels: fp32 is ~57% off at x = -5.5 and exactly 0.0 from x ~ -6 on (fp64 from x ~ -9). Normal.cdf and special.ndtr had the same pattern.

MPS had a second problem: c10::metal::erfc was itself defined as 1.0 - erf(x), so even a direct erfc rewrite would still cancel there.

Linux builds had a third: eager exact gelu short-circuits contiguous fp32/bf16/fp16 CPU tensors to oneDNN's eltwise_gelu_erf, which evaluates the same cancelling form internally (macOS has no oneDNN, so this one surfaced in CI).

Fix

Rewrite 1 + erf(u) as erfc(-u) everywhere: gelu forward, the cdf subterms of gelu backward and of the composite infinitely_differentiable_gelu_backward (pdf terms untouched), Normal.cdf, special_ndtr, and the _refs/_decomp twins so eager and torch.compile agree. CUDA and CPU-scalar just call their existing accurate erfc. Exact gelu no longer dispatches to oneDNN (forward and backward): it always uses the fixed ATen kernel, and the aarch64-only oneDNN tanh-gelu fast path stays.

Two backends needed a real erfc:

  • Metal: MPS gets its accurate c10::metal::erfc from Add an accurate Metal erfc for MPS (eager + inductor) #189291 (merged); this PR's MPS gelu consumes it.
  • CPU vectorized: SLEEF's u15 Vectorized::erfc() is 9.2x slower than erf() (eager gelu would be ~8x slower), so cpu/Gelu.h gains a branch-free vectorized_normal_cdf for float using a degree-10 fit of the same construction, shared by forward and backward. Double keeps full-precision Vectorized::erfc().

Compile/export plumbing and test expectations kept in sync:

  • mkldnn gelu fusion pattern (one node fewer, test count updated) and the CPP GEMM gelu epilogue
  • CUTLASS EVT matcher folds the erfc-form gelu back into the native gelu functor (the old matcher only knew 1 + erf, so gelu would have silently stopped re-fusing on the CUTLASS backend); its trigger guards match word boundaries so an erfc epilogue cannot suppress unrelated folds; pattern tests in test_cutlass_evt.py
  • 1 - erf emission for Triton-CPU (its libdevice lacks erfc), which also un-xfails test_erfc there. Known gap: 1 - erf still cancels, so erfc and the decomposed gelu/ndtr tails stay inaccurate under torch.compile on Triton-CPU (comment at the emission site). Triton-CPU has no erfc symbol at our pin or on its current main, so no accurate emission exists today
  • aten.erfc tagged core so decomposed ndtr/cdf stay core-IR valid
  • TS ONNX aten::erfc symbolic so Normal.cdf still exports with dynamo=False
  • tests that hardcoded the old decomposition shape (checkpointing op counts, pattern-matcher targets, provenance-tracing mappings)
  • BertForMaskedLM joins the flaky list in check_accuracy.py, scoped to huggingface training: its scalar-loss-vs-fp64 check is noise-marginal on A10G (the ~1e-7 gelu shift tipped it 2.9% over the 3x band, then it passed a rerun of identical numerics; an A40 passes with 5x margin)

Deliberately excluded from the 1 +/- erf sweep:

  • quantized qgelu (quant grid dominates the tail)
  • oneDNN where it is the only executor: opaque mkldnn-layout tensors and fused post-op epilogues (third_party-internal, they keep the flushed tail)
  • legacy NNC lowering (off by default)
  • the exported ONNX gelu graph (no Erfc op in ONNX)
  • trunc_normal_ (float64 math near zero)
  • log_ndtr (already erfcx-based)
  • gelu_double_backward (pdf terms only)
  • XPU (out of tree)

Verification

fp32 CPU shown; MPS matches to the last digit; reference is float64 via the cancellation-free identity:

x gelu before gelu after float64 reference
-10.0 -0.000000e+00 -7.619854e-23 -7.619853e-23
-8.0 -0.000000e+00 -4.976774e-15 -4.976768e-15
-6.0 -0.000000e+00 -5.919536e-09 -5.919526e-09
-5.5 -1.639128e-07 -1.044427e-07 -1.044426e-07
-5.0 -1.490116e-06 -1.433258e-06 -1.433258e-06
-2.0 -4.550010e-02 -4.550027e-02 -4.550026e-02
3.0 2.995950e+00 2.995950e+00 2.995950e+00

Normal(0,1).cdf(-10): 0.0 before, 7.619854e-24 after (reference 7.619853e-24). Positive side unchanged.

infinitely_differentiable_gelu_backward (public composite with the same cdf subterm, review find): its tail was up to 2.8e-2 relative off in fp32 and 1.0e-2 in fp64 (the cdf subterm flushed; the pdf term dominates there, so percent-level rather than 100%). Now 4.6e-8 (CPU) / 2.0e-7 (MPS) / 1.3e-7 (CUDA) in fp32 and exact in fp64, asserted by the extended test_gelu_tail_accuracy backward case.

CUDA (A40, sm86, source build of this PR): same fix, measured directly. Before, the fp32 tail flushed identically (gelu(-6/-8/-10) = -0.0, ndtr(-10) = 0.0); after: gelu = -5.919536e-09 / -4.976774e-15 / -7.619853e-23 and ndtr(-10) = 7.619853e-24, matching the references above. Dense sweeps on CUDA (eager + compiled): gelu/cdf/ndtr max 1.03e-5, erfc max 3.1e-7, specials preserved.

Linux x86 (oneDNN build): the previously-dispatched path flushed the same way; with the dispatch fix the same probe matches the references and the CPU test_gelu_tail_accuracy cases pass on an mkldnn-enabled build.

Dense sweeps vs float64 (2M-point erfc, op sweeps over [-12, 12], CPU + MPS, eager + compiled): erfc max 3.5e-7 relative over the fp32-normal range; gelu/cdf/ndtr max ~1.04e-5, which is the inherent fp32 rounding of x / sqrt(2) and identical across backends. Specials preserved (erfc(0) = 1, inf/nan, gelu(0) = 0).

New device-generic tests (CPU/CUDA/MPS): test_nn.py::test_gelu_tail_accuracy (fwd + bwd, both backward entry points) and test_distributions.py::test_normal_cdf_tail_accuracy. Four CUTLASS EVT pattern tests in test_cutlass_evt.py (erfc-form gelu folds, legacy 1 + erf still folds, standalone erfc bails cleanly, word-boundary trigger) run without a GPU; end-to-end EVT fusion is exercised by the existing sm90 CI job. Local suites green on CPU and MPS (nn, mps consistency, decomp, ops, unary_ufuncs, distributions, inductor); the touched suites (ops, checkpointing decomps, pattern matcher, provenance tracing, mkldnn, inductor gelu/erfc) are also green on the A40/Linux build; lintrunner clean on all changed files.

Performance (M5, eager, fp32)

op n before after ratio
gelu fwd 2^20 1.29 ms 2.56 ms 1.98x
gelu bwd 2^20 2.60 ms 3.96 ms 1.52x
gelu fwd / bwd (CUDA, A40) 2^24 251.7 / 369.4 us 251.6 / 367.5 us 1.00x

2^20 runs are launch-bound and wobble within a few percent in both directions on that host.

The accurate tail costs one exp plus a polynomial where a bare erf sufficed; the naive Vectorized::erfc() route would have been 7.8x. MPS is noise-level at bandwidth sizes (+2.7% fwd / -1.5% bwd at 2^24). Double gelu keeps SLEEF's erfc and gets slower; correctness over speed for fp64.

Linux eager fp32 moves off oneDNN (the dispatch fix): at 2^22, fwd is ~2.35x vs the oneDNN path (fp32 and bf16 alike); small sizes get faster (2^16: 157 us -> 18 us, no oneDNN thread-pool spinup); fwd+bwd did not regress on that host. Indicative numbers from a CPU-quota-bound shared Xeon.

Benchmark script
import torch
import torch.utils.benchmark as tb

for dev in ["cpu", "mps"]:
    if dev == "mps" and not torch.backends.mps.is_available():
        continue
    sync = "; torch.mps.synchronize()" if dev == "mps" else ""
    for n in (1 << 20, 1 << 24):
        x = torch.randn(n, device=dev)
        g = torch.ones_like(x)
        for name, stmt in [
            ("gelu_fwd", f"torch.nn.functional.gelu(x){sync}"),
            ("gelu_bwd", f"torch.ops.aten.gelu_backward(g, x){sync}"),
            ("erfc", f"torch.special.erfc(x){sync}"),
        ]:
            m = tb.Timer(stmt, globals={"torch": torch, "x": x, "g": g}).blocked_autorange(min_run_time=1.0)
            print(f"{dev} n=2^{n.bit_length() - 1} {name}: {m.median * 1e6:9.1f} us")

Residual risk:

  • Opaque mkldnn-layout tensors and oneDNN fused post-op epilogues still evaluate gelu inside oneDNN and keep the flushed tail; fixing those needs an upstream oneDNN change.
  • torch.compile with the Triton-CPU backend keeps the flushed tails (triton-cpu's libdevice has no erfc, so 1 - erf is emitted there); eager CPU is fixed independently of it. The emission special case can be dropped once triton-cpu gains erfc.
  • BertForMaskedLM's training-accuracy status on A10G sits at the edge of its noise band and is now tolerated in both directions (huggingface training suite only).

Base commit: 7216f00 (upstream main, 2026-09-05); rebased over the NVGEMM epilogue refactor (#190821, #191515), which changed the CUTLASS EVT return type. The new EVT tests read the returned plan's fields like the existing tests now do.

@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/189234

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

⚠️ 5 Awaiting Approval

As of commit 167ef11 with merge base 0077244 (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests module: cpu CPU specific problem (e.g., perf, algorithm) module: dynamo module: inductor release notes: mps Release notes category labels Jul 8, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.

@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/mps
  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

2 similar comments
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/mps
  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/mps
  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@qflen
qflen force-pushed the 187806-mps branch 2 times, most recently from e30d7f7 to 86f5e26 Compare July 8, 2026 11:56
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this

@claude

claude Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 9m 7s —— View job


PR Review: #189234

Summary: Rewrites 1 + erf(u) as erfc(-u) across gelu/Normal.cdf/ndtr in eager, refs, decomp, and codegen, and adds an accurate branch-based erfc for Metal and a branch-free float erfc for the CPU vector path. The numerical core is well-constructed, but the 1 + erf sweep missed one live kernel, and the new erfc decomposition silently breaks a CUTLASS fusion pass.

Full review

Correctness / Completeness

infinitely_differentiable_gelu_backward still uses 1.0 + erf (aten/src/ATen/native/Activation.cpp:748). This is the same catastrophic-cancellation pattern the PR is fixing:

Tensor cdf = (1.0 + (self_ * M_SQRT1_2).erf_()).mul_(0.5);

It is a live, public aten op (native_functions.yaml:5191, vmap-registered, and exercised by test/inductor/test_torchinductor.py:7944), and it computes the CDF term exactly like the paths that were fixed — so its negative tail still flushes to zero. It is not in the PR's "deliberately excluded" list (that list only names gelu_double_backward, which is pdf-only). Either fix it to erfc(-self_ * M_SQRT1_2).mul_(0.5) or add it to the exclusions with a justification. Fix this →

Performance / Optimization regressions

The CUTLASS EVT gelu fusion no longer matches, and the erf/erfc substring collision can suppress unrelated folds (torch/_inductor/codegen/cutlass/python_evt.py). _match_gelu_erf matches only the old x * 0.5 * (1 + erf(x/sqrt(2))) structure (:59-100), but Inductor's gelu now decomposes to erfc, so gelu will never re-fuse into the CUTLASS functor epilogue — a silent perf regression for gelu on the CUTLASS backend. Worse, the trigger string is "erf" (:164), which is a substring of "erfc":

  • active = [p for p in ... if p.trigger in code] (:180) now flags the gelu pattern active for any epilogue containing erfc.
  • The post-fold validation for p in active: if p.trigger in folded: return code (:280-282) then sees "erf" in "...erfc..." as true and discards the folded result, so a kernel that contains an erfc plus a genuinely-foldable silu will bail out and lose the silu fusion too.

At minimum, either update _match_gelu_erf to the erfc form and make the trigger match on word boundaries (e.g. "erf(" / "erfc("), or exclude gelu from this matcher and note it. This isn't covered by any updated test in the PR.

Testing

Triton-CPU tail accuracy is silently unverified. triton.py:2043-2045 emits (1.0 - libdevice.erf(x)) for CPU, which reintroduces the exact cancellation this PR fixes — so gelu/ndtr/Normal.cdf tails remain wrong on the Triton-CPU backend. Removing @xfail_if_triton_cpu from test_erfc (test/inductor/test_torchinductor.py:14905) only checks erfc on a generic input, not the tail. This is an acceptable limitation given libdevice has no erfc, but it should be called out as a known gap (the PR text lists Triton-CPU as plumbing "kept in sync," which understates that the accuracy fix does not hold there), and ideally the new tail-accuracy tests should be xfailed/skipped rather than silently passing on that backend.

Minor

  • ONNX erfc symbolic (symbolic_opset9.py:4910-4914) lowers to 1 - erf, so Normal.cdf exported via the TS exporter still cancels in the tail. This is unavoidable (ONNX has no Erfc) and is no worse than before, but a one-line comment noting the exported graph retains the tail inaccuracy would prevent a future reader from assuming the fix carries into ONNX.
  • erfc tagged core but erf is not (native_functions.yaml:2524). This is defensible (core decompositions now emit erfc, not erf), but the asymmetry is worth a brief comment or PR note so it doesn't read as accidental.
  • Scalar vs. vector divergence in CPU gelu: scalar_gelu uses accurate std::erfc while vectorized_normal_cdf uses the ~5-ulp polynomial, so tail (remainder) elements and vector-lane elements of the same tensor take different-accuracy paths. Within tolerance and standard for cpu_kernel_vec, but worth confirming the OpInfo tolerances cover the polynomial path rather than only the scalar one.

Recommendation

Request Changes — the infinitely_differentiable_gelu_backward miss leaves a live gelu-CDF path with the exact bug being fixed, and the CUTLASS EVT matcher change is an untested, latent fusion regression. Both should be addressed (or explicitly excluded with justification) before merge. The core numerical work (Metal/CPU erfc, decomp/refs sync, test coverage for the fixed paths) looks solid.
· branch 187806-mps

@jhavukainen

Copy link
Copy Markdown
Collaborator

Thanks for the PR @qflen. On the MPS part I agree with the premise that we should go for the erfc implementation to get rid of the cancellation issue. I'm happy to test and review that portion but I would like it to be split into a separate PR focused on the code relevant to the MPS backend before doing that.

On the other hand I see the point that the other backends hit the same issue. So if the maintainers rather have the changes in single PR and review it as an entity I'll defer to them

@janeyx99
janeyx99 requested a review from lakshayg July 8, 2026 17:46
@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
@qflen

qflen commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Review points done:

  • infinitely_differentiable_gelu_backward:
    cdf subterm rewritten via erfc. fp32 tail error 2.8e-2 -> 4.6e-8 (CPU) / 2.0e-7 (MPS) / 1.3e-7 (CUDA A40); fp64 exact. Now covered by test_gelu_tail_accuracy backward at the 5e-5 bound. gelu_double_backward excluded: pdf-only, no cdf term.
  • CUTLASS EVT:
    matcher folds the erfc-form gelu (legacy 1 + erf still folds); CutlassEVTOpsMixIn gained erfc; trigger guards are now word-boundary regexes, not substring. Four GPU-free pattern tests in test_cutlass_evt.py; e2e fusion stays covered by the sm90 job.
  • Triton-CPU:
    no erfc symbol at our pin or on current main, so unfixable from PyTorch today. Noted at the emission site and in the PR body. Tail tests not xfailed: they never execute through this backend, so an xfail would assert nothing.
  • ONNX symbolic:
    exported graphs keep the erf-form tail (no Erfc in ONNX); comment added.
  • erfc core tag:
    core decompositions now emit erfc. Tag-only change on an existing op in native_functions.yaml, no schema change, so no FC window.
  • Scalar vs vector paths:
    tail-test tensor is 1536 contiguous elements (multiple of every Vectorized<float> width), so the polynomial path hits all lanes at 5e-5; OpInfo gelu samples (10×10) vectorize 96/100

@jhavukainen I can split the MPS portion out and link it.

Edit:
MPS portion split out: #189291.

Note I kept the two erfc files appear in both until that one lands.

@qflen
qflen marked this pull request as draft July 8, 2026 19:15
pytorchmergebot pushed a commit that referenced this pull request Jul 12, 2026
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:

- eager `torch.erfc` / `torch.special.erfc`
- `igammac` (`torch.special.gammaincc`), whose large-a asymptotic path evaluates `0.5 * erfc(...)`
- the gelu cancellation fix in #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: #189291
Approved by: https://github.com/jhavukainen, https://github.com/malfet
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
laifenxiawucha pushed a commit to intel/torch-xpu-ops that referenced this pull request Aug 25, 2026
Exact GELU computed the normal CDF term as 0.5 * (1 + erf(x / sqrt(2))).
For large negative x, erf(x / sqrt(2)) -> -1 and the "1 + erf" form
cancels catastrophically in fp32, flushing gelu to exactly 0.0 from
x ~ -6 on. Rewrite the CDF term in both GeluErfFunctor and
GeluErfBackwardFunctor as the cancellation-free 0.5 * erfc(-x / sqrt(2)),
aligning XPU with the upstream CPU/CUDA/MPS fix in pytorch/pytorch#189234.
Add a tail-accuracy regression test.

Fixes #4753
laifenxiawucha pushed a commit to intel/torch-xpu-ops that referenced this pull request Aug 31, 2026
Exact GELU computed the normal CDF term as 0.5 * (1 + erf(x / sqrt(2))).
For large negative x, erf(x / sqrt(2)) -> -1 and the "1 + erf" form
cancels catastrophically in fp32, flushing gelu to exactly 0.0 from
x ~ -6 on. Rewrite the CDF term in both GeluErfFunctor and
GeluErfBackwardFunctor as the cancellation-free 0.5 * erfc(-x / sqrt(2)),
aligning XPU with the upstream CPU/CUDA/MPS fix in pytorch/pytorch#189234.
Add a tail-accuracy regression test.

Fixes #4753
laifenxiawucha pushed a commit to intel/torch-xpu-ops that referenced this pull request Sep 2, 2026
Exact GELU computed the normal CDF term as 0.5 * (1 + erf(x / sqrt(2))).
For large negative x, erf(x / sqrt(2)) -> -1 and the "1 + erf" form
cancels catastrophically in fp32, flushing gelu to exactly 0.0 from
x ~ -6 on. Rewrite the CDF term in both GeluErfFunctor and
GeluErfBackwardFunctor as the cancellation-free 0.5 * erfc(-x / sqrt(2)),
aligning XPU with the upstream CPU/CUDA/MPS fix in pytorch/pytorch#189234.
Add a tail-accuracy regression test.

Fixes #4753
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Nov 9, 2026
## Description

Fixes #5700

The exact (`approximate="none"`) gelu forward and backward lowerings computed the normal CDF as `0.5 * (1 + erf(x / sqrt(2)))`. For negative `x`, `erf(x / sqrt(2))` is close to -1 and the sum cancels: in float32 the result is 0 from about `x = -6`, and the relative error is large well before that.

This change computes the CDF as `0.5 * erfc(-x / sqrt(2))`, which is the same value without the cancellation. JAX uses the same form (`jax.nn.gelu(approximate=False)`). XLA's `chlo.erfc` uses a dedicated approximation for `|x| >= 1`, so it does not reintroduce `1 - erf`. The tanh approximation is unchanged.

Note: PyTorch's own CPU gelu still uses `1 + erf` (pytorch/pytorch#187806, fix proposed in pytorch/pytorch#189234), so in the far negative tail TorchTPU is now more accurate than the CPU reference. The new test therefore compares against a float64 `erfc` reference, not against CPU `F.gelu`.

## Test Plan

Added `OpsUnitTest.test_gelu_exact_negative_tail_precision_float32`: float32 gelu and `gelu_backward` for `x` in [-9, -3], compared with a float64 `erfc` reference (`rtol=1e-4`).

TPU v5e-1 (Colab), Python 3.13, torch 2.14.1+cpu, libtpu 0.0.50. Built the wheel with `ci/build_wheels.sh` at ca656f7 without and with this change (`csrc/ops/gelu/` is identical at ca656f7 and current `main`), and ran:

- `tests/ops_unit_test.py OpsUnitTest.test_gelu_exact_negative_tail_precision_float32 --test_mode=torch_tpu_vs_cpu` (the flag is needed at ca656f7, not after 319a782): fails without the change, passes with it.
- `tests/ops_test.py TestOps.test_nn_functional_gelu`, with the golden files from `tests/goldens.pin`: passes without and with the change.

float32 error on TPU against a float64 reference, before -> after:

| inputs | output, max rel. error | output, max ULP | gradient, max rel. error |
|---|---|---|---|
| `x` in [-9, -3] (601 points) | 1.88 -> 9.0e-6 | 16,772,148 -> 129 | 0.055 -> 7.6e-6 |
| 1M samples of N(0, 1) | 0.022 -> 4.7e-6 | 363,376 -> 65 | unchanged |

(The gradient's relative error on N(0, 1) inputs is dominated by its zero crossing near `x = -0.75` and is the same before and after.)

`nox -s lint` passes.

### After review (171633d)

TPU v5e-1 (Colab), Python 3.13, torch 2.14.1+cpu, wheel built at main 34d73a1 with this change: `OpsUnitTest.test_gelu_exact_negative_tail_precision_float32` and `TestOps.test_nn_functional_gelu` pass. float32 max rel. error against a float64 reference for `x` in [-9, -3]: output 9.0e-6, gradient 7.6e-6 (unchanged from above).

Closes #5714

Generated from cl/1017436524

COPYBARA_INTEGRATE_REVIEW=#5714 from ParitKansal:fix-gelu-erfc-5700 95f98b9
PiperOrigin-RevId: 1017436524
@egeboy35

Copy link
Copy Markdown
Contributor

@qflen I've been looking into float16 GELU performance and tested your CPU changes on my Intel laptop.

I was able to reproduce the accuracy fix. I've included benchmarks across different sizes and thread counts below. I also tried a small optimization on top of your changes and wanted to get your thoughts on whether it would make sense as a follow-up.

Drafted by Claude (AI) for @egeboy35.

Sharing an independent CPU data point: i7-11800H (AVX512 dispatch), WSL2, main at 30c5b5d with oneDNN on (default), plus only this PR's eager CPU gelu changes (native/Activation.cpp dispatch hunks, cpu/Activation.cpp, cpu/Gelu.h).

The tail fix reproduces (x in [-10, -3]: fp32 forward max relative error 1.0 on main, 5.3e-6 with the PR; bf16/fp16 correctly rounded).

The description already reports about 2.35x forward against oneDNN at 2^22. PR/main time ratio by size and threads (exact gelu, min over 5-6 interleaved rounds, one physical core per thread):

size threads fp32 fwd fp32 bwd bf16 fwd bf16 bwd fp16 fwd fp16 bwd
4096 1 0.70 0.52 0.71 0.52 1.25 1.11
2^16 1 2.64 1.55 2.20 1.46 1.39 1.25
2^16 4 1.47 1.70 1.40 1.77 1.30 1.22
2^20 1 3.15 1.96 2.56 1.74 1.42 1.26
2^20 4 2.99 1.85 2.52 1.71 1.39 1.25
8x197x3072 1 1.82 1.66 2.47 1.70 1.38 1.22
8x197x3072 4 1.32 1.18 2.58 1.91 1.40 1.21

fp16 never used oneDNN here, so its column is the native kernel change alone. At 8x197x3072 (4.8M elements; noisier) the fp32 ratio is lower, likely because main's fp32 path is memory-bound there (main bf16 beats it). The description's 157 us at 2^16 did not show up (main fp32 forward 19 us at 1 thread, 10 us at 4). With the PR at 2^20, bf16 is 7-11% slower than fp32.

A Half/BFloat16-only prototype on this PR (exp_u20 in vectorized_normal_cdf; the backward reuses that exp for the pdf term) cuts fp16 fwd/bwd time to 0.85x/0.61x of the PR, bf16 to 0.86x/0.65x (2^20, 1 thread). With AVX512 dispatch its forward matches the PR bitwise for every fp16/bf16 input (NaN sign bits aside), and the backward differs by at most 1 ulp in a few elements (153 of 1M random fp16). AVX2 was checked only by error statistics, NEON/SVE not at all. Would that be welcome as a follow-up once this lands?

Exact gelu computes 0.5*x*(1 + erf(x/sqrt(2))). For negative x the
addition cancels: fp32 is ~57% off near x = -5.5 and returns exactly 0
from x ~ -6 (fp64 from x ~ -9). Normal.cdf and special.ndtr share the
pattern, and Linux CPU builds hit it a second time inside oneDNN's
eltwise_gelu_erf, which exact gelu was routed to.

The fix substitutes 1 + erf(u) = erfc(-u) at every site: gelu forward,
the cdf terms of gelu_backward and infinitely_differentiable_gelu_backward,
Normal.cdf, special_ndtr, and the _refs/_decomp versions so eager and
torch.compile agree. CUDA and CPU-scalar call their existing erfc, MPS
uses the accurate c10::metal::erfc from pytorch#189291. Exact gelu no longer
dispatches to oneDNN; the aarch64 oneDNN tanh-gelu path is unchanged.

For the CPU float vector path, SLEEF's Vectorized<float>::erfc() is 9.2x
slower than erf() and made eager gelu ~8x slower, so cpu/Gelu.h gains a
branch-free vectorized_normal_cdf (one exp plus a degree-10 fit) shared
by forward and backward. Double keeps SLEEF's erfc.

Because aten.erfc now replaces aten.erf in decomposed graphs, the rest
of the diff keeps compile and export working: mkldnn gelu fusion
pattern, CPP GEMM gelu epilogue, the CUTLASS EVT matcher (folds the
erfc form back into the native gelu functor, word-boundary triggers),
1 - erf emission for Triton-CPU (no libdevice erfc there, so its
compiled tails stay inaccurate), aten.erfc tagged core, a TorchScript
ONNX aten::erfc symbolic, and tests that hardcoded the old decomposition.
BertForMaskedLM joins the huggingface-training flaky list: its
loss-vs-fp64 check lands 2.9% outside the band on A10G and passes with
5x margin on A40.

Not changed: qgelu, oneDNN-only paths (mkldnn-layout tensors, fused
post-ops), NNC, the exported ONNX gelu graph, trunc_normal_, log_ndtr,
gelu_double_backward, XPU, and tanh-approximate gelu.

Review order: cpu/Gelu.h (the numerics), then the kernel call sites and
the oneDNN dispatch removal in Activation.cpp, then the composites
(calc_ndtr, normal.py, _refs, _decomp), then the inductor/ONNX plumbing,
then the tests.

Test Plan:

Run on the pre-rebase head (CPU/MPS on M5; CUDA and Linux x86 oneDNN
build on an A40), all green:

```
python test/test_nn.py -v -k test_gelu_tail_accuracy
python test/distributions/test_distributions.py -v -k test_normal_cdf_tail_accuracy
python test/test_mps.py -k gelu
python test/test_decomp.py -k gelu
python test/test_ops.py -k gelu
python test/test_mkldnn.py -v -k gelu
python test/dynamo/test_activation_checkpointing.py -k test_tags_decomps
python test/inductor/test_pattern_matcher.py -k get_decomp_fn
python test/inductor/test_provenance_tracing.py
python test/inductor/test_torchinductor.py -k gelu
python test/inductor/test_cutlass_evt.py
```

Rebasing onto upstream/main needed only mechanical conflict resolution
(the oneDNN API rename from pytorch#205709, c10::frac_sqrt_2 from pytorch#200676) and
dropping the TorchScript ONNX test, whose file pytorch#203621 deleted. The
rebased tree was not rebuilt locally; CI covers it.
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.
@qflen

qflen commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Closing this. The gelu rewrite makes eager CPU gelu 2-3x slower (and compiled CPU gelu likely more) to fix outputs below 1e-7 in magnitude, which isn't a good trade for one of the most common activations. The part where the tail actually matters, Normal.cdf and special.ndtr, will go in its own small PR.

@egeboy35 thanks for the independent benchmarks, they made the cost clear.

@qflen qflen closed this Nov 23, 2026
torchxpubot pushed a commit to intel/torch-xpu-ops that referenced this pull request Nov 30, 2026
Exact GELU computed the normal CDF term as 0.5 * (1 + erf(x / sqrt(2))).
For large negative x, erf(x / sqrt(2)) -> -1 and the "1 + erf" form
cancels catastrophically in fp32, flushing gelu to exactly 0.0 from
x ~ -6 on. Rewrite the CDF term in both GeluErfFunctor and
GeluErfBackwardFunctor as the cancellation-free 0.5 * erfc(-x / sqrt(2)),
aligning XPU with the upstream CPU/CUDA/MPS fix in pytorch/pytorch#189234.
Add a tail-accuracy regression test.

Fixes #4753
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 module: cpu CPU specific problem (e.g., perf, algorithm) module: dynamo module: inductor open source release notes: mps Release notes 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.

F.gelu(approximate='none'): 1+erf catastrophic cancellation — up to 57% relative error in fp32 around x≈−5, zeros the negative tail

8 participants