Skip to content

Primitives & Helpers

Cross-cutting functions that back the layers on the other pages — the Hyperboloid transformation/regularization components, point-assembly and concatenation helpers, midpoints, residuals, and the statistical reductions used by normalization. They are collected here (rather than scattered across consumer pages) so a given helper has one documented home.

HTC / HRC components

The Hyperbolic Transformation Component (HTC) applies a Euclidean function to the full point; the Hyperbolic Regularization Component (HRC) applies it to the space components only, then reconstructs time. Both support curvature changes (c_in → c_out) and underpin HTCLinear, the HRC* norms, and LorentzConv2D.

hyperbolix.nn_layers.htc

htc(
    x: Float[Array, "... in_dim_plus_1"],
    f_t: Callable[[Float[Array, ...]], Float[Array, ...]],
    c_in: float,
    c_out: float,
    eps: float = 1e-07,
) -> Float[Array, "... out_dim_plus_1"]

Hyperbolic Transformation Component.

Applies a Euclidean linear transformation f_t to the full hyperboloid point (including time component), then maps the result to the hyperboloid with curvature c_out.

Mathematical formula: space = sqrt(c_in/c_out) * f_t(x) time = sqrt(||space||^2 + 1/c_out) output = [time, space]

where f_t takes the full (dim+1)-dimensional input and produces the output spatial components.

Parameters:

Name Type Description Default
x Array of shape (..., in_dim+1)

Input point(s) on the hyperboloid manifold with curvature c_in. All components (time and spatial) are passed to f_t.

required
f_t Callable

Euclidean linear transformation applied to the full input. Takes (in_dim+1)-dimensional input and produces out_dim-dimensional output (which becomes the spatial components of the output).

required
c_in float

Input curvature parameter (must be positive, c > 0).

required
c_out float

Output curvature parameter (must be positive, c > 0).

required
eps float

Small value for numerical stability (default: 1e-7).

1e-07

Returns:

Name Type Description
y Array of shape (..., out_dim+1)

Output point(s) on the hyperboloid manifold with curvature c_out.

Notes
  • Unlike HRC, f_t operates on the full point including the time component
  • f_t's output dimension determines the output spatial dimension
  • This is typically used for learnable linear transformations
  • The spatial scaling factor sqrt(c_in/c_out) ensures proper curvature transformation
See Also

hrc : Hyperbolic Regularization Component for spatial-only operations. HTCLinear : Module wrapper for htc with learnable linear transformation.

References

Yang et al., "Hypformer: Exploring Efficient Transformer Fully in Hyperbolic Space", 2025.

Examples:

>>> import jax
>>> import jax.numpy as jnp
>>> from hyperbolix.nn_layers.hyperboloid_core import htc
>>> from hyperbolix.manifolds import Hyperboloid
>>>
>>> # Create a point on the hyperboloid
>>> manifold = Hyperboloid()
>>> x = jnp.array([1.05, 0.1, -0.2, 0.15])
>>> x = manifold.proj(x, c=1.0)
>>>
>>> # Define a linear transformation
>>> W = jax.random.normal(jax.random.PRNGKey(0), (3, 4))
>>> def linear(z):
...     return z @ W.T
>>>
>>> # Apply HTC
>>> y = htc(x, linear, c_in=1.0, c_out=2.0)
>>> y.shape
(4,)  # (3 spatial + 1 time)
Source code in hyperbolix/nn_layers/hyperboloid_core.py
def htc(
    x: Float[Array, "... in_dim_plus_1"],
    f_t: Callable[[Float[Array, "..."]], Float[Array, "..."]],
    c_in: float,
    c_out: float,
    eps: float = 1e-7,
) -> Float[Array, "... out_dim_plus_1"]:
    """Hyperbolic Transformation Component.

    Applies a Euclidean linear transformation f_t to the full hyperboloid point
    (including time component), then maps the result to the hyperboloid with
    curvature c_out.

    Mathematical formula:
        space = sqrt(c_in/c_out) * f_t(x)
        time  = sqrt(||space||^2 + 1/c_out)
        output = [time, space]

    where f_t takes the full (dim+1)-dimensional input and produces the output
    spatial components.

    Parameters
    ----------
    x : Array of shape (..., in_dim+1)
        Input point(s) on the hyperboloid manifold with curvature c_in.
        All components (time and spatial) are passed to f_t.
    f_t : Callable
        Euclidean linear transformation applied to the full input. Takes
        (in_dim+1)-dimensional input and produces out_dim-dimensional output
        (which becomes the spatial components of the output).
    c_in : float
        Input curvature parameter (must be positive, c > 0).
    c_out : float
        Output curvature parameter (must be positive, c > 0).
    eps : float, optional
        Small value for numerical stability (default: 1e-7).

    Returns
    -------
    y : Array of shape (..., out_dim+1)
        Output point(s) on the hyperboloid manifold with curvature c_out.

    Notes
    -----
    - Unlike HRC, f_t operates on the full point including the time component
    - f_t's output dimension determines the output spatial dimension
    - This is typically used for learnable linear transformations
    - The spatial scaling factor sqrt(c_in/c_out) ensures proper curvature transformation

    See Also
    --------
    hrc : Hyperbolic Regularization Component for spatial-only operations.
    HTCLinear : Module wrapper for htc with learnable linear transformation.

    References
    ----------
    Yang et al., "Hypformer: Exploring Efficient Transformer Fully in
    Hyperbolic Space", 2025.

    Examples
    --------
    >>> import jax
    >>> import jax.numpy as jnp
    >>> from hyperbolix.nn_layers.hyperboloid_core import htc
    >>> from hyperbolix.manifolds import Hyperboloid
    >>>
    >>> # Create a point on the hyperboloid
    >>> manifold = Hyperboloid()
    >>> x = jnp.array([1.05, 0.1, -0.2, 0.15])
    >>> x = manifold.proj(x, c=1.0)
    >>>
    >>> # Define a linear transformation
    >>> W = jax.random.normal(jax.random.PRNGKey(0), (3, 4))
    >>> def linear(z):
    ...     return z @ W.T
    >>>
    >>> # Apply HTC
    >>> y = htc(x, linear, c_in=1.0, c_out=2.0)
    >>> y.shape
    (4,)  # (3 spatial + 1 time)
    """
    # f_t: (..., A_in) → (..., D_out) where A_in = in_dim+1
    out_D = f_t(x)

    # Curvature scaling sqrt(c_in/c_out) + time reconstruction (shared hrc/htc tail).
    return spatial_to_hyperboloid(out_D, c_in, c_out, eps)  # (..., D_out+1)

hyperbolix.nn_layers.hrc

hrc(
    x: Float[Array, "... dim_plus_1"],
    f_r: Callable[[Float[Array, ...]], Float[Array, ...]],
    c_in: float,
    c_out: float,
    eps: float = 1e-07,
) -> Float[Array, "... out_dim_plus_1"]

Hyperbolic Regularization Component.

Applies a Euclidean regularization/activation function f_r to the spatial components of hyperboloid points, then maps the result to the hyperboloid with curvature c_out.

Mathematical formula: space = sqrt(c_in/c_out) * f_r(x[..., 1:]) time = sqrt(||space||^2 + 1/c_out) output = [time, space]

When c_in = c_out = c, this reduces to: output = [sqrt(||f_r(x_s)||^2 + 1/c), f_r(x_s)] which is the pattern used by curvature-preserving hyperboloid activations.

Parameters:

Name Type Description Default
x Array of shape (..., dim+1)

Input point(s) on the hyperboloid manifold with curvature c_in. The first element is the time-like component, remaining are spatial.

required
f_r Callable

Euclidean function to apply to spatial components. Can be any activation, normalization, dropout, etc. Takes spatial components and returns transformed spatial components (may change dimension).

required
c_in float

Input curvature parameter (must be positive, c > 0).

required
c_out float

Output curvature parameter (must be positive, c > 0).

required
eps float

Small value for numerical stability (default: 1e-7).

1e-07

Returns:

Name Type Description
y Array of shape (..., out_dim+1)

Output point(s) on the hyperboloid manifold with curvature c_out.

Notes
  • f_r operates only on spatial components x[..., 1:], not the time component
  • The time component is reconstructed using the hyperboloid constraint: -x₀² + ||x_rest||² = -1/c_out
  • This avoids expensive exp/log maps while maintaining mathematical correctness
  • The spatial scaling factor sqrt(c_in/c_out) ensures proper curvature transformation
See Also

htc : Hyperbolic Transformation Component for full-point operations.

References

Yang et al., "Hypformer: Exploring Efficient Transformer Fully in Hyperbolic Space", 2025.

Examples:

>>> import jax.numpy as jnp
>>> from hyperbolix.nn_layers.hyperboloid_core import hrc
>>> from hyperbolix.manifolds import Hyperboloid
>>>
>>> # Create a point on the hyperboloid
>>> manifold = Hyperboloid()
>>> x = jnp.array([1.05, 0.1, -0.2, 0.15])
>>> x = manifold.proj(x, c=1.0)
>>>
>>> # Apply HRC with ReLU (curvature-preserving)
>>> y = hrc(x, jax.nn.relu, c_in=1.0, c_out=1.0)
>>>
>>> # Apply HRC with curvature change
>>> y = hrc(x, jax.nn.relu, c_in=1.0, c_out=2.0)
>>>
>>> # Custom activation
>>> def custom_act(z):
...     return jax.nn.gelu(z) * 0.5
>>> y = hrc(x, custom_act, c_in=1.0, c_out=0.5)
Source code in hyperbolix/nn_layers/hyperboloid_core.py
def hrc(
    x: Float[Array, "... dim_plus_1"],
    f_r: Callable[[Float[Array, "..."]], Float[Array, "..."]],
    c_in: float,
    c_out: float,
    eps: float = 1e-7,
) -> Float[Array, "... out_dim_plus_1"]:
    """Hyperbolic Regularization Component.

    Applies a Euclidean regularization/activation function f_r to the spatial
    components of hyperboloid points, then maps the result to the hyperboloid
    with curvature c_out.

    Mathematical formula:
        space = sqrt(c_in/c_out) * f_r(x[..., 1:])
        time  = sqrt(||space||^2 + 1/c_out)
        output = [time, space]

    When c_in = c_out = c, this reduces to:
        output = [sqrt(||f_r(x_s)||^2 + 1/c), f_r(x_s)]
    which is the pattern used by curvature-preserving hyperboloid activations.

    Parameters
    ----------
    x : Array of shape (..., dim+1)
        Input point(s) on the hyperboloid manifold with curvature c_in.
        The first element is the time-like component, remaining are spatial.
    f_r : Callable
        Euclidean function to apply to spatial components. Can be any activation,
        normalization, dropout, etc. Takes spatial components and returns
        transformed spatial components (may change dimension).
    c_in : float
        Input curvature parameter (must be positive, c > 0).
    c_out : float
        Output curvature parameter (must be positive, c > 0).
    eps : float, optional
        Small value for numerical stability (default: 1e-7).

    Returns
    -------
    y : Array of shape (..., out_dim+1)
        Output point(s) on the hyperboloid manifold with curvature c_out.

    Notes
    -----
    - f_r operates only on spatial components x[..., 1:], not the time component
    - The time component is reconstructed using the hyperboloid constraint:
      -x₀² + ||x_rest||² = -1/c_out
    - This avoids expensive exp/log maps while maintaining mathematical correctness
    - The spatial scaling factor sqrt(c_in/c_out) ensures proper curvature transformation

    See Also
    --------
    htc : Hyperbolic Transformation Component for full-point operations.

    References
    ----------
    Yang et al., "Hypformer: Exploring Efficient Transformer Fully in
    Hyperbolic Space", 2025.

    Examples
    --------
    >>> import jax.numpy as jnp
    >>> from hyperbolix.nn_layers.hyperboloid_core import hrc
    >>> from hyperbolix.manifolds import Hyperboloid
    >>>
    >>> # Create a point on the hyperboloid
    >>> manifold = Hyperboloid()
    >>> x = jnp.array([1.05, 0.1, -0.2, 0.15])
    >>> x = manifold.proj(x, c=1.0)
    >>>
    >>> # Apply HRC with ReLU (curvature-preserving)
    >>> y = hrc(x, jax.nn.relu, c_in=1.0, c_out=1.0)
    >>>
    >>> # Apply HRC with curvature change
    >>> y = hrc(x, jax.nn.relu, c_in=1.0, c_out=2.0)
    >>>
    >>> # Custom activation
    >>> def custom_act(z):
    ...     return jax.nn.gelu(z) * 0.5
    >>> y = hrc(x, custom_act, c_in=1.0, c_out=0.5)
    """
    x_space_D = x[..., 1:]  # (..., D) spatial components

    out_space_D = f_r(x_space_D)  # (..., D') — may change dim

    # Curvature scaling sqrt(c_in/c_out) + time reconstruction (shared hrc/htc tail).
    return spatial_to_hyperboloid(out_space_D, c_in, c_out, eps)  # (..., D'+1)

Point assembly & concatenation

Helpers that build valid hyperboloid points from spatial/tangent data and extract convolution patches. busemann_fc_poincare_output is the Poincaré counterpart of sinh_lift_to_hyperboloid — the same score → manifold-point output map, landing on the ball instead of the hyperboloid. hcat_ambient_dim gives the ambient width that HCat / LogCat produce over a receptive field, which is what you need to size the layer that consumes a concatenating conv.

hyperbolix.nn_layers.spatial_to_hyperboloid

spatial_to_hyperboloid(
    spatial: Float[Array, "... D"],
    c_in: ScalarCurvature,
    c_out: ScalarCurvature,
    eps: float = 1e-07,
) -> Float[Array, "... D_plus_1"]

Scale spatial components and reconstruct time to produce a hyperboloid point.

Extracts the common tail of hrc/htc: curvature scaling + time reconstruction via the hyperboloid constraint.

Parameters:

Name Type Description Default
spatial (Array, shape(..., D))

Spatial components (no time coordinate).

required
c_in float

Source curvature (positive).

required
c_out float

Target curvature (positive).

required
eps float

Numerical stability floor (default: 1e-7).

1e-07

Returns:

Type Description
(Array, shape(..., D + 1))

Points on the hyperboloid with curvature c_out.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def spatial_to_hyperboloid(
    spatial: Float[Array, "... D"],
    c_in: ScalarCurvature,
    c_out: ScalarCurvature,
    eps: float = 1e-7,
) -> Float[Array, "... D_plus_1"]:
    """Scale spatial components and reconstruct time to produce a hyperboloid point.

    Extracts the common tail of ``hrc``/``htc``: curvature scaling + time
    reconstruction via the hyperboloid constraint.

    Parameters
    ----------
    spatial : Array, shape (..., D)
        Spatial components (no time coordinate).
    c_in : float
        Source curvature (positive).
    c_out : float
        Target curvature (positive).
    eps : float, optional
        Numerical stability floor (default: 1e-7).

    Returns
    -------
    Array, shape (..., D+1)
        Points on the hyperboloid with curvature ``c_out``.
    """
    # The input's dtype decides: a float64 curvature must not promote a float32 point under x64.
    # The ratio is cast, not `c_in` and `c_out` one by one, so Python-float curvatures give the same
    # scale as before, bit for bit (`c_out` is cast below).
    scale = jnp.sqrt(jnp.asarray(c_in / c_out, dtype=spatial.dtype))
    scaled_D = scale * spatial  # (..., D)

    # x0 = sqrt(sum(s**2) + 1/c_out) in ONE reduction over the spatial part. This is the hot path:
    # `spatial_to_hyperboloid` sits behind every `HTCLinear` forward, so it reads `s` once.
    # The sum of squares is kept intact under the sqrt rather than being rounded to ||s|| and
    # squared again -- the caller's constraint check `-x0**2 + sum(s**2) = -1/c_out` cancels the
    # rounding of the sum against itself, and it does not cancel a re-squared norm (at c_out = 0.1
    # the residual grew from 6.1e-5 to 2.4e-4 against a 1e-4 tolerance).
    # Plain `jnp.sqrt`: the argument is >= 1/c_out > 0, so it is never zero and the derivative is
    # never infinite. The floor sits on the ARGUMENT, as it did before PR #75:
    # `sqrt(floor_at(a, eps)) == floor_at(sqrt(a), sqrt(eps))` for a >= 0, so this is the same
    # value; it only bites when 1/c_out is itself below eps.
    # `sum(s**2)` overflows float32 past coordinate 1.8e19 -- geodesic radius ~45 at c = 1, ~139 at
    # c = 0.1 -- where the network producing it is already diverging, and gives an infinite time
    # slot there, the intended signal, rather than a quietly saturated one.
    inv_c_out = jnp.asarray(1.0, dtype=scaled_D.dtype) / jnp.asarray(c_out, dtype=scaled_D.dtype)
    x0 = jnp.sqrt(floor_at(jnp.sum(scaled_D**2, axis=-1) + inv_c_out, jnp.asarray(eps, dtype=scaled_D.dtype)))

    return jnp.concatenate([x0[..., None], scaled_D], axis=-1)  # (..., D+1)

hyperbolix.nn_layers.sinh_lift_to_hyperboloid

sinh_lift_to_hyperboloid(
    spatial_BO: Float[Array, "... O"],
    c: ScalarCurvature,
    v_max: float,
    eps: float = 1e-07,
) -> Float[Array, "... O_plus_1"]

Lift spatial pre-activations to the hyperboloid via the element-wise sinh diffeomorphism.

Shared output map of HypLinearHyperboloidPLFC (Shi et al. 2026, point-to-hyperplane) and HypLinearHyperboloidBusemann (Chen et al. 2026, Thm. 4.2, point-to-horosphere): both compute a per-output score, then recover a hyperboloid point by ::

y_s = sinh(clip(√c · score, ±v_max)) / √c
y_t = √(‖y_s‖² + 1/c)

The clip is an output-side overflow guard: the score ∝ ‖kernel_row‖ is unbounded (neither compute_mlr nor the Busemann logit bounds anything — compute_mlr's smooth_clamp was removed in this release), and the sinh exponentiates it. Hard jnp.clip (not smooth_clamp) matches the Shi et al. 2026 reference and is value-identical for |√c·score| ≤ v_max — it only zeroes the gradient in the already-saturated tail. Callers must _assert_v_max_safe(v_max) so the bare jnp.sinh below cannot overflow float32.

The clip guards finite scores only: a non-finite √c · score (the input point's time coordinate already overflowed float32 upstream) is passed through unchanged instead of being clipped to ±v_max, so the spatial slot stays inf/NaN, the reconstructed time slot goes non-finite with it, and the loss goes NaN at the onset minibatch rather than a plausible saturated point hiding the divergence behind a finite loss and a NaN parameter gradient. Finite rows take the same expression as before op-for-op — value and jax.grad are unchanged — and the inner where keeps the non-finite row's NaN out of the sinh VJP, so it cannot contaminate the finite rows' cotangents.

Parameters:

Name Type Description Default
spatial_BO (Array, shape(..., O))

Per-output scores (the sinh argument, pre-scaling). O = out_dim - 1.

required
c float

Curvature parameter (positive).

required
v_max float

Hard clip bound on √c · spatial (output-side overflow guard).

required
eps float

Numerical stability floor passed to :func:spatial_to_hyperboloid (default: 1e-7).

1e-07

Returns:

Type Description
(Array, shape(..., O + 1))

Points on the hyperboloid with curvature c (time coordinate first).

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def sinh_lift_to_hyperboloid(
    spatial_BO: Float[Array, "... O"],
    c: ScalarCurvature,
    v_max: float,
    eps: float = 1e-7,
) -> Float[Array, "... O_plus_1"]:
    """Lift spatial pre-activations to the hyperboloid via the element-wise sinh diffeomorphism.

    Shared output map of ``HypLinearHyperboloidPLFC`` (Shi et al. 2026, point-to-hyperplane)
    and ``HypLinearHyperboloidBusemann`` (Chen et al. 2026, Thm. 4.2, point-to-horosphere):
    both compute a per-output score, then recover a hyperboloid point by ::

        y_s = sinh(clip(√c · score, ±v_max)) / √c
        y_t = √(‖y_s‖² + 1/c)

    The ``clip`` is an output-side overflow guard: the score ∝ ``‖kernel_row‖`` is unbounded
    (neither ``compute_mlr`` nor the Busemann logit bounds anything — ``compute_mlr``'s
    ``smooth_clamp`` was removed in this release), and the ``sinh`` exponentiates it. Hard
    ``jnp.clip`` (not ``smooth_clamp``) matches the Shi
    et al. 2026 reference and is value-identical for ``|√c·score| ≤ v_max`` — it only zeroes
    the gradient in the already-saturated tail. Callers must ``_assert_v_max_safe(v_max)`` so
    the bare ``jnp.sinh`` below cannot overflow float32.

    The clip guards *finite* scores only: a non-finite ``√c · score`` (the input point's time
    coordinate already overflowed float32 upstream) is passed through unchanged instead of being
    clipped to ``±v_max``, so the spatial slot stays ``inf``/NaN, the reconstructed time slot goes
    non-finite with it, and the loss goes NaN at the onset minibatch rather than a plausible
    saturated point hiding the divergence behind a finite loss and a NaN parameter gradient.
    Finite rows take the same expression as before op-for-op — value and ``jax.grad`` are
    unchanged — and the inner ``where`` keeps the non-finite row's NaN out of the ``sinh`` VJP,
    so it cannot contaminate the finite rows' cotangents.

    Parameters
    ----------
    spatial_BO : Array, shape (..., O)
        Per-output scores (the sinh argument, pre-scaling). ``O = out_dim - 1``.
    c : float
        Curvature parameter (positive).
    v_max : float
        Hard clip bound on ``√c · spatial`` (output-side overflow guard).
    eps : float, optional
        Numerical stability floor passed to :func:`spatial_to_hyperboloid` (default: 1e-7).

    Returns
    -------
    Array, shape (..., O+1)
        Points on the hyperboloid with curvature ``c`` (time coordinate first).
    """
    c = jnp.asarray(c, dtype=spatial_BO.dtype)  # the input's dtype decides, not a float64 `c`
    sqrt_c = jnp.sqrt(c)
    arg_BO = sqrt_c * spatial_BO
    # Double `where`, both branching on a constant `isfinite` predicate (no measured quantity is
    # clipped or maximised here). The inner one keeps a NaN out of the sinh VJP, so a diverged row
    # cannot poison the finite rows' cotangents; the outer one routes the non-finite score around
    # both the clip and the sinh, so it reaches `spatial_to_hyperboloid` intact and the point comes
    # out loudly non-finite instead of saturated at ±sinh(v_max)/√c.
    finite_BO = jnp.isfinite(arg_BO)
    safe_arg_BO = jnp.where(finite_BO, arg_BO, jnp.zeros_like(arg_BO))
    # safe_sinh: the argument is already bounded to ±v_max ≪ the math_utils.sinh overflow clamp
    # (callers assert v_max safety), so the clamp itself is redundant here — but the wrapper's
    # expm1-form is an accuracy fix (XLA's CPU jnp.sinh is up to ~17-496 ulps off for |x| >= 16),
    # not just a clamp, so it is still worth routing through.
    res_rem_BO = jnp.where(finite_BO, safe_sinh(clamp_to(safe_arg_BO, -v_max, v_max)) / sqrt_c, arg_BO)
    # Time reconstruction via the hyperboloid constraint (scale = 1 since c_in == c_out).
    return spatial_to_hyperboloid(res_rem_BO, c_in=c, c_out=c, eps=eps)

hyperbolix.nn_layers.busemann_fc_poincare_output

busemann_fc_poincare_output(
    u_BO: Float[Array, "batch out_spatial"],
    c: float,
    v_max: float,
) -> Float[Array, "batch out_spatial"]

Poincaré BFC output map (Chen et al. 2026, Thm. 4.1).

Maps the (activated) Busemann logits to a Poincaré ball point::

ω   = sinh(clip(√c · u, ±v_max)) / √c
y   = ω / (1 + √(1 + c·‖ω‖²))

The clip is the same output-side overflow guard as the hyperboloid path (:func:hyperboloid_core.sinh_lift_to_hyperboloid); callers must _assert_v_max_safe(v_max). The second line is evaluated by :func:~hyperbolix.nn_layers.poincare_linear._poincare_sinh_lift without forming ‖ω‖², so it cannot overflow float32 for any v_max, O or c; saturated rows land at the ball's edge, not the origin. In exact arithmetic the closed form lands strictly inside the ball (√c·‖y‖ < 1); in float32 a saturated row can round onto or past the boundary, and the caller's proj pulls it back.

The clip bounds finite logits only: an inf or NaN √c · u gives a NaN row, so a runaway log_scale (exp overflow) shows up as a NaN loss rather than a finite point at the ball's edge with a zero gradient.

Parameters:

Name Type Description Default
u_BO (Array, shape(B, O))

Activated Busemann logits. O = out_spatial = out_dim (Poincaré has no time coord).

required
c float

Curvature (positive).

required
v_max float

Hard clip bound on √c · u (output-side overflow guard).

required

Returns:

Type Description
(Array, shape(B, O))

Points in the Poincaré ball with curvature c, before the caller's proj.

Source code in hyperbolix/nn_layers/busemann_core.py
def busemann_fc_poincare_output(
    u_BO: Float[Array, "batch out_spatial"],
    c: float,
    v_max: float,
) -> Float[Array, "batch out_spatial"]:
    """Poincaré BFC output map (Chen et al. 2026, Thm. 4.1).

    Maps the (activated) Busemann logits to a Poincaré ball point::

        ω   = sinh(clip(√c · u, ±v_max)) / √c
        y   = ω / (1 + √(1 + c·‖ω‖²))

    The ``clip`` is the same output-side overflow guard as the hyperboloid path
    (:func:`hyperboloid_core.sinh_lift_to_hyperboloid`); callers must
    ``_assert_v_max_safe(v_max)``. The second line is evaluated by
    :func:`~hyperbolix.nn_layers.poincare_linear._poincare_sinh_lift` without forming ``‖ω‖²``,
    so it cannot overflow float32 for any ``v_max``, ``O`` or ``c``; saturated rows land at the
    ball's edge, not the origin. In exact arithmetic the closed form lands strictly inside the
    ball (``√c·‖y‖ < 1``); in float32 a saturated row can round onto or past the boundary, and the
    caller's ``proj`` pulls it back.

    The clip bounds *finite* logits only: an ``inf`` or NaN ``√c · u`` gives a NaN row, so a
    runaway ``log_scale`` (``exp`` overflow) shows up as a NaN loss rather than a finite point at the
    ball's edge with a zero gradient.

    Parameters
    ----------
    u_BO : Array, shape (B, O)
        Activated Busemann logits. ``O = out_spatial = out_dim`` (Poincaré has no time coord).
    c : float
        Curvature (positive).
    v_max : float
        Hard clip bound on ``√c · u`` (output-side overflow guard).

    Returns
    -------
    Array, shape (B, O)
        Points in the Poincaré ball with curvature ``c``, before the caller's ``proj``.
    """
    sqrt_c = jnp.sqrt(jnp.asarray(c, dtype=u_BO.dtype))
    arg_BO = sqrt_c * u_BO  # (B, O)
    # `+ 0·arg` makes the clip loud: 0·(±inf) is NaN, so an overflowed logit (e.g. alpha = exp(log_scale)
    # = inf) gives a NaN output instead of a finite point at ±v_max with a zero gradient. For finite
    # arg, 0·arg is a zero with arg's sign, so value and gradient are bit-identical to the plain clip.
    # (A NaN arg was already passed through by `clamp_to`.)
    clipped_BO = clamp_to(arg_BO, -v_max, v_max) + 0.0 * arg_BO  # (B, O)
    # safe_sinh: expm1-form is an accuracy fix over XLA's CPU jnp.sinh (up to ~17-496 ulps off for
    # |x| >= 16), not just a clamp — the ±v_max clip here is still the output-side overflow guard.
    s_BO = safe_sinh(clipped_BO)  # (B, O), s = √c·ω
    return _poincare_sinh_lift(s_BO, c)

hyperbolix.nn_layers.build_spacelike_V

build_spacelike_V(
    U_IO: Float[Array, "I O"],
    b_O: Float[Array, O],
    c: ScalarCurvature,
    eps: float = 1e-07,
) -> Float[Array, "Ai O"]

Build spacelike V matrix with Minkowski metric absorbed.

Constructs the spacelike weight vectors from Euclidean weights U and bias b via parallel transport (Eq. 12, Klis et al. 2026). The Minkowski metric signature diag(-1, +1, ..., +1) is absorbed into the time row so that the forward pass reduces to a single x @ V matmul.

Parameters:

Name Type Description Default
U_IO (Array, shape(I, O))

Euclidean weight matrix. I = in_spatial, O = out_spatial.

required
b_O (Array, shape(O))

Bias per output neuron.

required
c float

Curvature parameter (positive).

required
eps float

Numerical stability floor for column norms (default: 1e-7).

1e-07

Returns:

Name Type Description
V_AiO (Array, shape(I + 1, O))

Spacelike V matrix with negated time row (Minkowski metric absorbed). Columns are v^(i) with v_time_mink = -||w|| * sinh(arg).

References

Klis et al. "Fast and Geometrically Grounded Lorentz Neural Networks" (2026), Eq. 12.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def build_spacelike_V(
    U_IO: Float[Array, "I O"],
    b_O: Float[Array, "O"],
    c: ScalarCurvature,
    eps: float = 1e-7,
) -> Float[Array, "Ai O"]:
    """Build spacelike V matrix with Minkowski metric absorbed.

    Constructs the spacelike weight vectors from Euclidean weights U and bias b
    via parallel transport (Eq. 12, Klis et al. 2026). The Minkowski metric
    signature diag(-1, +1, ..., +1) is absorbed into the time row so that the
    forward pass reduces to a single ``x @ V`` matmul.

    Parameters
    ----------
    U_IO : Array, shape (I, O)
        Euclidean weight matrix. I = in_spatial, O = out_spatial.
    b_O : Array, shape (O,)
        Bias per output neuron.
    c : float
        Curvature parameter (positive).
    eps : float, optional
        Numerical stability floor for column norms (default: 1e-7).

    Returns
    -------
    V_AiO : Array, shape (I+1, O)
        Spacelike V matrix with negated time row (Minkowski metric absorbed).
        Columns are v^(i) with ``v_time_mink = -||w|| * sinh(arg)``.

    References
    ----------
    Klis et al. "Fast and Geometrically Grounded Lorentz Neural Networks" (2026), Eq. 12.
    """
    # Dimension key: I=in_spatial, O=out_spatial, Ai=in_ambient (I+1)

    # The weight's dtype decides: a float64 `c` must not promote a float32 V under x64.
    c = jnp.asarray(c, dtype=U_IO.dtype)

    # Column norms of U: ||w^(i)||_E. `safe_hypot_norm(w, sqrt(eps))` **is** the old
    # `sqrt(sum(w**2) + eps)`, bit for bit, but never materialises the square, so a large-magnitude
    # column cannot overflow the reduction. The `eps` floor stays: `norm_O` is a divisor below and
    # the smooth gate on the next line is tied to the same `eps`.
    norm_sq_O = jnp.sum(U_IO**2, axis=0)  # (O,) -- gate only, never square-rooted
    norm_O = safe_hypot_norm(U_IO.T, jnp.sqrt(jnp.asarray(eps, dtype=U_IO.dtype)))  # (O,)

    # Smooth gate: 0 for zero-norm columns, ~1 for normal columns.
    # Ensures arg→0 smoothly when U column→0 (no weight → no bias transport).
    gate_O = norm_sq_O / (norm_sq_O + eps)  # (O,)

    # Argument for sinh/cosh: -sqrt(c) * b / ||w||, gated for zero columns
    arg_O = clamp_to(-jnp.sqrt(c) * b_O * gate_O / norm_O, -100.0, 100.0)  # (O,)

    # Time row: negate to absorb Minkowski metric I_{1,D}
    # v_time = ||w|| * sinh(arg), v_time_mink = -v_time
    v_time_mink_O = -norm_O * safe_sinh(arg_O)  # (O,)

    # Spatial rows: w^(i) * cosh(arg)
    v_space_IO = U_IO * safe_cosh(arg_O)[None, :]  # (I, O)

    # Stack: [v_time_mink; v_space] -> (I+1, O) = (Ai, O)
    V_AiO = jnp.concatenate([v_time_mink_O[None, :], v_space_IO], axis=0)  # (Ai, O)

    return V_AiO

hyperbolix.nn_layers.hcat_ambient_dim

hcat_ambient_dim(
    in_channels: int, kernel_size: tuple[int, int]
) -> int

Output ambient dimension of HCat/LogCat over a kh*kw receptive field.

Concatenating N = kh*kw hyperboloid points (each with in_channels - 1 spatial dims) yields one point of spatial dim (in_channels - 1) * N plus a single reconstructed time coordinate.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def hcat_ambient_dim(in_channels: int, kernel_size: tuple[int, int]) -> int:
    """Output ambient dimension of HCat/LogCat over a ``kh*kw`` receptive field.

    Concatenating ``N = kh*kw`` hyperboloid points (each with ``in_channels - 1``
    spatial dims) yields one point of spatial dim ``(in_channels - 1) * N`` plus a
    single reconstructed time coordinate.
    """
    kh, kw = kernel_size
    return (in_channels - 1) * kh * kw + 1

hyperbolix.nn_layers.extract_patches

extract_patches(
    x: Float[Array, "batch height width in_channels"],
    kernel_size: tuple[int, int],
    stride: tuple[int, int],
    padding: str,
    pad_mode: str = "edge",
    c: float | None = None,
) -> Float[
    Array,
    "batch out_height out_width kernel_h kernel_w in_channels",
]

Extract receptive-field patches for hyperboloid convolutions.

Shared by all hyperboloid conv layers (HypConv2DHyperboloid, HypConv2DHyperboloidFHNN, FGGConv2D, HypConv2DHyperboloidILNN). The patches are returned in point-major (kh, kw, C) order so that the downstream per-point ops (hcat / log_radius_concat) can consume them as (K, C) after flattening; this is why the channel-major output of jax.lax.conv_general_dilated_patches is transposed.

Padding is applied manually because the conv primitive zero-pads, and zero is not a point on the hyperboloid:

  • pad_mode="edge" — replicate the border (default).
  • pad_mode="origin" — fill with the manifold origin (sqrt(1/c), 0, ..., 0); c is required in this mode (matching the Shi et al. 2026 / Klis et al. 2026 reference padding).

Parameters:

Name Type Description Default
x (Array, shape(B, H, W, in_channels))

Input feature map of hyperboloid points (ambient channels, time first).

required
kernel_size tuple[int, int]

(kernel_h, kernel_w).

required
stride tuple[int, int]

(stride_h, stride_w).

required
padding str

"SAME" or "VALID". Only "SAME" triggers manual padding.

required
pad_mode str

"edge" or "origin" (default: "edge").

'edge'
c float or None

Curvature, required only for pad_mode="origin" (default: None).

None

Returns:

Type Description
(Array, shape(B, out_height, out_width, kernel_h, kernel_w, in_channels))

Receptive-field patches in point-major order.

Raises:

Type Description
ValueError

If pad_mode="origin" is used without an explicit curvature c.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def extract_patches(
    x: Float[Array, "batch height width in_channels"],
    kernel_size: tuple[int, int],
    stride: tuple[int, int],
    padding: str,
    pad_mode: str = "edge",
    c: float | None = None,
) -> Float[Array, "batch out_height out_width kernel_h kernel_w in_channels"]:
    """Extract receptive-field patches for hyperboloid convolutions.

    Shared by all hyperboloid conv layers (``HypConv2DHyperboloid``,
    ``HypConv2DHyperboloidFHNN``, ``FGGConv2D``, ``HypConv2DHyperboloidILNN``). The
    patches are returned in **point-major** ``(kh, kw, C)`` order so that the
    downstream per-point ops (``hcat`` / ``log_radius_concat``) can consume them as
    ``(K, C)`` after flattening; this is why the channel-major output of
    ``jax.lax.conv_general_dilated_patches`` is transposed.

    Padding is applied **manually** because the conv primitive zero-pads, and zero is
    not a point on the hyperboloid:

    - ``pad_mode="edge"``   — replicate the border (default).
    - ``pad_mode="origin"`` — fill with the manifold origin ``(sqrt(1/c), 0, ..., 0)``;
      ``c`` is required in this mode (matching the Shi et al. 2026 / Klis et al. 2026
      reference padding).

    Parameters
    ----------
    x : Array, shape (B, H, W, in_channels)
        Input feature map of hyperboloid points (ambient channels, time first).
    kernel_size : tuple[int, int]
        ``(kernel_h, kernel_w)``.
    stride : tuple[int, int]
        ``(stride_h, stride_w)``.
    padding : str
        ``"SAME"`` or ``"VALID"``. Only ``"SAME"`` triggers manual padding.
    pad_mode : str, optional
        ``"edge"`` or ``"origin"`` (default: ``"edge"``).
    c : float or None, optional
        Curvature, required only for ``pad_mode="origin"`` (default: None).

    Returns
    -------
    Array, shape (B, out_height, out_width, kernel_h, kernel_w, in_channels)
        Receptive-field patches in point-major order.

    Raises
    ------
    ValueError
        If ``pad_mode="origin"`` is used without an explicit curvature ``c``.
    """
    batch, height, width, in_channels = x.shape
    kernel_h, kernel_w = kernel_size
    stride_h, stride_w = stride

    # 1. Manual padding (the conv primitive's zero-pad is off-manifold)
    if padding == "SAME":
        out_height = (height + stride_h - 1) // stride_h
        out_width = (width + stride_w - 1) // stride_w
        pad_h = max((out_height - 1) * stride_h + kernel_h - height, 0)
        pad_w = max((out_width - 1) * stride_w + kernel_w - width, 0)
        pad_top = pad_h // 2
        pad_bottom = pad_h - pad_top
        pad_left = pad_w // 2
        pad_right = pad_w - pad_left

        if pad_mode == "origin":
            if c is None:
                raise ValueError('hyp_pad2d: pad_mode="origin" needs an explicit curvature `c`.')
            # Pad with manifold origin: (√(1/c), 0, ..., 0).
            # Buffer and fill value follow x's dtype: a float64 `c` would otherwise promote under
            # x64 (and the scatter below warns about the float64 -> float32 cast). `1/c` is cast,
            # not `c`, so a Python-float `c` gives the same fill value as before, bit for bit.
            inv_c = jnp.asarray(1.0 / c, dtype=x.dtype)
            padded_h = height + pad_h
            padded_w = width + pad_w
            padded = jnp.zeros((batch, padded_h, padded_w, in_channels), dtype=x.dtype)
            padded = padded.at[..., 0].set(jnp.sqrt(inv_c))
            x = padded.at[:, pad_top : pad_top + height, pad_left : pad_left + width, :].set(x)
        else:  # edge
            x = jnp.pad(
                x,
                ((0, 0), (pad_top, pad_bottom), (pad_left, pad_right), (0, 0)),
                mode="edge",
            )

    # 2. Extract patches — output: (B, H, W, C*kh*kw), channel-major (C, kh, kw)
    patches_flat_BHW_CKhKw = jax.lax.conv_general_dilated_patches(
        lhs=x,
        filter_shape=(kernel_h, kernel_w),
        window_strides=(stride_h, stride_w),
        padding="VALID",
        dimension_numbers=("NHWC", "OIHW", "NHWC"),
        # Pinned HIGHEST: XLA implements the patch extraction as a convolution against a 0/1
        # filter, so this is a pure data copy — under TF32 it would round every input value to
        # a 10-bit mantissa before the layer's own GEMM ever sees it, for no throughput gain.
        precision=MATMUL_PRECISION,
    )

    # 3. Reshape to separate channels and kernel dims, then transpose to point-major.
    # conv_general_dilated_patches always emits channel-major (C, kh, kw) regardless of
    # the rhs spec letters, so the transpose to (kh, kw, C) is required (and is cheap).
    out_h, out_w = patches_flat_BHW_CKhKw.shape[1], patches_flat_BHW_CKhKw.shape[2]
    patches_BHWCkhkw = patches_flat_BHW_CKhKw.reshape(batch, out_h, out_w, in_channels, kernel_h, kernel_w)
    patches_BHWkhkwC = patches_BHWCkhkw.transpose(0, 1, 2, 4, 5, 3)  # move C last

    return patches_BHWkhkwC

Midpoints & residuals

hyperbolix.nn_layers.lorentz_midpoint

lorentz_midpoint(
    points: Float[Array, "... M A"],
    weights: Float[Array, "... N M"],
    c: ScalarCurvature,
    eps: float = 1e-07,
    form: Literal["variance", "gemm"] = "variance",
) -> Float[Array, "... N A"]

Weighted Lorentzian midpoint over M points.

Generalises :func:lorentz_residual (which handles two points) to an arbitrary weighted combination used by full attention aggregation and multi-head averaging.

Formula (HELM, He et al. 2025): h = weights @ points (weighted sum) mu = h / (sqrt(c) * ||h||_L)

where ||h||_L = sqrt(-<h,h>_L). The literal Lorentz square subtracts two large terms for a tight cloud far from the origin. Instead, set t_m = x_{m,0}, z_m = x_{m,s}/t_m, T = h_0 and z_bar = h_s/T::

D² = T * sum_m w_m * (1/t_m + c*t_m*||z_m - z_bar||²)
mu_s = h_s / sqrt(max(abs(D²), eps))

On-sheet, 1 - ||z_m||² = 1/(c*t_m²). Expanding the weighted variance therefore gives D² = c*(T² - ||h_s||²) exactly. The variance is evaluated directly as squared coordinate differences, without expanding the cancelling squares. For non-negative weights every summand is non-negative. Unlike a radius/unit-direction factorization, z_m is smooth at the origin, so gradients through an origin point in a mixed cloud retain its contribution.

weights must be non-negative; negative weights are unsupported. An all-zero weight row returns the origin, preserving the existing convention. Its division by T is guarded. That value convention does not prescribe a weight derivative: the normalized mean has no continuous extension at zero weights. The existing abs and eps normalization remains in effect.

Cost is O(N*M*D): the direct variance uses one (..., N, M, D) broadcast and reduction. For batch means and head averages, N = 1 and this is linear in the number of points. All contractions use HIGHEST precision. Output time is reconstructed from the normalized spatial part.

form="gemm" instead evaluates -c<h,h>_L = c*(h_0² - ||h_s||²) on h itself, the literal HELM centroid h / sqrt(c*|<h,h>_L|) (floored at eps), with the same time rebuild. Its cost is one GEMM plus O(N*A) work, against the variance form's elementwise (..., N, M, D) intermediate, which in attention (N = S queries, M = T keys) is S*T*D per head: O(S*T*D) work outside the GEMM, and as much memory where XLA materializes it (measured: XLA:CPU does in the backward, XLA:GPU fused it away; logs/2026-09-30_helm-centroid/). The price is cancellation: the two squares are O(cosh²(a)) at scaled radius a = sqrt(c)*d, so when -c<h,h>_L ≈ 1 (a tight cloud, or a peaked softmax row) it loses relative accuracy of about eps*cosh²(a) (float32: 9e-5 at a = 4, 0.27 at a = 8), and the midpoint's geodesic error is of the same order (measured, float32, M = 16: 1.2e-4 at a = 4, 0.35 at a = 8; logs/2026-09-30_helm-centroid/accuracy_probe.out). Spread clouds lose less, as -c<h,h>_L grows with the spread. The default, "variance", is unchanged bit for bit. The error depends on the radius of the points alone, not on how the weights were formed: in attention, float32 "gemm" loses the centroid of values at a = 9 (5.7 to 11 nats from the float64 run, against 5e-7 to 4.5e-4 for "variance") even when queries and keys sit near the origin and the scores are accurate (logs/2026-09-30_helm-decisions/far_values_gemm_probe.out). So "gemm" does not break only where GEMM-formed attention scores already have (docs/user-guide/numerical-stability.md#attention-score-floor). Pick it where the cost matters (long sequences) and the points stay well inside a ≈ 6 in float32, or run in float64; otherwise use "variance".

Historical measurements of the preceding radius/direction variance form (probe C.i in logs/2026-09-08_hyperboloid_tangent_primitives, M = 16, D = 16, c = 0.5, uniform weights, four seeds) reported median geodesic errors against a longdouble reference::

               a = 6      a = 8      a = 9      a = 12
radial         1.5e-5     1.0e-4     3.2e-4     5.0e-3
angular        3.6e-7     4.6e-7     3.6e-7     3.5e-7
mixed          3.2e-7     3.6e-7     3.6e-7     3.7e-7

Here a = sqrt(c)*d; radial clouds have spread 0.3 in a, angular clouds have spread 0.3 radians at one radius, and mixed clouds have both. These are historical value measurements, not derivative or timing guarantees for this implementation. Rounding a direction by delta can cause a geodesic error of order sinh(a)*delta. A comparison with unrounded inputs includes that storage error as well as arithmetic error; it cannot identify either component by itself.

Parameters:

Name Type Description Default
points (Array, shape(..., M, A))

Points on the hyperboloid with curvature c. A = d + 1.

required
weights (Array, shape(..., N, M))

Combination weights (e.g. attention weights, uniform 1/M). Keep each row's sum near 1: the centroid itself does not depend on the weights' common scale, but the eps floor does. Once a row sums to less than sqrt(eps) (about 3e-4) the floor can bind, and then the midpoint moves toward the origin (for a tight cloud at scaled radius 1: off by about 0.03 at a sum of 3e-4 and by 0.6 at 1e-4, in both dtypes). An all-zero row returns the origin.

required
c float

Curvature parameter (positive).

required
eps float

Numerical stability floor (default: 1e-7).

1e-07
form (variance, gemm)

How -c<h,h>_L is evaluated; a static Python choice (default: "variance", the cancellation-free direct variance; "gemm" is the single-GEMM literal form, see above).

"variance"

Returns:

Type Description
(Array, shape(..., N, A))

Midpoints on the hyperboloid with curvature c.

Raises:

Type Description
ValueError

If form is not "variance" or "gemm".

Notes

The identity assumes the points are exactly on-sheet — an assumption float storage cannot honour at large radius, since x_0 is only accurate to eps * x_0 and the sheet constraint needs eps * x_0^2 << 1/c (violated beyond ||s|| ~ 3e3 in float32, ~1e8 in float64, e.g. a Poincare point lifted from the ball boundary). The old naive h / sqrt(-c <h,h>_L) was self-normalizing — it put whatever timelike vector it got exactly onto the sheet — while the identity form would return an off-sheet midpoint (which then diverges any downstream Karcher iteration). To keep that invariant, only the spatial part of h / denom is taken and the time coordinate is rebuilt as sqrt(||s||^2 + 1/c) (:func:spatial_to_hyperboloid, the same convention as hrc/htc). That reconstruction is itself cancellation-free — it adds, never subtracts — so the identity's large-radius accuracy gain in the spatial scale is preserved. Consequence: the output's time coordinate is a function of its spatial part, so its gradient flows through the spatial components (as in every HRC/HTC layer) rather than through the input time coordinates directly.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def lorentz_midpoint(
    points: Float[Array, "... M A"],
    weights: Float[Array, "... N M"],
    c: ScalarCurvature,
    eps: float = 1e-7,
    form: Literal["variance", "gemm"] = "variance",
) -> Float[Array, "... N A"]:
    """Weighted Lorentzian midpoint over M points.

    Generalises :func:`lorentz_residual` (which handles two points) to an
    arbitrary weighted combination used by full attention aggregation and
    multi-head averaging.

    Formula (HELM, He et al. 2025):
        ``h = weights @ points``  (weighted sum)
        ``mu = h / (sqrt(c) * ||h||_L)``

    where ``||h||_L = sqrt(-<h,h>_L)``. The literal Lorentz square subtracts
    two large terms for a tight cloud far from the origin. Instead, set
    ``t_m = x_{m,0}``, ``z_m = x_{m,s}/t_m``, ``T = h_0`` and ``z_bar = h_s/T``::

        D² = T * sum_m w_m * (1/t_m + c*t_m*||z_m - z_bar||²)
        mu_s = h_s / sqrt(max(abs(D²), eps))

    On-sheet, ``1 - ||z_m||² = 1/(c*t_m²)``. Expanding the weighted variance
    therefore gives ``D² = c*(T² - ||h_s||²)`` exactly. The variance is evaluated
    directly as squared coordinate differences, without expanding the cancelling
    squares. For non-negative weights every summand is non-negative. Unlike a
    radius/unit-direction factorization, ``z_m`` is smooth at the origin, so
    gradients through an origin point in a mixed cloud retain its contribution.

    ``weights`` must be non-negative; negative weights are unsupported. An
    all-zero weight row returns the origin, preserving the existing convention.
    Its division by ``T`` is guarded. That value convention does not prescribe a
    weight derivative: the normalized mean has no continuous extension at zero
    weights. The existing ``abs`` and ``eps`` normalization remains in effect.

    Cost is ``O(N*M*D)``: the direct variance uses one ``(..., N, M, D)``
    broadcast and reduction. For batch means and head averages, ``N = 1`` and
    this is linear in the number of points. All contractions use HIGHEST
    precision. Output time is reconstructed from the normalized spatial part.

    ``form="gemm"`` instead evaluates ``-c<h,h>_L = c*(h_0² - ||h_s||²)`` on ``h`` itself,
    the literal HELM centroid ``h / sqrt(c*|<h,h>_L|)`` (floored at ``eps``), with the same
    time rebuild. Its cost is one GEMM plus ``O(N*A)`` work, against the variance form's
    elementwise ``(..., N, M, D)`` intermediate, which in attention (``N = S`` queries,
    ``M = T`` keys) is ``S*T*D`` per head: ``O(S*T*D)`` work outside the GEMM, and as much
    memory where XLA materializes it (measured: XLA:CPU does in the backward, XLA:GPU fused
    it away; ``logs/2026-09-30_helm-centroid/``). The price is cancellation: the two
    squares are ``O(cosh²(a))`` at scaled radius ``a = sqrt(c)*d``, so when ``-c<h,h>_L ≈ 1`` (a tight
    cloud, or a peaked softmax row) it loses relative accuracy of about ``eps*cosh²(a)``
    (float32: 9e-5 at ``a = 4``, 0.27 at ``a = 8``), and the midpoint's geodesic error is of
    the same order (measured, float32, M = 16: 1.2e-4 at ``a = 4``, 0.35 at ``a = 8``;
    ``logs/2026-09-30_helm-centroid/accuracy_probe.out``). Spread clouds lose less, as
    ``-c<h,h>_L`` grows with the spread. The default, ``"variance"``, is unchanged bit for
    bit. The error depends on the radius of the ``points`` alone, not on how the weights
    were formed: in attention, float32 ``"gemm"`` loses the centroid of values at ``a = 9``
    (5.7 to 11 nats from the float64 run, against 5e-7 to 4.5e-4 for ``"variance"``) even
    when queries and keys sit near the origin and the scores are accurate
    (``logs/2026-09-30_helm-decisions/far_values_gemm_probe.out``). So ``"gemm"`` does not
    break only where GEMM-formed attention scores already have
    (``docs/user-guide/numerical-stability.md#attention-score-floor``). Pick it where the
    cost matters (long sequences) and the points stay well inside ``a ≈ 6`` in float32, or
    run in float64; otherwise use ``"variance"``.

    Historical measurements of the preceding radius/direction variance form
    (probe C.i in ``logs/2026-09-08_hyperboloid_tangent_primitives``, M = 16,
    D = 16, c = 0.5, uniform weights, four seeds) reported median geodesic
    errors against a longdouble reference::

                       a = 6      a = 8      a = 9      a = 12
        radial         1.5e-5     1.0e-4     3.2e-4     5.0e-3
        angular        3.6e-7     4.6e-7     3.6e-7     3.5e-7
        mixed          3.2e-7     3.6e-7     3.6e-7     3.7e-7

    Here ``a = sqrt(c)*d``; radial clouds have spread 0.3 in ``a``, angular
    clouds have spread 0.3 radians at one radius, and mixed clouds have both.
    These are historical value measurements, not derivative or timing guarantees
    for this implementation. Rounding a direction by ``delta`` can cause a
    geodesic error of order ``sinh(a)*delta``. A comparison with unrounded inputs
    includes that storage error as well as arithmetic error; it cannot identify
    either component by itself.

    Parameters
    ----------
    points : Array, shape (..., M, A)
        Points on the hyperboloid with curvature ``c``.  ``A = d + 1``.
    weights : Array, shape (..., N, M)
        Combination weights (e.g. attention weights, uniform ``1/M``). Keep each row's sum near 1:
        the centroid itself does not depend on the weights' common scale, but the ``eps`` floor
        does. Once a row sums to less than ``sqrt(eps)`` (about 3e-4) the floor can bind, and then
        the midpoint moves toward the origin (for a tight cloud at scaled radius 1: off by about
        0.03 at a sum of 3e-4 and by 0.6 at 1e-4, in both dtypes). An all-zero row returns the
        origin.
    c : float
        Curvature parameter (positive).
    eps : float, optional
        Numerical stability floor (default: 1e-7).
    form : {"variance", "gemm"}, optional
        How ``-c<h,h>_L`` is evaluated; a static Python choice (default: ``"variance"``, the
        cancellation-free direct variance; ``"gemm"`` is the single-GEMM literal form, see
        above).

    Returns
    -------
    Array, shape (..., N, A)
        Midpoints on the hyperboloid with curvature ``c``.

    Raises
    ------
    ValueError
        If ``form`` is not ``"variance"`` or ``"gemm"``.

    Notes
    -----
    The identity assumes the ``points`` are *exactly* on-sheet — an assumption float storage cannot
    honour at large radius, since ``x_0`` is only accurate to ``eps * x_0`` and the sheet constraint
    needs ``eps * x_0^2 << 1/c`` (violated beyond ``||s|| ~ 3e3`` in float32, ``~1e8`` in float64,
    e.g. a Poincare point lifted from the ball boundary). The old naive ``h / sqrt(-c <h,h>_L)`` was
    self-normalizing — it put *whatever* timelike vector it got exactly onto the sheet — while the
    identity form would return an off-sheet midpoint (which then diverges any downstream Karcher
    iteration). To keep that invariant, only the *spatial* part of ``h / denom`` is taken and the
    time coordinate is rebuilt as ``sqrt(||s||^2 + 1/c)`` (:func:`spatial_to_hyperboloid`, the same
    convention as ``hrc``/``htc``). That reconstruction is itself cancellation-free — it adds, never
    subtracts — so the identity's large-radius accuracy gain in the spatial scale is preserved.
    Consequence: the output's time coordinate is a function of its spatial part, so its gradient
    flows through the spatial components (as in every HRC/HTC layer) rather than through the input
    time coordinates directly.
    """
    if form not in ("variance", "gemm"):
        raise ValueError(f"form must be 'variance' or 'gemm', got {form!r}")
    c = jnp.asarray(c, dtype=points.dtype)  # the input's dtype decides, not a float64 `c`
    # h = sum_m w_{n,m} * points_m  →  (..., N, A)
    # Pinned HIGHEST: the cancellation-free identity below only holds to O(eps) if its inputs
    # are float32-accurate; at the TF32 default the f32-vs-f64 relative error of this function
    # is 4.6e-5 … 2.6e-4 instead of 2.6e-8 … 1.6e-7 (see hyperbolix.utils.precision).
    h_NA = jnp.einsum("...nm,...ma->...na", weights, points, precision=MATMUL_PRECISION)
    if form == "gemm":
        # Literal -c<h,h>_L from h alone: O(N*A) elementwise work, no (..., N, M, D) intermediate.
        # Cancels as eps*cosh²(a) at large radius (docstring); elementwise, so no TF32 either.
        neg_c_mink_N1 = c * (h_NA[..., :1] ** 2 - jnp.sum(h_NA[..., 1:] ** 2, axis=-1, keepdims=True))  # (..., N, 1)
    else:
        time_M = points[..., 0]  # (..., M), positive on the upper sheet
        velocity_MD = points[..., 1:] / time_M[..., None]  # (..., M, D)
        time_N = h_NA[..., 0]  # (..., N)
        safe_time_N = jnp.where(time_N != 0, time_N, 1.0)
        mean_ND = h_NA[..., 1:] / safe_time_N[..., None]  # (..., N, D)
        # Direct variance: expanding these squares reintroduces large-radius cancellation.
        dev_sq_NM = jnp.sum((velocity_MD[..., None, :, :] - mean_ND[..., :, None, :]) ** 2, axis=-1)
        terms_NM = 1.0 / time_M[..., None, :] + c * time_M[..., None, :] * dev_sq_NM
        weighted_N = jnp.einsum("...nm,...nm->...n", weights, terms_NM, precision=MATMUL_PRECISION)
        neg_c_mink_N1 = (time_N * weighted_N)[..., None]  # (..., N, 1), = -c*<h,h>_L
    denom_N1 = jnp.sqrt(floor_at(jnp.abs(neg_c_mink_N1), eps))  # (..., N, 1)
    z_NA = h_NA / denom_N1  # (..., N, A)
    # The identity above assumes *exactly* on-sheet points, which float storage cannot guarantee at
    # large radius (eps*x_0^2 > 1/c beyond ||s|| ~ 3e3 in float32 / ~1e8 in float64): for such inputs
    # the identity's scale is right but z_NA itself lands off the sheet, whereas the old naive
    # h/sqrt(-c<h,h>_L) was self-normalizing. Reconstructing the time coordinate from the (correctly
    # scaled) spatial part restores that invariant — cancellation-free, and the same convention as
    # hrc/htc.
    return spatial_to_hyperboloid(z_NA[..., 1:], c_in=c, c_out=c, eps=eps)  # (..., N, A)

hyperbolix.nn_layers.lorentz_residual

lorentz_residual(
    x: Float[Array, "... dim_plus_1"],
    y: Float[Array, "... dim_plus_1"],
    w_y: float | Float[Array, ...],
    c: ScalarCurvature,
    eps: float = 1e-07,
) -> Float[Array, "... dim_plus_1"]

Lorentzian residual connection (LResNet, He et al. 2025).

Computes the weighted Lorentzian midpoint of x and y, projecting back to the hyperboloid:

ave = x + w_y * y
result = ave / sqrt(-c * <ave, ave>_L)   (time coordinate then reconstructed, see Notes)

where _L = -a_0^2 + ||a_s||^2 is the Minkowski inner product. <ave, ave>_L is not evaluated by that literal formula: for on-sheet x, y (<x,x>_L = <y,y>_L = -1/c) it is obtained from the exact, cancellation-free identity ::

<x + w y, x + w y>_L = -(1 + w)^2 / c - w * <x - y, x - y>_L

(see Notes).

.. warning:: w_y must be non-negative. For x, y on the upper sheet, any conic combination x + w_y * y with w_y >= 0 stays future-directed timelike, so the normalization returns a valid hyperboloid point. For w_y < 0 the combination can turn spacelike (<ave, ave>_L > 0, which by the identity above happens exactly when w_y * <x - y, x - y>_L < -(1 + w_y)^2 / c; roughly w_y < -1 for nearby points), and then the output is NaN. For w_y < -1 it can also stay timelike but point to the past (ave_0 < 0), and then the output is a finite upper-sheet point with no error. This is why callers must not expose w_y as an unconstrained learnable parameter unless they accept that behaviour (see Notes, "Negative weights").

Parameters:

Name Type Description Default
x (Array, shape(..., d + 1))

Points on hyperboloid with curvature c.

required
y (Array, shape(..., d + 1))

Points on hyperboloid with curvature c (to be added with weight w_y).

required
w_y (float or Array, shape() or ... or (..., 1))

Weight for the y contribution. Must be >= 0 (see warning above). A scalar applies one weight to every point; an array of shape x.shape[:-1] or x.shape[:-1] + (1,) gives one weight per point (e.g. per-token gate weights in a mixture of experts). A weight array of shape x.shape[:-1] gets a trailing axis added internally; any other non-scalar shape raises ValueError.

required
c float

Curvature parameter (positive, c > 0).

required
eps float

Floor under the squared time coordinate when it is rebuilt from the spatial part (:func:spatial_to_hyperboloid; default: 1e-7). The normalizer itself has no floor.

1e-07

Returns:

Type Description
(Array, shape(..., d + 1))

Points on hyperboloid with curvature c.

Notes

The naive -ave_0^2 + ||ave_s||^2 subtracts two O(||s||^2) squares to reach an O(1/c) result, so its float32 relative error grows like eps * c * ||s||^2 and the computed value flips sign above ||s|| ~ 1e4. Both terms of the identity in the formula block are non-positive for w_y >= 0, so combining them adds magnitudes rather than cancelling, and the accuracy of the normalizer is the accuracy of the single term <x - y, x - y>_L. That term is evaluated by :func:_lorentz_sqdist_polar as 4(P^2 + q^2)/c — the hyperbolic haversine form, a sum of non-negatives read off the spatial radii — and not as the literal -d_0^2 + ||d_s||^2, which is itself a difference of two O(e^{2a}) squares (a the scaled geodesic radius) and returns noise for a radial pair once a exceeds ~8 in float32. The one float32 limit that remains is the direction the two points share: past ||s|| ~ 1e4 the chord ||x_hat - y_hat|| is dominated by rounding before either form sees it, and float64 is required (the naive form is no better there).

For w_y >= 0 the normalizer needs no abs() and no floor: the difference of two on-sheet points is spacelike (<x - y, x - y>_L >= 0, and the polar form is a sum of non-negatives, so it is >= 0 in floating point too), so -c * <ave, ave>_L = (1 + w_y)^2 + c * w_y * <x - y, x - y>_L >= (1 + w_y)^2 >= 1. The output is bit-identical to the earlier sqrt(max(c |<ave, ave>_L|, eps)) (so are eager gradients; under jit XLA may compile the backward differently, a rounding-level change). The bound holds per point, so it covers per-point weight arrays as well.

Negative weights. The weight is not checked: an unconstrained w_y (HELM's raw nn.Parameter, a call-time LorentzResidual weight= override, or a direct call of this function) can go negative, and w_y < 0 is evaluated, not rejected. Such a weight leaves the domain of the paper's guarantee: LResNet's Lemma 4.1 bounds the normalizer only for (w_x, w_y) in R+ x R+ \ {(0, 0)}, where ave is future timelike, so the absolute value in its Lorentzian norm is notation there, not a mechanism. Where ave turns spacelike (always at w_y = -1, where -c <ave, ave>_L = -c <x - y, x - y>_L <= 0; for -1 < w_y < 0 once x and y are far enough apart), -c <ave, ave>_L < 0 and the output is NaN: the intended signal that the combination has left the hyperboloid. This deliberately differs from the HELM / LResNet reference, whose .abs() (with a 1e-4 clamp) turns a spacelike ave into a valid-looking hyperboloid point that is not a midpoint of x and y in any sense. One case stays silent: for w_y < -1, ave can be timelike but past-directed (ave_0 < 0); the normalizer is then finite and the time-coordinate rebuild below returns the upper-sheet point with spatial part ave_s / sqrt(-c <ave, ave>_L), with no error. A learnable LorentzResidual weight is softplus-constrained and stays in the domain.

The identity assumes x, y are exactly on-sheet — an assumption float storage cannot honour at large radius, since x_0 is only accurate to eps * x_0 and the sheet constraint needs eps * x_0^2 << 1/c (violated beyond ||s|| ~ 3e3 in float32, ~1e8 in float64, e.g. a Poincare point lifted from the ball boundary). The old naive ave / sqrt(-c <ave,ave>_L) was self-normalizing — it put whatever timelike vector it got exactly onto the sheet — while the identity form would return an off-sheet point. To keep that invariant, only the spatial part of ave / denom is taken and the time coordinate is rebuilt as sqrt(||s||^2 + 1/c) (:func:spatial_to_hyperboloid, the same convention as hrc/htc). That reconstruction is itself cancellation-free — it adds, never subtracts — so the identity's large-radius accuracy gain in the spatial scale is preserved. Consequence: the output's time coordinate is a function of its spatial part, so its gradient flows through the spatial components (as in every HRC/HTC layer) rather than through the input time coordinates directly.

References

He, Neil, Menglin Yang, and Rex Ying. "Lorentzian residual neural networks." Proceedings of the 31st ACM SIGKDD Conference on Knowledge Discovery and Data Mining V. 1. 2025. (Also adopted as the residual connection in HELM, He et al. 2025.)

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def lorentz_residual(
    x: Float[Array, "... dim_plus_1"],
    y: Float[Array, "... dim_plus_1"],
    w_y: float | Float[Array, "..."],
    c: ScalarCurvature,
    eps: float = 1e-7,
) -> Float[Array, "... dim_plus_1"]:
    """Lorentzian residual connection (LResNet, He et al. 2025).

    Computes the weighted Lorentzian midpoint of x and y, projecting back
    to the hyperboloid:

        ave = x + w_y * y
        result = ave / sqrt(-c * <ave, ave>_L)   (time coordinate then reconstructed, see Notes)

    where <a, a>_L = -a_0^2 + ||a_s||^2 is the Minkowski inner product. ``<ave, ave>_L`` is
    **not** evaluated by that literal formula: for on-sheet ``x``, ``y``
    (``<x,x>_L = <y,y>_L = -1/c``) it is obtained from the exact, cancellation-free identity ::

        <x + w y, x + w y>_L = -(1 + w)^2 / c - w * <x - y, x - y>_L

    (see Notes).

    .. warning::
        ``w_y`` must be **non-negative**. For x, y on the upper sheet, any conic
        combination ``x + w_y * y`` with ``w_y >= 0`` stays future-directed
        timelike, so the normalization returns a valid hyperboloid point. For
        ``w_y < 0`` the combination can turn spacelike (``<ave, ave>_L > 0``,
        which by the identity above happens exactly when
        ``w_y * <x - y, x - y>_L < -(1 + w_y)^2 / c``; roughly ``w_y < -1`` for
        nearby points), and then the output is NaN. For ``w_y < -1`` it can
        also stay timelike but point to the past (``ave_0 < 0``), and then the
        output is a finite upper-sheet point with no error. This is why callers
        must not expose ``w_y`` as an unconstrained learnable parameter unless
        they accept that behaviour (see Notes, "Negative weights").

    Parameters
    ----------
    x : Array, shape (..., d+1)
        Points on hyperboloid with curvature c.
    y : Array, shape (..., d+1)
        Points on hyperboloid with curvature c (to be added with weight w_y).
    w_y : float or Array, shape () or (...) or (..., 1)
        Weight for the y contribution. Must be >= 0 (see warning above). A scalar applies one
        weight to every point; an array of shape ``x.shape[:-1]`` or ``x.shape[:-1] + (1,)``
        gives one weight per point (e.g. per-token gate weights in a mixture of experts). A
        weight array of shape ``x.shape[:-1]`` gets a trailing axis added internally; any
        other non-scalar shape raises ``ValueError``.
    c : float
        Curvature parameter (positive, c > 0).
    eps : float, optional
        Floor under the squared time coordinate when it is rebuilt from the spatial part
        (:func:`spatial_to_hyperboloid`; default: 1e-7). The normalizer itself has no floor.

    Returns
    -------
    Array, shape (..., d+1)
        Points on hyperboloid with curvature c.

    Notes
    -----
    The naive ``-ave_0^2 + ||ave_s||^2`` subtracts two ``O(||s||^2)`` squares to reach an
    ``O(1/c)`` result, so its float32 relative error grows like ``eps * c * ||s||^2`` and the
    computed value flips sign above ``||s|| ~ 1e4``. Both terms of the identity in the formula block are
    non-positive for ``w_y >= 0``, so combining them adds magnitudes rather than cancelling, and the
    accuracy of the normalizer is the accuracy of the single term ``<x - y, x - y>_L``. That term is
    evaluated by :func:`_lorentz_sqdist_polar` as ``4(P^2 + q^2)/c`` — the hyperbolic haversine form,
    a sum of non-negatives read off the spatial radii — and **not** as the literal
    ``-d_0^2 + ||d_s||^2``, which is itself a difference of two ``O(e^{2a})`` squares (``a`` the
    scaled geodesic radius) and returns noise for a radial pair once ``a`` exceeds ~8 in float32.
    The one float32 limit that remains is the *direction* the two points share: past ``||s|| ~ 1e4``
    the chord ``||x_hat - y_hat||`` is dominated by rounding before either form sees it, and float64
    is required (the naive form is no better there).

    For ``w_y >= 0`` the normalizer needs no ``abs()`` and no floor: the difference of two
    on-sheet points is spacelike (``<x - y, x - y>_L >= 0``, and the polar form is a sum of
    non-negatives, so it is ``>= 0`` in floating point too), so
    ``-c * <ave, ave>_L = (1 + w_y)^2 + c * w_y * <x - y, x - y>_L >= (1 + w_y)^2 >= 1``. The
    output is bit-identical to the earlier ``sqrt(max(c |<ave, ave>_L|, eps))`` (so are eager
    gradients; under ``jit`` XLA may compile the backward differently, a rounding-level change).
    The bound holds
    per point, so it covers per-point weight arrays as well.

    Negative weights. The weight is not checked: an unconstrained ``w_y`` (HELM's raw
    ``nn.Parameter``, a call-time ``LorentzResidual`` ``weight=`` override, or a direct call
    of this function) can go negative, and ``w_y < 0`` is evaluated, not rejected. Such a weight leaves the domain of the
    paper's guarantee: LResNet's Lemma 4.1 bounds the normalizer only for
    ``(w_x, w_y) in R+ x R+ \\ {(0, 0)}``, where ``ave`` is future timelike, so the absolute value
    in its Lorentzian norm is notation there, not a mechanism. Where ``ave`` turns spacelike (always
    at ``w_y = -1``, where ``-c <ave, ave>_L = -c <x - y, x - y>_L <= 0``; for
    ``-1 < w_y < 0`` once ``x`` and ``y`` are far enough apart), ``-c <ave, ave>_L < 0`` and the
    output is NaN: the intended signal that the combination has left the hyperboloid. This
    deliberately differs from the HELM / LResNet reference, whose ``.abs()`` (with a ``1e-4``
    clamp) turns a spacelike ``ave`` into a valid-looking hyperboloid point that is not a
    midpoint of ``x`` and ``y`` in any sense. One case stays silent: for ``w_y < -1``, ``ave``
    can be timelike but past-directed (``ave_0 < 0``); the normalizer is then finite and the
    time-coordinate rebuild below returns the upper-sheet point with spatial part
    ``ave_s / sqrt(-c <ave, ave>_L)``, with no error. A learnable
    ``LorentzResidual`` weight is softplus-constrained and stays in the domain.

    The identity assumes ``x``, ``y`` are *exactly* on-sheet — an assumption float storage cannot
    honour at large radius, since ``x_0`` is only accurate to ``eps * x_0`` and the sheet constraint
    needs ``eps * x_0^2 << 1/c`` (violated beyond ``||s|| ~ 3e3`` in float32, ``~1e8`` in float64,
    e.g. a Poincare point lifted from the ball boundary). The old naive ``ave / sqrt(-c <ave,ave>_L)``
    was self-normalizing — it put *whatever* timelike vector it got exactly onto the sheet — while
    the identity form would return an off-sheet point. To keep that invariant, only the *spatial*
    part of ``ave / denom`` is taken and the time coordinate is rebuilt as
    ``sqrt(||s||^2 + 1/c)`` (:func:`spatial_to_hyperboloid`, the same convention as ``hrc``/``htc``).
    That reconstruction is itself cancellation-free — it adds, never subtracts — so the identity's
    large-radius accuracy gain in the spatial scale is preserved. Consequence: the output's time
    coordinate is a function of its spatial part, so its gradient flows through the spatial
    components (as in every HRC/HTC layer) rather than through the input time coordinates directly.

    References
    ----------
    He, Neil, Menglin Yang, and Rex Ying. "Lorentzian residual neural networks."
    Proceedings of the 31st ACM SIGKDD Conference on Knowledge Discovery and Data Mining V. 1. 2025.
    (Also adopted as the residual connection in HELM, He et al. 2025.)
    """
    # The input's dtype decides: a strongly typed weight (a float64 parameter in a float32 network,
    # a NumPy scalar) is cast to it, or `x + w_y * y` would promote the output. A weakly typed one
    # (a Python number, also once traced as a jit argument) never promotes and is left alone, which
    # keeps that path bit-for-bit unchanged.
    if type(w_y) not in (int, float) and not getattr(w_y, "weak_type", False):
        w_y = jnp.asarray(w_y, dtype=x.dtype)
    # Per-point weights: (...,) -> (..., 1) so they broadcast over the ambient axis.
    if jnp.ndim(w_y) > 0:
        w_shape = tuple(jnp.shape(w_y))
        if w_shape == tuple(x.shape[:-1]):
            w_y = jnp.expand_dims(jnp.asarray(w_y), -1)  # (..., 1)
        elif w_shape != (*x.shape[:-1], 1):
            raise ValueError(
                f"lorentz_residual: w_y must be a scalar or have shape x.shape[:-1] or x.shape[:-1] + (1,); "
                f"got w_y.shape={w_shape} for x.shape={tuple(x.shape)}"
            )
    ave_A = x + w_y * y  # (..., A) where A = d+1
    # Exact for on-sheet x, y:  <x + w y, x + w y>_L = -(1+w)^2/c - w <x-y, x-y>_L.
    # The naive -ave_0^2 + ||ave_s||^2 subtracts two O(||s||^2) squares to reach an O(1/c) result
    # (float32 rel. error ~ eps*c*||s||^2, sign flip above ||s|| ~ 1e4); both terms below are
    # non-positive for w >= 0, so the combination itself adds magnitudes instead of cancelling.
    # <x-y, x-y>_L is the polar form 4(P^2 + q^2)/c, not the literal -d_0^2 + ||d_s||^2, which is
    # itself a difference of two O(e^{2a}) squares and keeps no float32 bits for a radial pair
    # past a ~ 8 — the accuracy of the whole normalizer is the accuracy of this one term.
    # The input's dtype decides, not a float64 `c`. The term `-(1 + w)^2/c` is formed from the
    # caller's `c` and cast as a whole, so a Python-float `c` and `w_y` give the same value as
    # before, bit for bit; everything after it uses `c` cast to x's dtype.
    sheet_1 = jnp.asarray(-((1.0 + w_y) ** 2) / c, dtype=x.dtype)  # () or (..., 1)
    c = jnp.asarray(c, dtype=x.dtype)
    dd_1 = _lorentz_sqdist_polar(x, y, c)[..., None]  # (..., 1), >= 0 on-sheet
    mink_1 = sheet_1 - w_y * dd_1  # (..., 1)
    # No abs() and no floor: for w >= 0, -c*mink >= (1 + w)^2 >= 1 (see Notes), so both were
    # inactive and this is the same value bit for bit. Where a w < 0 makes ave spacelike,
    # -c*mink < 0 and the sqrt returns NaN, the intended signal.
    denom_1 = jnp.sqrt(-c * mink_1)  # (..., 1)
    z_A = ave_A / denom_1  # (..., A)
    # The identity above assumes *exactly* on-sheet inputs, which float storage cannot guarantee at
    # large radius (eps*x_0^2 > 1/c beyond ||s|| ~ 3e3 in float32 / ~1e8 in float64): for such inputs
    # the identity's scale is right but z_A itself lands off the sheet, whereas the old naive
    # h/sqrt(-c<h,h>_L) was self-normalizing. Reconstructing the time coordinate from the (correctly
    # scaled) spatial part restores that invariant — cancellation-free, and the same convention as
    # hrc/htc.
    return spatial_to_hyperboloid(z_A[..., 1:], c_in=c, c_out=c, eps=eps)  # (..., A)

hyperbolix.nn_layers.lorentz_scale

lorentz_scale(
    m: Float[Array, "... dim_plus_1"],
    gamma: float | Float[Array, ""],
    c: float,
    eps: float = 1e-07,
) -> Float[Array, "... dim_plus_1"]

Klein-geodesic output rescaling of a hyperboloid point (LResNet, Eq. 10).

Scales the spatial part by gamma and recomputes the time component so the result stays on the hyperboloid::

m_s' = gamma * m_s
m_t' = sqrt(||m_s'||^2 + 1/c)

The isometry to the Klein model is phi_K(x) = x_s / x_t and Klein geodesics are Euclidean lines through the origin, so this simply slides m along the geodesic ray from the origin -- changing the Euclidean / geodesic norm of the output while keeping it on the manifold. It restores expressiveness the bare Lorentzian residual lacks: :func:lorentz_residual's output is bounded by the larger of its two inputs, whereas gamma > 1 can push the norm beyond both.

Unlike lorentz_residual's w_y, any real gamma yields a valid hyperboloid point (m_t' > 0 always), so a learnable gamma is safe. gamma = 1 is the identity (for an on-manifold m, recomputing the time coordinate returns it unchanged); the LResNet reference uses a fixed gamma = 2 for its CIFAR configurations.

Parameters:

Name Type Description Default
m (Array, shape(..., d + 1))

Points on the hyperboloid with curvature c.

required
gamma float or scalar Array

Scaling constant. Positive values slide toward (< 1) or away from (> 1) the origin along the geodesic ray.

required
c float

Curvature parameter (positive, c > 0).

required
eps float

Numerical stability floor (default: 1e-7).

1e-07

Returns:

Type Description
(Array, shape(..., d + 1))

Rescaled points on the hyperboloid with curvature c.

References

He, Neil, Menglin Yang, and Rex Ying. "Lorentzian residual neural networks." Proceedings of the 31st ACM SIGKDD Conference on Knowledge Discovery and Data Mining V. 1. 2025. Eq. (10) (optional output scaling). See :func:lorentz_residual for the residual this complements.

Source code in hyperbolix/nn_layers/hyperboloid_core.py
def lorentz_scale(
    m: Float[Array, "... dim_plus_1"],
    gamma: float | Float[Array, ""],
    c: float,
    eps: float = 1e-7,
) -> Float[Array, "... dim_plus_1"]:
    """Klein-geodesic output rescaling of a hyperboloid point (LResNet, Eq. 10).

    Scales the spatial part by ``gamma`` and recomputes the time component so the
    result stays on the hyperboloid::

        m_s' = gamma * m_s
        m_t' = sqrt(||m_s'||^2 + 1/c)

    The isometry to the Klein model is ``phi_K(x) = x_s / x_t`` and Klein geodesics
    are Euclidean lines through the origin, so this simply slides ``m`` along the
    geodesic ray from the origin -- changing the Euclidean / geodesic norm of the
    output while keeping it on the manifold. It restores expressiveness the bare
    Lorentzian residual lacks: :func:`lorentz_residual`'s output is bounded by the
    larger of its two inputs, whereas ``gamma > 1`` can push the norm beyond both.

    Unlike ``lorentz_residual``'s ``w_y``, *any* real ``gamma`` yields a valid
    hyperboloid point (``m_t' > 0`` always), so a learnable ``gamma`` is safe.
    ``gamma = 1`` is the identity (for an on-manifold ``m``, recomputing the time
    coordinate returns it unchanged); the LResNet reference uses a fixed
    ``gamma = 2`` for its CIFAR configurations.

    Parameters
    ----------
    m : Array, shape (..., d+1)
        Points on the hyperboloid with curvature ``c``.
    gamma : float or scalar Array
        Scaling constant. Positive values slide toward (``< 1``) or away from
        (``> 1``) the origin along the geodesic ray.
    c : float
        Curvature parameter (positive, c > 0).
    eps : float, optional
        Numerical stability floor (default: 1e-7).

    Returns
    -------
    Array, shape (..., d+1)
        Rescaled points on the hyperboloid with curvature ``c``.

    References
    ----------
    He, Neil, Menglin Yang, and Rex Ying. "Lorentzian residual neural networks."
    Proceedings of the 31st ACM SIGKDD Conference on Knowledge Discovery and Data Mining V. 1. 2025.
    Eq. (10) (optional output scaling). See :func:`lorentz_residual` for the residual
    this complements.
    """
    spatial = m[..., 1:]  # (..., d)
    # The input's dtype decides: a float64 `gamma` must not promote a float32 point under x64
    # (`c` is cast by spatial_to_hyperboloid).
    gamma = jnp.asarray(gamma, dtype=m.dtype)
    # Reuse the scale + time-reconstruction tail; c_in == c_out makes the curvature
    # factor sqrt(c/c) = 1, leaving a pure spatial gamma-scale.
    return spatial_to_hyperboloid(gamma * spatial, c_in=c, c_out=c, eps=eps)

Attention focus transform

hyperbolix.nn_layers.focus_transform

focus_transform(
    x_D: Float[Array, "... D"],
    temperature: Float[Array, ""],
    power: float,
    eps: float = 1e-07,
) -> Float[Array, "... D"]

Norm-preserving focus function (Eq 19, Hypformer).

Applies temperature-scaled ReLU followed by element-wise power sharpening while preserving the original norm.

Up to the eps floors, the output is phi(x) / (|t| + eps) with phi independent of the temperature t. In a linear-attention kernel ratio, where the query and key features both carry the factor, it cancels; :class:HyperbolicLinearAttention therefore has no temperature parameter and passes t = 1.

Parameters:

Name Type Description Default
x_D (Array, shape(..., D))

Input spatial features.

required
temperature scalar Array

Temperature t; the features are divided by |t| + eps.

required
power float

Sharpening exponent (p > 1 concentrates mass).

required
eps float

Numerical stability floor (default: 1e-7).

1e-07

Returns:

Type Description
(Array, shape(..., D))

Focus-transformed features with ||output|| ≈ ||relu(x)/|t|||.

Source code in hyperbolix/nn_layers/hyperboloid_attention.py
def focus_transform(
    x_D: Float[Array, "... D"],
    temperature: Float[Array, ""],
    power: float,
    eps: float = 1e-7,
) -> Float[Array, "... D"]:
    """Norm-preserving focus function (Eq 19, Hypformer).

    Applies temperature-scaled ReLU followed by element-wise power sharpening
    while preserving the original norm.

    Up to the ``eps`` floors, the output is ``phi(x) / (|t| + eps)`` with ``phi`` independent
    of the temperature ``t``. In a linear-attention kernel ratio, where the query and key
    features both carry the factor, it cancels; :class:`HyperbolicLinearAttention`
    therefore has no temperature parameter and passes ``t = 1``.

    Parameters
    ----------
    x_D : Array, shape (..., D)
        Input spatial features.
    temperature : scalar Array
        Temperature ``t``; the features are divided by ``|t| + eps``.
    power : float
        Sharpening exponent (``p > 1`` concentrates mass).
    eps : float, optional
        Numerical stability floor (default: 1e-7).

    Returns
    -------
    Array, shape (..., D)
        Focus-transformed features with ``||output|| ≈ ||relu(x)/|t|||``.
    """
    # Temperature-scaled ReLU
    scaled_relu_D = (jax.nn.relu(x_D) + eps) / (jnp.abs(temperature) + eps)  # (..., D)

    # Element-wise power sharpening
    sharpened_D = scaled_relu_D**power  # (..., D)

    # Norm-preserving rescaling. `safe_hypot_norm(., sqrt(eps))` **is** `sqrt(sum(.**2) + eps)`,
    # bit for bit, but nothing is squared unscaled, so a large activation cannot overflow the
    # reduction. The `eps` floor itself is deliberate and unchanged: `norm_sharpened` is a divisor.
    sqrt_eps = jnp.sqrt(jnp.asarray(eps, dtype=x_D.dtype))
    norm_scaled = safe_hypot_norm(scaled_relu_D, sqrt_eps)[..., None]  # (..., 1)
    norm_sharpened = safe_hypot_norm(sharpened_D, sqrt_eps)[..., None]  # (..., 1)

    return (norm_scaled / norm_sharpened) * sharpened_D  # (..., D)

Poincaré statistics & midpoints

Reductions used by PoincareBatchNorm2D and the Poincaré VQ codebook. frechet_variance is manifold-agnostic (mean squared geodesic distance); poincare_weighted_midpoint is the GGBall weighted gyromidpoint (the Poincaré analog of lorentz_midpoint).

hyperbolix.nn_layers.poincare_midpoint

poincare_midpoint(
    x_NC: Float[Array, "N C"],
    manifold: Poincare,
    c: float,
    eps: float = 1e-06,
) -> Float[Array, C]

Compute the (Einstein) gyromidpoint of Poincaré ball points.

Delegates to :func:poincare_weighted_midpoint (GGBall Eq. 41) with uniform weights::

mu = (1/2) ⊗_c [ Σ λ(x_n)·x_n / Σ (λ(x_n) - 1) ]

NOTE: an earlier version computed Σ(λ²·x) / Σ(λ²), which is not a midpoint (it is not equidistant for two points and is biased toward points near the ball boundary, where λ explodes).

Parameters:

Name Type Description Default
x_NC (Array, shape(N, C))

Points on the Poincaré ball.

required
manifold Poincare

Poincaré manifold instance.

required
c float

Curvature (positive).

required
eps float

Numerical stability floor (default: 1e-6).

1e-06

Returns:

Type Description
(Array, shape(C))

Gyromidpoint on the Poincaré ball.

Source code in hyperbolix/nn_layers/poincare_batchnorm.py
def poincare_midpoint(
    x_NC: Float[Array, "N C"],
    manifold: Poincare,
    c: float,
    eps: float = 1e-6,
) -> Float[Array, "C"]:
    """Compute the (Einstein) gyromidpoint of Poincaré ball points.

    Delegates to :func:`poincare_weighted_midpoint` (GGBall Eq. 41) with uniform
    weights::

        mu = (1/2) ⊗_c [ Σ λ(x_n)·x_n / Σ (λ(x_n) - 1) ]

    NOTE: an earlier version computed ``Σ(λ²·x) / Σ(λ²)``, which is *not* a
    midpoint (it is not equidistant for two points and is biased toward points
    near the ball boundary, where λ explodes).

    Parameters
    ----------
    x_NC : Array, shape (N, C)
        Points on the Poincaré ball.
    manifold : Poincare
        Poincaré manifold instance.
    c : float
        Curvature (positive).
    eps : float
        Numerical stability floor (default: 1e-6).

    Returns
    -------
    Array, shape (C,)
        Gyromidpoint on the Poincaré ball.
    """
    weights_1N = jnp.ones((1, x_NC.shape[0]), dtype=x_NC.dtype)  # (1, N) uniform
    return poincare_weighted_midpoint(x_NC, weights_1N, manifold, c, eps)[0]

hyperbolix.nn_layers.poincare_weighted_midpoint

poincare_weighted_midpoint(
    points_MC: Float[Array, "M C"],
    weights_NM: Float[Array, "N M"],
    manifold: Poincare,
    c: float,
    eps: float = 1e-06,
) -> Float[Array, "N C"]

Weighted Poincaré gyromidpoint over M points (GGBall Eq. 41).

Generalises :func:poincare_midpoint (the unweighted Einstein midpoint of N points) to N weighted midpoints, mirroring the hyperboloid :func:hyperbolix.nn_layers.lorentz_midpoint. For weight-vector w_n over the M points::

mu_n = (1/2) ⊗_c [ Σ_m w_nm · λ(x_m) · x_m  /  Σ_m w_nm · (λ(x_m) - 1) ]

where λ(x) = 2 / (1 - c‖x‖²) is the conformal factor and ⊗_c is Möbius scalar multiplication. The ½ ⊗_c half-scaling is exactly what turns the conformal-weighted Euclidean average into the gyro-midpoint on the ball (for N copies of a single point it returns that point — see the algebra in the tests).

This is the codebook-centroid operator of the hyperbolic-EMA VQ update (GGBall, Bu et al. 2026): pass the assigned encoder points as points and the transposed one-hot assignment matrix (num_codes, N) as weights to get one midpoint per code.

Parameters:

Name Type Description Default
points_MC (Array, shape(M, C))

Points on the Poincaré ball with curvature c.

required
weights_NM (Array, shape(N, M))

Combination weights, one row per output midpoint. Typically non-negative (assignment / attention weights). Because λ(x) ≥ 2 the denominator Σ_m w_nm (λ-1) is strictly positive whenever a row carries any mass; an all-zero row maps to the origin.

required
manifold Poincare

Poincaré manifold instance (supplies conformal_factor, scalar_mul, proj).

required
c float

Curvature (positive).

required
eps float

Denominator floor guarding the empty-row 0/0 (default: 1e-6).

1e-06

Returns:

Type Description
(Array, shape(N, C))

Weighted gyromidpoints on the Poincaré ball.

Source code in hyperbolix/nn_layers/poincare_batchnorm.py
def poincare_weighted_midpoint(
    points_MC: Float[Array, "M C"],
    weights_NM: Float[Array, "N M"],
    manifold: Poincare,
    c: float,
    eps: float = 1e-6,
) -> Float[Array, "N C"]:
    """Weighted Poincaré gyromidpoint over M points (GGBall Eq. 41).

    Generalises :func:`poincare_midpoint` (the unweighted Einstein midpoint of N
    points) to N *weighted* midpoints, mirroring the hyperboloid
    :func:`hyperbolix.nn_layers.lorentz_midpoint`. For weight-vector ``w_n`` over
    the M points::

        mu_n = (1/2) ⊗_c [ Σ_m w_nm · λ(x_m) · x_m  /  Σ_m w_nm · (λ(x_m) - 1) ]

    where ``λ(x) = 2 / (1 - c‖x‖²)`` is the conformal factor and ``⊗_c`` is
    Möbius scalar multiplication. The ``½ ⊗_c`` half-scaling is exactly what turns
    the conformal-weighted Euclidean average into the gyro-midpoint *on* the ball
    (for N copies of a single point it returns that point — see the algebra in
    the tests).

    This is the codebook-centroid operator of the hyperbolic-EMA VQ update
    (GGBall, Bu et al. 2026): pass the assigned encoder points as ``points`` and
    the transposed one-hot assignment matrix ``(num_codes, N)`` as ``weights`` to
    get one midpoint per code.

    Parameters
    ----------
    points_MC : Array, shape (M, C)
        Points on the Poincaré ball with curvature ``c``.
    weights_NM : Array, shape (N, M)
        Combination weights, one row per output midpoint. Typically non-negative
        (assignment / attention weights). Because ``λ(x) ≥ 2`` the denominator
        ``Σ_m w_nm (λ-1)`` is strictly positive whenever a row carries any mass;
        an all-zero row maps to the origin.
    manifold : Poincare
        Poincaré manifold instance (supplies ``conformal_factor``, ``scalar_mul``,
        ``proj``).
    c : float
        Curvature (positive).
    eps : float
        Denominator floor guarding the empty-row 0/0 (default: 1e-6).

    Returns
    -------
    Array, shape (N, C)
        Weighted gyromidpoints on the Poincaré ball.
    """
    # lambda per point — conformal_factor is batched and returns (M, 1).
    lambda_M = manifold.conformal_factor(points_MC, c)[:, 0]  # (M,)

    # Eq. 41 numerator / denominator, contracted over the M axis:
    #   numerator_n = Σ_m w_nm · λ(x_m) · x_m   (N, C)
    #   denom_n     = Σ_m w_nm · (λ(x_m) - 1)   (N,)
    # Both contractions are pinned HIGHEST: this is the Poincaré counterpart of
    # `lorentz_midpoint`, and λ grows without bound near the boundary, so a TF32 ~1e-3
    # relative error on either sum lands directly on the midpoint (see hyperbolix.utils.precision).
    numerator_NC = jnp.einsum("nm,mc->nc", weights_NM, lambda_M[:, None] * points_MC, precision=MATMUL_PRECISION)  # (N, C)
    denom_N = jnp.einsum("nm,m->n", weights_NM, lambda_M - 1.0, precision=MATMUL_PRECISION)  # (N,)
    # Empty row (all-zero weights) -> denom 0 and numerator 0; map to origin
    # rather than 0/0. λ ≥ 2 keeps denom > 0 for any row with mass.
    denom_safe_N = jnp.where(jnp.abs(denom_N) < eps, 1.0, denom_N)  # (N,)
    inner_NC = numerator_NC / denom_safe_N[:, None]  # (N, C) — argument of ½ ⊗_c

    # Boundary guard before the Möbius half-scaling (keeps scalar_mul's atanh in domain).
    inner_NC = jax.vmap(manifold.proj, in_axes=(0, None))(inner_NC, c)

    # mu_n = ½ ⊗_c inner_n  (single-point scalar_mul, vmapped over N).
    mu_NC = jax.vmap(lambda v: manifold.scalar_mul(0.5, v, c))(inner_NC)  # (N, C)
    return jax.vmap(manifold.proj, in_axes=(0, None))(mu_NC, c)

hyperbolix.nn_layers.frechet_variance

frechet_variance(
    x_NC: Float[Array, "N C"],
    mean_C: Float[Array, C],
    manifold: Manifold,
    c: float,
) -> Float[Array, ""]

Compute Fréchet variance: mean squared geodesic distance to mean.

Manifold-generic: only dist is used, so any Manifold works — the gyro normalization layers call this with Hyperboloid and ProperVelocity instances too.

Parameters:

Name Type Description Default
x_NC (Array, shape(N, C))

Points on the manifold.

required
mean_C (Array, shape(C))

Mean point on the manifold.

required
manifold Manifold

Manifold instance (anything satisfying the Manifold protocol).

required
c float

Curvature (positive).

required

Returns:

Type Description
(Array, scalar)

Mean of squared geodesic distances.

Source code in hyperbolix/nn_layers/poincare_batchnorm.py
def frechet_variance(
    x_NC: Float[Array, "N C"],
    mean_C: Float[Array, "C"],
    manifold: Manifold,
    c: float,
) -> Float[Array, ""]:
    """Compute Fréchet variance: mean squared geodesic distance to mean.

    Manifold-generic: only ``dist`` is used, so any ``Manifold`` works — the gyro
    normalization layers call this with Hyperboloid and ProperVelocity instances too.

    Parameters
    ----------
    x_NC : Array, shape (N, C)
        Points on the manifold.
    mean_C : Array, shape (C,)
        Mean point on the manifold.
    manifold : Manifold
        Manifold instance (anything satisfying the ``Manifold`` protocol).
    c : float
        Curvature (positive).

    Returns
    -------
    Array, scalar
        Mean of squared geodesic distances.
    """
    # dist per point: (N,)
    dists_N = jax.vmap(manifold.dist, in_axes=(0, None, None))(x_NC, mean_C, c)
    return jnp.mean(dists_N**2)

Example

import jax, jax.numpy as jnp
from hyperbolix.nn_layers import lorentz_residual
from hyperbolix.manifolds import Hyperboloid

hyperboloid, c, d = Hyperboloid(), 1.0, 6
x = jax.random.normal(jax.random.PRNGKey(0), (8, d + 1))
y = jax.random.normal(jax.random.PRNGKey(1), (8, d + 1))
x = jax.vmap(hyperboloid.proj, in_axes=(0, None))(x, c)
y = jax.vmap(hyperboloid.proj, in_axes=(0, None))(y, c)
result = lorentz_residual(x, y, w_y=0.3, c=c)  # weighted Lorentzian midpoint (skip connection)
print(result.shape)  # (8, 7)