PyTorch MPS fix resolves NaN in complex exponential functions
A patch tackles NaN errors when computing complex exponentials on real axis inputs.
PyTorch has merged pull request #184749, addressing a critical numerical stability bug in complex exponential functions on Apple's Metal Performance Shaders (MPS) backend. The issue manifested as NaN values appearing in the imaginary part of complex exponential operations—specifically exp, expm1, exp2, sinh, and cosh—when the input's imaginary component was exactly zero (e.g., re + 0i). The root cause was the naive application of Euler's formula, which produced an inf * 0 multiplication, yielding NaN. This bug could silently corrupt gradients and calculations in machine learning models that rely on complex numbers, particularly on Apple Silicon hardware.
The fix also introduces a performance and precision improvement by replacing separate sin and cos calls with the fused precise::sincos function in trigonometric operations (as part of ongoing work in #184769). This optimization reduces redundant computation and improves accuracy for complex-valued tensors. The commit was approved by PyTorch maintainers Skylion007 and malfet, and is now part of the main trunk. Developers using complex numbers on MPS should update their PyTorch installation to avoid unexpected NaN errors and benefit from more robust arithmetic.
- Fixes NaN in imaginary part of complex exp, expm1, exp2, sinh, and cosh on MPS when input is on real axis (re + 0i)
- Root cause: naive Euler formula caused inf * 0 = NaN; fix uses proper handling of zero imaginary component
- Also collapses separate sin/cos calls into precise::sincos for improved accuracy and performance in trig functions
Why It Matters
Ensures stable complex number computations on Apple Silicon, preventing silent NaN corruption in models and simulations.