jax icon indicating copy to clipboard operation
jax copied to clipboard

`jax.hessian` returns `nan` for a finite `float16` scalar example involving `atan2(x, x)`

Open shadow-orange41 opened this issue 6 months ago • 3 comments

Description

I found a small float16 example where jax.hessian returns nan, while the same mathematical function gives a finite second derivative in both PyTorch and TensorFlow.

Minimal reproducer

import torch
import jax.numpy as jnp
import jax
import tensorflow as tf

def f_j(x):
    c16 = jnp.array(1.0, dtype=jnp.float16)
    s0 = (x / jnp.atan2(x, x)) / 2.0
    return c16 / s0

def f_t(x):
    c16 = torch.tensor(1.0, dtype=torch.float16)
    s0 = (x / torch.atan2(x, x)) / 2.0
    return c16 / s0

def f_tf(x):
    c16 = tf.constant(1.0, dtype=tf.float16)
    s0 = (x / tf.atan2(x, x)) / 2.0
    return c16 / s0

def hessian_tf_scalar(f, x):
    x = tf.Variable(x, dtype=tf.float16)
    with tf.GradientTape() as tape2:
        with tf.GradientTape() as tape1:
            y = f(x)
        dy_dx = tape1.gradient(y, x)
    return tape2.gradient(dy_dx, x)

x0 = -0.12

xj = jnp.array(x0, dtype=jnp.float16)
xt = torch.tensor(x0, dtype=torch.float16, requires_grad=True)
xtf = tf.constant(x0, dtype=tf.float16)

print("Jax: ", jax.hessian(f_j)(xj))
print("Pytorch: ", torch.autograd.functional.hessian(f_t, xt))
print("Tensorflow: ", hessian_tf_scalar(f_tf, xtf))

I got:

Jax:  nan
Pytorch:  tensor(5456., dtype=torch.float16)
Tensorflow:  tf.Tensor(5456.0, shape=(), dtype=float16)

If I switch the JAX input to float32, jax.hessian(f_j) is also finite. Also, I tried the mathematical equivalent version of this function, f(x) = 2 * atan2(x, x) / x, and it gave me the finite results.

Could this be a numerical stability bug in JAX's handling of atan2?

System info (python version, jaxlib version, accelerator, etc.)

jax: 0.6.2 jaxlib: 0.6.2 numpy: 2.2.6 python: 3.10.19 (main, Oct 21 2025, 16:37:10) [Clang 20.1.8 ] device info: cpu-1, 1 local devices" process_count: 1 platform: uname_result(system='Darwin', node='x', release='25.5.0', version='Darwin Kernel Version 25.5.0: Mon Apr 27 20:41:19 PDT 2026; root:xnu-12377.121.6~2/RELEASE_ARM64_T8122', machine='arm64')

shadow-orange41 avatar May 21 '26 21:05 shadow-orange41

It looks like the issue is that intermediate results in the computation exceed the range of float16. One way to work around this in JAX is to JIT-compile the whole sequence, so that the compiler optimizes away the problematic computations:

>>> jax.hessian(f_j)(xj)
Array(nan, dtype=float16)

>>>  jax.jit(jax.hessian(f_j))(xj)
Array(5.456e+03, dtype=float16)

Otherwise, as it appears you're working with numbers near the limit of the range of float16, you might consider moving to a data type with more range, like float32 or bfloat16 (keeping in mind that the latter trades range for accuracy).

jakevdp avatar May 26 '26 16:05 jakevdp

Thanks, that makes sense. However, is the eager mode NaN considered as the expected behavior or a bug, especially because the eager mode in PyTorch and Tensorflow produced the finite results?

shadow-orange41 avatar Jun 28 '26 17:06 shadow-orange41

The NaN comes from the algebraic form of JAX's division / integer-power JVP rules. I inspected the Hessian jaxpr, the first non-finite value is:

a:f16[] = mul -2.0 b        inputs: [-2.0, 60576.0]  ->  -inf

With s0 = (x/atan2(x,x))/2 = 0.02547, that 60576.0 is s0**-3. Multiplying by the constant 2 overflows to -inf, and the -inf propagates to NaN.

The numerical unstable derivative rules involved are:

  • Rule 1: https://github.com/jax-ml/jax/blob/main/jax/_src/lax/lax.py#L5137-L5139
  • Rule 2: https://github.com/jax-ml/jax/blob/main/jax/_src/lax/lax.py#L4889-L4896

Rule 1 turns 1/s0 into integer_pow(s0, -2); rule 2 then differentiates that into the standalone -2 · s0**-3 that overflows.

Pytorch and Tensorflow, instead, write the derivative rule in another form (i.e., keeping the divisions nested instead of forming a reciprocal power), which is more numerically stable.

  • PyTorch: https://github.com/pytorch/pytorch/blob/main/tools/autograd/derivatives.yaml#L589-L592
  • Tensorflow: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/math_grad.py#L1507-L1515

For example, PyTorch and TensorFlow write the derivative of x/y with respect to the denominator as -(x/y)/y: it divides twice, so every intermediate stays on the order of the result. JAX writes that same derivative as -x · y⁻², which first builds y² as an independent quantity whose magnitude is unrelated to the answer, and so can overflow on its own.

The NaN above is this same pattern one derivative level up: differentiating integer_pow(s0, -2) builds s0⁻³ as a standalone value, and 2 · s0⁻³ then leaves fp16 range — even though s0, s0⁻³ (60576) and the true Hessian (5454) are each individually representable.

PyTorch hit exactly this and changed their rule for exactly this reason:pytorch#43414.

Would Jax developer consider express div_p's denominator JVP as a nested division, similar to torch/TF, i.e.,mul(neg(g), div(div(x, y), y))? @jakevdp

shadow-orange41 avatar Aug 06 '26 21:08 shadow-orange41