Repository navigation
Conversation
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.
🔗 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 FailuresAs of commit 625197b with merge base 135435f ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
@claude review these changes |
|
Claude finished @jansel's task in 5m 27s —— View job PR Review: #189291SummaryReplaces the flush-to-zero Detailed reviewTesting
Code Quality
API Design / Consistency
Correctness (verified, no action needed)
RecommendationApprove — solid, well-documented numerics fix with CI green. Suggest confirming special-value ( |
|
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. |
|
Ok so some findings here so far: Yes the two divisions are significant. At least on some hardware. On M2 Max old 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. |
There was a problem hiding this comment.
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.
|
For completeness the runtimes I saw on M2 Max using |
|
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.
|
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:
One extra data point: |
|
Also added the compiled-path tail test. It and the eager test now pin the specials and the clamp branch exactly The second suggestion is applied through a |
jhavukainen
left a comment
There was a problem hiding this comment.
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.
|
Thank you for your contributions, looks good to me! |
|
@pytorchbot merge -f "Lint + MPS are green" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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
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.
Splits the MPS backend portion out of #189234 (gh-187806) per review.
Problem
c10::metal::erfcis1.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:torch.erfc/torch.special.erfcigammac(torch.special.gammaincc), whose large-a asymptotic path evaluates0.5 * erfc(...)1 + erf(u)aserfc(-u)and needs an accurate erfc to build onFix
1 - erf(x): exact there.erfc(a) = (1 + p(q)) / (1 + 2a) * exp(-a * a)withq = (a - 4)/(a + 4), p a degree-9 Remez fit against 60-digit mpmath references, and the squared exp argument fma-compensated. Negative x via2 - erfc(-x). The scaled-rational construction follows N. Juffa's vectorizable erfcf.::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)
gammaincc(1200, x): tracks float64 to ~7e-5 relative down to values of 1e-33. Before: flushed to zero below ~1e-8.test_mps_basic.py,test_erfc_tail_accuracy) that fails if the codegen op-set entry is dropped and compiled erfc falls back to1 - erf.erfc(0) = 1,erfc(+inf) = 0,erfc(-inf) = 2, nan propagates,erfc(+-10.5) = erfc(+-1e30) =exactly0/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