Skip to content

incomplete_beta: second z-derivative is nan at z = 1 for b = 1 (and at z = 0 for a = 1) #73

Open

Description

@nstarman

The second z-derivative of incomplete_beta is nan at an endpoint where the base of the z-rule's power is 0 and its exponent is exactly 0: at z = 1 for b = 1, and at z = 0 for a = 1. The true values are finite. The value and the first derivative are fine.

import jax
import spexial as sp

jax.config.update("jax_enable_x64", True)

d2 = lambda a, b, z: jax.grad(jax.grad(lambda zz: sp.incomplete_beta(a, b, zz)))(z)

d2(9.0, 1.0, 1.0)  # nan, expected 8   (a - 1)
d2(2.0, 1.0, 1.0)  # nan, expected 1
d2(1.0, 3.0, 0.0)  # nan, expected -2  -(b - 1)
d2(2.0, 2.0, 1.0)  # -1.0, correct: the exponent is not 0

The same happens with b traced. Reproduced on main (e982e80) and on #65, with jax 0.10.2.

Cause

The custom JVP gives d/dz B = z**(a-1) * (1-z)**(b-1). At b = 1 the second factor is (1-z)**0.0, and JAX differentiates a float-exponent pow as y * x**(y-1), which is 0 * inf = nan at x = 0:

jax.grad(lambda z: (1.0 - z) ** 0.0)(1.0)  # nan
jax.grad(lambda z: (1.0 - z) ** 0)(1.0)    # 0.0 (integer exponent)

Upstream treats this as intended and won't change it: a float-exponent ** is the real function x^y, which is not differentiable at (0, 0) (jax-ml/jax#14397, and jax-ml/jax#12033 for why the old y == 0 special case was dropped). So the fix belongs here. An integer exponent isn't an option, since b may be traced.

Possible fix

Guard each factor of the z-rule when its exponent is exactly 0, with a double where so the masked pow cannot put a nan into a cotangent:

b1 = b == 1.0
one_minus_z_pow = jnp.where(b1, 1.0, jnp.where(b1, 0.5, 1.0 - z) ** (b - 1.0))

The same applies to z**(a-1) at a == 1. With b traced, this has to fit around the existing log1p form, which serves the b-derivative (GH-68). Regression tests: the second and third z-derivatives at (a, 1, 1) and (1, b, 0), with b both concrete and traced. On #63, which adds a closed form for a static a == 1, a == 1 at z = 0 should be checked as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions