Skip to content

Utilities API

Utility functions for hyperbolic deep learning.

Math Utilities

Hyperbolic functions with domain and overflow guards: acosh/atanh clamp their argument into the open domain, cosh/sinh clip it at ±0.99·log(finfo.max), and asinh/acosh have overflow-free derivatives.

Most per-sample norms in the library use the max-scaled safe_norm / safe_hypot_norm / safe_normalize, which read the input twice and are safe over the full float32 range; use them in your own code. A few hot operations (proj, Hyperboloid.dist_0, Poincare.expmap, HTCLinear and the FHCNN/FGG linears) use a single reduction instead. See Norms: one reduction, gradient-safe at zero.

hyperbolix.utils.math_utils

Math utils functions for hyperbolic operations with numerically stable limits.

Direct JAX port of PyTorch math_utils.py with type annotations using jaxtyping.

cosh

cosh(x: Float[Array, ...]) -> Float[Array, ...]

Hyperbolic cosine with overflow protection. Domain=(-inf, inf).

Hard-clips the input to ±0.99*log(finfo.max) (≈±87.8 for f32, ±702.7 for f64) before computing the value so the result cannot overflow the dtype. This is a pure overflow guard: for any input that is not about to overflow the clip is a value- and gradient-identity, so the forward pass and the VJP match an unguarded cosh throughout the entire valid regime.

A hard jnp.clip is used deliberately rather than a softplus smooth_clamp: it matches the domain guards in acosh/atanh below, is free on accelerators, and avoids the ~2 extra exp per call that the smooth clamp evaluated on every element with no benefit. The only difference is in the saturated tail (|x| ≥ clamp), where the clip's gradient is 0 instead of a tiny nonzero value — acceptable, because that regime is already degenerate (the output is ~1e37) and you never want gradients pushing further into overflow.

XLA's CPU jnp.cosh is inaccurate: ~17 ulps off for |x| in [16, 512] and ~496 ulps for [512, 710] (f64; the jump sits exactly at the power-of-two boundary 512 — NumPy's cosh is ≤1.8 ulps throughout), and ~24.5 ulps in f32. The exp-form identity cosh(x) = 0.5*(exp(x) + exp(-x)) has no cancellation (both terms are positive) and measures ≤1.8 ulps f64 / ≤1.4 ulps f32 against an extended-precision reference. But its naive autodiff derivative is 0.5*(exp(x) - exp(-x)), which cancels near 0 (relative error ~eps/|x|) — the same failure mode the atanh rewrite above avoids for its own function. _cosh_stable fixes this with a custom_jvp that routes d/dx cosh to the accurate expm1-form sinh below (0.5*(expm1(x) - expm1(-x))) instead of differentiating the exp-form value expression.

Args: x: Input array of any shape

Returns: cosh(x) with overflow protection

Source code in hyperbolix/utils/math_utils.py
@_jit
def cosh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Hyperbolic cosine with overflow protection. Domain=(-inf, inf).

    Hard-clips the input to ``±0.99*log(finfo.max)`` (≈±87.8 for f32, ±702.7 for f64) before
    computing the value so the result cannot overflow the dtype. This is a *pure overflow guard*:
    for any input that is not about to overflow the clip is a value- and gradient-identity, so the
    forward pass and the VJP match an unguarded ``cosh`` throughout the entire valid regime.

    A hard ``jnp.clip`` is used deliberately rather than a softplus ``smooth_clamp``: it matches the
    domain guards in ``acosh``/``atanh`` below, is free on accelerators, and avoids the ~2 extra
    ``exp`` per call that the smooth clamp evaluated on every element with no benefit. The only
    difference is in the saturated tail (|x| ≥ clamp), where the clip's gradient is 0 instead of a
    tiny nonzero value — acceptable, because that regime is already degenerate (the output is ~1e37)
    and you never want gradients pushing further into overflow.

    XLA's CPU ``jnp.cosh`` is inaccurate: ~17 ulps off for ``|x|`` in ``[16, 512]`` and ~496 ulps for
    ``[512, 710]`` (f64; the jump sits exactly at the power-of-two boundary 512 — NumPy's ``cosh`` is
    ≤1.8 ulps throughout), and ~24.5 ulps in f32. The exp-form identity ``cosh(x) = 0.5*(exp(x) +
    exp(-x))`` has no cancellation (both terms are positive) and measures ≤1.8 ulps f64 / ≤1.4 ulps
    f32 against an extended-precision reference. But its *naive* autodiff derivative is ``0.5*(exp(x) - exp(-x))``, which
    cancels near 0 (relative error ~eps/|x|) — the same failure mode the ``atanh`` rewrite above
    avoids for its own function. ``_cosh_stable`` fixes this with a ``custom_jvp`` that routes
    ``d/dx cosh`` to the accurate expm1-form ``sinh`` below (``0.5*(expm1(x) - expm1(-x))``) instead
    of differentiating the exp-form value expression.

    Args:
        x: Input array of any shape

    Returns:
        cosh(x) with overflow protection
    """
    # cosh(x) ≈ exp(x)/2 for large x, so the overflow boundary is x = log(max).
    clamp = jnp.log(jnp.finfo(x.dtype).max) * 0.99
    x = clamp_to(x, -clamp, clamp)
    # exp-form value (≤1.8 ulps f64 / ≤1.4 ulps f32 vs XLA CPU cosh's 17-496 / 24.5 ulps); the
    # custom_jvp above keeps the gradient on the accurate expm1-form sinh instead of the naive
    # cancelling exp-form derivative.
    return _cosh_stable(x)

sinh

sinh(x: Float[Array, ...]) -> Float[Array, ...]

Hyperbolic sine with overflow protection. Domain=(-inf, inf).

Hard-clips the input to ±0.99*log(finfo.max) (≈±87.8 for f32, ±702.7 for f64) before computing the value so the result cannot overflow the dtype. This is a pure overflow guard: for any input that is not about to overflow the clip is a value- and gradient-identity, so the forward pass and the VJP match an unguarded sinh throughout the entire valid regime.

A hard jnp.clip is used deliberately rather than a softplus smooth_clamp: it matches the domain guards in acosh/atanh below, is free on accelerators, and avoids the ~2 extra exp per call that the smooth clamp evaluated on every element with no benefit. The only difference is in the saturated tail (|x| ≥ clamp), where the clip's gradient is 0 instead of a tiny nonzero value — acceptable, because that regime is already degenerate (the output is ~1e37) and you never want gradients pushing further into overflow.

XLA's CPU jnp.sinh is inaccurate the same way jnp.cosh is: ~17 ulps off for |x| in [16, 512] and ~496 ulps for [512, 710] (f64, jump at the power-of-two boundary 512; NumPy's sinh is ≤1.8 ulps throughout), and ~24.5 ulps in f32. The expm1-form identity sinh(x) = 0.5*(expm1(x) - expm1(-x)) is cancellation-free everywhere, including near 0 — unlike the naive exp-form 0.5*(exp(x) - exp(-x)), the two expm1 terms have opposite signs (expm1(x) >= 0 and -expm1(-x) >= 0 for x >= 0, and symmetrically for x < 0), so the subtraction adds magnitudes instead of cancelling them. This measures ≤3.9 ulps f64 / ≤4.2 ulps f32 against an extended-precision reference, everywhere, and is faster than jnp.sinh. Unlike cosh above, sinh needs no custom_jvp: its natural autodiff derivative is exactly the accurate exp-form 0.5*(exp(x) + exp(-x)) (_cosh_stable's value expression), which has no cancellation to begin with.

Args: x: Input array of any shape

Returns: sinh(x) with overflow protection

Source code in hyperbolix/utils/math_utils.py
@_jit
def sinh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Hyperbolic sine with overflow protection. Domain=(-inf, inf).

    Hard-clips the input to ``±0.99*log(finfo.max)`` (≈±87.8 for f32, ±702.7 for f64) before
    computing the value so the result cannot overflow the dtype. This is a *pure overflow guard*:
    for any input that is not about to overflow the clip is a value- and gradient-identity, so the
    forward pass and the VJP match an unguarded ``sinh`` throughout the entire valid regime.

    A hard ``jnp.clip`` is used deliberately rather than a softplus ``smooth_clamp``: it matches the
    domain guards in ``acosh``/``atanh`` below, is free on accelerators, and avoids the ~2 extra
    ``exp`` per call that the smooth clamp evaluated on every element with no benefit. The only
    difference is in the saturated tail (|x| ≥ clamp), where the clip's gradient is 0 instead of a
    tiny nonzero value — acceptable, because that regime is already degenerate (the output is ~1e37)
    and you never want gradients pushing further into overflow.

    XLA's CPU ``jnp.sinh`` is inaccurate the same way ``jnp.cosh`` is: ~17 ulps off for ``|x|`` in
    ``[16, 512]`` and ~496 ulps for ``[512, 710]`` (f64, jump at the power-of-two boundary 512;
    NumPy's ``sinh`` is ≤1.8 ulps throughout), and ~24.5 ulps in f32. The expm1-form identity
    ``sinh(x) = 0.5*(expm1(x) - expm1(-x))`` is cancellation-free *everywhere*, including near 0 —
    unlike the naive exp-form ``0.5*(exp(x) - exp(-x))``, the two ``expm1`` terms have opposite signs
    (``expm1(x) >= 0`` and ``-expm1(-x) >= 0`` for ``x >= 0``, and symmetrically for ``x < 0``), so
    the subtraction adds magnitudes instead of cancelling them. This measures ≤3.9 ulps f64 / ≤4.2
    ulps f32 against an extended-precision reference, everywhere, and is faster than ``jnp.sinh``. Unlike ``cosh`` above,
    ``sinh`` needs no ``custom_jvp``: its natural autodiff derivative is exactly the accurate exp-form
    ``0.5*(exp(x) + exp(-x))`` (``_cosh_stable``'s value expression), which has no cancellation to
    begin with.

    Args:
        x: Input array of any shape

    Returns:
        sinh(x) with overflow protection
    """
    # sinh(x) ≈ exp(x)/2 for large x, so the overflow boundary is x = log(max).
    clamp = jnp.log(jnp.finfo(x.dtype).max) * 0.99
    x = clamp_to(x, -clamp, clamp)
    # expm1-form: cancellation-free everywhere (opposite-signed terms), ≤3.9 ulps f64 vs XLA CPU
    # sinh's 17-496 ulps, and faster than the builtin. Autodiff of this expression is already the
    # accurate exp-form cosh, so no custom_jvp is needed here (contrast cosh above).
    return 0.5 * (jnp.expm1(x) - jnp.expm1(-x))

tanh

tanh(x: Float[Array, ...]) -> Float[Array, ...]

Hyperbolic tangent clamped so the output stays strictly inside (-1, 1). Domain=(-inf, inf).

Clips the input to ±0.5*log(2/machine_eps) (≈±8.3 for f32, ≈±18.4 for f64) AND clips the output to ±(1 - 10*machine_eps). The input clip is the analytic point where 1 - tanh reaches eps; the output clip is required in addition because XLA's float32 tanh saturates to exactly 1.0 slightly earlier (≈ x = 8), which the input clip alone does not prevent — and an exact 1.0 would make a downstream atanh singular. The output bound matches atanh's own ±(1 - 10*eps) domain guard, so atanh(tanh(x)) can never reach the pole. Outside the saturated tail the guards are a value- and gradient-identity (the tail's gradient is 0, as for cosh/sinh). Mirrors the domain-guard philosophy of acosh/atanh above and the tanh(clamp) guard in the geoopt κ-stereographic reference.

Away from zero the value comes from the algebraic identity tanh(x) = expm1(2x)/(expm1(2x) + 2) rather than XLA's rational approximation to tanh. Evaluated on |x| (sign restored by jnp.where, so the result is odd to the last bit), the form is cancellation-free — numerator and denominator are both positive and the denominator never drops below 2 — and it keeps the saturating tail accurate, where the whole signal lives in 1 - tanh(x) = 2/(expm1(2|x|) + 2). It is worse than the builtin near zero (where expm1(2x) ≈ 2x and the division adds roundings the builtin does not pay), so it is used only above a measured, precision-dependent seam: 1/8 in float32, 1/2 in float64 (see the _TANH_EXPM1_SEAM_* comment above for the ulp table behind both). Measured on 20k log-uniform float32 inputs, max ulp: [0.9, 7] 4 -> 2 on XLA GPU and 4 -> 1 on XLA CPU.

Below |x| = 1/8 in float32 neither kernel is used: the value comes from the odd Maclaurin series x - x^3/3 + 2x^5/15 - 17x^7/315 (Horner in x**2, evaluated on |x| so the sign restoration below keeps it odd to the last bit), mirroring atanh's series branch above. The series is exact to float32 rounding on that range — the first dropped term is 62 x^9/2835, 1.6e-10 absolute (1.3e-9 relative) at x = 1/8 against a float32 eps of 1.2e-7 — so it replaces XLA's 4 ulp rational approximation with a polynomial whose only error is its own rounding, and unlike the expm1 form it does not pay a division near zero. Measured on 20k log-uniform float32 inputs in [1e-4, 0.125], max / mean ulp: 4 / 0.96 -> 1 / 0.16 on XLA CPU and 4 / 0.87 -> 1 / 0.16 on XLA GPU (the expm1 form on that same range is 3 on GPU but 6 on CPU, which is why the seam does not simply move down). float64 keeps XLA's tanh below its own 1/2 seam: 1.3e-9 relative is ~6e6 float64 ulps, so the series is unusable there.

Args: x: Input array of any shape

Returns: tanh(x) clamped strictly inside (-1, 1)

Source code in hyperbolix/utils/math_utils.py
@_jit
def tanh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Hyperbolic tangent clamped so the output stays strictly inside (-1, 1). Domain=(-inf, inf).

    Clips the input to ``±0.5*log(2/machine_eps)`` (≈±8.3 for f32, ≈±18.4 for f64) AND clips the output to
    ``±(1 - 10*machine_eps)``. The input clip is the analytic point where ``1 - tanh`` reaches ``eps``; the
    output clip is required *in addition* because XLA's float32 ``tanh`` saturates to **exactly** ``1.0``
    slightly earlier (≈ x = 8), which the input clip alone does not prevent — and an exact ``1.0`` would make
    a downstream ``atanh`` singular. The output bound matches ``atanh``'s own ``±(1 - 10*eps)`` domain guard,
    so ``atanh(tanh(x))`` can never reach the pole. Outside the saturated tail the guards are a value- and
    gradient-identity (the tail's gradient is 0, as for ``cosh``/``sinh``). Mirrors the domain-guard
    philosophy of ``acosh``/``atanh`` above and the ``tanh(clamp)`` guard in the geoopt κ-stereographic
    reference.

    Away from zero the value comes from the algebraic identity ``tanh(x) = expm1(2x)/(expm1(2x) +
    2)`` rather than XLA's rational approximation to ``tanh``. Evaluated on ``|x|`` (sign restored
    by ``jnp.where``, so the result is odd to the last bit), the form is cancellation-free —
    numerator and denominator are both positive and the denominator never drops below 2 — and it
    keeps the saturating tail accurate, where the whole signal lives in
    ``1 - tanh(x) = 2/(expm1(2|x|) + 2)``. It is *worse* than the builtin near zero (where
    ``expm1(2x) ≈ 2x`` and the division adds roundings the builtin does not pay), so it is used
    only above a measured, precision-dependent seam: 1/8 in float32, 1/2 in float64 (see the
    ``_TANH_EXPM1_SEAM_*`` comment above for the ulp table behind both). Measured on 20k
    log-uniform float32 inputs, max ulp: ``[0.9, 7]`` 4 -> 2 on XLA GPU and 4 -> 1 on XLA CPU.

    Below ``|x| = 1/8`` **in float32** neither kernel is used: the value comes from the odd
    Maclaurin series ``x - x^3/3 + 2x^5/15 - 17x^7/315`` (Horner in ``x**2``, evaluated on
    ``|x|`` so the sign restoration below keeps it odd to the last bit), mirroring ``atanh``'s
    series branch above. The series is exact to float32 rounding on that range — the first
    dropped term is ``62 x^9/2835``, 1.6e-10 absolute (1.3e-9 relative) at ``x = 1/8`` against a
    float32 eps of 1.2e-7 — so it replaces XLA's 4 ulp rational approximation with a polynomial
    whose only error is its own rounding, and unlike the ``expm1`` form it does not pay a
    division near zero. Measured on 20k log-uniform float32 inputs in ``[1e-4, 0.125]``, max /
    mean ulp: 4 / 0.96 -> 1 / 0.16 on XLA CPU and 4 / 0.87 -> 1 / 0.16 on XLA GPU (the
    ``expm1`` form on that same range is 3 on GPU but **6** on CPU, which is why the seam does
    not simply move down). float64 keeps XLA's ``tanh`` below its own 1/2 seam: 1.3e-9 relative
    is ~6e6 float64 ulps, so the series is unusable there.

    Args:
        x: Input array of any shape

    Returns:
        tanh(x) clamped strictly inside (-1, 1)
    """
    # 1 - tanh(x) ≈ 2*exp(-2x); require it ≥ eps ⇒ x ≤ 0.5*log(2/eps) is the analytic bound.
    clamp = 0.5 * jnp.log(2.0 / jnp.finfo(x.dtype).eps)
    # This clip is also the sanitised argument the expm1 branch needs. jnp.where evaluates BOTH
    # branches and their gradients, and expm1(2x) overflows to inf for x > 44 (f32) / 355 (f64),
    # where inf/inf = NaN would leak into the *selected* branch's cotangent. Clipping first bounds
    # the branch argument at ±8.32 (f32) / ±18.4 (f64), so expm1(2x) tops out at 1.7e7 / 9.5e15 —
    # finite in both dtypes, for every real input including ±inf.
    x_safe = clamp_to(x, -clamp, clamp)
    seam = _TANH_EXPM1_SEAM_LOW_PRECISION if _is_low_precision(x.dtype) else _TANH_EXPM1_SEAM_FLOAT64
    # Evaluated on |x| with the sign restored via `where`, exactly as `atanh` above: `expm1(2x)`
    # and `expm1(-2x)` are not negatives of each other, so the raw quotient is not an odd function
    # to the last bit. Restoring the sign this way (rather than with `sign(x)*...`, whose
    # product-rule gradient at x == 0 would collapse to 0) makes tanh(-x) == -tanh(x) bitwise for
    # every input, and keeps the gradient at 0 exactly 1 (jnp.abs' VJP at 0 is +1). The two
    # below-the-seam branches are odd on |x| for the same reason: XLA's own tanh is already
    # bitwise odd, and the series' leading factor is abs_x.
    abs_x = jnp.abs(x_safe)
    t = jnp.expm1(2.0 * abs_x)
    if _is_low_precision(x.dtype):
        # Degree-7 odd Maclaurin series, Horner in abs_x**2. Needs no sanitising of its own: on
        # the clipped |x| <= 8.32 the polynomial and its derivative are bounded (~1.5e5 and
        # ~1.3e5), so the branch jnp.where does not select is still finite in value and cotangent.
        x2 = abs_x * abs_x
        below_seam = abs_x * (1.0 + x2 * (-1.0 / 3.0 + x2 * (2.0 / 15.0 - x2 * (17.0 / 315.0))))
    else:
        below_seam = jnp.tanh(abs_x)
    magnitude = jnp.where(abs_x >= seam, t / (t + 2.0), below_seam)
    out = jnp.where(x_safe >= 0, magnitude, -magnitude)
    # Also clamp the output: XLA's float32 tanh reaches exactly 1.0 before the input bound bites.
    max_out = 1.0 - 10.0 * float(jnp.finfo(x.dtype).eps)
    return clamp_to(out, -max_out, max_out)

acosh

acosh(x: Float[Array, ...]) -> Float[Array, ...]

Inverse hyperbolic cosine with domain clamping. Domain=[1, inf).

Clamps to 1 + 10*machine_eps — NOT exactly 1.0. acosh'(1) = inf, so a hard clip at 1.0 lets inputs that land exactly on 1.0 (e.g. the distance argument at x == y) reach the singular derivative and produce NaN gradients; post-hoc jnp.where guards cannot remove them because the NaN cotangent already exists inside the VJP (0inf = NaN). The margin bounds the derivative at ~1/sqrt(2margin) and keeps the forward error sqrt(2*margin) below test tolerances (f32: ~1.5e-3, f64: ~6.6e-8).

The forward value is jnp.acosh on the floored argument, unchanged. What _acosh_stable above changes is the derivative at the other end of the domain: JAX's JVP rule for acosh_p is g * rsqrt(x*x - 1) (jax/_src/lax/lax.py, ~:4753 in 0.11.1, unchanged in the installed 0.9.1), and x*x overflows float32 for x > 1.84e19, making the derivative exactly 0.0 where the true 1/(sqrt(x-1)·sqrt(x+1)) ≈ 1/x is still an ordinary float. The factored spelling never materializes x². It agrees with the builtin rule to within a float32 ulp near the boundary (measured at x = 1 + 1e-3: 2.23545685e1 vs 2.23545704e1, true 2.23550917e1 — both dominated by the float32 rounding of x itself) and is the only correct one at 1e22. :func:safe_sqrt keeps the x = 1 end free of the 0 * inf = NaN the floor already guards against. Same removability note as :func:asinh.

Args: x: Input array of any shape

Returns: acosh(x) with domain and gradient protection

Source code in hyperbolix/utils/math_utils.py
@_jit
def acosh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Inverse hyperbolic cosine with domain clamping. Domain=[1, inf).

    Clamps to ``1 + 10*machine_eps`` — NOT exactly 1.0. ``acosh'(1) = inf``,
    so a hard clip at 1.0 lets inputs that land exactly on 1.0 (e.g. the
    distance argument at x == y) reach the singular derivative and produce
    NaN gradients; post-hoc ``jnp.where`` guards cannot remove them because
    the NaN cotangent already exists inside the VJP (0*inf = NaN). The
    margin bounds the derivative at ~1/sqrt(2*margin) and keeps the forward
    error sqrt(2*margin) below test tolerances (f32: ~1.5e-3, f64: ~6.6e-8).

    The forward value is ``jnp.acosh`` on the floored argument, unchanged. What ``_acosh_stable``
    above changes is the derivative at the *other* end of the domain: JAX's JVP rule for ``acosh_p``
    is ``g * rsqrt(x*x - 1)`` (``jax/_src/lax/lax.py``, ~:4753 in 0.11.1, unchanged in the installed
    0.9.1), and ``x*x`` overflows float32 for ``x > 1.84e19``, making the derivative exactly ``0.0``
    where the true ``1/(sqrt(x-1)·sqrt(x+1)) ≈ 1/x`` is still an ordinary float. The factored
    spelling never materializes ``x²``. It agrees with the builtin rule to within a float32 ulp near
    the boundary (measured at ``x = 1 + 1e-3``: 2.23545685e1 vs 2.23545704e1, true 2.23550917e1 —
    both dominated by the float32 rounding of ``x`` itself) and is the only correct one at ``1e22``.
    :func:`safe_sqrt` keeps the ``x = 1`` end free of the ``0 * inf = NaN`` the floor already guards
    against. Same removability note as :func:`asinh`.

    Args:
        x: Input array of any shape

    Returns:
        acosh(x) with domain and gradient protection
    """
    eps = 10.0 * float(jnp.finfo(x.dtype).eps)
    x = floor_at(x, 1.0 + eps)
    return _acosh_stable(x)

asinh

asinh(x: Float[Array, ...]) -> Float[Array, ...]

Inverse hyperbolic sine with an overflow-free derivative. Domain=(-inf, inf).

Forward value is jnp.arcsinh unchanged — bit-identical, same op, no clamp, no domain guard (asinh has no domain boundary). Only the derivative differs.

JAX's JVP rule for asinh_p is g * rsqrt(x*x + 1) (jax/_src/lax/lax.py, ~:4746 in 0.11.1 and unchanged in the installed 0.9.1). It materializes x*x, which overflows float32 for |x| > 1.84e19: rsqrt(inf) = 0, so the returned derivative is exactly 0.0 while the true value 1/hypot(1, x) ≈ 1/|x| is an ordinary normal float down to |x| ≈ 8.5e37. Nothing warns — forward values stay correct and the gradient silently freezes. The library hits this in manifolds/hyperboloid._compute_mlr, whose score ‖z‖·asinh(√c·alpha/‖z‖)/√c pushes asinh argument past 1.8e19 whenever ‖z‖ collapses, freezing the MLR bias and its input gradient (logs/2026-09-11_plfc_residual_nan/).

The custom_jvp above spells the same derivative as 1/hypot(1, x) via :func:safe_hypot, which rescales by an exact power of two instead of squaring, so no intermediate can overflow. Identical to the builtin rule wherever the builtin is finite, correct where it is not, and exactly 1.0 at x = 0. The only remaining floor is the dtype's: above |x| ≈ 8.5e37 in float32 the true tangent is subnormal and XLA flushes it to zero — a representation limit, not a cancellation.

Removable. This wrapper exists only to work around the upstream rule (bug report: logs/2026-09-11_plfc_residual_nan/jax_issue_asinh_jvp.md). Once JAX computes the asinh JVP without squaring its argument, _asinh_stable can be deleted and every call site can go back to jnp.arcsinh.

Args: x: Input array of any shape

Returns: asinh(x), with a derivative that does not overflow at large |x|

Source code in hyperbolix/utils/math_utils.py
@_jit
def asinh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Inverse hyperbolic sine with an overflow-free derivative. Domain=(-inf, inf).

    Forward value is ``jnp.arcsinh`` unchanged — bit-identical, same op, no clamp, no domain
    guard (``asinh`` has no domain boundary). Only the derivative differs.

    JAX's JVP rule for ``asinh_p`` is ``g * rsqrt(x*x + 1)`` (``jax/_src/lax/lax.py``, ~:4746 in
    0.11.1 and unchanged in the installed 0.9.1). It materializes ``x*x``, which overflows float32
    for ``|x| > 1.84e19``: ``rsqrt(inf) = 0``, so the returned derivative is **exactly 0.0** while
    the true value ``1/hypot(1, x) ≈ 1/|x|`` is an ordinary normal float down to ``|x| ≈ 8.5e37``.
    Nothing warns — forward values stay correct and the gradient silently freezes. The library hits
    this in ``manifolds/hyperboloid._compute_mlr``, whose score ``‖z‖·asinh(√c·alpha/‖z‖)/√c`` pushes
    ``asinh`` argument past 1.8e19 whenever ``‖z‖`` collapses, freezing the MLR bias and its input
    gradient (``logs/2026-09-11_plfc_residual_nan/``).

    The ``custom_jvp`` above spells the same derivative as ``1/hypot(1, x)`` via :func:`safe_hypot`,
    which rescales by an exact power of two instead of squaring, so no intermediate can overflow.
    Identical to the builtin rule wherever the builtin is finite, correct where it is not, and
    exactly ``1.0`` at ``x = 0``. The only remaining floor is the dtype's: above ``|x| ≈ 8.5e37`` in
    float32 the true tangent is subnormal and XLA flushes it to zero — a representation limit, not
    a cancellation.

    **Removable.** This wrapper exists only to work around the upstream rule (bug report:
    ``logs/2026-09-11_plfc_residual_nan/jax_issue_asinh_jvp.md``). Once JAX computes the ``asinh``
    JVP without squaring its argument, ``_asinh_stable`` can be deleted and every call site can go
    back to ``jnp.arcsinh``.

    Args:
        x: Input array of any shape

    Returns:
        ``asinh(x)``, with a derivative that does not overflow at large ``|x|``
    """
    return _asinh_stable(x)

atanh

atanh(x: Float[Array, ...]) -> Float[Array, ...]

Inverse hyperbolic tangent with domain clamping. Domain=(-1, 1).

Clamps input to ±(1 - 10*machine_eps). The factor 10 keeps the clamped value safely representable away from ±1.0 (where the float grid is coarsest) and bounds atanh' at ~1/(2*margin) instead of letting inputs ride the last representable value before the singularity.

XLA evaluates jnp.atanh as 0.5*(log1p(x) - log1p(-x)), and XLA's CPU float64 log1p is up to ~129 ulps off for arguments in [-0.53, -0.28] (NumPy's log1p is <1 ulp there) — jnp.atanh inherits ~129 ulp error for x in ~[0.28, 0.53], peaking at sqrt(2) - 1. Float32 is unaffected. The single-log1p identity atanh(|x|) = 0.5*log1p(2|x|/(1 - |x|)), computed on |x| with the sign restored via jnp.where, keeps the log1p argument non-negative (outside the bad window) for either sign of x. The plain (non-odd) rewrite 0.5*log1p(2x/(1-x)) is wrong for negative x — its inner argument re-enters the bad log1p window and still errs by ~211 ulps; a jnp.sign(x)*... spelling is also wrong (its product-rule gradient at x == 0 collapses to 0 instead of the analytic 1). This form measures at max 2.8 ulps (f64, both signs), bit-identical to the builtin at the clip boundary, exact gradients, and ~1.7x faster than jnp.atanh (one log1p instead of two). Upstream fixed the log1p hole in jax 0.11.1 (openxla/xla#46765, jax-ml/jax#39707), but the rewrite is kept: it costs nothing, and it is what protects users still on jax <= 0.11.0.

Below |x| = 1/8 in float32 the log1p form is replaced by the odd Maclaurin series x + x^3/3 + x^5/5 + x^7/7 + x^9/9 (Horner in x**2, evaluated on x itself so it is odd by construction). The series is exact to float32 rounding there — the first dropped term is x^11/11, 1.1e-11 relative at x = 1/8 against a float32 eps of 1.2e-7 — and it removes the rounding that the division 2|x|/(1 - |x|) costs the log1p form near zero. Measured on 20k log-uniform float32 inputs in [1e-4, 0.125]: max ulp 3 -> 1 (mean 0.48 -> 0.33) on XLA GPU, 2 -> 1 (mean 0.28 -> 0.33) on XLA CPU. float64 keeps the log1p form on the whole domain: 1.1e-11 relative is ~5e4 float64 ulps, so the series is unusable there.

Args: x: Input array of any shape

Returns: atanh(x) with domain and gradient protection

Source code in hyperbolix/utils/math_utils.py
@_jit
def atanh(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Inverse hyperbolic tangent with domain clamping. Domain=(-1, 1).

    Clamps input to ``±(1 - 10*machine_eps)``. The factor 10 keeps the
    clamped value safely representable away from ±1.0 (where the float grid
    is coarsest) and bounds ``atanh'`` at ~1/(2*margin) instead of letting
    inputs ride the last representable value before the singularity.

    XLA evaluates ``jnp.atanh`` as ``0.5*(log1p(x) - log1p(-x))``, and XLA's CPU float64
    ``log1p`` is up to ~129 ulps off for arguments in ``[-0.53, -0.28]`` (NumPy's ``log1p`` is <1
    ulp there) — ``jnp.atanh`` inherits ~129 ulp error for ``x`` in ~``[0.28, 0.53]``, peaking at
    ``sqrt(2) - 1``. Float32 is unaffected. The single-log1p identity
    ``atanh(|x|) = 0.5*log1p(2|x|/(1 - |x|))``, computed on ``|x|`` with the sign restored via
    ``jnp.where``, keeps the ``log1p`` argument non-negative (outside the bad window) for either
    sign of ``x``. The plain (non-odd) rewrite ``0.5*log1p(2x/(1-x))`` is wrong for negative ``x``
    — its inner argument re-enters the bad ``log1p`` window and still errs by ~211 ulps; a
    ``jnp.sign(x)*...`` spelling is also wrong (its product-rule gradient at ``x == 0`` collapses
    to 0 instead of the analytic 1). This form measures at max 2.8 ulps (f64, both signs),
    bit-identical to the builtin at the clip boundary, exact gradients, and ~1.7x faster than
    ``jnp.atanh`` (one ``log1p`` instead of two). Upstream fixed the ``log1p`` hole in jax 0.11.1
    (openxla/xla#46765, jax-ml/jax#39707), but the rewrite is kept: it costs nothing, and it is
    what protects users still on jax <= 0.11.0.

    Below ``|x| = 1/8`` **in float32** the ``log1p`` form is replaced by the odd Maclaurin series
    ``x + x^3/3 + x^5/5 + x^7/7 + x^9/9`` (Horner in ``x**2``, evaluated on ``x`` itself so it is
    odd by construction). The series is exact to float32 rounding there — the first dropped term
    is ``x^11/11``, 1.1e-11 relative at ``x = 1/8`` against a float32 eps of 1.2e-7 — and it
    removes the rounding that the division ``2|x|/(1 - |x|)`` costs the ``log1p`` form near zero.
    Measured on 20k log-uniform float32 inputs in ``[1e-4, 0.125]``: max ulp 3 -> 1 (mean 0.48 ->
    0.33) on XLA GPU, 2 -> 1 (mean 0.28 -> 0.33) on XLA CPU. float64 keeps the ``log1p`` form on
    the whole domain: 1.1e-11 relative is ~5e4 float64 ulps, so the series is unusable there.

    Args:
        x: Input array of any shape

    Returns:
        atanh(x) with domain and gradient protection
    """
    eps = 10.0 * float(jnp.finfo(x.dtype).eps)
    x = clamp_to(x, -1.0 + eps, 1.0 - eps)
    # XLA evaluates jnp.atanh as 0.5*(log1p(x) - log1p(-x)), and XLA's float64 log1p is up to
    # ~129 ulps off for arguments in [-0.53, -0.28] (numpy's: <1 ulp) — jnp.atanh inherits this
    # for x in ~[0.28, 0.53], peaking at sqrt(2)-1. The single-log1p identity
    # atanh(|x|) = 0.5*log1p(2|x|/(1 - |x|)) keeps the log1p argument non-negative (outside the
    # bad window) for either sign of x; restoring the sign via where (not sign(x)*...) keeps
    # the gradient at x == 0 exact. Measured: 129 -> 2.8 ulps max (f64), value- and
    # gradient-identical at the clip boundary, and ~1.7x faster (one log1p instead of two).
    abs_x = jnp.abs(x)
    # The clip above IS the sanitised argument this branch needs: it leaves 1 - abs_x >= 10*eps
    # (1.19e-6 in f32, 2.2e-15 in f64), so the quotient, the log1p and their gradients are finite
    # for every real input — required because jnp.where below evaluates BOTH branches and their
    # gradients, and a NaN in the unselected one would leak into the selected one's cotangent.
    half_log1p = 0.5 * jnp.log1p(2.0 * abs_x / (1.0 - abs_x))
    out = jnp.where(x >= 0, half_log1p, -half_log1p)
    if not _is_low_precision(x.dtype):
        return out
    # Odd Maclaurin series through x**9, Horner in x**2. Needs no sanitising of its own: a
    # degree-9 polynomial on |x| <= 1 is bounded (|series| <= 1.788), as is its derivative.
    x2 = x * x
    series = x * (1.0 + x2 * (1.0 / 3.0 + x2 * (1.0 / 5.0 + x2 * (1.0 / 7.0 + x2 / 9.0))))
    return jnp.where(abs_x >= _ATANH_SERIES_SEAM, out, series)

safe_norm

safe_norm(v: Float[Array, '... n']) -> Float[Array, ...]

Euclidean norm over the last axis, computed on a rescaled vector. Domain=R^n, Range=[0, inf).

Divides by the power of two just below max|v| (:func:_pow2_divisor) before squaring, so the sum of squares always sits in [1, 4n) no matter how large or small v is. The divisor being a power of two is what keeps this bit-identical to sqrt(sum(v**2)) wherever that neither overflows nor underflows -- see :func:_pow2_divisor. That is what the library's older sqrt(sum(v**2) + MIN_NORM**2) idiom cannot do, in both directions:

  • Overflow: sum(v**2) overflows float32 once |v| > 1.8e19 — reached by the spatial part of a hyperboloid point at geodesic radius ~45 (arcsinh(1.8e19) = 45.03 at c = 1; radius 44 is only coordinate 6.4e18), while the norm itself, 1.8e19, is perfectly representable.
  • Underflow: the + MIN_NORM**2 = 1e-30 floor dominates any genuinely small vector. A float32 chord of 1e-34 (a legitimate angular separation between two nearly parallel unit vectors) comes back as 1e-15, i.e. 19 orders of magnitude too large.

The scale is wrapped in stop_gradient, which makes the VJP exactly v/‖v‖ — the analytic derivative, with no contribution from differentiating the scaling itself.

At v == 0 the result is exactly 0 and the VJP is exactly 0 (the derivative does not exist there; zero is the finite, direction-free choice). Both need the double where below: sanitizing only the output leaves sqrt(0)'s infinite derivative inside the VJP, where it meets the outer where's zero cotangent as 0 * inf = NaN. The first where replaces the argument of the sqrt so the infinite derivative is never created.

Non-finite inputs are passed through rather than turned into NaN: a vector holding an inf returns inf. Callers use that to keep an out-of-range point visibly degenerate instead of silently NaN-poisoning everything downstream.

Args: v: Input array, norm taken over the last axis

Returns: ‖v‖₂ over the last axis, shape v.shape[:-1]

Source code in hyperbolix/utils/math_utils.py
@_jit
def safe_norm(v: Float[Array, "... n"]) -> Float[Array, "..."]:
    """Euclidean norm over the last axis, computed on a rescaled vector. Domain=R^n, Range=[0, inf).

    Divides by the power of two just below ``max|v|`` (:func:`_pow2_divisor`) before squaring, so
    the sum of squares always sits in ``[1, 4n)`` no matter how large or small ``v`` is. The
    divisor being a power of two is what keeps this **bit-identical to** ``sqrt(sum(v**2))``
    wherever that neither overflows nor underflows -- see :func:`_pow2_divisor`. That is what the library's older
    ``sqrt(sum(v**2) + MIN_NORM**2)`` idiom cannot do, in *both* directions:

    * **Overflow**: ``sum(v**2)`` overflows float32 once ``|v| > 1.8e19`` — reached by the spatial
      part of a hyperboloid point at geodesic radius ~45 (``arcsinh(1.8e19) = 45.03`` at ``c = 1``;
      radius 44 is only coordinate ``6.4e18``), while the norm itself, ``1.8e19``, is perfectly
      representable.
    * **Underflow**: the ``+ MIN_NORM**2 = 1e-30`` floor *dominates* any genuinely small vector.
      A float32 chord of ``1e-34`` (a legitimate angular separation between two nearly parallel
      unit vectors) comes back as ``1e-15``, i.e. 19 orders of magnitude too large.

    The scale is wrapped in ``stop_gradient``, which makes the VJP exactly ``v/‖v‖`` — the analytic
    derivative, with no contribution from differentiating the scaling itself.

    At ``v == 0`` the result is exactly ``0`` and the VJP is exactly ``0`` (the derivative does not
    exist there; zero is the finite, direction-free choice). Both need the **double** ``where``
    below: sanitizing only the output leaves ``sqrt(0)``'s infinite derivative inside the VJP,
    where it meets the outer ``where``'s zero cotangent as ``0 * inf = NaN``. The first ``where``
    replaces the *argument* of the ``sqrt`` so the infinite derivative is never created.

    Non-finite inputs are passed through rather than turned into NaN: a vector holding an ``inf``
    returns ``inf``. Callers use that to keep an out-of-range point visibly degenerate instead of
    silently NaN-poisoning everything downstream.

    Args:
        v: Input array, norm taken over the last axis

    Returns:
        ``‖v‖₂`` over the last axis, shape ``v.shape[:-1]``
    """
    scale = jax.lax.stop_gradient(jnp.max(jnp.abs(v), axis=-1))
    is_zero = scale == 0.0
    divisor = _pow2_divisor(scale)
    sq = jnp.sum((v / divisor[..., None]) ** 2, axis=-1)
    # Double-where, first half: sqrt'(0) = inf would become 0*inf = NaN in the VJP below.
    sq_safe = jnp.where(is_zero, jnp.ones_like(sq), sq)
    # Double-where, second half: exact 0 forward, exactly-zero VJP at v = 0.
    return jnp.where(is_zero, jnp.zeros_like(sq), divisor * jnp.sqrt(sq_safe))

safe_normalize

safe_normalize(
    v: Float[Array, "... n"],
) -> Float[Array, "... n"]

v/‖v‖ over the last axis, returning the exact zero vector at v == 0.

Same power-of-two-rescaled, double-where construction as :func:safe_norm, so the result is a unit vector for every non-zero v (including magnitudes that would overflow or flush a sum-of-squares) and exactly 0 with a finite (zero) gradient at v == 0.

There is deliberately no maximum(‖v‖, MIN_NORM) floor on the denominator. This is used to build the angular unit vector of a geodesic frame, whose pre-normalization length is sin(ψ) for the angle ψ between two points; a 1e-15 floor against a genuine sin(ψ) = 1e-19 would shrink the resulting direction by a factor of 1e4 instead of returning a unit vector. The exact-zero return at v == 0 is the well-defined case (ψ = 0: no angular direction exists, and the frame's angular coefficient is zero there), which is why the floor is not needed.

Args: v: Input array, normalized over the last axis

Returns: v/‖v‖₂, or the zero vector where v is zero

Source code in hyperbolix/utils/math_utils.py
@_jit
def safe_normalize(v: Float[Array, "... n"]) -> Float[Array, "... n"]:
    """``v/‖v‖`` over the last axis, returning the **exact zero vector** at ``v == 0``.

    Same power-of-two-rescaled, double-``where`` construction as :func:`safe_norm`, so the result is a unit
    vector for every non-zero ``v`` (including magnitudes that would overflow or flush a
    sum-of-squares) and exactly ``0`` with a finite (zero) gradient at ``v == 0``.

    There is deliberately **no** ``maximum(‖v‖, MIN_NORM)`` floor on the denominator. This is used
    to build the *angular* unit vector of a geodesic frame, whose pre-normalization length is
    ``sin(ψ)`` for the angle ``ψ`` between two points; a ``1e-15`` floor against a genuine
    ``sin(ψ) = 1e-19`` would shrink the resulting direction by a factor of ``1e4`` instead of
    returning a unit vector. The exact-zero return at ``v == 0`` is the well-defined case
    (``ψ = 0``: no angular direction exists, and the frame's angular coefficient is zero there),
    which is why the floor is not needed.

    Args:
        v: Input array, normalized over the last axis

    Returns:
        ``v/‖v‖₂``, or the zero vector where ``v`` is zero
    """
    scale = jax.lax.stop_gradient(jnp.max(jnp.abs(v), axis=-1, keepdims=True))
    is_zero = scale == 0.0
    divisor = _pow2_divisor(scale)
    scaled = v / divisor
    sq = jnp.sum(scaled**2, axis=-1, keepdims=True)
    sq_safe = jnp.where(is_zero, jnp.ones_like(sq), sq)
    return jnp.where(is_zero, jnp.zeros_like(v), scaled / jnp.sqrt(sq_safe))

safe_sqrt

safe_sqrt(x: Float[Array, ...]) -> Float[Array, ...]

sqrt(x) with an exactly-zero derivative at x == 0 instead of inf. Range=[0, inf).

The scalar counterpart of :func:safe_norm, for the quantities that are already a squared magnitude when they arrive: a Minkowski or Riemannian quadratic form g_x(v, v), a sum of per-factor squared distances. Those cannot be routed through safe_norm (its input is the vector, and a Minkowski form is not a Euclidean norm), yet they hit the same wall: at x = 0 the true derivative 1/(2*sqrt(x)) is infinite, and reverse-mode AD multiplies it by the incoming cotangent — which for the usual v = 0 case is exactly 0, giving 0 * inf = NaN for the whole row.

The library's older answer was to add MIN_NORM**2 under the sqrt, which has the same two defects :func:safe_norm documents: the 1e-30 floor dominates a genuinely small x (a form of 1e-40 comes back as 1e-15), and it does nothing about a large one.

Same double where as :func:safe_norm: the first replaces the argument so the infinite derivative is never created, the second restores the exact 0 forward value. A negative x still yields NaN (as jnp.sqrt does) — callers that can produce a slightly negative form from rounding wrap the argument in floor_at(x, 0.0) first, which is the honest place for that decision. inf passes through as inf.

Args: x: Non-negative input array of any shape

Returns: sqrt(x), with derivative 0 (not inf) wherever x == 0

Source code in hyperbolix/utils/math_utils.py
@_jit
def safe_sqrt(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """``sqrt(x)`` with an exactly-zero derivative at ``x == 0`` instead of ``inf``. Range=[0, inf).

    The scalar counterpart of :func:`safe_norm`, for the quantities that are already a squared
    magnitude when they arrive: a Minkowski or Riemannian quadratic form ``g_x(v, v)``, a sum of
    per-factor squared distances. Those cannot be routed through ``safe_norm`` (its input is the
    *vector*, and a Minkowski form is not a Euclidean norm), yet they hit the same wall: at
    ``x = 0`` the true derivative ``1/(2*sqrt(x))`` is infinite, and reverse-mode AD multiplies it
    by the incoming cotangent — which for the usual ``v = 0`` case is exactly ``0``, giving
    ``0 * inf = NaN`` for the whole row.

    The library's older answer was to add ``MIN_NORM**2`` under the ``sqrt``, which has the same
    two defects :func:`safe_norm` documents: the ``1e-30`` floor dominates a genuinely small ``x``
    (a form of ``1e-40`` comes back as ``1e-15``), and it does nothing about a large one.

    Same **double** ``where`` as :func:`safe_norm`: the first replaces the *argument* so the
    infinite derivative is never created, the second restores the exact ``0`` forward value. A
    negative ``x`` still yields NaN (as ``jnp.sqrt`` does) — callers that can produce a slightly
    negative form from rounding wrap the argument in ``floor_at(x, 0.0)`` first, which is the
    honest place for that decision. ``inf`` passes through as ``inf``.

    Args:
        x: Non-negative input array of any shape

    Returns:
        ``sqrt(x)``, with derivative ``0`` (not ``inf``) wherever ``x == 0``
    """
    is_zero = x == 0.0
    # Double-where, first half: sqrt'(0) = inf would become 0*inf = NaN in the VJP below.
    x_safe = jnp.where(is_zero, jnp.ones_like(x), x)
    # Double-where, second half: exact 0 forward, exactly-zero VJP at x = 0.
    return jnp.where(is_zero, jnp.zeros_like(x), jnp.sqrt(x_safe))

safe_hypot

safe_hypot(
    p: Float[Array, ...], q: Float[Array, ...]
) -> Float[Array, ...]

sqrt(p² + q²) without intermediate overflow or underflow. Range=[0, inf).

The two-argument form of :func:safe_norm, with the same power-of-two rescaling and the same double where: exact 0 and exactly-zero gradient at p == q == 0, no p**2 materialized (so safe_hypot(1e30, 1.0) is finite in float32 even though 1e30**2 is not), and non-finite inputs pass through as inf rather than NaN.

Used to build a hyperbolic sinh(θ/2) out of two non-negative contributions whose squares routinely straddle the dtype's whole exponent range.

Args: p: First leg (any shape, broadcast against q) q: Second leg

Returns: sqrt(p² + q²)

Source code in hyperbolix/utils/math_utils.py
@_jit
def safe_hypot(p: Float[Array, "..."], q: Float[Array, "..."]) -> Float[Array, "..."]:
    """``sqrt(p² + q²)`` without intermediate overflow or underflow. Range=[0, inf).

    The two-argument form of :func:`safe_norm`, with the same power-of-two rescaling and the same double
    ``where``: exact ``0`` and exactly-zero gradient at ``p == q == 0``, no ``p**2`` materialized
    (so ``safe_hypot(1e30, 1.0)`` is finite in float32 even though ``1e30**2`` is not), and
    non-finite inputs pass through as ``inf`` rather than NaN.

    Used to build a hyperbolic ``sinh(θ/2)`` out of two non-negative contributions whose squares
    routinely straddle the dtype's whole exponent range.

    Args:
        p: First leg (any shape, broadcast against ``q``)
        q: Second leg

    Returns:
        ``sqrt(p² + q²)``
    """
    scale = jax.lax.stop_gradient(jnp.maximum(jnp.abs(p), jnp.abs(q)))
    is_zero = scale == 0.0
    divisor = _pow2_divisor(scale)
    sq = (p / divisor) ** 2 + (q / divisor) ** 2
    sq_safe = jnp.where(is_zero, jnp.ones_like(sq), sq)
    return jnp.where(is_zero, jnp.zeros_like(sq), divisor * jnp.sqrt(sq_safe))

safe_hypot_norm

safe_hypot_norm(
    v: Float[Array, "... n"], q: Float[Array, ...]
) -> Float[Array, ...]

sqrt(‖v‖² + q²) over the last axis, in one reduction. Range=[0, inf).

Not safe_hypot(safe_norm(v), q). That spelling rounds ‖v‖ to the dtype and then squares it again, so the sum(v**2) it started from is not recoverable: r = round(sqrt(S)) gives r² = S(1 + 2δ), an error of up to one ulp of S. This form keeps the sum of squares intact and appends q² to it, exactly as the pre-safe_norm idiom sqrt(sum(v**2) + q**2) did, so it is bit-identical to that idiom wherever it neither overflows nor underflows — the same guarantee :func:_pow2_divisor gives :func:safe_norm, and for the same reason.

That matters because the library's callers recompute the same sum of squares right after. The hyperboloid time slot is x₀ = sqrt(‖x_s‖² + 1/c) and its own constraint is -x₀² + ‖x_s‖² = -1/c: when x₀ is built from the same sum(x_s**2) the check forms, the rounding cancels and the residual is one rounding of x₀; when it is built from a re-squared ‖x_s‖ the two no longer cancel. At x₀ ≈ 34 in float32 one ulp of x₀² is 1.2e-4, which is larger than the 1e-4 tolerance the manifold checks use (tests/nn_layers/test_hypformer.py::test_hrc_*_extreme_curvatures).

Overflow-free in the same way as :func:safe_norm: nothing is squared before the exact power-of-two rescale, so a spatial part at float32 radius 1e20 still returns a finite x₀. Same double where: exact 0 and an exactly-zero VJP where v and q are both zero, and a non-finite input passes through as inf rather than becoming NaN.

Args: v: Vector leg, norm taken over the last axis q: Scalar leg, broadcast against v.shape[:-1]

Returns: sqrt(‖v‖₂² + q²), shape broadcast(v.shape[:-1], q.shape)

Source code in hyperbolix/utils/math_utils.py
@_jit
def safe_hypot_norm(v: Float[Array, "... n"], q: Float[Array, "..."]) -> Float[Array, "..."]:
    """``sqrt(‖v‖² + q²)`` over the last axis, in **one** reduction. Range=[0, inf).

    Not ``safe_hypot(safe_norm(v), q)``. That spelling rounds ``‖v‖`` to the dtype and then squares
    it again, so the ``sum(v**2)`` it started from is not recoverable: ``r = round(sqrt(S))`` gives
    ``r² = S(1 + 2δ)``, an error of up to one ulp *of S*. This form keeps the sum of squares intact
    and appends ``q²`` to it, exactly as the pre-``safe_norm`` idiom ``sqrt(sum(v**2) + q**2)`` did,
    so it is bit-identical to that idiom wherever it neither overflows nor underflows — the same
    guarantee :func:`_pow2_divisor` gives :func:`safe_norm`, and for the same reason.

    That matters because the library's callers **recompute the same sum of squares** right after.
    The hyperboloid time slot is ``x₀ = sqrt(‖x_s‖² + 1/c)`` and its own constraint is
    ``-x₀² + ‖x_s‖² = -1/c``: when ``x₀`` is built from the same ``sum(x_s**2)`` the check forms,
    the rounding cancels and the residual is one rounding of ``x₀``; when it is built from a
    re-squared ``‖x_s‖`` the two no longer cancel. At ``x₀ ≈ 34`` in float32 one ulp of ``x₀²`` is
    1.2e-4, which is larger than the 1e-4 tolerance the manifold checks use
    (``tests/nn_layers/test_hypformer.py::test_hrc_*_extreme_curvatures``).

    Overflow-free in the same way as :func:`safe_norm`: nothing is squared before the exact
    power-of-two rescale, so a spatial part at float32 radius 1e20 still returns a finite ``x₀``.
    Same double ``where``: exact ``0`` and an exactly-zero VJP where ``v`` and ``q`` are both zero,
    and a non-finite input passes through as ``inf`` rather than becoming NaN.

    Args:
        v: Vector leg, norm taken over the last axis
        q: Scalar leg, broadcast against ``v.shape[:-1]``

    Returns:
        ``sqrt(‖v‖₂² + q²)``, shape ``broadcast(v.shape[:-1], q.shape)``
    """
    scale = jax.lax.stop_gradient(jnp.maximum(jnp.max(jnp.abs(v), axis=-1), jnp.abs(q)))
    is_zero = scale == 0.0
    divisor = _pow2_divisor(scale)
    # `sum(...) + (q/divisor)**2`, not one reduction over the concatenation: this reproduces the
    # association of the idiom it replaces, `sum(v**2) + q**2`, which is what makes it bit-identical.
    sq = jnp.sum((v / divisor[..., None]) ** 2, axis=-1) + (q / divisor) ** 2
    sq_safe = jnp.where(is_zero, jnp.ones_like(sq), sq)
    return jnp.where(is_zero, jnp.zeros_like(sq), divisor * jnp.sqrt(sq_safe))

smooth_clamp

smooth_clamp(
    x: Float[Array, ...],
    min_value: float,
    max_value: float,
    smoothing_factor: float = 50.0,
) -> Float[Array, ...]

Smoothly clamp array values to a range [min_value, max_value]. Range=(min_value, max_value).

The two-sided clamp is a difference of scaled softplus terms, not a composition of :func:smooth_clamp_min and :func:smooth_clamp_max (beta = smoothing_factor)::

smooth_clamp(x) = min_value + sp(x - min_value) - sp(x - max_value)

with sp(u) = log(1 + exp(beta*u)) / beta, evaluated in the stable hinge + remainder form (see _softplus_tail). For every window width w = max_value - min_value > 0 and every beta > 0:

  • Bounded: sp is increasing so the output is above min_value, and sp(u) - sp(u - beta*w) < w reduces to 1 < exp(beta*w) — true for any positive window. The output is therefore strictly inside the window, with no constraint linking w to beta.
  • Smooth and monotone: C^inf with derivative sigmoid(beta*(x - min_value)) - sigmoid(beta*(x - max_value)) in (0, 1), exact at the two bounds as well.
  • Identity in the interior: the output differs from x by [exp(-beta*d_min) - exp(-beta*d_max)]/beta up to higher order, where d_min/d_max are the distances to the two bounds; at beta=50 that is below the float32 noise floor once x is ~0.3 from both.

The composition smooth_clamp_min(smooth_clamp_max(x)) this replaces could return values outside the window whenever w < log(2)/beta (0.0139 at the default beta=50), because each gated one-sided clamp displaced its boundary input by log(2)/beta rather than by ~0 (see :func:smooth_clamp_min). Concretely, window [0, 0.01] at beta=50 returned 0.01386 for x = 0.0 — 39% above max_value for an input that needed no clamping at all. Note that a composition of gate-free one-sided clamps does not fix this: it still overshoots by log(1 + exp(-beta*w))/beta, which is of order the window itself in that regime. The difference form above is the one that is provably bounded.

In floating point the strictness degrades only in the saturated tails, where the remainder terms underflow to 0 and the output equals min_value/max_value exactly. That is an underflow of exp(-beta*d), not an overflow: it happens past -log(smallest_subnormal), measured at beta*d ~104 in float32 and ~745 in float64. Inclusion in [min_value, max_value] always holds.

Args: x: Input array of any shape min_value: Minimum value to clamp to max_value: Maximum value to clamp to smoothing_factor: Beta parameter for softplus (higher = sharper transition)

Returns: Array with values smoothly clamped to [min_value, max_value]

Source code in hyperbolix/utils/math_utils.py
@functools.partial(_jit, static_argnames=["smoothing_factor"])
def smooth_clamp(
    x: Float[Array, "..."], min_value: float, max_value: float, smoothing_factor: float = 50.0
) -> Float[Array, "..."]:
    """Smoothly clamp array values to a range [min_value, max_value]. Range=(min_value, max_value).

    The two-sided clamp is a *difference* of scaled softplus terms, **not** a composition of
    :func:`smooth_clamp_min` and :func:`smooth_clamp_max` (``beta = smoothing_factor``)::

        smooth_clamp(x) = min_value + sp(x - min_value) - sp(x - max_value)

    with ``sp(u) = log(1 + exp(beta*u)) / beta``, evaluated in the stable hinge + remainder form
    (see ``_softplus_tail``). For every window width ``w = max_value - min_value > 0`` and every
    ``beta > 0``:

    * **Bounded**: ``sp`` is increasing so the output is above ``min_value``, and
      ``sp(u) - sp(u - beta*w) < w`` reduces to ``1 < exp(beta*w)`` — true for any positive window.
      The output is therefore strictly inside the window, with no constraint linking ``w`` to
      ``beta``.
    * **Smooth and monotone**: ``C^inf`` with derivative ``sigmoid(beta*(x - min_value)) -
      sigmoid(beta*(x - max_value))`` in ``(0, 1)``, exact at the two bounds as well.
    * **Identity in the interior**: the output differs from ``x`` by ``[exp(-beta*d_min) -
      exp(-beta*d_max)]/beta`` up to higher order, where ``d_min``/``d_max`` are the distances to
      the two bounds; at ``beta=50`` that is below the float32 noise floor once ``x`` is ~0.3 from
      both.

    The composition ``smooth_clamp_min(smooth_clamp_max(x))`` this replaces could return values
    **outside** the window whenever ``w < log(2)/beta`` (0.0139 at the default ``beta=50``), because
    each gated one-sided clamp displaced its boundary input by ``log(2)/beta`` rather than by ~0
    (see :func:`smooth_clamp_min`). Concretely, window ``[0, 0.01]`` at ``beta=50`` returned 0.01386
    for ``x = 0.0`` — 39% above ``max_value`` for an input that needed no clamping at all. Note that
    a *composition* of gate-free one-sided clamps does not fix this: it still overshoots by
    ``log(1 + exp(-beta*w))/beta``, which is of order the window itself in that regime. The
    difference form above is the one that is provably bounded.

    In floating point the strictness degrades only in the saturated tails, where the remainder terms
    underflow to 0 and the output equals ``min_value``/``max_value`` exactly. That is an
    *underflow* of ``exp(-beta*d)``, not an overflow: it happens past ``-log(smallest_subnormal)``,
    measured at ``beta*d`` ~104 in float32 and ~745 in float64. Inclusion in
    ``[min_value, max_value]`` always holds.

    Args:
        x: Input array of any shape
        min_value: Minimum value to clamp to
        max_value: Maximum value to clamp to
        smoothing_factor: Beta parameter for softplus (higher = sharper transition)

    Returns:
        Array with values smoothly clamped to [min_value, max_value]
    """
    # clip(x) + tail(x - min) - tail(x - max) == min + sp(x - min) - sp(x - max). The clip supplies
    # the hinge part exactly (and exactly in range); the two remainders are each <= log(2)/beta.
    return (
        jnp.clip(x, min_value, max_value)
        + _softplus_tail(x - min_value, smoothing_factor)
        - _softplus_tail(x - max_value, smoothing_factor)
    )

smooth_clamp_min

smooth_clamp_min(
    x: Float[Array, ...],
    min_value: float,
    smoothing_factor: float = 50.0,
) -> Float[Array, ...]

Smoothly clamp array values to a minimum using softplus. Range=(min_value, inf).

Implements the gate-free lower clamp (beta = smoothing_factor)::

smooth_clamp_min(x) = min_value + sp(x - min_value),   sp(u) = log(1 + exp(beta*u)) / beta

evaluated in the numerically stable hinge + remainder form (see _softplus_tail). Properties, for every beta > 0:

  • Bounded: sp > 0 everywhere, so the output is strictly above min_value.
  • Smooth and monotone: C^inf with derivative sigmoid(beta*(x - min_value)) in (0, 1) — including at min_value, where it is exactly 1/2.
  • Identity away from the bound: above the bound the output exceeds x by log(1 + exp(-beta*d))/beta ~ exp(-beta*d)/beta with d = x - min_value; at beta=50 that is below the float32 noise floor for d >~ 0.3.

This replaces a jnp.where(x < min_value + eps, softplus_branch, x) gate. That gate was discontinuous: sp(0) = log(2)/beta, not 0, so the softplus branch did not glue onto the identity branch at the switch point but jumped by log(2)/beta (0.0139 at the default beta=50). Composing the two gated one-sided clamps is what let the old smooth_clamp leave its own window.

Args: x: Input array of any shape min_value: Minimum value to clamp to smoothing_factor: Beta parameter for softplus (higher = sharper transition)

Returns: Array with values smoothly clamped above min_value

Source code in hyperbolix/utils/math_utils.py
@functools.partial(_jit, static_argnames=["smoothing_factor"])
def smooth_clamp_min(x: Float[Array, "..."], min_value: float, smoothing_factor: float = 50.0) -> Float[Array, "..."]:
    """Smoothly clamp array values to a minimum using softplus. Range=(min_value, inf).

    Implements the gate-free lower clamp (``beta = smoothing_factor``)::

        smooth_clamp_min(x) = min_value + sp(x - min_value),   sp(u) = log(1 + exp(beta*u)) / beta

    evaluated in the numerically stable hinge + remainder form (see ``_softplus_tail``). Properties,
    for every ``beta > 0``:

    * **Bounded**: ``sp > 0`` everywhere, so the output is strictly above ``min_value``.
    * **Smooth and monotone**: ``C^inf`` with derivative ``sigmoid(beta*(x - min_value))`` in
      ``(0, 1)`` — including *at* ``min_value``, where it is exactly 1/2.
    * **Identity away from the bound**: above the bound the output exceeds ``x`` by
      ``log(1 + exp(-beta*d))/beta ~ exp(-beta*d)/beta`` with ``d = x - min_value``; at ``beta=50``
      that is below the float32 noise floor for ``d >~ 0.3``.

    This replaces a ``jnp.where(x < min_value + eps, softplus_branch, x)`` gate. That gate was
    discontinuous: ``sp(0) = log(2)/beta``, not 0, so the softplus branch did not glue onto the
    identity branch at the switch point but jumped by ``log(2)/beta`` (0.0139 at the default
    ``beta=50``). Composing the two gated one-sided clamps is what let the old ``smooth_clamp``
    leave its own window.

    Args:
        x: Input array of any shape
        min_value: Minimum value to clamp to
        smoothing_factor: Beta parameter for softplus (higher = sharper transition)

    Returns:
        Array with values smoothly clamped above min_value
    """
    # max(x, min) + tail(x - min) == min + sp(x - min), without evaluating sp directly.
    return jnp.maximum(x, min_value) + _softplus_tail(x - min_value, smoothing_factor)

smooth_clamp_max

smooth_clamp_max(
    x: Float[Array, ...],
    max_value: float,
    smoothing_factor: float = 50.0,
) -> Float[Array, ...]

Smoothly clamp array values to a maximum using softplus. Range=(-inf, max_value).

The mirror image of :func:smooth_clamp_min (beta = smoothing_factor)::

smooth_clamp_max(x) = max_value - sp(max_value - x),  sp(u) = log(1 + exp(beta*u)) / beta

so the output is strictly below max_value, C^inf, monotone increasing with derivative sigmoid(beta*(max_value - x)) in (0, 1), and falls short of x below the bound by log(1 + exp(-beta*d))/beta with d = max_value - x. Gate-free for the same reason as the min-side clamp — see :func:smooth_clamp_min.

Args: x: Input array of any shape max_value: Maximum value to clamp to smoothing_factor: Beta parameter for softplus (higher = sharper transition)

Returns: Array with values smoothly clamped below max_value

Source code in hyperbolix/utils/math_utils.py
@functools.partial(_jit, static_argnames=["smoothing_factor"])
def smooth_clamp_max(x: Float[Array, "..."], max_value: float, smoothing_factor: float = 50.0) -> Float[Array, "..."]:
    """Smoothly clamp array values to a maximum using softplus. Range=(-inf, max_value).

    The mirror image of :func:`smooth_clamp_min` (``beta = smoothing_factor``)::

        smooth_clamp_max(x) = max_value - sp(max_value - x),  sp(u) = log(1 + exp(beta*u)) / beta

    so the output is strictly below ``max_value``, ``C^inf``, monotone increasing with derivative
    ``sigmoid(beta*(max_value - x))`` in ``(0, 1)``, and falls short of ``x`` below the bound by
    ``log(1 + exp(-beta*d))/beta`` with ``d = max_value - x``. Gate-free for the same reason as the
    min-side clamp — see :func:`smooth_clamp_min`.

    Args:
        x: Input array of any shape
        max_value: Maximum value to clamp to
        smoothing_factor: Beta parameter for softplus (higher = sharper transition)

    Returns:
        Array with values smoothly clamped below max_value
    """
    # min(x, max) - tail(x - max) == max - sp(max - x); tail is even, so the same helper serves.
    return jnp.minimum(x, max_value) - _softplus_tail(x - max_value, smoothing_factor)

capped_exp

capped_exp(x: Float[Array, ...]) -> Float[Array, ...]

Exponential with an overflow cap on the argument. Domain=(-inf, inf).

Computes exp(minimum(x, 0.99*log(finfo.max))) (cap ≈ 87.8 for f32, ≈ 702.7 for f64), so the result cannot overflow to +inf. The argument is capped rather than the output (clip(exp(x), max)): an output clip still materializes exp(x) = inf in the forward pass and inf in its VJP.

Below the cap this is a bitwise value- and gradient-identity to jnp.exp. Above the cap the gradient is exactly 0 (the minimum selects the constant side), so a parameter past the cap receives no gradient signal to come back down: the saturation hides the divergence and is not recoverable. LearnableCurvature's "log" parameterization caps its exponent the same way. The library's layers do not use capped_exp: their scale parameters go through plain jnp.exp, so a runaway scale overflows to inf and shows up as a NaN loss.

Args: x: Input array of any shape

Returns: exp(x) with the argument capped so the result is always finite

Source code in hyperbolix/utils/math_utils.py
@_jit
def capped_exp(x: Float[Array, "..."]) -> Float[Array, "..."]:
    """Exponential with an overflow cap on the argument. Domain=(-inf, inf).

    Computes ``exp(minimum(x, 0.99*log(finfo.max)))`` (cap ≈ 87.8 for f32, ≈ 702.7 for f64), so the
    result cannot overflow to ``+inf``. The argument is capped rather than the output
    (``clip(exp(x), max)``): an output clip still materializes ``exp(x) = inf`` in the forward pass
    and ``inf`` in its VJP.

    Below the cap this is a bitwise value- and gradient-identity to ``jnp.exp``. Above the cap the
    gradient is exactly 0 (the ``minimum`` selects the constant side), so a parameter past the cap
    receives no gradient signal to come back down: the saturation hides the divergence and is not
    recoverable. ``LearnableCurvature``'s ``"log"`` parameterization caps its exponent the same
    way. The library's layers do not use ``capped_exp``: their scale parameters go through plain
    ``jnp.exp``, so a runaway scale overflows to ``inf`` and shows up as a NaN loss.

    Args:
        x: Input array of any shape

    Returns:
        exp(x) with the argument capped so the result is always finite
    """
    clamp = jnp.log(jnp.finfo(x.dtype).max) * 0.99
    return jnp.exp(cap_at(x, clamp))

Usage Example

from hyperbolix.utils.math_utils import acosh
import jax.numpy as jnp

x = jnp.array([1.5, 2.0, 10.0])
y = acosh(x)  # argument clamped into the open domain near 1.0

smooth_clamp is a differentiable clamp for user code (e.g. bounding a parameter); the library itself does not use it.

capped_exp caps its argument at 0.99·log(finfo.max), so past ≈87.8 (float32) it returns a finite value with zero gradient; the library's layers no longer use it, so a runaway scale parameter shows up as a NaN loss.

Matmul Precision

MATMUL_PRECISION pins the geometry dots (manifold reductions, midpoints, attention scores, MLR heads, the point-to-hyperplane layers, and the x @ V product of FGGLinear/FGGConv2D) to jax.lax.Precision.HIGHEST, so XLA:GPU's default TF32 rounding does not hit the cancellations they rely on; it is not user-configurable, with one exception: LorentzMLA(score_precision=...) sets the precision of its two attention-score einsums only, and defaults to this pin. The other layer weight GEMMs (HTCLinear, the FHCNN/FHNN linears, HypLinearPoincare, LorentzConv2D) pass no precision and follow JAX's jax_default_matmul_precision, which means TF32 on Ampere/Hopper GPUs. To run those in full float32 too, at some cost in throughput, set:

import jax

# JAX-wide (jit-cache aware — changing it re-traces)
jax.config.update("jax_default_matmul_precision", "highest")

# or scoped to a block
with jax.default_matmul_precision("highest"):
    ...

The full list of pinned sites and the measured costs are in TF32 on Ampere and Hopper GPUs.

hyperbolix.utils.precision

Matmul precision for the float32 dot products that touch manifold data.

:data:MATMUL_PRECISION (jax.lax.Precision.HIGHEST) is pinned on the sites where the geometry is computed, and nowhere else. It is not user-configurable, with one named exception: LorentzMLA(score_precision=...) sets the precision of the two attention-score einsums only, and defaults to this pin. A layer's weight GEMM passes no precision keyword at all and follows JAX's own jax_default_matmul_precision, which on Ampere/Hopper means TF32, with two exceptions: the point-to-hyperplane layers, whose kernel dot is one of the pinned geometry einsums, and the FGG layers, whose x @ V is a Minkowski inner product — see the two lists below.

Pinned to HIGHEST
  • the vector-vector reductions inside manifolds/ (behind dist, addition, gyration, expmap, logmap, ptransp, tangent_inner, egrad2rgrad, the Lorentz inner product, the Busemann coordinate and the boundary factors) and the decomposition/ (HoroPCA) contractions. XLA lowers a vector-vector dot to a reduction rather than a tensor-core GEMM, so HIGHEST costs essentially nothing here;
  • lorentz_midpoint and poincare_weighted_midpoint — the two Fréchet-mean normalizers, whose whole design is a cancellation-free identity that only holds to O(eps) if its inputs are float32-accurate;
  • the patch extraction in the hyperboloid, Poincaré and proper-velocity convolutions. XLA implements conv_general_dilated_patches as a convolution against a 0/1 filter, i.e. a pure data copy, so TF32 there would round every input to a 10-bit mantissa for nothing;
  • the attention score and aggregation einsums in hyperboloid_attention.py (the Lorentzian similarity, the softmax scores and weighted values, the linear-attention kernel sums) and the spatial residual projection that is added to that aggregate;
  • the point-to-hyperplane einsums — Hyperboloid._compute_mlr, Poincare._compute_mlr_pp, ProperVelocity._compute_mlr, and the HypRegressionHyperboloid / FGGLorentzMLR heads — because the asinh argument they form is a difference of a radial and an angular term that cancels. The hidden PLFC, Poincaré++ and proper-velocity linear and convolution layers are those einsums applied to their own kernel, so their weight GEMM runs at HIGHEST too: HypLinearHyperboloidPLFC, HypLinearPoincarePP, HypLinearPV, HypConv2DHyperboloidILNN, HypConv2DPoincare and HypConv2DPV;
  • the FGG product x @ V in nn_layers/hyperboloid_linear._fgg_linear_forward, the one weight GEMM of FGGLinear and FGGConv2D. V absorbs the Minkowski metric, so the -x0*V0 + <x_s, V_s> cancellation happens inside a single accumulation — the same product FGGLorentzMLR pins. It followed the default until it was measured on a trained network: see "Why the FGG product is pinned" below.
Following JAX's default

The remaining layer weight GEMMs — HTCLinear (including the attention Q/K/V projections), the FHCNN and FHNN linears, HypLinearPoincare, LorentzConv2D's Euclidean convolution, HypVQMLRPoincare's implicit-codebook matmul and hybrid_regularization's nnx.Linear — carry no precision keyword. These are sites where HIGHEST actually costs throughput (it replaces one TF32 pass with a three-pass float32 emulation; measured +10 % to +25 % on a jitted HyperbolicFullAttention forward on an A100, the two ends from two sessions on the same card), and whether to pay that is the user's call, not the library's.

To run everything in full float32, set JAX's own knob — one line, and jit-cache aware, so changing it re-traces::

jax.config.update("jax_default_matmul_precision", "highest")

or scoped to a block::

with jax.default_matmul_precision("highest"):
    logits = model(x)

A deep, fully hyperbolic stack of these layers is a good reason to do so: the pinned sites keep the geometry honest, but a TF32 error introduced in an early layer's weight GEMM is carried forward by every layer after it. The size of that error on one layer was measured on the FGG product before it was pinned (A100, jax 0.9.1, ambient dim 33, batch 64, c in {0.1, 1.0} x spatial radius in {0.5, 5, 20}, float32 against a float64 reference): FGGLinear 2.6e-4 under TF32 against 6.8e-8 under HIGHEST — roughly ~1e-4 against ~1e-7 on a layer, three of float32's seven significant digits. The FGGLinear arms of the depth comparisons in the next paragraph predate the pin in the same way: their "default" is the FGG product at TF32, which the library no longer runs, and they stay as the comparison for HTCLinear.

Depth decides whether that matters, and at depth 2 it does not. An independent teacher-student comparison (5 seeds per arm, D = 128, B = 256, c = 1, 2 000 Adam updates, independent A100 measurement, jax 0.9.1) found no mean heldout-loss difference between the default and global HIGHEST: 0.27736 against 0.27738 for an HTCLinear stack, 0.28610 against 0.28614 for an FGGLinear one, against a per-arm seed spread of ~0.015-0.017. The float32-vs-float64 gradient error does grow with depth. At depth 16, c = 1, input geodesic radius 5 (same measurement; the grid is in logs/2026-09-06_numerics_independent_review/training/gpu/depth.json): the HTCLinear stack's parameter gradient is 1.539 % relative L2 off a float64 reference under the default against 2.5e-6 under global HIGHEST, and its input gradient 2.013 % against 1.2e-5; the FGGLinear stack at the same cell is 0.199 % against 8.0e-7 and 0.274 % against 1.0e-6. That cell is the worst of a 24-cell grid (depths 2/8/16, c in {0.1, 1}, input radius {0.5, 5}), with one initialisation and one input draw per cell and no seeds — so these are maxima over the grid, not means, and n = 1 per cell. What that grid does record is a radius climb (follow-up probes and their re-derivation in logs/2026-09-06_numerics_review_followup/depth_reversal/ and its audit/): HTCLinear applies its kernel to the full ambient point (x_0, x_s) with zero bias at init, so ||z||^2 ~ x_0^2 + ||x_s||^2 = (1 + 2 sinh(rho_in)^2)/c and the curvature-scaled radius rho = sqrt(c) * r maps forward as rho_out = asinh(sqrt(1 + 2 sinh(rho_in)^2)), an increment of exactly log(sqrt(2)) = 0.347 at large rho — though from a small input radius the first layer jumps to ~0.9 rather than adding 0.35 — and against the recorded per-layer radii that closed form holds within +-0.10 nats (54 % of layers within +-0.04; the residuals are layer-index-dependent, i.e. the gain of that one weight draw); excluding the input->layer-1 step, HTC's mean per-layer increment is 0.36-0.38 nats at depths 8 and 16 and 0.37-0.45 at depth 2 (individual layers 0.29-0.45), against -0.011 … +0.002 for FGGLinear (individual -0.041 … +0.022). At the one pair where it can be checked c enters only through sqrt(c) * r — depth-16 HTC at rho = 6.67 (c = 0.1) and 6.77 (c = 1) give 1.639e-3 and 1.643e-3, 0.24 % apart — but that is n = 1, the matching depth-8 and depth-2 pairs are 10 % and 12 % apart, and the cells do not collapse onto one curve (sorted by rho the HTC cells invert twice, by 9.0 % and 5.9 %, and FGGLinear at depth 16, rho = 4.88 is 2.2x worse than HTC at depth 2, rho = 5.77). That the climb is what makes the TF32 error grow is a hypothesis, with evidence in one direction only: rescaling the HTC kernel by 1/sqrt(2) at c = 1, radius 5, depth 16 holds the radius flat (5.00 -> 4.55) and cuts the parameter-gradient error from 3.23e-3 to 8.31e-4 (3.9x, disjoint ranges, Welch t = 4.6), but the opposite rescaling by sqrt(2) runs the radius up to 15.6 without raising the error (3.39e-3, t = 0.20), and in that same emulation HTC and FGG are indistinguishable at the cell where the GPU grid puts them 7.75x apart (3.23e-3 against 3.11e-3, t = 0.23) — CPU TF32 emulation, 8 rounding realizations, one weight draw, and a different HTC draw from the grid's. At depth 2 the HTC/FGG parameter-gradient ratios are 0.87/0.93/0.97/0.97, which is not an ordering: the single-GEMM TF32 floor with two perturbed operands is sqrt(2)*u/sqrt(3) ~ 4.0e-4 for TF32's unit roundoff u = 2^-11 (3.97e-4 measured on these operands), the r = 0.5 cells sit at that floor (2.9-3.4e-4) while the c = 1, r = 5 cells are 2.3x above it (9.2e-4, 9.5e-4), and on cell means the emulation flips the depth-2 sign in exactly one of the four. Single HTC cells are not tight either — the emulation's realization sd is 6-61 % of the cell mean for HTC against 2-11 % for FGG, and on its weight draw HTC depth 8 is worse than depth 16 in one cell (1.15e-2 against 3.23e-3). Finally, the grid's error is one relative L2 over the whole flattened gradient tree, and at depth 16, c = 1, radius 5 the head kernel carries 86 % of HTC's squared error and 87 % of its squared reference norm (FGGLinear 49 % / 34 %); the per-leaf errors are individually elevated (HTC layers 5-15 ~1.7e-2 against FGG's ~2.5e-3), so this is not a layer-counting artefact, but the reported number is in practice the head-kernel gradient's relative error, on a gradient whose norm the radius inflates (60.8 against 3.53). For a deep or gradient-sensitive stack of these layers, set the global knob (the snippet above).

Why the FGG product is pinned

Until this pin FGGLinear and FGGConv2D followed the default as well, although their x @ V carries the cancellation described in the first list. The depth grid above was the reason: at depth 16 an FGG stack's float32 gradient error under TF32 is smaller than an HTCLinear stack's, which has no cancellation at all. That grid measures gradients at one initialisation per cell. A float64 replay of a trained network overrules that reading.

The network is a Procgen PPO agent (BigFish) with an IMPALA-style encoder of 15 FGGConv2D and one FGGLinear, c = 0.1, trained on an A100 under the JAX default. 72 checkpoints, 2 048 states each, were replayed in float32 at the JAX default, in float32 with jax_default_matmul_precision="highest" and in float64 (audit scripts: logs/2026-10-07_rl-f64-replay-audit/). At the JAX default the greedy action changes 120 times over the 72 checkpoints. In the runs trained without a cap on the feature radius, the relative gap of the head input to float64 is 6e-4 to 7.5e-3 (maxima over the replayed states) and the actor logits are up to 0.14 off (the largest of the 6 144 states of one checkpoint age, three seeds; the median is 2.8e-4 to 1.0e-3 from 32k training steps on and 8.7e-3 at initialisation). With "highest" no greedy action changes, the head input is within about 5e-6 and the actor logits within 1.03e-4, and the forward gaps of those runs drop by a factor of 740 to 2 570. The 16 FGG products are the only products in that network that the setting changes, and they are the products this pin sets to HIGHEST. The relative error enters at the first conv stage (4e-4) and stays near 1e-3: in this network it does not grow with depth. Not measured: any effect on the return.

Why the geometry is pinned rather than left to the same knob

On Ampere/Hopper, XLA:GPU defaults float32 matmuls to TF32, whose 10-bit mantissa carries ~1e-3 relative error — far coarser than float32's ~1e-7. Hyperbolic geometry spends that budget on cancellations whose entire design assumes float32 accuracy:

  • the Lorentz inner product <x,y>_L = -x_0 y_0 + <x_s, y_s>, formed as a difference of two dots (hyperboloid dist/expmap/ptransp, the attention scores, the Busemann coordinate, the HoroPCA ideal-span projections) or inside one accumulation, with the metric absorbed into the weight (the FGG product and the FGGLorentzMLR logits);
  • the lorentz_midpoint normalizer, a cancellation-free identity that exists precisely to keep the float32 error at O(eps) at any radius;
  • the Poincaré/stereographic boundary factors 1 - c*||x||^2 and 1 - 2c<x,y> + c^2||x||^2||y||^2, which cancel to O(eps) for a near-boundary point;
  • the MLR asinh arguments on both models, a difference of a radial and an angular term.

Measured on an A100 (jax 0.9.1): the f32-vs-f64 relative error of lorentz_midpoint is 4.6e-5 … 2.6e-4 at the TF32 default and 2.6e-8 … 1.6e-7 with HIGHEST — a ~2000x accuracy loss that HIGHEST removes. The eager float32 gradient of the hyperboloid MLR improves from 1.5e-4 to 2.7e-7 relative over the same switch. These are not throughput-critical sites, so the library pays for the accuracy rather than exposing the choice. The FGG product is different in kind, the weight GEMM of every FGG layer, and is pinned on the measurement in the section above. Its cost on one H100: 2 % on the forward pass and 9 % on forward plus backward for an IMPALA-ResNet of FGG layers at batch 1,024, and 5 to 16 % on forward plus backward for a single layer.

This module lives in utils/ — a neutral home both manifolds/ and nn_layers/ can import from, since manifolds/ must not depend on nn_layers/. MATMUL_PRECISION was originally defined in hyperbolix.nn_layers.hyperboloid_core, which re-exports it, so hyperboloid_core.MATMUL_PRECISION keeps working.

HIGHEST is a no-op on CPU (no TF32 path) and for float64 anywhere, so the pinning costs nothing outside float32 GPU matmuls.

MATMUL_PRECISION module-attribute

MATMUL_PRECISION = HIGHEST

Precision for every dot product that computes geometry rather than a layer's weights.

Fixed at HIGHEST and not user-configurable, except for the two score einsums of LorentzMLA(score_precision=...) (which default to this value): accuracy here is a property of the geometry, not a knob. The module docstring lists the pinned sites and the measurements behind them. The layer weight GEMMs pass no precision keyword and follow jax_default_matmul_precision instead — all but the point-to-hyperplane layers, whose kernel dot is one of the pinned einsums, and the FGG layers, whose x @ V is a Minkowski inner product.

Learnable Curvature

LearnableCurvature is an nnx.Module that bundles a Euclidean raw parameter, a curvature reparameterization (positive softplus/log, or the signed identity — c = raw — for the Stereographic manifold), and a [c_min, c_max] clamp (on by default: [init_c/10, init_c·10] for softplus/log, [-10, 10] for identity; pass None to disable) into one object. Assign one instance per distinct curvature on your model and call it in the forward pass to obtain the (optionally clamped) curvature.

hyperbolix.utils.curvature.LearnableCurvature

LearnableCurvature(
    init_c: float = 1.0,
    *,
    parameterization: Parameterization = "log",
    c_min: float | None | Auto = AUTO,
    c_max: float | None | Auto = AUTO,
    param_dtype: DTypeLike = jnp.float32,
)

Bases: Module

Reparameterized learnable curvature parameter.

Stores a single Euclidean nnx.Param whose value is mapped to a curvature on every forward call — positive for softplus/log, signed for identity. Three parameterizations are supported, with optional clamping of the recovered curvature to [c_min, c_max] for hard stability guarantees in compiled training loops; the log parameterization additionally caps its exponent so a large raw cannot overflow exp to a NaN gradient.

Usage::

self.curvature = LearnableCurvature(init_c=0.1)
...
c = self.curvature()  # positive jax.Array

Args: init_c: Initial curvature value. Must be positive for softplus/log; any sign (including 0.0) for identity. If clamp bounds are set, must also satisfy c_min <= init_c <= c_max; it may sit on a bound. parameterization: Reparameterization scheme.

    - ``"log"`` (default): ``c = exp(raw)`` — strictly positive. Scale-invariant
      gradient (``dc/draw = c``); preferred when ``c`` may span orders of
      magnitude or for long compiled RL training loops. Matches the
      MERU convention.
    - ``"softplus"``: ``c = softplus(raw)`` — strictly positive. Gradient
      bounded by ``sigmoid(raw) in (0, 1)``; smooth near zero. The
      reparameterization itself (``raw`` = inverse-softplus of ``c``) is
      geoopt's ``Stereographic``/``PoincareBall`` convention, and is the
      code default (``learnable=True``) in the van Spengler et al. 2023
      Poincare ResNet reference implementation, which builds its manifold
      on geoopt. Note the paper's own reported curvature experiments
      (Sec. 4.2) sweep fixed values ``c in {1, 0.1, 0.01}`` and settle on
      ``c=0.1`` — not this learnable scheme.
    - ``"identity"``: ``c = raw`` — **signed**. Spans hyperbolic (``c>0``),
      Euclidean (``c=0``), and spherical (``c<0``) curvature for the
      :class:`~hyperbolix.manifolds.Stereographic` manifold; ``dc/draw = 1``,
      so it can cross zero. The only parameterization that reaches ``c<=0``.

c_min: Lower clamp applied to the recovered ``c``. The default,
    :data:`AUTO`, resolves per parameterization: ``init_c / 10`` for
    ``softplus``/``log`` (a decade below the init, PhyCLIP's range),
    ``-10.0`` for the signed ``identity``. Pass ``None`` to disable, or a
    float to override.
c_max: Upper clamp applied to the recovered ``c``. The default,
    :data:`AUTO`, resolves to ``init_c * 10`` for ``softplus``/``log``
    (``[0.1, 10]`` at the default ``init_c=1.0``), ``10.0`` for
    ``identity``. Pass ``None`` to disable, or a float to override.
param_dtype: Storage dtype of the raw parameter (default:
    ``jnp.float32``), pinned so it does not become float64 under
    global ``jax_enable_x64``.

Sharing note: Do not assign the same LearnableCurvature instance to multiple fields if you want independent learnable curvatures — instantiate one per location. Sharing creates a shared-reference pattern in the NNX pytree that breaks nnx.scan / nnx.fori_loop (same root cause as the pre-refactor manifold bug).

Clamp: the forward value is the recovered c clipped to [c_min, c_max]. Strictly inside the interval the gradient is the full chain rule, dc/draw times the incoming gradient. On a bound or outside it, the gradient passes only if it points inside (at or below c_min, one under which gradient descent raises c; at or above c_max, one under which it lowers c); an outward gradient is set to exactly 0. This is projected gradient descent with the projection folded into the forward pass, so the train step needs no extra call: c rests on a bound while the loss pushes it outward and comes off it once the loss pulls it back, and a blocked gradient does not feed Adam's moments. raw itself is not clamped, but it does not drift: it leaves the interval only by the step that crossed the bound (plus the optimizer's decaying momentum). Coming back takes only the few steps that walk that overshoot back, each sized like an interior step at the bound, so no damping is needed. A c that sits on a bound for many steps is held there by the loss; widen the bound if that is unwanted. The clamp sees each call's gradient separately, so call the instance once per forward and reuse c: in a toy fit where two calls of one instance pulled opposite ways at the floor, c hovered up to 0.21 % above it under Adam at 1e-2 (a level reached after about 10,000 steps and then held; 0.15 % under SGD), while one reused call held it on the floor.

Forward mode: the clamp's backward is a custom VJP, so jax.jvp and jax.jacfwd through a clamped instance raise a TypeError (jax.hessian, which is forward-over-reverse, works); with c_min=None, c_max=None it is plain autodiff.

Init: raw is the inverse of init_c rounded to param_dtype. For an init_c on a bound, that rounding can recover a c exactly on it, one float outside it (float32 exp(float32(log 0.1)) = 0.099999994) or one float inside it (float64 exp(log 0.1) = 0.10000000000000002). On or outside the bound, c starts on the bound, where from the first step the outward gradient is blocked and the inward one passes. One float inside, c starts as an interior point.

Source code in hyperbolix/utils/curvature.py
def __init__(
    self,
    init_c: float = 1.0,
    *,
    parameterization: Parameterization = "log",
    c_min: float | None | Auto = AUTO,
    c_max: float | None | Auto = AUTO,
    param_dtype: DTypeLike = jnp.float32,
):
    if parameterization not in ("softplus", "log", "identity"):
        raise ValueError(f"parameterization must be 'softplus', 'log', or 'identity', got {parameterization!r}")
    signed = parameterization == "identity"

    # NaN slips through every range check below (all comparisons with NaN are False), silently storing
    # a NaN raw param that poisons the whole model — reject it up front.
    if not math.isfinite(init_c):
        raise ValueError(f"init_c must be finite, got {init_c}")
    # softplus/exp map onto (0, inf) and cannot represent c <= 0, so a non-positive init is a usage error
    # there. identity is signed and accepts any init_c (including 0.0 and negatives).
    if not signed and init_c <= 0:
        raise ValueError(f"LearnableCurvature requires init_c > 0 for parameterization {parameterization!r}, got {init_c}")

    # Resolve sentinel clamp bounds from the parameterization: softplus/log default to a decade either side
    # of init_c; identity uses a symmetric magnitude cap [-10, 10]. Explicit None still disables a bound;
    # explicit numeric bounds are honored verbatim.
    if isinstance(c_min, Auto):
        c_min = -_C_ABS_MAX if signed else init_c / _SPAN
    if isinstance(c_max, Auto):
        c_max = _C_ABS_MAX if signed else init_c * _SPAN

    if c_min is not None and c_max is not None and c_min > c_max:
        raise ValueError(f"c_min ({c_min}) must be <= c_max ({c_max})")
    if c_min is not None and init_c < c_min:
        raise ValueError(f"init_c ({init_c}) must be >= c_min ({c_min})")
    if c_max is not None and init_c > c_max:
        raise ValueError(f"init_c ({init_c}) must be <= c_max ({c_max})")

    self._parameterization = parameterization
    self._c_min = c_min
    self._c_max = c_max

    self.raw = nnx.Param(jnp.array(self._inverse(init_c), dtype=param_dtype))

AUTO is the default of c_min and c_max: it resolves each bound from the parameterization, as described above. Auto is its type.

hyperbolix.utils.curvature.AUTO module-attribute

AUTO = Auto()

Default c_min/c_max of :class:LearnableCurvature: resolve the bound from the parameterization.

hyperbolix.utils.curvature.Auto

Type of :data:AUTO, the default c_min/c_max of :class:LearnableCurvature.

AUTO means "resolve this clamp bound from the parameterization" (see :class:LearnableCurvature), as opposed to None, which disables the bound. Layers that build LearnableCurvature instances, such as :class:~hyperbolix.nn_layers.LorentzMoE, take AUTO as their default too and forward it. Test for it with isinstance(bound, Auto).

Usage Example

from flax import nnx
import optax
from hyperbolix import LearnableCurvature
from hyperbolix.manifolds import Hyperboloid
from hyperbolix.nn_layers import HypLinearHyperboloidPLFC


class Model(nnx.Module):
    def __init__(self, rngs: nnx.Rngs):
        self.manifold = Hyperboloid(c=1.0)               # static, shared
        self.curvature = LearnableCurvature(             # one per distinct c
            init_c=1.0,
            parameterization="log",                      # default; or "softplus"
            c_min=0.1, c_max=10.0,                       # the default: init_c / 10, init_c * 10
        )
        self.fc = HypLinearHyperboloidPLFC(self.manifold, 33, 65, rngs=rngs)

    def __call__(self, x):
        c = self.curvature()                              # positive, clamped
        return self.fc(x, c=c)


# Updated by any standard Euclidean optimizer — no Riemannian optimizer needed.
model = Model(nnx.Rngs(0))
optimizer = nnx.Optimizer(model, optax.adam(1e-3), wrt=nnx.Param)

See the Manifolds User Guide — Working with Curvature for the full discussion of parameterizations, clamping, the nnx.scan sharing rule, and per-factor ProductManifold usage.

Helper Functions

Helper utilities for distance computation and delta-hyperbolicity analysis.

hyperbolix.utils.helpers

Helper utilities for hyperbolic geometry computations.

This module provides utilities for computing pairwise distances, delta-hyperbolicity metrics, and other geometric measures on hyperbolic manifolds.

compute_pairwise_distances

compute_pairwise_distances(
    points: Float[Array, "n_points dim"],
    manifold_module: Manifold,
    c: ScalarCurvature,
    version_idx: int = 0,
) -> Float[Array, "n_points n_points"]

Compute pairwise geodesic distances between points on a manifold.

This function computes the full distance matrix efficiently by leveraging JAX's vmap for vectorization. The computation is NOT chunked - the entire distance matrix is computed in a single pass using nested vmap operations.

Memory Considerations: For n points, this computes an n-by-n distance matrix in memory. For very large point sets (>5000-10000 points depending on available memory), consider subsampling or implementing a chunked version. The current implementation prioritizes simplicity and leverages XLA's automatic memory optimizations.

Args: points: Points on the manifold, shape (n_points, dim) For Hyperboloid: dim is ambient dimension (dim+1) For PoincareBall: dim is intrinsic dimension manifold_module: Manifold instance (anything satisfying the Manifold protocol) c: Curvature parameter (positive scalar; a per-factor sequence for ProductManifold) version_idx: Distance version index (manifold-specific, default: 0) For Hyperboloid: 0 = VERSION_DEFAULT (cancellation-free hyperbolic haversine) 1 = VERSION_SMOOTHENED (smoothened distance) For PoincareBall: 0 = VERSION_MOBIUS_DIRECT (direct Möbius formula) 1 = VERSION_MOBIUS (via addition) 2 = VERSION_METRIC_TENSOR (metric tensor induced) Euclidean, Stereographic and ProductManifold have a single distance implementation and accept-and-ignore this argument.

Returns: Symmetric distance matrix of shape (n_points, n_points)

Examples: >>> import jax >>> from hyperbolix.manifolds import Hyperboloid >>> from hyperbolix.utils.helpers import compute_pairwise_distances >>> >>> # Generate random hyperboloid points >>> manifold = Hyperboloid() >>> key = jax.random.PRNGKey(0) >>> points = jax.random.normal(key, (100, 11)) >>> points = jax.vmap(manifold.proj, in_axes=(0, None))(points, 1.0) >>> >>> # Compute pairwise distances >>> distmat = compute_pairwise_distances( ... points, manifold, c=1.0, version_idx=manifold.VERSION_DEFAULT ... ) >>> distmat.shape (100, 100)

Notes: - The PyTorch reference implementation used explicit chunking for memory management. This JAX version uses vmap and relies on XLA optimization. - The distance matrix is symmetric: distmat[i, j] == distmat[j, i] - Diagonal elements are zero: distmat[i, i] == 0 - For large datasets, consider subsampling before calling this function

Source code in hyperbolix/utils/helpers.py
def compute_pairwise_distances(
    points: Float[Array, "n_points dim"],
    manifold_module: Manifold,
    c: ScalarCurvature,
    version_idx: int = 0,
) -> Float[Array, "n_points n_points"]:
    """Compute pairwise geodesic distances between points on a manifold.

    This function computes the full distance matrix efficiently by leveraging
    JAX's vmap for vectorization. The computation is NOT chunked - the entire
    distance matrix is computed in a single pass using nested vmap operations.

    Memory Considerations:
        For n points, this computes an n-by-n distance matrix in memory. For very
        large point sets (>5000-10000 points depending on available memory),
        consider subsampling or implementing a chunked version. The current
        implementation prioritizes simplicity and leverages XLA's automatic
        memory optimizations.

    Args:
        points: Points on the manifold, shape (n_points, dim)
            For Hyperboloid: dim is ambient dimension (dim+1)
            For PoincareBall: dim is intrinsic dimension
        manifold_module: Manifold instance (anything satisfying the ``Manifold`` protocol)
        c: Curvature parameter (positive scalar; a per-factor sequence for ``ProductManifold``)
        version_idx: Distance version index (manifold-specific, default: 0)
            For Hyperboloid:
                0 = VERSION_DEFAULT (cancellation-free hyperbolic haversine)
                1 = VERSION_SMOOTHENED (smoothened distance)
            For PoincareBall:
                0 = VERSION_MOBIUS_DIRECT (direct Möbius formula)
                1 = VERSION_MOBIUS (via addition)
                2 = VERSION_METRIC_TENSOR (metric tensor induced)
            Euclidean, Stereographic and ProductManifold have a single distance
            implementation and accept-and-ignore this argument.

    Returns:
        Symmetric distance matrix of shape (n_points, n_points)

    Examples:
        >>> import jax
        >>> from hyperbolix.manifolds import Hyperboloid
        >>> from hyperbolix.utils.helpers import compute_pairwise_distances
        >>>
        >>> # Generate random hyperboloid points
        >>> manifold = Hyperboloid()
        >>> key = jax.random.PRNGKey(0)
        >>> points = jax.random.normal(key, (100, 11))
        >>> points = jax.vmap(manifold.proj, in_axes=(0, None))(points, 1.0)
        >>>
        >>> # Compute pairwise distances
        >>> distmat = compute_pairwise_distances(
        ...     points, manifold, c=1.0, version_idx=manifold.VERSION_DEFAULT
        ... )
        >>> distmat.shape
        (100, 100)

    Notes:
        - The PyTorch reference implementation used explicit chunking for memory
          management. This JAX version uses vmap and relies on XLA optimization.
        - The distance matrix is symmetric: distmat[i, j] == distmat[j, i]
        - Diagonal elements are zero: distmat[i, i] == 0
        - For large datasets, consider subsampling before calling this function
    """

    # We need to compute dist for all pairs (i, j)
    def dist_fn(x, y):
        return manifold_module.dist(x, y, c, version_idx)

    # Use vmap to vectorize over both dimensions
    # First vmap over y (columns), then over x (rows)
    dist_col = jax.vmap(dist_fn, in_axes=(None, 0))  # Broadcasts x over all y
    dist_matrix_fn = jax.vmap(dist_col, in_axes=(0, None))  # Broadcasts over all x

    # Compute full distance matrix
    distmat = dist_matrix_fn(points, points)

    return distmat

compute_hyperbolic_delta

compute_hyperbolic_delta(
    distmat: Float[Array, "n_points n_points"],
    version: str = "average",
) -> Float[Array, ""]

Compute the delta-hyperbolicity value from a distance matrix.

Delta-hyperbolicity is a metric space property that quantifies how "tree-like" or "hyperbolic" a metric space is. It is based on the Gromov 4-point condition.

For any four points w, x, y, z in a metric space, define: S1 = d(w,x) + d(y,z) S2 = d(w,y) + d(x,z) S3 = d(w,z) + d(x,y)

The 4-point condition requires that the two largest of these sums differ by at most 2δ. A space is δ-hyperbolic if this holds for all quadruples.

This implementation uses a reference point (the first point) to compute Gromov products efficiently: (x|y)_w = [d(w,x) + d(w,y) - d(x,y)] / 2

Args: distmat: Symmetric distance matrix, shape (n_points, n_points) version: Which delta statistic to compute (default: "average") - "average": Mean of delta values over all point quadruples - "smallest": Maximum delta (worst-case over all quadruples)

Returns: Delta-hyperbolicity value (scalar)

References: Gromov, M. (1987). "Hyperbolic groups." Essays in group theory. Chami, I., et al. (2021). "HoroPCA: Hyperbolic dimensionality reduction via horospherical projections." ICML 2021.

Examples: >>> import jax.numpy as jnp >>> from hyperbolix.utils.helpers import compute_hyperbolic_delta >>> >>> # Create a distance matrix (should be symmetric) >>> distmat = jnp.array([ ... [0.0, 1.0, 2.0, 3.0], ... [1.0, 0.0, 1.5, 2.5], ... [2.0, 1.5, 0.0, 1.0], ... [3.0, 2.5, 1.0, 0.0] ... ]) >>> >>> delta_avg = compute_hyperbolic_delta(distmat, version="average") >>> delta_max = compute_hyperbolic_delta(distmat, version="smallest")

Notes: - The result is scaled by 2 because we fix a reference point - Lower delta values indicate more hyperbolic (tree-like) structure - Euclidean spaces have unbounded delta; hyperbolic spaces have bounded delta

Source code in hyperbolix/utils/helpers.py
def compute_hyperbolic_delta(distmat: Float[Array, "n_points n_points"], version: str = "average") -> Float[Array, ""]:
    """Compute the delta-hyperbolicity value from a distance matrix.

    Delta-hyperbolicity is a metric space property that quantifies how "tree-like"
    or "hyperbolic" a metric space is. It is based on the Gromov 4-point condition.

    For any four points w, x, y, z in a metric space, define:
        S1 = d(w,x) + d(y,z)
        S2 = d(w,y) + d(x,z)
        S3 = d(w,z) + d(x,y)

    The 4-point condition requires that the two largest of these sums differ by at
    most 2δ. A space is δ-hyperbolic if this holds for all quadruples.

    This implementation uses a reference point (the first point) to compute
    Gromov products efficiently:
        (x|y)_w = [d(w,x) + d(w,y) - d(x,y)] / 2

    Args:
        distmat: Symmetric distance matrix, shape (n_points, n_points)
        version: Which delta statistic to compute (default: "average")
            - "average": Mean of delta values over all point quadruples
            - "smallest": Maximum delta (worst-case over all quadruples)

    Returns:
        Delta-hyperbolicity value (scalar)

    References:
        Gromov, M. (1987). "Hyperbolic groups." Essays in group theory.
        Chami, I., et al. (2021). "HoroPCA: Hyperbolic dimensionality reduction
            via horospherical projections." ICML 2021.

    Examples:
        >>> import jax.numpy as jnp
        >>> from hyperbolix.utils.helpers import compute_hyperbolic_delta
        >>>
        >>> # Create a distance matrix (should be symmetric)
        >>> distmat = jnp.array([
        ...     [0.0, 1.0, 2.0, 3.0],
        ...     [1.0, 0.0, 1.5, 2.5],
        ...     [2.0, 1.5, 0.0, 1.0],
        ...     [3.0, 2.5, 1.0, 0.0]
        ... ])
        >>>
        >>> delta_avg = compute_hyperbolic_delta(distmat, version="average")
        >>> delta_max = compute_hyperbolic_delta(distmat, version="smallest")

    Notes:
        - The result is scaled by 2 because we fix a reference point
        - Lower delta values indicate more hyperbolic (tree-like) structure
        - Euclidean spaces have unbounded delta; hyperbolic spaces have bounded delta
    """
    # Set the first point as reference and compute pairwise Gromov products
    # Gromov product: (x|y)_w = [d(w,x) + d(w,y) - d(x,y)] / 2
    # We use point 0 as reference: (i|j)_0 = [d(0,i) + d(0,j) - d(i,j)] / 2

    # distmat_i0[i, j] = d(i, 0) for all j (broadcast column 0 across columns)
    distmat_i0 = jnp.tile(distmat[:, 0:1], (1, distmat.shape[0]))  # shape: (n, n)
    # distmat_0j[i, j] = d(0, j) for all i (broadcast row 0 across rows)
    distmat_0j = jnp.tile(distmat[0:1, :], (distmat.shape[0], 1))  # shape: (n, n)

    # Compute Gromov product matrix: (i|j)_0 for all pairs (i, j)
    gromov_prod_mat = (distmat_i0 + distmat_0j - distmat) / 2.0  # shape: (n, n)

    # (max, min)-matrix product of the Gromov product matrix with itself:
    #     (G ⊠ G)[i, j] = max_k min( (i|k)_0 , (k|j)_0 )
    # The two operands must be indexed on DIFFERENT rows — the first on i, the second on the
    # summation index k. Indexing both on row i (the historical bug) gives
    # max_k min(G[i,k], G[i,j]) == G[i,j] whenever k = j is admissible, so `delta_matrix` was
    # identically 0 for every input and `get_delta` always reported 0.

    # Computed as a scan over k with a running elementwise maximum, NOT as one broadcast
    # jnp.minimum((n, 1, n), (1, n, n)): that materializes an (n, n, n) buffer — 27 GB in
    # float64 at get_delta's default sample_size=1500 — while the scan needs O(n^2) memory
    # (one (n, n) candidate per step, executed as a compiled loop even when called eagerly).
    def _step(running_max_NN, gromov_k):
        col_N, row_N = gromov_k  # G[:, k] = (i|k)_0 and G[k, :] = (k|j)_0
        cand_NN = jnp.minimum(col_N[:, None], row_N[None, :])  # (i, j) -> min((i|k)_0, (k|j)_0)
        return jnp.maximum(running_max_NN, cand_NN), None

    init_NN = jnp.full_like(gromov_prod_mat, -jnp.inf)
    # xs leading axis is k: (gromov_prod_mat.T)[k] = G[:, k], (gromov_prod_mat)[k] = G[k, :]
    max_min_prod, _ = jax.lax.scan(_step, init_NN, (gromov_prod_mat.T, gromov_prod_mat))

    # Compute delta for each pair: max_k{min((i|k)_0, (k|j)_0)} - (i|j)_0
    delta_matrix = max_min_prod - gromov_prod_mat  # shape: (n, n)

    # Compute the requested statistic
    if version == "average":
        delta = jnp.mean(delta_matrix)
    else:  # "smallest" (which is actually the maximum delta value)
        delta = jnp.max(delta_matrix)

    # Rescale delta since a reference point was fixed
    # The factor of 2 accounts for the fact that we fixed one point
    res = 2.0 * delta

    return res

get_delta

get_delta(
    points: Float[Array, "n_points dim"],
    manifold_module: Manifold,
    c: ScalarCurvature,
    version_idx: int = 0,
    sample_size: int = 1500,
    version: str = "average",
    key: Key[Array, ""] | None = None,
) -> tuple[
    Float[Array, ""], Float[Array, ""], Float[Array, ""]
]

Compute delta-hyperbolicity and related metrics for a point set.

This function subsamples points (if needed), computes the pairwise distance matrix, and then calculates the delta-hyperbolicity value along with the diameter and relative delta (delta normalized by diameter).

Args: points: Points on the manifold, shape (n_points, dim) manifold_module: Manifold instance (anything satisfying the Manifold protocol) c: Curvature parameter (positive scalar; a per-factor sequence for ProductManifold) version_idx: Distance version index (manifold-specific, default: 0) sample_size: Maximum number of points to use for delta computation (default: 1500). If n_points > sample_size, randomly subsample. version: Which delta statistic to compute (default: "average") - "average": Mean of delta values - "smallest": Maximum delta (worst-case) key: JAX random key for subsampling (required if n_points > sample_size)

Returns: Tuple of (delta, diameter, relative_delta): - delta: Delta-hyperbolicity value - diameter: Maximum pairwise distance in the point set - relative_delta: delta / diameter (scale-invariant measure)

Examples: >>> import jax >>> from hyperbolix.manifolds import Hyperboloid >>> from hyperbolix.utils.helpers import get_delta >>> >>> # Generate random hyperboloid points >>> manifold = Hyperboloid() >>> key = jax.random.PRNGKey(42) >>> points = jax.random.normal(key, (400, 11)) >>> points = jax.vmap(manifold.proj, in_axes=(0, None))(points, 1.0) >>> >>> # Compute delta metrics (subsampling 200 of the 400 points) >>> key, subkey = jax.random.split(key) >>> delta, diam, rel_delta = get_delta( ... points, manifold, c=1.0, sample_size=200, key=subkey ... ) >>> bool(delta > 0.0) and bool(0.0 < rel_delta < 1.0) True

Notes: - Subsampling is done randomly without replacement - For reproducibility, always provide the same random key - The PyTorch version used torch.randperm; we use jax.random.permutation

Source code in hyperbolix/utils/helpers.py
def get_delta(
    points: Float[Array, "n_points dim"],
    manifold_module: Manifold,
    c: ScalarCurvature,
    version_idx: int = 0,
    sample_size: int = 1500,
    version: str = "average",
    key: Key[Array, ""] | None = None,
) -> tuple[Float[Array, ""], Float[Array, ""], Float[Array, ""]]:
    """Compute delta-hyperbolicity and related metrics for a point set.

    This function subsamples points (if needed), computes the pairwise distance
    matrix, and then calculates the delta-hyperbolicity value along with the
    diameter and relative delta (delta normalized by diameter).

    Args:
        points: Points on the manifold, shape (n_points, dim)
        manifold_module: Manifold instance (anything satisfying the ``Manifold`` protocol)
        c: Curvature parameter (positive scalar; a per-factor sequence for ``ProductManifold``)
        version_idx: Distance version index (manifold-specific, default: 0)
        sample_size: Maximum number of points to use for delta computation
            (default: 1500). If n_points > sample_size, randomly subsample.
        version: Which delta statistic to compute (default: "average")
            - "average": Mean of delta values
            - "smallest": Maximum delta (worst-case)
        key: JAX random key for subsampling (required if n_points > sample_size)

    Returns:
        Tuple of (delta, diameter, relative_delta):
            - delta: Delta-hyperbolicity value
            - diameter: Maximum pairwise distance in the point set
            - relative_delta: delta / diameter (scale-invariant measure)

    Examples:
        >>> import jax
        >>> from hyperbolix.manifolds import Hyperboloid
        >>> from hyperbolix.utils.helpers import get_delta
        >>>
        >>> # Generate random hyperboloid points
        >>> manifold = Hyperboloid()
        >>> key = jax.random.PRNGKey(42)
        >>> points = jax.random.normal(key, (400, 11))
        >>> points = jax.vmap(manifold.proj, in_axes=(0, None))(points, 1.0)
        >>>
        >>> # Compute delta metrics (subsampling 200 of the 400 points)
        >>> key, subkey = jax.random.split(key)
        >>> delta, diam, rel_delta = get_delta(
        ...     points, manifold, c=1.0, sample_size=200, key=subkey
        ... )
        >>> bool(delta > 0.0) and bool(0.0 < rel_delta < 1.0)
        True

    Notes:
        - Subsampling is done randomly without replacement
        - For reproducibility, always provide the same random key
        - The PyTorch version used torch.randperm; we use jax.random.permutation
    """
    n_points = points.shape[0]

    # Subsample points if necessary
    if n_points > sample_size:
        if key is None:
            raise ValueError(f"Random key required for subsampling (n_points={n_points} > sample_size={sample_size})")
        # Random permutation of indices
        indices = jax.random.permutation(key, n_points)[:sample_size]
        sub_points = points[indices]
    else:
        sub_points = points

    # Compute pairwise distances
    distmat = compute_pairwise_distances(sub_points, manifold_module, c, version_idx)

    # Compute delta-hyperbolicity
    delta = compute_hyperbolic_delta(distmat, version)

    # Compute diameter (maximum distance)
    diam = jnp.max(distmat)

    # Compute relative delta (scale-invariant)
    rel_delta = delta / diam

    return delta, diam, rel_delta

Usage Examples

Pairwise Distances

import jax
import jax.numpy as jnp
from hyperbolix.utils.helpers import compute_pairwise_distances
from hyperbolix.manifolds import Poincare

poincare = Poincare()

# Set of points on Poincaré ball
points = jnp.array([
    [0.1, 0.2],
    [0.3, -0.1],
    [-0.2, 0.4],
    [0.0, 0.0]
])

# Compute all pairwise distances
dist_matrix = compute_pairwise_distances(
    points,
    manifold_module=poincare,
    c=1.0,
    version_idx=0
)

# Result: (4, 4) matrix of distances
print(dist_matrix.shape)  # (4, 4)

Delta-Hyperbolicity

Measure how "hyperbolic" a dataset is using the Gromov delta metric:

import jax
import jax.numpy as jnp
from hyperbolix.utils.helpers import get_delta
from hyperbolix.manifolds import Poincare

poincare = Poincare()

# Generate random points
key = jax.random.PRNGKey(0)
points = jax.random.normal(key, (100, 2)) * 0.3

# Project to Poincaré ball
points_proj = jax.vmap(poincare.proj, in_axes=(0, None))(points, 1.0)

# Compute delta-hyperbolicity
delta, diameter, rel_delta = get_delta(
    points_proj,
    manifold_module=poincare,
    c=1.0,
    sample_size=500,  # at most this many points are used (default 1500)
    key=jax.random.PRNGKey(42),  # Only used when len(points) > sample_size
)

print(f"Delta: {delta:.4f}")
print(f"Diameter: {diameter:.4f}")
print(f"Relative delta: {rel_delta:.4f}")

The Gromov delta quantifies tree-likeness:

  • δ ≈ 0: Perfect tree structure (hyperbolic)
  • δ > 0: Non-tree structure (less hyperbolic)
  • δ/diameter: Normalized measure (relative delta)

Performance Tips

JIT Compilation

The helpers can be jitted by closing over the manifold, as below:

import jax
from hyperbolix.manifolds import Poincare
from hyperbolix.utils.helpers import compute_pairwise_distances

poincare = Poincare()

@jax.jit
def compute_all_distances(points, c):
    return compute_pairwise_distances(
        points,
        manifold_module=poincare,
        c=c,
        version_idx=0
    )

Subsampling

For large datasets, a smaller sample_size makes delta-hyperbolicity faster:

delta, diameter, rel_delta = get_delta(
    points,
    manifold_module=poincare,
    c=1.0,
    sample_size=100,  # default sample_size is 1500
    key=jax.random.PRNGKey(42),
)

References

  • Gromov Delta: Gromov, M. (1987). "Hyperbolic groups."

See also: