Repository navigation
Conversation
🔗 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.
|
Attention! native_functions.yaml was changedIf 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. |
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
e30d7f7 to
86f5e26
Compare
|
@claude review this |
|
Claude finished @Skylion007's task in 9m 7s —— View job PR Review: #189234Summary: Rewrites Full reviewCorrectness / Completeness
Tensor cdf = (1.0 + (self_ * M_SQRT1_2).erf_()).mul_(0.5);It is a live, public aten op ( Performance / Optimization regressionsThe CUTLASS EVT gelu fusion no longer matches, and the
At minimum, either update TestingTriton-CPU tail accuracy is silently unverified. Minor
RecommendationRequest Changes — the |
|
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 |
|
Review points done:
@jhavukainen I can split the MPS portion out and link it. Edit: Note I kept the two erfc files appear in both until that one lands. |
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
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
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
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
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
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
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
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
## 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
|
@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.
|
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.
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.
|
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, @egeboy35 thanks for the independent benchmarks, they made the cost clear. |
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
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.cdfandspecial.ndtrhad the same pattern.MPS had a second problem:
c10::metal::erfcwas itself defined as1.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)aserfc(-u)everywhere: gelu forward, the cdf subterms of gelu backward and of the compositeinfinitely_differentiable_gelu_backward(pdf terms untouched),Normal.cdf,special_ndtr, and the_refs/_decomptwins 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:
c10::metal::erfcfrom Add an accurate Metal erfc for MPS (eager + inductor) #189291 (merged); this PR's MPS gelu consumes it.Vectorized::erfc()is 9.2x slower thanerf()(eager gelu would be ~8x slower), socpu/Gelu.hgains a branch-freevectorized_normal_cdffor float using a degree-10 fit of the same construction, shared by forward and backward. Double keeps full-precisionVectorized::erfc().Compile/export plumbing and test expectations kept in sync:
gelufunctor (the old matcher only knew1 + erf, so gelu would have silently stopped re-fusing on the CUTLASS backend); its trigger guards match word boundaries so anerfcepilogue cannot suppress unrelated folds; pattern tests intest_cutlass_evt.py1 - erfemission for Triton-CPU (its libdevice lacks erfc), which also un-xfailstest_erfcthere. Known gap:1 - erfstill 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 todayaten.erfctaggedcoreso decomposed ndtr/cdf stay core-IR validaten::erfcsymbolic soNormal.cdfstill exports withdynamo=Falsecheck_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 +/- erfsweep:trunc_normal_(float64 math near zero)log_ndtr(already erfcx-based)gelu_double_backward(pdf terms only)Verification
fp32 CPU shown; MPS matches to the last digit; reference is float64 via the cancellation-free identity:
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 extendedtest_gelu_tail_accuracybackward 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-23andndtr(-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_accuracycases 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) andtest_distributions.py::test_normal_cdf_tail_accuracy. Four CUTLASS EVT pattern tests intest_cutlass_evt.py(erfc-form gelu folds, legacy1 + erfstill 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;lintrunnerclean on all changed files.Performance (M5, eager, fp32)
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
Residual risk:
1 - erfis emitted there); eager CPU is fixed independently of it. The emission special case can be dropped once triton-cpu gains erfc.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.