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
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 | |
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
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 | |
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 |
Source code in hyperbolix/nn_layers/hyperboloid_core.py
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). |
required |
c
|
float
|
Curvature parameter (positive). |
required |
v_max
|
float
|
Hard clip bound on |
required |
eps
|
float
|
Numerical stability floor passed to :func: |
1e-07
|
Returns:
| Type | Description |
|---|---|
(Array, shape(..., O + 1))
|
Points on the hyperboloid with curvature |
Source code in hyperbolix/nn_layers/hyperboloid_core.py
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. |
required |
c
|
float
|
Curvature (positive). |
required |
v_max
|
float
|
Hard clip bound on |
required |
Returns:
| Type | Description |
|---|---|
(Array, shape(B, O))
|
Points in the Poincaré ball with curvature |
Source code in hyperbolix/nn_layers/busemann_core.py
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 |
References
Klis et al. "Fast and Geometrically Grounded Lorentz Neural Networks" (2026), Eq. 12.
Source code in hyperbolix/nn_layers/hyperboloid_core.py
hyperbolix.nn_layers.hcat_ambient_dim ¶
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
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);cis 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]
|
|
required |
stride
|
tuple[int, int]
|
|
required |
padding
|
str
|
|
required |
pad_mode
|
str
|
|
'edge'
|
c
|
float or None
|
Curvature, required only for |
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 |
Source code in hyperbolix/nn_layers/hyperboloid_core.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
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 |
required |
weights
|
(Array, shape(..., N, M))
|
Combination weights (e.g. attention weights, uniform |
required |
c
|
float
|
Curvature parameter (positive). |
required |
eps
|
float
|
Numerical stability floor (default: 1e-7). |
1e-07
|
form
|
(variance, gemm)
|
How |
"variance"
|
Returns:
| Type | Description |
|---|---|
(Array, shape(..., N, A))
|
Midpoints on the hyperboloid with curvature |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
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)
<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 |
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: |
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
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
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 |
required |
gamma
|
float or scalar Array
|
Scaling constant. Positive values slide toward ( |
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 |
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
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 |
required |
power
|
float
|
Sharpening exponent ( |
required |
eps
|
float
|
Numerical stability floor (default: 1e-7). |
1e-07
|
Returns:
| Type | Description |
|---|---|
(Array, shape(..., D))
|
Focus-transformed features with |
Source code in hyperbolix/nn_layers/hyperboloid_attention.py
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
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 |
required |
weights_NM
|
(Array, shape(N, M))
|
Combination weights, one row per output midpoint. Typically non-negative
(assignment / attention weights). Because |
required |
manifold
|
Poincare
|
Poincaré manifold instance (supplies |
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
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 |
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
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)