Skip to content
fn

complex_abs_forward

int complex_abs_forward(const int & a)

Autograd node for the element-wise absolute value y=∣x∣y = |x|.

Saves the input x so the backward pass can recover sign(x)\mathrm{sign}(x) and scale the upstream gradient by it. The derivative is undefined at x=0x = 0; the implementation follows the reference framework's convention of returning 00 there (sub-gradient).

Math

\frac{\partial y}{\partial x} = \mathrm{sign}(x), \qquad \frac{\partial \mathcal{L}}{\partial x} = \mathrm{sign}(x)\,\frac{\partial \mathcal{L}}{\partial y}.$$

Notes

Dispatch: Accelerate vDSP_vabs (CPU) / MLX abs (GPU). Backward for abs of a complex input.

The forward is a composite (scale, divide, square, sqrt) chosen to be overflow-safe, and its derivative cannot be, at exactly zero: the divide's own backward forms -re / m^2, and the clamped m is FLT_MIN, whose square underflows to zero in float32. 0 / 0 is NaN, so abs(fft2(x)) came back all-NaN whenever one coefficient of the transform was zero — which for most real inputs, one is.

Raising the clamp is not available: the trailing multiply uses the unclamped magnitude, so a floor above |z| would silently wreck genuinely tiny inputs. The derivative is exact and simple enough to state directly instead:

d|z| / dz = z / |z|, and 0 at z = 0

which is the subgradient the reference reports there.