Skip to content

Positional Encoding

Position-aware layers for hyperbolic Transformers on the hyperboloid. HOPE (hope / HyperbolicRoPE) is a deterministic rotary encoding with no learnable parameters that preserves relative position (⟨HOPE(q,i), HOPE(k,j)⟩_L depends only on i-j); HypformerPositionalEncoding is learnable (HTCLinear + Lorentzian residual). For when to prefer each, see the NN Layers guide.

The lorentz_residual / lorentz_scale functions that back the residual skip connection are documented under Primitives; the LorentzResidual NNX module wrapper is here.

HOPE (Hyperbolic Rotary Positional Encoding)

hyperbolix.nn_layers.hope

hope(
    z: Float[Array, "... seq d_plus_1"],
    positions: Float[Array, ...],
    c: float = 1.0,
    base: float = 10000.0,
    eps: float = 1e-07,
) -> Float[Array, "... seq d_plus_1"]

Hyperbolic Rotary Positional Encoding (HOPE).

Applies RoPE-style rotation to the spatial components of hyperboloid points, then reconstructs the time component to satisfy the manifold constraint. Equivalent to hrc(z, R_{i,Theta}, c, c) where R is a block-diagonal rotation matrix.

Since rotation preserves norms, the Minkowski inner product between encoded points depends only on the relative position offset, giving the standard RoPE relative-position property on the hyperboloid.

Parameters:

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

Points on hyperboloid. The spatial dimension d must be even; an odd d raises ValueError.

required
positions Array

Integer position indices, broadcastable against z.shape[:-1]: (seq_len,) for one position sequence shared by all leading axes, or e.g. (batch, seq_len) for per-row positions with z of shape (batch, seq_len, d+1). Axes are aligned from the right, so axes between batch and sequence need singleton axes ((batch, 1, seq_len) for (batch, heads, seq_len, d+1)). See :func:hope_rotate_space.

required
c float

Curvature parameter (default: 1.0).

1.0
base float

Frequency base for rotation angles (default: 10000.0).

10000.0
eps float

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

1e-07

Returns:

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

Rotated points on hyperboloid with curvature c.

References

He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722).

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def hope(
    z: Float[Array, "... seq d_plus_1"],
    positions: Float[Array, "..."],
    c: float = 1.0,
    base: float = 10000.0,
    eps: float = 1e-7,
) -> Float[Array, "... seq d_plus_1"]:
    """Hyperbolic Rotary Positional Encoding (HOPE).

    Applies RoPE-style rotation to the spatial components of hyperboloid
    points, then reconstructs the time component to satisfy the manifold
    constraint. Equivalent to ``hrc(z, R_{i,Theta}, c, c)`` where R is a
    block-diagonal rotation matrix.

    Since rotation preserves norms, the Minkowski inner product between
    encoded points depends only on the *relative* position offset, giving
    the standard RoPE relative-position property on the hyperboloid.

    Parameters
    ----------
    z : Array, shape (..., seq_len, d+1)
        Points on hyperboloid. The spatial dimension ``d`` must be even; an odd ``d`` raises
        ``ValueError``.
    positions : Array
        Integer position indices, broadcastable against ``z.shape[:-1]``:
        ``(seq_len,)`` for one position sequence shared by all leading axes,
        or e.g. ``(batch, seq_len)`` for per-row positions with ``z`` of shape
        ``(batch, seq_len, d+1)``. Axes are aligned from the right, so axes between
        batch and sequence need singleton axes (``(batch, 1, seq_len)`` for
        ``(batch, heads, seq_len, d+1)``). See :func:`hope_rotate_space`.
    c : float, optional
        Curvature parameter (default: 1.0).
    base : float, optional
        Frequency base for rotation angles (default: 10000.0).
    eps : float, optional
        Numerical stability floor (default: 1e-7).

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

    References
    ----------
    He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722).
    """
    spatial_SD = z[..., 1:]  # (..., S, D) where S=seq, D=spatial dim

    # Rotate spatial components (interleaved pairs)
    rotated_SD = hope_rotate_space(spatial_SD, positions, base)  # (..., S, D)

    # Reconstruct time via the hyperboloid constraint (scale = 1 since c_in == c_out),
    # which is exactly the hrc(z, R, c, c) tail this function is documented to equal.
    return spatial_to_hyperboloid(rotated_SD, c_in=c, c_out=c, eps=eps)  # (..., S, A)

hyperbolix.nn_layers.hope_rotate_space

hope_rotate_space(
    x_space: Float[Array, "... seq d"],
    positions: Float[Array, ...],
    base: float = 10000.0,
) -> Float[Array, "... seq d"]

Rotate a spatial tensor with the HOPE / RoPE interleaved-pair rotation.

The spatial-only half of :func:hope: it rotates adjacent pairs (x_0, x_1), (x_2, x_3), ... of the last axis by the angles positions * theta_i with theta_i = 1 / base^(2i/d), and does not rebuild a time coordinate. This is HELM's apply_rotary_emb (a complex multiply over adjacent pairs), used by multi-head latent attention's decoupled RoPE, which rotates only a slice of the space part of the queries and keys and assembles the full point afterwards.

Parameters:

Name Type Description Default
x_space (Array, shape(..., seq_len, d))

Spatial components. d must be even, because the rotation acts on pairs of coordinates; an odd d raises ValueError. Any leading axes.

required
positions Array

Integer position indices, broadcastable against x_space.shape[:-1] after the angle axis is appended (positions[..., None] * theta): (seq_len,) applies one position sequence to every leading axis, (batch, seq_len) gives each batch row its own positions for an x_space of shape (batch, seq_len, d). Axes are aligned from the right, so other layouts need singleton axes: heads before the sequence, (batch, heads, seq_len, d), take (batch, 1, seq_len); heads after it, (batch, seq_len, heads, d) as in HELM, take positions[:, None] of shape (seq_len, 1).

required
base float

Frequency base for rotation angles (default: 10000.0).

10000.0

Returns:

Type Description
Array, same shape and dtype as ``x_space``

Rotated spatial components; every pair keeps its Euclidean norm.

Notes

The rotation is computed in promote_types(x_space.dtype, float32) and cast back to the input dtype: bfloat16/float16 inputs are rotated in float32, as HELM does (x.float() ... .to(dtype)), float32 stays float32 and float64 stays float64.

References

He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722).

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def hope_rotate_space(
    x_space: Float[Array, "... seq d"],
    positions: Float[Array, "..."],
    base: float = 10000.0,
) -> Float[Array, "... seq d"]:
    """Rotate a spatial tensor with the HOPE / RoPE interleaved-pair rotation.

    The spatial-only half of :func:`hope`: it rotates adjacent pairs
    ``(x_0, x_1), (x_2, x_3), ...`` of the last axis by the angles
    ``positions * theta_i`` with ``theta_i = 1 / base^(2i/d)``, and does not
    rebuild a time coordinate. This is HELM's ``apply_rotary_emb`` (a complex
    multiply over adjacent pairs), used by multi-head latent attention's
    decoupled RoPE, which rotates only a slice of the space part of the
    queries and keys and assembles the full point afterwards.

    Parameters
    ----------
    x_space : Array, shape (..., seq_len, d)
        Spatial components. ``d`` must be even, because the rotation acts on pairs of
        coordinates; an odd ``d`` raises ``ValueError``. Any leading axes.
    positions : Array
        Integer position indices, broadcastable against ``x_space.shape[:-1]``
        after the angle axis is appended (``positions[..., None] * theta``):
        ``(seq_len,)`` applies one position sequence to every leading axis,
        ``(batch, seq_len)`` gives each batch row its own positions for an
        ``x_space`` of shape ``(batch, seq_len, d)``. Axes are aligned from the
        right, so other layouts need singleton axes: heads before the sequence,
        ``(batch, heads, seq_len, d)``, take ``(batch, 1, seq_len)``; heads after
        it, ``(batch, seq_len, heads, d)`` as in HELM, take ``positions[:, None]``
        of shape ``(seq_len, 1)``.
    base : float, optional
        Frequency base for rotation angles (default: 10000.0).

    Returns
    -------
    Array, same shape and dtype as ``x_space``
        Rotated spatial components; every pair keeps its Euclidean norm.

    Notes
    -----
    The rotation is computed in ``promote_types(x_space.dtype, float32)`` and cast
    back to the input dtype: bfloat16/float16 inputs are rotated in float32, as
    HELM does (``x.float()`` ... ``.to(dtype)``), float32 stays float32 and float64
    stays float64.

    References
    ----------
    He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722).
    """
    d = x_space.shape[-1]
    if d % 2 != 0:
        raise ValueError(
            f"The rotation acts on pairs of spatial coordinates, so the spatial dimension must be even, got {d} "
            f"(x_space has shape {x_space.shape}; for hope() this is the ambient dimension minus the time coordinate)."
        )
    in_dtype = x_space.dtype
    dtype = jnp.promote_types(in_dtype, jnp.float32)  # f32 for bf16/f16, unchanged for f32/f64
    x_SD = x_space.astype(dtype)  # (..., S, D); no-op for f32/f64

    # Frequency schedule: theta_i = 1 / base^(2i/d). Build the index grid in the
    # compute dtype: bare jnp.arange is int64 under global jax_enable_x64, and the
    # subsequent division would promote the whole encoding to float64.
    freqs_F = 1.0 / (base ** (jnp.arange(0, d, 2, dtype=dtype) / d))  # (F,) where F = d//2
    angles_SF = positions[..., None].astype(dtype) * freqs_F  # (..., S, F), positions' shape + (F,)
    cos_SF = jnp.cos(angles_SF)
    sin_SF = jnp.sin(angles_SF)

    # Rotate interleaved pairs; cos/sin broadcast against the (..., S, F) pair grid.
    rotated_SD = _apply_rotary_interleaved(x_SD, cos_SF, sin_SF)  # (..., S, D)
    return rotated_SD.astype(in_dtype)

hyperbolix.nn_layers.HyperbolicRoPE

HyperbolicRoPE(
    dim: int,
    max_seq_len: int = 2048,
    base: float = 10000.0,
    eps: float = 1e-07,
)

Bases: Module

NNX module wrapper for HOPE (Hyperbolic Rotary Positional Encoding).

This is a stateless module (no learnable parameters) that wraps the functional :func:hope for convenient use in NNX model definitions.

Parameters:

Name Type Description Default
dim int

Spatial dimension d (must be even; an odd dim raises ValueError). The call raises ValueError on points whose spatial dimension is not dim.

required
max_seq_len int

Maximum sequence length (default: 2048). Stored only, it has no effect: the rotation angles are computed from positions on the fly, and positions of any size are accepted.

2048
base float

Frequency base for rotation angles (default: 10000.0).

10000.0
eps float

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

1e-07
References

He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722).

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def __init__(
    self,
    dim: int,
    max_seq_len: int = 2048,
    base: float = 10000.0,
    eps: float = 1e-7,
):
    if dim < 2 or dim % 2 != 0:
        raise ValueError(
            f"HyperbolicRoPE: dim is the spatial dimension and must be even and >= 2 (the rotation "
            f"acts on adjacent pairs), got {dim}"
        )
    self.dim = dim
    self.max_seq_len = max_seq_len
    self.base = base
    self.eps = eps

__call__

__call__(
    z: Float[Array, "... seq d_plus_1"],
    positions: Float[Array, ...],
    c: float = 1.0,
) -> Float[Array, "... seq d_plus_1"]

Apply HOPE positional encoding.

Parameters:

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

Points on hyperboloid; the spatial dim d must equal self.dim, otherwise ValueError.

required
positions Array

Integer position indices, broadcastable against z.shape[:-1] ((seq_len,) or e.g. (batch, seq_len); see :func:hope).

required
c float

Curvature parameter (default: 1.0).

1.0

Returns:

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

Rotated points on hyperboloid.

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def __call__(
    self,
    z: Float[Array, "... seq d_plus_1"],
    positions: Float[Array, "..."],
    c: float = 1.0,
) -> Float[Array, "... seq d_plus_1"]:
    """Apply HOPE positional encoding.

    Parameters
    ----------
    z : Array, shape (..., seq_len, d+1)
        Points on hyperboloid; the spatial dim ``d`` must equal ``self.dim``, otherwise
        ``ValueError``.
    positions : Array
        Integer position indices, broadcastable against ``z.shape[:-1]``
        (``(seq_len,)`` or e.g. ``(batch, seq_len)``; see :func:`hope`).
    c : float, optional
        Curvature parameter (default: 1.0).

    Returns
    -------
    Array, shape (..., seq_len, d+1)
        Rotated points on hyperboloid.
    """
    if z.shape[-1] != self.dim + 1:
        raise ValueError(
            f"HyperbolicRoPE: z must have dim + 1 = {self.dim + 1} ambient coordinates (spatial dim "
            f"{self.dim}) on its last axis, got shape {z.shape}"
        )
    return hope(z, positions, c, self.base, self.eps)

Hypformer Positional Encoding

hyperbolix.nn_layers.HypformerPositionalEncoding

HypformerPositionalEncoding(
    in_features: int,
    out_features: int,
    *,
    rngs: Rngs,
    epsilon: float = 1.0,
    init_bound: float | None = None,
    eps: float = 1e-07,
    param_dtype: DTypeLike = jnp.float32,
)

Bases: Module

Relative positional encoding from Hypformer.

Computes a position vector via HTCLinear, then combines it with the input using a Lorentzian residual connection:

p = HTCLinear(x)
result = lorentz_residual(x, p, w_y=epsilon, c=c)

where epsilon is a FIXED scalar weight on the position contribution. The Hypformer reference keeps it a plain (non-learnable) tensor fixed at 1.0; making it a trainable parameter is unsafe because gradient descent can drive it below -1, where x + epsilon * p leaves the upper hyperboloid sheet: a spacelike combination gives NaN, and a past-directed one a valid-looking but wrong point with no error (see :func:~hyperbolix.nn_layers.hyperboloid_core.lorentz_residual).

Parameters:

Name Type Description Default
in_features int

Input ambient dimension (d+1, including time component).

required
out_features int

Output spatial dimension (d). The HTCLinear output will have ambient dimension d+1 (= out_features + 1), matching the input.

required
rngs Rngs

Random number generators for parameter initialization.

required
epsilon float

Fixed scalar weight for the position encoding contribution (default: 1.0, matching the Hypformer reference). Must be >= 0 so the Lorentzian residual stays on the upper hyperboloid sheet.

1.0
init_bound float or None

Bound for HTCLinear uniform weight initialization; None resolves to HTCLinear's fan-in-aware default sqrt(3 / in_features) (default: None).

None
eps float

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

1e-07
param_dtype DTypeLike

Storage dtype of the trainable parameters, forwarded to the internal HTCLinear (default: jnp.float32). Compute precision follows the input array's dtype.

float32

Attributes:

Name Type Description
htc_linear HTCLinear

Linear transformation producing the position encoding vector.

epsilon float

Fixed scalar weight for the position encoding contribution.

eps float

Numerical stability parameter.

References

He et al., "HELM: Hyperbolic Large Language Models via Mixture-of-Curvature Experts", 2025 (arXiv:2505.24722). Yang et al., "Hypformer: Exploring Efficient Transformer Fully in Hyperbolic Space", 2025.

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def __init__(
    self,
    in_features: int,
    out_features: int,
    *,
    rngs: nnx.Rngs,
    epsilon: float = 1.0,
    init_bound: float | None = None,
    eps: float = 1e-7,
    param_dtype: DTypeLike = jnp.float32,
):
    if epsilon < 0:
        raise ValueError(
            f"epsilon must be >= 0 (got {epsilon}): a negative weight can push the "
            "Lorentzian residual off the upper hyperboloid sheet."
        )
    self.htc_linear = HTCLinear(in_features, out_features, rngs=rngs, init_bound=init_bound, param_dtype=param_dtype)
    self.epsilon = epsilon
    self.eps = eps

__call__

__call__(
    x: Float[Array, "... dim_plus_1"], c: float = 1.0
) -> Float[Array, "... dim_plus_1"]

Apply learnable positional encoding.

Parameters:

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

Points on hyperboloid with curvature c.

required
c float

Curvature parameter (default: 1.0).

1.0

Returns:

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

Positionally-encoded points on hyperboloid with curvature c.

Source code in hyperbolix/nn_layers/hyperboloid_positional.py
def __call__(
    self,
    x: Float[Array, "... dim_plus_1"],
    c: float = 1.0,
) -> Float[Array, "... dim_plus_1"]:
    """Apply learnable positional encoding.

    Parameters
    ----------
    x : Array, shape (..., d+1)
        Points on hyperboloid with curvature c.
    c : float, optional
        Curvature parameter (default: 1.0).

    Returns
    -------
    Array, shape (..., d+1)
        Positionally-encoded points on hyperboloid with curvature c.
    """
    p = self.htc_linear(x, c_in=c, c_out=c)  # (..., d+1)
    return lorentz_residual(x, p, w_y=self.epsilon, c=c, eps=self.eps)

Why epsilon is not learnable

The Hypformer reference keeps epsilon a plain (non-trainable) tensor fixed at 1.0. Making it a parameter is unsafe: gradient descent can drive it below -1, where x + epsilon·p leaves the upper hyperboloid sheet. A spacelike combination then gives NaN, and a past-directed one a valid-looking but wrong point with no error. For the same reason, lorentz_residual's w_y must always be non-negative.

Lorentzian residual connection

hyperbolix.nn_layers.LorentzResidual

LorentzResidual(
    *,
    init_w_y: float = 1.0,
    learnable_weight: bool = True,
    scale: bool = False,
    init_gamma: float = 2.0,
    learnable_scale: bool = False,
    param_dtype: DTypeLike = jnp.float32,
    eps: float = 1e-07,
    scale_parameterization: Literal[
        "softplus", "exp"
    ] = "softplus",
)

Bases: Module

LResNet residual (skip) connection with a safely-constrained weight.

Computes the weighted Lorentzian midpoint of a skip branch x and a residual branch y (the latter weighted by w_y), optionally rescaling the result along the geodesic ray from the origin (LResNet Eq. 10)::

out = lorentz_residual(x, y, w_y, c)            # weighted Lorentzian midpoint
if scale:
    out = lorentz_scale(out, gamma, c)          # optional Eq. 10 norm control

Both x and y are points on the hyperboloid with curvature c; the caller produces y (e.g. via a conv / linear layer). This mirrors how :class:~hyperbolix.nn_layers.HypformerPositionalEncoding composes a transform with lorentz_residual -- except that layer keeps its weight fixed (a trainable position weight is unsafe there), whereas this module makes a trainable w_y safe via the softplus reparameterization.

HELM building blocks (He et al. 2025, helm/modules/helm_mice.py and mice.py; HELM's curvature k is 1/c here). The forward pass matches HELM's LResNet for w_y >= 0. The ambient input gradients differ from HELM's naive |<ave, ave>| normalizer only along the hyperboloid normal; the tangential parts agree (measured in float64 by the HELM port: below 7e-16 after projection onto the tangent space, Riemannian gradients equal to 1.3e-14). There is no abs / 1e-4 clamp. The rescale is not skipped at a log-scale of exactly 0, which in the released code is a torch tensor-truthiness quirk that this building block does not copy. HELM learns w_y as a raw, unconstrained nn.Parameter; here a learnable w_y is always softplus-constrained, so it cannot make the combination spacelike (NaN). ::

# after each attention / FFN block: learnable softplus w_y, fixed scale sqrt(dim)
block_res = LorentzResidual(scale=True, init_gamma=math.sqrt(dim))
x = block_res(x, attn_out, c=c)

# MoE weighted sum of routed experts: per-token gate weight, fixed scale 2.0
weighted_sum = LorentzResidual(learnable_weight=False, scale=True, init_gamma=2.0)
y = weighted_sum(y, expert_out, c=c, weight=gate_N1)   # gate_N1: shape (N, 1) or (N,)

# shared + routed experts combine: learnable softplus w_y, learnable exp scale init 2.0
add_experts = LorentzResidual(
    scale=True,
    init_gamma=2.0,
    learnable_scale=True,
    scale_parameterization="exp",
)
out = add_experts(shared_out, y, c=c)

The call-time weight= override is not constrained: a negative value that makes the combination spacelike gives NaN from :func:~hyperbolix.nn_layers.hyperboloid_core.lorentz_residual, and a past-directed combination (w_y < -1) gives a valid-looking but wrong point with no error (see its Notes). A negative w_y is outside the domain of LResNet's Lemma 4.1, which bounds the normalizer only for (w_x, w_y) in R+ x R+ \ {(0, 0)}.

Parameters:

Name Type Description Default
init_w_y float

Initial value of the residual-branch weight w_y (default: 1.0). Must be >= 0 (> 0 when learnable_weight=True, since softplus cannot represent exactly 0).

1.0
learnable_weight bool

If True (default), w_y is a learnable nnx.Param with w_y = softplus(raw) > 0; if False it is a fixed Python float.

True
scale bool

If True, apply the Eq. 10 Klein-geodesic output scaling after the residual (default: False -- the paper frames it as optional, for low-curvature manifolds).

False
init_gamma float

Initial value of the scaling constant gamma (default: 2.0, the LResNet CIFAR reference value). Must be > 0. Ignored when scale=False.

2.0
learnable_scale bool

If True, gamma is a softplus-constrained nnx.Param; if False (default) it is a fixed Python float. Ignored when scale=False.

False
param_dtype DTypeLike

Storage dtype of any learnable raw parameter (default: jnp.float32), pinned so it does not become float64 under global jax_enable_x64.

float32
eps float

Numerical stability floor passed to lorentz_residual / lorentz_scale (default: 1e-7).

1e-07
scale_parameterization (softplus, exp)

How a learnable gamma is recovered from its raw parameter: "softplus" (default) gives gamma = softplus(raw); "exp" gives gamma = exp(raw) with raw initialized at log(init_gamma) (HELM's learn_scale=True). Ignored unless scale and learnable_scale.

"softplus"

Attributes:

Name Type Description
w_y_raw Param or None

Raw weight (pre-softplus) when learnable_weight=True; otherwise None (the fixed value is stored statically).

gamma_raw Param or None

Raw scaling constant (pre-softplus, or log gamma under "exp") when scale and learnable_scale; otherwise None.

use_scale bool

Whether the Eq. 10 scaling is applied.

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. Residual: :func:~hyperbolix.nn_layers.hyperboloid_core.lorentz_residual; Eq. 10 scaling: :func:~hyperbolix.nn_layers.hyperboloid_core.lorentz_scale.

Source code in hyperbolix/nn_layers/hyperboloid_residual.py
def __init__(
    self,
    *,
    init_w_y: float = 1.0,
    learnable_weight: bool = True,
    scale: bool = False,
    init_gamma: float = 2.0,
    learnable_scale: bool = False,
    param_dtype: DTypeLike = jnp.float32,
    eps: float = 1e-7,
    scale_parameterization: Literal["softplus", "exp"] = "softplus",
):
    if scale_parameterization not in ("softplus", "exp"):
        raise ValueError(
            f"LorentzResidual: scale_parameterization must be 'softplus' or 'exp', got {scale_parameterization!r}"
        )
    if init_w_y < 0:
        raise ValueError(f"LorentzResidual requires init_w_y >= 0, got {init_w_y}")
    if learnable_weight and init_w_y == 0:
        raise ValueError(
            "LorentzResidual with learnable_weight=True requires init_w_y > 0 (softplus cannot represent exactly 0)."
        )
    if init_gamma <= 0:
        raise ValueError(f"LorentzResidual requires init_gamma > 0, got {init_gamma}")

    self.use_scale = scale
    self.eps = eps
    self.scale_parameterization = scale_parameterization

    # y-weight: learnable nnx.Param (softplus-constrained) when learnable, plain float otherwise.
    if learnable_weight:
        self.w_y_raw = nnx.Param(jnp.array(_inv_softplus(init_w_y), dtype=param_dtype))
        self._w_y = None
    else:
        self.w_y_raw = None
        self._w_y = init_w_y

    # Eq. 10 scaling constant gamma (only consulted when use_scale is True).
    if scale and learnable_scale:
        raw_gamma = _inv_softplus(init_gamma) if scale_parameterization == "softplus" else math.log(init_gamma)
        self.gamma_raw = nnx.Param(jnp.array(raw_gamma, dtype=param_dtype))
        self._gamma = None
    else:
        self.gamma_raw = None
        self._gamma = init_gamma

__call__

__call__(
    x: Float[Array, "... dim_plus_1"],
    y: Float[Array, "... dim_plus_1"],
    c: float = 1.0,
    weight: float | Float[Array, ...] | None = None,
) -> Float[Array, "... dim_plus_1"]

Apply the (optionally scaled) Lorentzian residual connection.

Parameters:

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

Skip / main branch on the hyperboloid with curvature c.

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

Residual branch on the hyperboloid with curvature c (weighted by w_y).

required
c float

Curvature parameter (default: 1.0).

1.0
weight float or Array

If given, used as w_y in place of the module's own weight (fixed or learnable), as HELM's LResNet.forward(x, y, weight=...). A scalar, or one weight per point with shape x.shape[:-1] or x.shape[:-1] + (1,) (e.g. per-token gate weights). Not constrained: a negative value is passed through as is.

None

Returns:

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

Points on the hyperboloid with curvature c.

Source code in hyperbolix/nn_layers/hyperboloid_residual.py
def __call__(
    self,
    x: Float[Array, "... dim_plus_1"],
    y: Float[Array, "... dim_plus_1"],
    c: float = 1.0,
    weight: float | Float[Array, "..."] | None = None,
) -> Float[Array, "... dim_plus_1"]:
    """Apply the (optionally scaled) Lorentzian residual connection.

    Parameters
    ----------
    x : Array, shape (..., d+1)
        Skip / main branch on the hyperboloid with curvature ``c``.
    y : Array, shape (..., d+1)
        Residual branch on the hyperboloid with curvature ``c`` (weighted by
        ``w_y``).
    c : float, optional
        Curvature parameter (default: 1.0).
    weight : float or Array, optional
        If given, used as ``w_y`` in place of the module's own weight (fixed
        or learnable), as HELM's ``LResNet.forward(x, y, weight=...)``. A
        scalar, or one weight per point with shape ``x.shape[:-1]`` or
        ``x.shape[:-1] + (1,)`` (e.g. per-token gate weights). Not
        constrained: a negative value is passed through as is.

    Returns
    -------
    Array, shape (..., d+1)
        Points on the hyperboloid with curvature ``c``.
    """
    # Recover w_y from its raw param when learnable (softplus > 0);
    # cast to the input dtype so a float32-pinned param does not silently downcast a float64
    # forward pass. A call-time `weight` overrides the module's own w_y.
    if weight is not None:
        w_y = weight
    elif self.w_y_raw is None:
        w_y = self._w_y
    else:
        w_y = jax.nn.softplus(self.w_y_raw[...])
    out = lorentz_residual(x, y, w_y=jnp.asarray(w_y, dtype=x.dtype), c=c, eps=self.eps)

    if self.use_scale:
        if self.gamma_raw is None:
            gamma = self._gamma
        elif self.scale_parameterization == "softplus":
            gamma = jax.nn.softplus(self.gamma_raw[...])
        else:
            gamma = jnp.exp(self.gamma_raw[...])
        out = lorentz_scale(out, gamma=jnp.asarray(gamma, dtype=x.dtype), c=c, eps=self.eps)

    return out

Example

import jax, jax.numpy as jnp
from flax import nnx
from hyperbolix.nn_layers import hope, HyperbolicRoPE
from hyperbolix.manifolds import Hyperboloid

batch, seq_len, d = 4, 16, 8
spatial = jax.random.normal(jax.random.PRNGKey(42), (batch, seq_len, d)) * 0.1
time = jnp.sqrt(jnp.sum(spatial**2, axis=-1, keepdims=True) + 1.0)
z = jnp.concatenate([time, spatial], axis=-1)  # (4, 16, 9)
positions = jnp.arange(seq_len)

z_enc = hope(z, positions, c=1.0)                          # functional interface
rope = HyperbolicRoPE(dim=d, max_seq_len=64, base=10000.0)  # or the NNX module
z_enc = rope(z, positions, c=1.0)
print(z_enc.shape)  # (4, 16, 9)