Skip to content

Attention & Transformer

Three hyperbolic attention variants from the Hypformer paper (Yang et al. 2025, Section 4.3). All operate on hyperboloid points and support independent curvatures for input (c_in), attention computation (c_attn), and output (c_out), plus causal (autoregressive) masking via causal=True. c_attn and c_out default to c_in, so a call that passes only c_in keeps all three curvatures equal. For complexity/use-case trade-offs see the NN Layers guide.

The supporting utilities (spatial_to_hyperboloid, lorentz_midpoint, focus_transform) are documented under Primitives. The Hypformer transformation component HTCLinear (used for MLP sublayers) is on the Linear page; HRC normalization is on the Normalization page.

Attention modules

hyperbolix.nn_layers.HyperbolicLinearAttention

HyperbolicLinearAttention(
    in_features: int,
    out_features: int,
    *,
    num_heads: int = 1,
    power: float = 2.0,
    init_bound: float | None = None,
    eps: float = 1e-07,
    param_dtype: DTypeLike = jnp.float32,
    rngs: Rngs,
)

Bases: _HyperbolicAttentionBase

Hyperbolic linear attention with focus function (Eq 14-19).

The paper's main contribution: O(N) attention using the kernel trick in the spatial domain of the hyperboloid. Focus function φ sharpens query and key.

Differences from Hypformer
  • No focus temperature. Hypformer learns a temperature t inside the focus function. :func:focus_transform is homogeneous of degree 1 in 1/(|t| + eps), so φ(Q) and φ(K) both scale by it, and the output φ(Q)(φ(K)^T V) / φ(Q)(φ(K)^T 1) sees t only through the eps floors inside :func:focus_transform, in the bidirectional and the causal form alike. Its gradient measured 5 to 7 orders of magnitude below the other parameters', so it stays near its init; the parameter is omitted and the layer uses t = 1, the old init, which leaves the output at init unchanged.
  • No additive eps on the kernel-ratio denominator. Hypformer divides by den + 1e-6. φ is strictly positive, so den > 0, but a query whose spatial part is ≤ 0 on a head has φ(Q) ≈ eps^power and den ~ 1e-13 at the default power = 2, where + eps returns ≈ 0 for that head instead of its attention average. The layer divides by den floored at the smallest normal number of the working dtype promoted to at least float32, a floor that acts only on an underflowed den.

Parameters:

Name Type Description Default
in_features int

Ambient input dimension (d_in + 1).

required
out_features int

Spatial output dimension per head.

required
num_heads int

Number of attention heads (default: 1).

1
power float

Focus function sharpening exponent (default: 2.0).

2.0
init_bound float or None

Uniform init bound forwarded to the HTCLinear projections; None resolves to HTCLinear's fan-in-aware default sqrt(3 / in_features) (default: None).

None
eps float

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

1e-07
param_dtype DTypeLike

Storage dtype of the trainable parameters (default: jnp.float32). This layer takes no manifold_module, so compute precision follows the input array's dtype (the parameters are cast to it).

float32
rngs Rngs

Random number generators.

required
Source code in hyperbolix/nn_layers/hyperboloid_attention.py
def __init__(
    self,
    in_features: int,
    out_features: int,
    *,
    num_heads: int = 1,
    power: float = 2.0,
    init_bound: float | None = None,
    eps: float = 1e-7,
    param_dtype: DTypeLike = jnp.float32,
    rngs: nnx.Rngs,
):
    super().__init__(
        in_features,
        out_features,
        num_heads=num_heads,
        init_bound=init_bound,
        eps=eps,
        param_dtype=param_dtype,
        rngs=rngs,
    )
    self.power = power
    # No temperature parameter: it cancels in the kernel ratio (class docstring).
    # Spatial residual projection ψ: D → D (shared across heads). Its output is added to the
    # attention aggregate, so it is pinned HIGHEST like the aggregate: measured, leaving it at
    # the TF32 default reddens the eager-vs-jit and causal shape-invariance GPU tests even
    # when every attention einsum is already pinned (see hyperbolix.utils.precision). Its
    # parameters are cast to the input dtype at use, so they don't promote a bfloat16 input.
    self.residual_proj = nnx.Linear(
        out_features,
        out_features,
        param_dtype=param_dtype,
        precision=MATMUL_PRECISION,
        promote_dtype=_cast_params_to_input_dtype,
        rngs=rngs,
    )

hyperbolix.nn_layers.HyperbolicSoftmaxAttention

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

Bases: _HyperbolicAttentionBase

Hyperbolic softmax attention in the spatial domain.

Standard scaled dot-product attention applied to spatial components of query, key, value, followed by the same HRC pipeline (residual + time calibration) as the linear variant.

The scores are scaled, masked and softmaxed in at least float32, and the weights are cast back to the working dtype, so bfloat16/float16 inputs get a float32 softmax; float32 and float64 inputs are unaffected.

Parameters:

Name Type Description Default
in_features int

Ambient input dimension (d_in + 1).

required
out_features int

Spatial output dimension per head.

required
num_heads int

Number of attention heads (default: 1).

1
init_bound float or None

Uniform init bound forwarded to the HTCLinear projections; None resolves to HTCLinear's fan-in-aware default sqrt(3 / in_features) (default: None).

None
eps float

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

1e-07
param_dtype DTypeLike

Storage dtype of the trainable parameters (default: jnp.float32). This layer takes no manifold_module, so compute precision follows the input array's dtype (the parameters are cast to it).

float32
rngs Rngs

Random number generators.

required
Source code in hyperbolix/nn_layers/hyperboloid_attention.py
def __init__(
    self,
    in_features: int,
    out_features: int,
    *,
    num_heads: int = 1,
    init_bound: float | None = None,
    eps: float = 1e-7,
    param_dtype: DTypeLike = jnp.float32,
    rngs: nnx.Rngs,
):
    super().__init__(
        in_features,
        out_features,
        num_heads=num_heads,
        init_bound=init_bound,
        eps=eps,
        param_dtype=param_dtype,
        rngs=rngs,
    )
    # Spatial residual projection ψ: D → D (shared across heads). Its output is added to the
    # attention aggregate, so it is pinned HIGHEST like the aggregate: measured, leaving it at
    # the TF32 default reddens the eager-vs-jit and causal shape-invariance GPU tests even
    # when every attention einsum is already pinned (see hyperbolix.utils.precision). Its
    # parameters are cast to the input dtype at use, so they don't promote a bfloat16 input.
    self.residual_proj = nnx.Linear(
        out_features,
        out_features,
        param_dtype=param_dtype,
        precision=MATMUL_PRECISION,
        promote_dtype=_cast_params_to_input_dtype,
        rngs=rngs,
    )

hyperbolix.nn_layers.HyperbolicFullAttention

HyperbolicFullAttention(
    in_features: int,
    out_features: int,
    *,
    num_heads: int = 1,
    init_bound: float | None = None,
    eps: float = 1e-07,
    param_dtype: DTypeLike = jnp.float32,
    score_dtype: DTypeLike | None = None,
    centroid_form: Literal["variance", "gemm"] = "variance",
    init_tau: float | None = None,
    rngs: Rngs,
)

Bases: _HyperbolicAttentionBase

Full Lorentzian attention with midpoint aggregation.

Uses the Lorentzian inner product for similarity and weighted Lorentzian midpoint for aggregation — operating on full hyperboloid points throughout.

The score of query Q and key K is (2/c + 2<Q,K>_L) / tau, which is -d_L^2(Q, K) / tau with d_L^2 = -2/c - 2<Q,K>_L the squared Lorentzian distance. tau = exp(log_tau) is one learnable temperature shared by all heads. The scores are masked and softmaxed in at least float32, and the weights are cast back to the working dtype.

Differences from Hypformer
  • Temperature parameterization. Hypformer divides by a raw learnable scale. Nothing keeps it positive: an optimizer step can drive it to 0 or below, and a negative value flips the softmax so each query attends to its farthest keys. Here the parameter is log_tau and tau = exp(log_tau) is positive for any parameter value. The init is Hypformer's, tau = sqrt(out_features) (the per-head spatial width), unless init_tau is given.
  • No score bias. Hypformer adds one learnable scalar to every score. A constant shared by all keys of a row cancels in the softmax, so that parameter changes nothing and its gradient is exactly zero; it is omitted.
  • Curvature constant. Hypformer writes 2 + 2<Q,K>_L, the c = 1 form; here it is 2/c. The constant cancels in the softmax as well, so the weights are the same, but the score is the scaled negative squared distance for any c.
Float32 score floor

The score contains <Q,K>_L = -Q_0 K_0 + <Q_s, K_s>, a difference of two Minkowski terms each of size cosh(a_q) cosh(a_k) / c — writing a = sqrt(c) d for the geodesic radius of a point in nats — whose O(1) difference is the only part the softmax sees. Unlike the other cancellations in the library this one has no GEMM-compatible cancellation-free spelling: any matrix product of the ambient coordinates returns the Gram matrix to absolute eps, so the angular term alone already carries an error of eps sinh(a_q) sinh(a_k) / c, the same order as the literal form. The absolute error on one score is therefore

eps * cosh(a_q) * cosh(a_k) / (c * tau)

which with float32's eps ≈ 1.19e-7 (c = 1, tau = 1) is about 4.8e-3 at a = 6, 0.26 at a = 8 and 2.0 at a = 9. The default tau = sqrt(out_features) divides these numbers by tau, but it divides the score spread by the same factor, so the radius where the error overtakes the spread does not move: from a ≈ 8 the error exceeds the score spread the softmax is meant to resolve, and the weights are wrong while staying perfectly finite. Three remedies, cheapest first: keep the radius down (a :class:HyperboloidGyroRMSNorm in front of the layer), use a smaller c, or pass score_dtype=jnp.float64 to run the score computation as a float64 island. The island casts only the spatial parts of the queries and keys and rebuilds both time coordinates from them in float64, so its scores are those of a float64 layer fed the same float32 spatial coordinates; what is left is the cost of storing the spatial part in float32, far below the cancellation. Measured against a float64 layer on the unrounded points (c = 1, tau = 1, 16 spatial dimensions, 12 tokens, query and key clouds at scaled radius a whose directions lie within about 8/sinh(a) of each other, worst of three draws), the largest score error at a = 4 / 8 / 12 is 3.8e-4 / 1.1 / 4.2e3 by default and 1.1e-5 / 4.9e-4 / 2.7e-2 with the island, and the largest attention-weight error 7.5e-5 / 0.21 / 1.0 against 9.4e-7 / 3.4e-5 / 1.7e-3; other draws move these maxima by up to a factor of 2. The value aggregation stays in the working dtype: in self-attention at a = 8 and a = 12 the island's float32 output lies 1.2e-4 and 7.7e-3 nats from the float64 output, against 6e-4 to 1e-2 (depending on the draw) and 4.2 by default. The exact pairwise polar-frame evaluation, which would remove the cancellation in float32, is O(N·M·D) in memory and is not implemented here.

Centroid form

Each head aggregates its values with :func:lorentz_midpoint in form=centroid_form. "variance" (the default) is the cancellation-free direct variance, accurate to the storage floor. It is the default because this layer is the library's geometrically faithful O(N²) attention, and its accuracy on far-out values is pinned by tests (test_full_attention_aggregates_far_values_accurately and its per-head-ray sibling). Its cost is an elementwise (B, H, N, M, D) intermediate: O(N M D) work outside the GEMMs, materialized in memory where XLA does not fuse it away.

"gemm" is for long sequences. It normalizes h = sum_m w_m v_m by the literal c (h_0^2 - ||h_s||^2): one GEMM plus O(N) work per head. Measured on an A100, float32 forward+backward, B = 2, H = 4, D = 32, causal, variance against gemm: compile 15.9 s against 4.0 s and step 2.44 ms against 1.93 ms at N = 512; compile 17.2 s against 4.8 s and step 16.5 ms against 9.5 ms at N = 2048 (logs/2026-09-30_helm-decisions/full_attention_centroid_probe_gpu*.out). The normalizer cancels, with relative error up to eps cosh^2(a) at value radius a (float32: 9e-5 at a = 4, 0.27 at a = 8). This depends on the values alone: with queries and keys near the origin, where the scores are float32-accurate, and values at a = 9, the float32 output of "gemm" lies 5.7 to 11 nats from the float64 run, against 5e-7 to 4.5e-4 for "variance" (logs/2026-09-30_helm-decisions/far_values_gemm_probe.out). Use "gemm" only when the values stay well inside a ≈ 6 or run in float64.

The average over heads (a midpoint of the H head aggregates of each token) always uses the variance form: its intermediate is (B, N, H, D), the size of the layer's input, so the GEMM form would save next to nothing (measured: 0.7 s of compile, under 2 % of the step) and would cancel when the head aggregates lie close together.

Parameters:

Name Type Description Default
in_features int

Ambient input dimension (d_in + 1).

required
out_features int

Spatial output dimension per head.

required
num_heads int

Number of attention heads (default: 1).

1
init_bound float or None

Uniform init bound forwarded to the HTCLinear projections; None resolves to HTCLinear's fan-in-aware default sqrt(3 / in_features) (default: None).

None
eps float

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

1e-07
param_dtype DTypeLike

Storage dtype of the trainable parameters (default: jnp.float32). This layer takes no manifold_module, so compute precision follows the input array's dtype (the parameters are cast to it).

float32
score_dtype DTypeLike or None

When set, the spatial parts of the queries and keys are cast to this dtype, both time coordinates are rebuilt from them in this dtype at the attention curvature, and the Lorentzian similarity and the (2/c + 2<Q,K>_L) / tau score are computed in it; the scores are then cast to the softmax dtype (the working dtype, promoted to at least float32) before the softmax. With jnp.float64 this is an opt-in float64 island against the floor above: the scores equal a float64 layer's on the same stored spatial coordinates, and at a = 8 the largest attention-weight error drops from 0.21 to 3.4e-5 (see "Float32 score floor"). jnp.float64 needs jax.config.update("jax_enable_x64", True); without it JAX computes in float32. None (the default) computes the similarity from the stored points in the working dtype and the rest of the score in at least float32.

None
centroid_form (variance, gemm)

form of the per-head :func:lorentz_midpoint that aggregates the values (default: "variance", the aggregation of earlier releases, bit for bit); see "Centroid form". "gemm" is the opt-in faster form for long sequences.

"variance"
init_tau float or None

Initial score temperature tau (must be positive; stored as log(init_tau)). None (the default) is Hypformer's sqrt(out_features). init_tau=1.0 gives the attention of earlier releases at init (their scale = 1, attn_bias = 0) up to the + eps their divisor carried; init_tau=1.0 + eps matches it to rounding (bit for bit at c = 1).

None
rngs Rngs

Random number generators.

required

Attributes:

Name Type Description
log_tau Param

Scalar log temperature, init log(init_tau); the score temperature is tau = exp(log_tau).

Source code in hyperbolix/nn_layers/hyperboloid_attention.py
def __init__(
    self,
    in_features: int,
    out_features: int,
    *,
    num_heads: int = 1,
    init_bound: float | None = None,
    eps: float = 1e-7,
    param_dtype: DTypeLike = jnp.float32,
    score_dtype: DTypeLike | None = None,
    centroid_form: Literal["variance", "gemm"] = "variance",
    init_tau: float | None = None,
    rngs: nnx.Rngs,
):
    if centroid_form not in ("variance", "gemm"):
        raise ValueError(f"centroid_form must be 'variance' or 'gemm', got {centroid_form!r}")
    tau = init_tau if init_tau is not None else math.sqrt(out_features)
    if not tau > 0.0:
        raise ValueError(f"init_tau must be positive, got {init_tau}")
    super().__init__(
        in_features,
        out_features,
        num_heads=num_heads,
        init_bound=init_bound,
        eps=eps,
        param_dtype=param_dtype,
        rngs=rngs,
    )
    self.score_dtype = score_dtype
    self.centroid_form: Literal["variance", "gemm"] = centroid_form
    # tau = exp(log_tau) > 0 for any parameter value (Hypformer learns a raw scale; class docstring).
    self.log_tau = nnx.Param(jnp.asarray(math.log(tau), dtype=param_dtype))

Latent attention (HELM)

LorentzMLA is the attention block of HELM (He et al. 2025): DeepSeek-style multi-head latent attention on the hyperboloid. Keys and values are decompressed from one low-rank latent point per token, queries and keys carry a decoupled HOPE-rotated slice, and each head averages its values with the weighted Lorentzian centroid. It takes one model curvature c and supports causal, packed-sequence (segment_ids) and padding (attention_mask) masks. The mixture-of-curvature feed-forward block that pairs with it is on the Mixture of Curvature Experts page.

hyperbolix.nn_layers.LorentzMLA

LorentzMLA(
    dim: int,
    num_heads: int,
    kv_lora_rank: int,
    qk_nope_head_dim: int,
    qk_rope_head_dim: int,
    v_head_dim: int,
    *,
    rngs: Rngs,
    rope_base: float = 10000.0,
    rms_epsilon: float = 1e-08,
    init_tau: float | None = None,
    init_bound: float | None = None,
    param_dtype: DTypeLike = jnp.float32,
    eps: float = 1e-07,
    centroid_form: Literal["gemm", "variance"] = "gemm",
    score_precision: PrecisionLike = MATMUL_PRECISION,
)

Bases: Module

Hyperbolic multi-head latent attention (HMLA, HELM's LorentzMLA).

Forward pass, for input points x on the hyperboloid <x, x>_L = -1/c:

  1. q = wq(x) (spatial, H * K wide), split per head into q_nope (N) and q_pe (P); q_pe is HOPE-rotated.
  2. wkv_a(x) (spatial, R + P wide) is split into the latent (R,) and one k_pe (P,) per token, shared by all heads and HOPE-rotated.
  3. The latent is RMS-normalized and given a time coordinate (HRCRMSNorm, spatial input), then wkv_b decompresses it into k_nope (N) and the value space (V) per head.
  4. q = [q_nope, q_pe], k = [k_nope, k_pe] and v get their time coordinates rebuilt from the hyperboloid constraint (HELM's "Lorentz concatenation").
  5. Scores (2/c + 2 <q, k>_L) / tau -- the negative squared Lorentzian distance divided by one learnable temperature tau = exp(log_tau) shared by all heads; masked, softmaxed in at least float32.
  6. Each head takes the weighted Lorentzian centroid of its values (:func:lorentz_midpoint with form=centroid_form; the default "gemm" is HELM's lorentzian_centroid, one GEMM plus O(S) work per head), the per-head ambient points (time included) are flattened to (H * W,), and wo maps them to the output point.

Only HELM's q_lora_rank = 0 path (a direct query projection) is implemented; HELM's YaRN mscale adjustment of tau for extended contexts and its (commented-out) KV cache are not.

Differences from the HELM code
  • Temperature init. HELM initializes tau = sqrt(H * L) (L the ambient query/key head width), sqrt(H) larger than the per-head sqrt(L) of standard scaled dot-product attention, so its initial softmax is sqrt(H) times flatter. That is the default here too; init_tau=math.sqrt(qk_nope_head_dim + qk_rope_head_dim) gives the per-head scaling.
  • Temperature parameterization. HELM learns tau itself (self.softmax_scale, a raw parameter that its training script weight-decays toward 0). Nothing keeps that tau positive: an optimizer step can drive it to 0 or below, and a negative tau flips the softmax so each query attends to its farthest keys. Here the parameter is log_tau and tau = exp(log_tau), positive for any parameter value, with the same tau at init. The gradient step is then relative to tau, and weight decay on log_tau pulls tau toward 1 rather than 0.
  • No score bias. HELM adds one learnable scalar to every score (scores / self.softmax_scale + self.bias). A constant shared by all keys of a row cancels in the softmax, so that parameter changes nothing and its gradient is exactly zero; it is omitted.
  • Library forms replace HELM's clamps: the centroid is :func:lorentz_midpoint, whose eps floor sits on c |<h, h>_L| rather than HELM's 1e-8 on |<h, h>_L| and whose time coordinate is rebuilt from the spatial part; the other time coordinates come from :func:spatial_to_hyperboloid.
  • Score and centroid GEMMs. The two score GEMMs default to HIGHEST and can be lowered with score_precision. The centroid GEMM is always HIGHEST. HELM's code runs both at the framework default.
Conventions
  • Head dimensions follow HELM: qk_nope_head_dim counts spatial coordinates, while qk_rope_head_dim and v_head_dim count ambient coordinates (their spatial widths are qk_rope_head_dim - 1 and v_head_dim - 1). A query/key head is therefore a point with qk_nope_head_dim + qk_rope_head_dim ambient coordinates and a value head one with v_head_dim. dim is ambient.
  • Curvature: HELM's manifold parameter k has <x, x>_L = -k; hyperbolix's c has <x, x>_L = -1/c, so c = 1/k and HELM's score 2k + 2<q, k>_L is 2/c + 2<q, k>_L here.
Float32 score floor

The score is formed from GEMMs of the ambient coordinates, so it inherits the floor of :class:HyperbolicFullAttention (docs: numerical-stability.md#attention-score-floor): <q, k>_L = -q_0 k_0 + <q_s, k_s> subtracts two terms of size cosh(a_q) cosh(a_k) / c (a = sqrt(c) d the scaled radius) to reach an O(1) difference, and the absolute score error is about 2 eps cosh(a_q) cosh(a_k) / (c tau). In float32 (c = 1, tau = 1) it reaches O(1) near a ~ 8. A bfloat16 input runs these GEMMs in bfloat16, whose eps is 2^16 times float32's; since the error grows as e^(2a), that moves the same error down by ln(2^16) / 2 ~ 5.5 nats of radius. The weights stay finite either way, just wrong. Keep the radius down, or run the layer in float32/float64. The two score GEMMs are pinned to HIGHEST by default; a lower score_precision (DEFAULT, which is TF32 on Ampere/Hopper) adds its own rounding on top of the cancellation described here. The measured trade-off is under score_precision.

Centroid form

centroid_form="gemm" (the default) normalizes h = sum_t w_t v_t by the literal c (h_0^2 - ||h_s||^2): one GEMM and O(S T) memory per head, like the scores. This is the HELM paper form of the centroid, the one HELM uses. It is the default because at LLM context lengths the alternative is impractical on GPU: centroid_form="variance", the cancellation-free direct variance of :func:lorentz_midpoint, forms an elementwise (B, H, S, T, v_head_dim - 1) intermediate, O(S T D) work outside the GEMMs and as much memory where XLA materializes it (XLA:CPU does in the backward, about 100 GB in float32 at B = 8, H = 12, S = T = 2048, v_head_dim = 64). XLA:GPU fuses it away, but that fused kernel took about 55 s to compile against 9 s for "gemm" at S = 512 (forward plus backward, A100, jax 0.9.1; a forward-only jit took about 9 min against 3 s), and ptxas had not finished it after 10 min at S = 2048.

The price of "gemm" is cancellation in the normalizer, with relative error up to eps cosh^2(a) at value radius a (float32: 9e-5 at a = 4, 0.27 at a = 8). This depends on the values alone, not on the score floor above: in float32 "gemm" loses the centroid once the values lie beyond scaled radius a ≈ 6, even when the queries and keys sit near the origin and the scores are accurate (measured on this layer, values at a ≈ 9: 11.4 nats from the float64 centroid, against at most 6.4e-4 for "variance"; logs/2026-09-30_helm-decisions/mla_far_values_probe.out, pinned by test_variance_centroid_aggregates_far_values_accurately). For short sequences, or whenever the values can lie far out, use centroid_form="variance", which is accurate to the storage floor. The centroid GEMM h = sum_t w_t v_t is always HIGHEST, whatever score_precision says.

Parameters:

Name Type Description Default
dim int

Model ambient dimension A (input and output points have dim coordinates).

required
num_heads int

Number of attention heads H.

required
kv_lora_rank int

Spatial width R of the key/value latent.

required
qk_nope_head_dim int

Spatial width N of the non-rotated query/key slice per head (may be 0).

required
qk_rope_head_dim int

Ambient width of the rotated slice; its spatial width qk_rope_head_dim - 1 must be even and positive.

required
v_head_dim int

Ambient width W of a value head (>= 2).

required
rngs Rngs

Random number generators for parameter initialization.

required
rope_base float

HOPE frequency base (default: 10000.0, HELM's).

10000.0
rms_epsilon float

Epsilon of the latent RMSNorm (default: 1e-8, HELM's LorentzRMSNorm).

1e-08
init_tau float or None

Initial temperature tau (must be positive; stored as log(init_tau)). None (the default) is HELM's sqrt(num_heads * (qk_nope_head_dim + qk_rope_head_dim)); see "Differences from the HELM code" for the per-head alternative.

None
init_bound float or None

Uniform init bound shared by all four projections. None (the default) gives each projection HELM's reference init, Xavier-uniform with gain sqrt(2): sqrt(12 / (in_features + out_features)) with ambient in_features and spatial out_features. All biases start at 0.

None
param_dtype DTypeLike

Storage dtype of the parameters (default: jnp.float32). Compute follows the input dtype.

float32
eps float

Numerical floor for the time rebuilds and the centroid (default: 1e-7).

1e-07
centroid_form (gemm, variance)

form of the per-head :func:lorentz_midpoint (default: "gemm", O(S T) memory, HELM's centroid); "variance" for short sequences or far-out values. See "Centroid form".

"gemm"
score_precision PrecisionLike

Precision of the two attention-score einsums only (default: MATMUL_PRECISION, i.e. jax.lax.Precision.HIGHEST). The centroid GEMM inside :func:lorentz_midpoint stays HIGHEST. The Q/K/V projections (wq, wkv_a, wkv_b) and wo follow JAX's default regardless. See "Float32 score floor" for why the default is pinned.

In the trained HELM-MiCE 120M model (queries and keys below scaled radius a = 3.9), DEFAULT (TF32 on an A100) raised the worst-token output error from 0.017 to 0.035 nats and cut the layer's forward plus backward time to 0.74x at 4 x 2,048 tokens. So DEFAULT is a reasonable choice while queries and keys stay below about a = 4; past that, keep the pin. Measurement and the growth with radius are in the docs: numerical-stability.md#attention-score-floor.

MATMUL_PRECISION

Attributes:

Name Type Description
wq HTCLinear

dim -> num_heads * (N + P) query projection.

wkv_a HTCLinear

dim -> R + P latent and shared rotated-key projection.

kv_norm HRCRMSNorm

RMSNorm of the R latent coordinates.

wkv_b HTCLinear

R + 1 -> num_heads * (N + V) key/value decompression.

wo HTCLinear

num_heads * v_head_dim -> dim - 1 output projection.

log_tau Param

Scalar log temperature, init log(init_tau); the score temperature (HELM's softmax_scale) is tau = exp(log_tau).

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_mla.py
def __init__(
    self,
    dim: int,
    num_heads: int,
    kv_lora_rank: int,
    qk_nope_head_dim: int,
    qk_rope_head_dim: int,
    v_head_dim: int,
    *,
    rngs: nnx.Rngs,
    rope_base: float = 10000.0,
    rms_epsilon: float = 1e-8,
    init_tau: float | None = None,
    init_bound: float | None = None,
    param_dtype: DTypeLike = jnp.float32,
    eps: float = 1e-7,
    centroid_form: Literal["gemm", "variance"] = "gemm",
    score_precision: jax.lax.PrecisionLike = MATMUL_PRECISION,
):
    if dim < 2:
        raise ValueError(f"dim is the ambient model width and must be >= 2, got {dim}")
    if num_heads < 1:
        raise ValueError(f"num_heads must be >= 1, got {num_heads}")
    if kv_lora_rank < 1:
        raise ValueError(f"kv_lora_rank must be >= 1, got {kv_lora_rank}")
    if qk_nope_head_dim < 0:
        raise ValueError(f"qk_nope_head_dim (spatial) must be >= 0, got {qk_nope_head_dim}")
    rope_spatial = qk_rope_head_dim - 1
    if rope_spatial < 2 or rope_spatial % 2 != 0:
        raise ValueError(
            "qk_rope_head_dim is ambient: its spatial width qk_rope_head_dim - 1 must be even and >= 2 "
            f"(HOPE rotates coordinate pairs), got qk_rope_head_dim={qk_rope_head_dim}"
        )
    if v_head_dim < 2:
        raise ValueError(f"v_head_dim is ambient and must be >= 2, got {v_head_dim}")
    if centroid_form not in ("gemm", "variance"):
        raise ValueError(f"centroid_form must be 'gemm' or 'variance', got {centroid_form!r}")

    self.dim = dim
    self.num_heads = num_heads
    self.kv_lora_rank = kv_lora_rank
    self.qk_nope_head_dim = qk_nope_head_dim
    self.qk_rope_head_dim = qk_rope_head_dim
    self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim  # ambient L
    self.v_head_dim = v_head_dim
    self.rope_base = rope_base
    self.eps = eps
    self.centroid_form: Literal["gemm", "variance"] = centroid_form
    self.score_precision: jax.lax.PrecisionLike = score_precision

    def projection(in_features: int, out_features: int) -> HTCLinear:
        bound = init_bound if init_bound is not None else _helm_xavier_bound(in_features, out_features)
        return HTCLinear(
            in_features, out_features, rngs=rngs, use_bias=True, init_bound=bound, eps=eps, param_dtype=param_dtype
        )

    self.wq = projection(dim, num_heads * (self.qk_head_dim - 1))
    self.wkv_a = projection(dim, kv_lora_rank + rope_spatial)
    self.kv_norm = HRCRMSNorm(kv_lora_rank, rngs=rngs, epsilon=rms_epsilon, eps=eps, param_dtype=param_dtype)
    self.wkv_b = projection(kv_lora_rank + 1, num_heads * (qk_nope_head_dim + v_head_dim - 1))
    self.wo = projection(num_heads * v_head_dim, dim - 1)
    tau = init_tau if init_tau is not None else math.sqrt(num_heads * self.qk_head_dim)
    if not tau > 0.0:
        raise ValueError(f"init_tau must be positive, got {init_tau}")
    self.log_tau = nnx.Param(jnp.asarray(math.log(tau), dtype=param_dtype))

__call__

__call__(
    x_BSA: Float[Array, "B S A"],
    c: float = 1.0,
    *,
    positions: Int[Array, S]
    | Int[Array, "B S"]
    | None = None,
    causal: bool = True,
    segment_ids: Int[Array, "B S"] | None = None,
    attention_mask: Bool[Array, "B S"] | None = None,
) -> Float[Array, "B S A"]

Attend over a sequence of hyperboloid points.

Parameters:

Name Type Description Default
x_BSA (Array, shape(B, S, A))

Input points on the hyperboloid with curvature c.

required
c float

Curvature (<x, x>_L = -1/c); input, attention and output all use it (default: 1.0).

1.0
positions int Array of shape (S,) or (B, S)

HOPE positions of the tokens; None uses arange(S) (default: None).

None
causal bool

If True, query s attends only to keys t <= s (default: True).

True
segment_ids int Array of shape (B, S)

Document ids of packed sequences; a query attends only to keys with the same id (HELM's block-diagonal document mask) (default: None).

None
attention_mask bool Array of shape (B, S)

True marks a valid key; False keys (e.g. padding) receive no weight (default: None).

None

Returns:

Type Description
(Array, shape(B, S, A))

Output points on the hyperboloid with curvature c.

Notes

The masks are combined with a logical AND and applied as HELM does, by filling the masked scores with -1e18: a query row with no valid key gets a uniform (finite) softmax over all keys rather than NaN.

Source code in hyperbolix/nn_layers/hyperboloid_mla.py
def __call__(
    self,
    x_BSA: Float[Array, "B S A"],
    c: float = 1.0,
    *,
    positions: Int[Array, "S"] | Int[Array, "B S"] | None = None,
    causal: bool = True,
    segment_ids: Int[Array, "B S"] | None = None,
    attention_mask: Bool[Array, "B S"] | None = None,
) -> Float[Array, "B S A"]:
    """Attend over a sequence of hyperboloid points.

    Parameters
    ----------
    x_BSA : Array, shape (B, S, A)
        Input points on the hyperboloid with curvature ``c``.
    c : float, optional
        Curvature (``<x, x>_L = -1/c``); input, attention and output all use it
        (default: 1.0).
    positions : int Array of shape (S,) or (B, S), optional
        HOPE positions of the tokens; ``None`` uses ``arange(S)`` (default: None).
    causal : bool, optional
        If True, query ``s`` attends only to keys ``t <= s`` (default: True).
    segment_ids : int Array of shape (B, S), optional
        Document ids of packed sequences; a query attends only to keys with the same id
        (HELM's block-diagonal document mask) (default: None).
    attention_mask : bool Array of shape (B, S), optional
        ``True`` marks a valid key; ``False`` keys (e.g. padding) receive no weight
        (default: None).

    Returns
    -------
    Array, shape (B, S, A)
        Output points on the hyperboloid with curvature ``c``.

    Notes
    -----
    The masks are combined with a logical AND and applied as HELM does, by filling the
    masked scores with ``-1e18``: a query row with no valid key gets a uniform (finite)
    softmax over all keys rather than NaN.
    """
    if x_BSA.ndim != 3 or x_BSA.shape[-1] != self.dim:
        raise ValueError(f"x_BSA must have shape (B, S, {self.dim}), got {x_BSA.shape}")
    B, S, _A = x_BSA.shape
    H = self.num_heads
    N = self.qk_nope_head_dim
    P = self.qk_rope_head_dim - 1
    R = self.kv_lora_rank
    V = self.v_head_dim - 1
    eps = self.eps
    work_dtype = x_BSA.dtype

    if positions is None:
        positions = jnp.arange(S, dtype=jnp.int32)  # (S,)
    if positions.shape not in ((S,), (B, S)):
        raise ValueError(f"positions must have shape (S,) = {(S,)} or (B, S) = {(B, S)}, got {positions.shape}")

    # 1. Queries: one GEMM over all heads, then [nope | rope] per head.
    query_space_BSX = self.wq(x_BSA, c, c, return_space=True)  # (B, S, X) = (B, S, H*K)
    query_space_BSHK = query_space_BSX.reshape(B, S, H, N + P)  # (B, S, H, K)
    query_nope_BSHN = query_space_BSHK[..., :N]  # (B, S, H, N)
    # Heads sit after the sequence axis: positions (S,) -> (S, 1), (B, S) -> (B, S, 1).
    query_rope_BSHP = hope_rotate_space(query_space_BSHK[..., N:], positions[..., None], self.rope_base)  # (B, S, H, P)

    # 2. Latent and the shared rotated key: one GEMM, split [latent | rope].
    latent_rope_BSY = self.wkv_a(x_BSA, c, c, return_space=True)  # (B, S, Y) = (B, S, R+P)
    latent_BSR = latent_rope_BSY[..., :R]  # (B, S, R)
    key_rope_BSP = hope_rotate_space(latent_rope_BSY[..., R:], positions, self.rope_base)  # (B, S, P), one per token

    # 3. Normalize the latent into a point, then decompress keys and values for all heads.
    # nnx.RMSNorm promotes a low-precision input to its float32 scale; cast back so a
    # bfloat16 forward stays bfloat16 (HELM's F.rms_norm keeps the input dtype).
    latent_point_BSZ = self.kv_norm(latent_BSR, c, c, space_only=True).astype(work_dtype)  # (B, S, Z) = (B, S, R+1)
    key_value_BSG = self.wkv_b(latent_point_BSZ, c, c, return_space=True)  # (B, S, G) = (B, S, H*U)
    key_value_BSHU = key_value_BSG.reshape(B, S, H, N + V)  # (B, S, H, U)
    key_nope_BSHN = key_value_BSHU[..., :N]  # (B, S, H, N)
    value_space_BSHV = key_value_BSHU[..., N:]  # (B, S, H, V)

    # 4. Lorentz concatenation: concatenate the spatial parts, rebuild the time coordinate.
    query_BSHL = spatial_to_hyperboloid(
        jnp.concatenate([query_nope_BSHN, query_rope_BSHP], axis=-1), c, c, eps
    )  # (B, S, H, L)
    key_rope_BSHP = jnp.broadcast_to(key_rope_BSP[:, :, None, :], (B, S, H, P))  # shared by all heads
    key_BTHL = spatial_to_hyperboloid(jnp.concatenate([key_nope_BSHN, key_rope_BSHP], axis=-1), c, c, eps)
    value_BTHW = spatial_to_hyperboloid(value_space_BSHV, c, c, eps)  # (B, T, H, W)

    # 5. Scores: negative squared Lorentzian distance 2/c + 2<q, k>_L.
    # The two GEMMs cancel at large radius (class docstring, "Float32 score floor"), so they default
    # to HIGHEST as in HyperbolicFullAttention; `score_precision` can lower these two only. The
    # centroid GEMM in step 6 stays HIGHEST, and the projection GEMMs above follow JAX's default.
    lorentz_inner_BHST = -jnp.einsum(
        "bshl,bthl->bhst", query_BSHL[..., :1], key_BTHL[..., :1], precision=self.score_precision
    ) + jnp.einsum(
        "bshk,bthk->bhst", query_BSHL[..., 1:], key_BTHL[..., 1:], precision=self.score_precision
    )  # (B, H, S, T)
    # Scale, mask and softmax run in at least float32 (HELM: softmax(dtype=float32)); a
    # float64 forward keeps float64.
    softmax_dtype = jnp.promote_types(work_dtype, jnp.float32)
    lorentz_inner_BHST = lorentz_inner_BHST.astype(softmax_dtype)
    inv_c = jnp.asarray(1.0, dtype=softmax_dtype) / jnp.asarray(c, dtype=softmax_dtype)
    # tau = exp(log_tau) > 0 for any parameter value (HELM learns tau raw; class docstring).
    tau = jnp.exp(self.log_tau[...].astype(softmax_dtype))
    # No score bias: HELM's `+ self.bias` is one scalar for every key and cancels in the softmax.
    scores_BHST = (2.0 * inv_c + 2.0 * lorentz_inner_BHST) / tau  # (B, H, S, T)
    valid_BST = self._valid_mask(B, S, causal, segment_ids, attention_mask)
    if valid_BST is not None:
        scores_BHST = jnp.where(valid_BST[:, None], scores_BHST, jnp.asarray(_MASK_FILL, dtype=softmax_dtype))
    weights_BHST = jax.nn.softmax(scores_BHST, axis=-1).astype(value_BTHW.dtype)  # (B, H, S, T)

    # 6. Per-head weighted Lorentzian centroid of the values.
    value_BHTW = jnp.transpose(value_BTHW, (0, 2, 1, 3))  # (B, H, T, W)
    centroid_BHSW = lorentz_midpoint(value_BHTW, weights_BHST, c, eps, form=self.centroid_form)  # (B, H, S, W)

    # 7. Flatten the per-head ambient points (time included) and project to the output point.
    heads_BSF = jnp.transpose(centroid_BHSW, (0, 2, 1, 3)).reshape(B, S, H * self.v_head_dim)  # (B, S, H*W)
    return self.wo(heads_BSF, c, c)  # (B, S, A)

Causal (autoregressive) masking

All three variants support causal=True: position n attends only to positions m ≤ n, required for autoregressive tasks. Masking is JIT-compatible.

How causal masking is implemented

  • HyperbolicSoftmaxAttention / HyperbolicFullAttention: lower-triangular mask on the score matrix before softmax, which sets the masked scores to the finite value -1e18 — O(N²) in both modes.
  • HyperbolicLinearAttention: a cumulative-sum recurrence (jax.lax.scan, Katharopoulos et al. 2020): S_i = Σ_{j≤i} φ(K_j) V_jᵀ, O(1) per step → O(N) total, well-suited to long autoregressive sequences.

Example

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

hyperboloid = Hyperboloid()
B, N, A_in, D_out = 4, 8, 9, 8  # 8-dim spatial + 1 time
spatial = jax.random.normal(jax.random.PRNGKey(0), (B, N, A_in - 1)) * 0.1
time = jnp.sqrt(jnp.sum(spatial**2, axis=-1, keepdims=True) + 1.0)
x = jnp.concatenate([time, spatial], axis=-1)  # (B, N, A_in) on the hyperboloid

attn = HyperbolicLinearAttention(in_features=A_in, out_features=D_out, num_heads=2, power=2.0, rngs=nnx.Rngs(0))
y = attn(x, c_in=1.0, c_attn=1.0, c_out=1.0)          # bidirectional
y_causal = attn(x, c_in=1.0, c_attn=1.0, c_out=1.0, causal=True)
print(y.shape)  # (4, 8, 9) — D_out spatial + 1 time

See the NN Layers guide (Pattern 3) for a full hyperbolic transformer block.