Skip to content

Decomposition API

Hyperbolic dimensionality reduction. HoroPCA (Chami et al. 2021) reduces the dimension of hyperbolic data — given on the hyperboloid, the Poincaré ball, or in the ProperVelocity, Klein or half-space model — by jointly optimizing a set of ideal points and projecting the data horospherically, preserving Busemann coordinates. CO-SNE (Guo et al. 2022) is the hyperbolic analogue of t-SNE, adding a magnitude loss that preserves each point's distance-to-origin (the hierarchy depth). The Fréchet mean is the data-centering primitive HoroPCA builds on.

Use float64 for fitting

HoroPCA fits a non-convex objective with Adam; the horospherical projection and Fréchet iteration are most accurate in dtype=jnp.float64. CO-SNE likewise fits most reliably in float64 — its projected gradient descent operates near the ball boundary, where float32 resolution runs out. Enable x64 (JAX_ENABLE_X64=1) and build the manifold with Hyperboloid(dtype=jnp.float64) / Poincare(dtype=jnp.float64) for reliable fits.

HoroPCA

A thin sklearn-style class over the functional core: fit the components at a chosen curvature, then transform points to their low-dimensional embedding. Poincaré input (N, D) maps to (N, K) ball coordinates; Hyperboloid input (N, A) maps to (N, K+1) hyperboloid points; ProperVelocity, Klein and HalfSpace input (N, D) maps to (N, K) points of the same model. Every model is carried onto the hyperboloid by its direct isometry (input is projected onto its model first; ProperVelocity needs no projection) and the result is carried back.

hyperbolix.decomposition.horopca.HoroPCA

HoroPCA(
    manifold: Manifold,
    n_components: int,
    *,
    lr: float = 0.001,
    max_steps: int = 100,
    center_data: bool = True,
    frechet_step_size: float = 1.0,
    frechet_tol: float = 1e-08,
    frechet_max_iters: int = 100,
)

HoroPCA — hyperbolic PCA via horospherical projections (Chami et al. 2021).

A thin sklearn-style wrapper over the functional core. Fit K ideal points to maximize the variance of the horospherically projected data, then transform points to K-dimensional ball coordinates. Input/output models follow the manifold: Poincaré input (N, D) maps to (N, K) ball coordinates; Hyperboloid input (N, A) maps to (N, K+1) hyperboloid points; ProperVelocity, Klein and HalfSpace input (N, D) maps to (N, K) points of the same model (the ball coordinates mapped back through the isometry). Klein and HalfSpace input is projected (proj_batch) before it is mapped onto the hyperboloid.

Args: manifold: A Poincare, Hyperboloid, ProperVelocity, Klein or HalfSpace instance (sets the I/O model and dtype). n_components: Number of components K (needs 1 <= K <= D, the spatial dim). lr: Adam learning rate (default 1e-3). max_steps: Number of optimization steps (default 100). center_data: Fréchet-mean-center the data before fitting (default True — the algorithm assumes mean-zero data). When False the boost is the identity. frechet_step_size: Multiplier on the Fréchet mean's curvature-aware Karcher step (default 1.0). frechet_tol: Karcher convergence tolerance (default 1e-8). frechet_max_iters: Karcher iteration cap (default 100).

Attributes (set after :meth:fit, sklearn trailing-underscore convention): components_: Row-orthonormal ideal directions, shape (K, D). mean_: Fréchet mean on the hyperboloid, shape (A,) (origin if not centering). boost_: Lorentz boost sending mean_ to the origin, shape (A, A) (identity if not centering). The centering itself applies the same map as (⊖mean_) ⊕ x (Hyperboloid.gyro_difference), which does not cancel far from the origin. c_: Curvature used at fit time. losses_: Per-step loss trace, shape (S,). total_variance_: Mean squared pairwise (default) distance of the working points. explained_variance_: Mean squared pairwise (default) distance of the projections. explained_variance_ratio_: explained_variance_ / total_variance_.

Note: total_variance_ / explained_variance_ use the pairwise variance matching the objective (mean squared pairwise geodesic distance), not point-to-mean scatter.

Source code in hyperbolix/decomposition/horopca.py
def __init__(
    self,
    manifold: Manifold,
    n_components: int,
    *,
    lr: float = 1e-3,
    max_steps: int = 100,
    center_data: bool = True,
    frechet_step_size: float = 1.0,
    frechet_tol: float = 1e-8,
    frechet_max_iters: int = 100,
) -> None:
    self._input_model = input_model(manifold, "HoroPCA")

    self.manifold = manifold
    self.n_components = n_components
    self.lr = lr
    self.max_steps = max_steps
    self.center_data = center_data
    self.frechet_step_size = frechet_step_size
    self.frechet_tol = frechet_tol
    self.frechet_max_iters = frechet_max_iters

    # All hyperboloid working-space ops share one internal Hyperboloid at the I/O dtype.
    self._hyperboloid = Hyperboloid(dtype=manifold.dtype)

    # Fitted state (populated by fit()).
    self.components_: Array | None = None
    self.mean_: Array | None = None
    self.boost_: Array | None = None
    self.c_: ScalarCurvature | None = None
    self.losses_: Array | None = None
    self.total_variance_: Array | None = None
    self.explained_variance_: Array | None = None
    self.explained_variance_ratio_: Array | None = None

fit

fit(
    x_ND: Float[Array, "N R"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
) -> HoroPCA

Fit the components on x_ND at curvature c.

Args: x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models. c: Curvature (positive) — bound into the fitted state. key: PRNG key for the Gaussian component init.

Returns: self.

Source code in hyperbolix/decomposition/horopca.py
def fit(self, x_ND: Float[Array, "N R"], c: ScalarCurvature, key: PRNGKeyArray) -> "HoroPCA":
    """Fit the components on ``x_ND`` at curvature ``c``.

    Args:
        x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models.
        c: Curvature (positive) — bound into the fitted state.
        key: PRNG key for the Gaussian component init.

    Returns:
        ``self``.
    """
    if x_ND.ndim != 2:
        raise ValueError(f"Expected a 2D array (n_points, dim), got shape {x_ND.shape}.")
    dim = self._spatial_dim(x_ND)
    if not (1 <= self.n_components <= dim):
        raise ValueError(f"n_components must satisfy 1 <= n_components <= {dim} (spatial dim), got {self.n_components}.")

    c_in = c
    # The manifold's dtype decides: a float64 `c` would otherwise promote the lifted points and
    # break the Fréchet-mean loop's carry dtype. The fitted `c_` keeps the caller's value.
    c = self._hyperboloid._cast_c(c)
    x_hyp_NA = self._to_hyperboloid(x_ND, c)

    if self.center_data:
        mean_A = frechet_mean(
            x_hyp_NA,
            self._hyperboloid,
            c,
            step_size=self.frechet_step_size,
            tol=self.frechet_tol,
            max_iters=self.frechet_max_iters,
        )
        boost_AA = self._hyperboloid.lorentz_boost(mean_A, c)
        x_work_NA = self._center(mean_A, x_hyp_NA, c)
    else:
        ambient = x_hyp_NA.shape[1]
        mean_A = _create_origin(c, ambient - 1, self.manifold.dtype)
        boost_AA = jnp.eye(ambient, dtype=self.manifold.dtype)
        x_work_NA = x_hyp_NA

    components_KD, losses_S = _fit_jit(
        x_work_NA, c, key, n_components=self.n_components, lr=self.lr, max_steps=self.max_steps
    )
    proj_work_NA, _ = _transform_jit(x_work_NA, components_KD, c)

    # Pairwise variance (mean squared pairwise geodesic distance), matching the objective.
    work_dists_NN = compute_pairwise_distances(x_work_NA, self._hyperboloid, c, VERSION_DEFAULT)
    proj_dists_NN = compute_pairwise_distances(proj_work_NA, self._hyperboloid, c, VERSION_DEFAULT)
    total_variance = jnp.mean(work_dists_NN**2)
    explained_variance = jnp.mean(proj_dists_NN**2)

    self.components_ = components_KD
    self.mean_ = mean_A
    self.boost_ = boost_AA
    self.c_ = c_in
    self.losses_ = losses_S
    self.total_variance_ = total_variance
    self.explained_variance_ = explained_variance
    self.explained_variance_ratio_ = explained_variance / floor_at(total_variance, MIN_NORM)
    return self

transform

transform(
    x_ND: Float[Array, "N R"],
) -> Float[Array, "N out"]

Project x_ND onto the fitted components and return the low-dim embedding.

Reuses the stored curvature and mean from :meth:fit (the fitted state is tied to the fit-time c).

Args: x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models.

Returns: Points of the input's model: hyperboloid points (N, K+1) for Hyperboloid input, (N, K) coordinates otherwise.

Source code in hyperbolix/decomposition/horopca.py
def transform(self, x_ND: Float[Array, "N R"]) -> Float[Array, "N out"]:
    """Project ``x_ND`` onto the fitted components and return the low-dim embedding.

    Reuses the stored curvature and mean from :meth:`fit` (the fitted state is tied to
    the fit-time ``c``).

    Args:
        x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models.

    Returns:
        Points of the input's model: hyperboloid points ``(N, K+1)`` for Hyperboloid input,
        ``(N, K)`` coordinates otherwise.
    """
    if self.components_ is None or self.c_ is None or self.mean_ is None:
        raise ValueError("HoroPCA must be fitted before calling transform().")

    c = self._hyperboloid._cast_c(self.c_)
    x_hyp_NA = self._to_hyperboloid(x_ND, c)
    x_work_NA = self._center(self.mean_, x_hyp_NA, c)
    _, ball_NK = _transform_jit(x_work_NA, self.components_, c)
    return map_batch(self._input_model.from_ball, ball_NK, c)  # (N, K+1) hyperboloid, else (N, K)

fit_transform

fit_transform(
    x_ND: Float[Array, "N R"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
) -> Float[Array, "N out"]

Fit on x_ND then return its embedding (equivalent to fit(...).transform(...)).

Source code in hyperbolix/decomposition/horopca.py
def fit_transform(self, x_ND: Float[Array, "N R"], c: ScalarCurvature, key: PRNGKeyArray) -> Float[Array, "N out"]:
    """Fit on ``x_ND`` then return its embedding (equivalent to ``fit(...).transform(...)``)."""
    return self.fit(x_ND, c, key).transform(x_ND)

Usage Example

import jax
import jax.numpy as jnp
from hyperbolix.manifolds import Hyperboloid
from hyperbolix.decomposition import HoroPCA

# HoroPCA optimizes Busemann coordinates near the ideal boundary — request x64
# before the first array is created, or every float64 below truncates to float32.
jax.config.update("jax_enable_x64", True)

manifold = Hyperboloid(dtype=jnp.float64)
key = jax.random.PRNGKey(0)

# x: (N, A) points on the hyperboloid (A = spatial dim + 1)
x = manifold.proj_batch(jax.random.normal(key, (256, 11), dtype=jnp.float64), c=1.0)

model = HoroPCA(manifold, n_components=2, max_steps=500, lr=1e-2)
model.fit(x, c=1.0, key=jax.random.PRNGKey(1))

z = model.transform(x)                       # (256, 3) — K=2 components + time
print(model.explained_variance_ratio_)       # fraction of pairwise variance retained

Functional core

The pure functions underneath HoroPCA — independently usable and JIT-friendly.

hyperbolix.decomposition.horopca

HoroPCA — hyperbolic dimensionality reduction via horospherical projections.

Port of the curvature-general HoroPCA variant (Chami et al., ICML 2021) to JAX. All computation runs on the hyperboloid; Poincaré, ProperVelocity, Klein and half-space input is mapped in via the exact isometries. K ideal points (horospheres) are jointly optimized to maximize the variance of the horospherically projected data (measured as the mean squared pairwise geodesic distance), using Adam with gradient clipping. Projecting onto the K-dimensional ideal span and reading off Busemann-style ball coordinates yields the low-dimensional embedding.

This module provides a pure functional core (independently usable and JIT-friendly) plus a thin sklearn-style :class:HoroPCA wrapper.

Dimension key: N: number of points D: spatial dim A: ambient dim (D + 1) K: number of components (ideal points) S: number of fit steps (max_steps)

References: Chami, Gu, Nguyen, Ré. "HoroPCA: Hyperbolic Dimensionality Reduction via Horospherical Projections." ICML 2021.

horo_projection

horo_projection(
    x_A: Float[Array, A],
    q_ortho_KD: Float[Array, "K D"],
    c: ScalarCurvature,
    version_idx: int = VERSION_DEFAULT,
) -> Float[Array, A]

Horospherical projection of a single hyperboloid point onto the K ideal directions.

Projects x onto the geodesic submanifold spanned by the K ideal points while preserving every Busemann coordinate B^{q_k}(x) (Chami et al. 2021). Dispatches on the static number of components K:

  • K = 1: closed form π(x) = expmap_0(-B_q(x)·[0, q]) (the reference's Sherman-Morrison inverse is singular at K=1). The sign convention matches :func:~hyperbolix.manifolds.hyperboloid._busemann.
  • K ≥ 2: (1) Minkowski-project x onto span(p_k) using the closed-form inverse of the null-lift Gram I - 𝟙𝟙ᵀ (Sherman-Morrison, exact for K ≥ 2); normalize to the manifold to get the spine point; (2) build the unit tangent at the spine pointing toward the origin (orthogonal to the ideal span); (3) walk a geodesic of length d(x, spine) along it.

Numerics of the K ≥ 2 branch. Both quantities that carry the point's radius are formed without a difference of O(x₀) terms. Write r = ‖x_s‖, x̂ = x_s/r and g_k = ⟨q_k, x̂⟩ (the q_k are Euclidean-orthonormal unit vectors, so the g_k are O(1) dots of unit vectors).

  • Sherman-Morrison coefficients. The two steps by_k = -x₀ + r·g_k then c_k = by_k + Σ_j by_j/(1 - K) cancel an O(x₀) term against an O(x₀) term to leave an O(1) result. Combined analytically they are c_k = x₀/(K - 1) + r·(g_k - Σ_j g_j/(K - 1)), which at the origin is exactly 1/(√c·(K - 1)).
  • Spine normalizer. n = x - mp is Minkowski-orthogonal to span(p_k), so n₀ = ⟨q_k, n_s⟩ for every k and the component of n_s outside the span is the component of x_s outside it. Hence ‖n_s‖² = K·n₀² + ‖x_s^⊥‖² and, using ⟨mp, mp⟩_L = ⟨x, x⟩_L - ⟨n, n⟩_L::

    -c·⟨mp, mp⟩_L = 1 + c·(‖x_s^⊥‖² + (K - 1)·n₀²) x_s^⊥ = x_s - Σ_k g_k·r·q_k, n₀ = -[1/(c·(x₀ + r)) + r·(1 - Σ_k g_k)]/(K - 1)

with 1/(c·(x₀ + r)) = x₀ - r on the sheet — the same cancellation-free spelling :func:~hyperbolix.manifolds.hyperboloid._busemann_arg uses for its own radial term. Every term is non-negative, so the result is ≥ 1 analytically and the MIN_NORM floor the literal _minkowski_inner needed is gone (a non-finite input now stays loud).

Measured, c = 1, D = 16, a point 1e-3 rad off q_1 — geodesic error of the float32 projection against the same call in float64, as-is → this form: 7.9e-3 → 1.0e-4 at a = 8, 0.18 to 0.31 → 3.8e-4 at 9, 0.58 → 6.7e-4 at 10, 2.5 → 2.6e-3 at 12, 9.2 → 2.8e-2 at 14. The Busemann coordinates the projection is supposed to preserve come back to ≤1.5e-4 (as-is 4e-2 to 0.17). Steps (2) and (3) are untouched: the unit tangent is built at origin scale and the geodesic walk goes through _dist/_expmap, both already cancellation-free.

Args: x_A: Hyperboloid point, shape (A,), A = D + 1. q_ortho_KD: Row-orthonormal ideal directions, shape (K, D). c: Curvature (positive). version_idx: Distance version used for the geodesic step length (default VERSION_DEFAULT; the loss passes VERSION_SMOOTHENED for smooth grads).

Returns: Projected hyperboloid point, shape (A,).

Source code in hyperbolix/decomposition/horopca.py
def horo_projection(
    x_A: Float[Array, "A"],
    q_ortho_KD: Float[Array, "K D"],
    c: ScalarCurvature,
    version_idx: int = VERSION_DEFAULT,
) -> Float[Array, "A"]:
    """Horospherical projection of a single hyperboloid point onto the K ideal directions.

    Projects ``x`` onto the geodesic submanifold spanned by the K ideal points while
    preserving every Busemann coordinate ``B^{q_k}(x)`` (Chami et al. 2021). Dispatches on
    the static number of components ``K``:

    - ``K = 1``: closed form ``π(x) = expmap_0(-B_q(x)·[0, q])`` (the reference's
      Sherman-Morrison inverse is singular at K=1). The sign convention matches
      :func:`~hyperbolix.manifolds.hyperboloid._busemann`.
    - ``K ≥ 2``: (1) Minkowski-project ``x`` onto ``span(p_k)`` using the closed-form
      inverse of the null-lift Gram ``I - 𝟙𝟙ᵀ`` (Sherman-Morrison, exact for K ≥ 2);
      normalize to the manifold to get the *spine* point; (2) build the unit tangent at the
      spine pointing toward the origin (orthogonal to the ideal span); (3) walk a geodesic of
      length ``d(x, spine)`` along it.

    Numerics of the ``K ≥ 2`` branch. Both quantities that carry the point's radius are formed
    without a difference of ``O(x₀)`` terms. Write ``r = ‖x_s‖``, ``x̂ = x_s/r`` and
    ``g_k = ⟨q_k, x̂⟩`` (the ``q_k`` are Euclidean-orthonormal unit vectors, so the ``g_k`` are
    ``O(1)`` dots of unit vectors).

    * **Sherman-Morrison coefficients.** The two steps
      ``by_k = -x₀ + r·g_k`` then ``c_k = by_k + Σ_j by_j/(1 - K)`` cancel an ``O(x₀)`` term against
      an ``O(x₀)`` term to leave an ``O(1)`` result. Combined analytically they are
      ``c_k = x₀/(K - 1) + r·(g_k - Σ_j g_j/(K - 1))``, which at the origin is exactly
      ``1/(√c·(K - 1))``.
    * **Spine normalizer.** ``n = x - mp`` is Minkowski-orthogonal to ``span(p_k)``, so
      ``n₀ = ⟨q_k, n_s⟩`` for *every* k and the component of ``n_s`` outside the span is the
      component of ``x_s`` outside it. Hence ``‖n_s‖² = K·n₀² + ‖x_s^⊥‖²`` and, using
      ``⟨mp, mp⟩_L = ⟨x, x⟩_L - ⟨n, n⟩_L``::

          -c·⟨mp, mp⟩_L = 1 + c·(‖x_s^⊥‖² + (K - 1)·n₀²)
          x_s^⊥ = x_s - Σ_k g_k·r·q_k,   n₀ = -[1/(c·(x₀ + r)) + r·(1 - Σ_k g_k)]/(K - 1)

      with ``1/(c·(x₀ + r)) = x₀ - r`` on the sheet — the same cancellation-free spelling
      :func:`~hyperbolix.manifolds.hyperboloid._busemann_arg` uses for its own radial term. Every
      term is non-negative, so the result is ``≥ 1`` analytically and the ``MIN_NORM`` floor the
      literal ``_minkowski_inner`` needed is gone (a non-finite input now stays loud).

    Measured, ``c = 1``, ``D = 16``, a point 1e-3 rad off ``q_1`` — geodesic error of the float32
    projection against the same call in float64, as-is → this form: 7.9e-3 → 1.0e-4 at ``a = 8``,
    0.18 to 0.31 → 3.8e-4 at 9, 0.58 → 6.7e-4 at 10, 2.5 → 2.6e-3 at 12, 9.2 → 2.8e-2 at 14. The
    Busemann coordinates the projection is supposed to preserve come back to ≤1.5e-4 (as-is 4e-2 to
    0.17). Steps (2) and (3) are untouched: the unit tangent is built at origin scale and the
    geodesic walk goes through ``_dist``/``_expmap``, both already cancellation-free.

    Args:
        x_A: Hyperboloid point, shape (A,), A = D + 1.
        q_ortho_KD: Row-orthonormal ideal directions, shape (K, D).
        c: Curvature (positive).
        version_idx: Distance version used for the geodesic step length (default
            ``VERSION_DEFAULT``; the loss passes ``VERSION_SMOOTHENED`` for smooth grads).

    Returns:
        Projected hyperboloid point, shape (A,).
    """
    num_components = q_ortho_KD.shape[0]
    dim = q_ortho_KD.shape[1]
    dtype = x_A.dtype
    c = jnp.asarray(c, dtype=dtype)  # the point's dtype decides, not a float64 `c`

    if num_components == 1:
        # Closed form: preserve the single Busemann coordinate B^q(x).
        q_D = q_ortho_KD[0]  # unit spatial ideal direction
        busemann = _busemann(x_A, q_D, c)  # B^q(x)
        tangent_A = -busemann * _embed_spatial_0(q_D)  # tangent at origin: -B·[0, q]
        return _proj(_expmap_0(tangent_A, c), c)

    p_KA = lift_ideals(q_ortho_KD)  # null lifts [1, q_k], shape (K, A)
    km1 = num_components - 1.0  # K - 1 >= 1 in this branch

    def _radial_split(y_A: Float[Array, "A"]) -> tuple[Float[Array, ""], Float[Array, "K"]]:
        # Radius and the K direction cosines g_k = ⟨q_k, ŷ_s⟩ — dots of unit vectors, so O(1).
        # `safe_normalize` returns the exact zero vector at y_s = 0 (the origin), where every
        # g_k is 0 and the coefficient below collapses to y_0/(K-1) = 1/(√c(K-1)). Correct.
        r = safe_norm(y_A[1:])
        g_K = jnp.matmul(q_ortho_KD, safe_normalize(y_A[1:]), precision=MATMUL_PRECISION)  # (K,)
        return r, g_K

    def _span_coeffs(y_A: Float[Array, "A"], r: Float[Array, ""], g_K: Float[Array, "K"]) -> Float[Array, "K"]:
        # ⟨y, p_k⟩_L = -y_0 + r·g_k, then the closed-form inverse of the null-lift Gram
        # G = I - 𝟙𝟙ᵀ: G⁻¹ = I + 𝟙𝟙ᵀ/(1-K) (Sherman-Morrison). Written out, the two steps cancel
        # y_0 against y_0 to leave an O(1) result; combined analytically they do not:
        #     c_k = y_0/(K-1) + r·(g_k - Σ_j g_j/(K-1)).
        # See the numerics note in the docstring.
        return y_A[0] / km1 + r * (g_K - jnp.sum(g_K) / km1)

    # (1) Minkowski projection of x onto span(p_k), normalized onto the manifold (the spine).
    r_x, g_K = _radial_split(x_A)
    coeffs_K = _span_coeffs(x_A, r_x, g_K)
    mp_A = jnp.matmul(coeffs_K, p_KA, precision=MATMUL_PRECISION)  # (A,) projection of x onto the ideal span
    # -c⟨mp, mp⟩_L in closed form: 1 + c(‖x_s^⊥‖² + (K-1)·n₀²) with n = x - mp ⊥_L span(p_k).
    # Every term is non-negative and the value is ≥ 1, so no floor: an already non-finite input
    # stays loud instead of being mapped onto a plausible finite spine.
    x_perp_D = x_A[1:] - jnp.matmul(r_x * g_K, q_ortho_KD, precision=MATMUL_PRECISION)  # (D,)
    # 1/(c(x₀ + r)) is x₀ - r on the sheet — the cancellation-free spelling `_busemann_arg` uses.
    n0 = -(1.0 / (c * (x_A[0] + r_x)) + r_x * (1.0 - jnp.sum(g_K))) / km1
    neg_c_mp_inner = 1.0 + c * (safe_norm(x_perp_D) ** 2 + km1 * n0**2)
    spine_A = mp_A / jnp.sqrt(neg_c_mp_inner)
    # Sheet hygiene BEFORE _proj: _proj rebuilds a positive time from the spatial part and
    # cannot itself flip a lower-sheet point back up, so reflect first (spine_0 != 0).
    spine_A = spine_A * jnp.sign(spine_A[0])
    spine_A = _proj(spine_A, c)

    # (2) Unit tangent at the spine pointing toward the origin (⊥ span(P) ⇒ tangent at spine).
    origin_A = _create_origin(c, dim, dtype)
    origin_coeffs_K = _span_coeffs(origin_A, *_radial_split(origin_A))
    # projection of the origin onto the ideal span
    proj_span_o_A = jnp.matmul(origin_coeffs_K, p_KA, precision=MATMUL_PRECISION)
    tangent_A = origin_A - proj_span_o_A  # spacelike, ⊥ span(P)
    tangent_inner = _minkowski_inner(tangent_A, tangent_A)  # > 0 (spacelike)
    unit_tangent_A = tangent_A / jnp.sqrt(floor_at(tangent_inner, MIN_NORM))

    # (3) Geodesic walk of length d(x, spine) along the unit tangent.
    step = _dist(x_A, spine_A, c, version_idx)
    return _proj(_expmap(step * unit_tangent_A, spine_A, c), c)

horopca_loss

horopca_loss(
    q_KD: Float[Array, "K D"],
    x_NA: Float[Array, "N A"],
    c: ScalarCurvature,
) -> Float[Array, ""]

Negative mean squared pairwise (smoothened) distance of the projected points.

Orthonormalizes q_KD internally, horospherically projects every point (with the smoothened distance version, differentiable at coincident points), then returns -mean(d(π(x_i), π(x_j))²) over the full NxN matrix (diagonal included, matching the reference). Maximizing projected variance ⇔ minimizing this loss.

Args: q_KD: Component directions (rows, pre-orthonormalization), shape (K, D). x_NA: Hyperboloid points, shape (N, A). c: Curvature (positive).

Returns: Scalar loss.

Source code in hyperbolix/decomposition/horopca.py
def horopca_loss(q_KD: Float[Array, "K D"], x_NA: Float[Array, "N A"], c: ScalarCurvature) -> Float[Array, ""]:
    """Negative mean squared pairwise (smoothened) distance of the projected points.

    Orthonormalizes ``q_KD`` internally, horospherically projects every point (with the
    smoothened distance version, differentiable at coincident points), then returns
    ``-mean(d(π(x_i), π(x_j))²)`` over the full NxN matrix (diagonal included, matching the
    reference). Maximizing projected variance ⇔ minimizing this loss.

    Args:
        q_KD: Component directions (rows, pre-orthonormalization), shape (K, D).
        x_NA: Hyperboloid points, shape (N, A).
        c: Curvature (positive).

    Returns:
        Scalar loss.
    """
    c = jnp.asarray(c, dtype=x_NA.dtype)  # the points' dtype decides, not a float64 `c`
    q_ortho_KD = orthonormalize_rows(q_KD)
    proj_fn = functools.partial(horo_projection, version_idx=VERSION_SMOOTHENED)
    proj_NA = jax.vmap(proj_fn, in_axes=(0, None, None))(x_NA, q_ortho_KD, c)

    dist_fn = functools.partial(_dist, version_idx=VERSION_SMOOTHENED)
    pairwise_NN = jax.vmap(jax.vmap(dist_fn, in_axes=(None, 0, None)), in_axes=(0, None, None))(proj_NA, proj_NA, c)
    return -jnp.mean(pairwise_NN**2)

fit_horopca

fit_horopca(
    x_NA: Float[Array, "N A"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
    *,
    n_components: int,
    lr: float = 0.001,
    max_steps: int = 100,
) -> tuple[Float[Array, "K D"], Float[Array, S]]

Fit HoroPCA components on hyperboloid data by Adam + gradient clipping.

Draws a Gaussian (K, D) component matrix, then runs max_steps of Adam (with global-norm clipping at 1e5) on :func:horopca_loss via lax.scan. Returns the final orthonormalized components and the per-step loss trace.

Args: x_NA: Hyperboloid points (Fréchet-centered for best results), shape (N, A). c: Curvature (positive). key: PRNG key for the Gaussian component init. n_components: Number of components K (static; needs 1 <= K <= D). lr: Adam learning rate (default 1e-3). max_steps: Number of optimization steps S (default 100).

Returns: Tuple (q_ortho_KD, losses_S): row-orthonormal components (K, D) and the loss trace (S,).

Source code in hyperbolix/decomposition/horopca.py
def fit_horopca(
    x_NA: Float[Array, "N A"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
    *,
    n_components: int,
    lr: float = 1e-3,
    max_steps: int = 100,
) -> tuple[Float[Array, "K D"], Float[Array, "S"]]:
    """Fit HoroPCA components on hyperboloid data by Adam + gradient clipping.

    Draws a Gaussian ``(K, D)`` component matrix, then runs ``max_steps`` of Adam (with
    global-norm clipping at 1e5) on :func:`horopca_loss` via ``lax.scan``. Returns the
    final orthonormalized components and the per-step loss trace.

    Args:
        x_NA: Hyperboloid points (Fréchet-centered for best results), shape (N, A).
        c: Curvature (positive).
        key: PRNG key for the Gaussian component init.
        n_components: Number of components K (static; needs 1 <= K <= D).
        lr: Adam learning rate (default 1e-3).
        max_steps: Number of optimization steps S (default 100).

    Returns:
        Tuple ``(q_ortho_KD, losses_S)``: row-orthonormal components (K, D) and the loss
        trace (S,).
    """
    dim = x_NA.shape[1] - 1
    c = jnp.asarray(c, dtype=x_NA.dtype)  # the points' dtype decides, not a float64 `c`
    q_KD = jax.random.normal(key, (n_components, dim), dtype=x_NA.dtype)

    tx = optax.chain(optax.clip_by_global_norm(1e5), optax.adam(lr))
    opt_state = tx.init(q_KD)

    def step_fn(carry: tuple[Array, optax.OptState], _: None) -> tuple[tuple[Array, optax.OptState], Array]:
        q, state = carry
        loss, grad = jax.value_and_grad(horopca_loss)(q, x_NA, c)
        updates, new_state = tx.update(grad, state, q)
        # `optax.apply_updates` is typed over the whole `Params` pytree; here the pytree is
        # the single (K, D) component array, so the result is an Array.
        new_q = cast(Array, optax.apply_updates(q, updates))
        return (new_q, new_state), loss

    (q_final_KD, _), losses_S = jax.lax.scan(step_fn, (q_KD, opt_state), None, length=max_steps)
    return orthonormalize_rows(q_final_KD), losses_S

transform_horopca

transform_horopca(
    x_NA: Float[Array, "N A"],
    q_ortho_KD: Float[Array, "K D"],
    c: ScalarCurvature,
) -> tuple[Float[Array, "N A"], Float[Array, "N K"]]

Project data and read off the K-dimensional Poincaré ball coordinates.

Horospherically projects each point (default distance version), maps the projections to the Poincaré ball, and reads the K ball coordinates as the component-frame coefficients y @ q_orthoᵀ (an isometry onto the K-ball, since the projected spatial parts lie in the span of the orthonormal rows).

Args: x_NA: Hyperboloid points, shape (N, A). q_ortho_KD: Row-orthonormal components, shape (K, D). c: Curvature (positive).

Returns: Tuple (proj_NA, ball_NK): the projected hyperboloid points (N, A) and the low-dimensional Poincaré ball coordinates (N, K).

Source code in hyperbolix/decomposition/horopca.py
def transform_horopca(
    x_NA: Float[Array, "N A"],
    q_ortho_KD: Float[Array, "K D"],
    c: ScalarCurvature,
) -> tuple[Float[Array, "N A"], Float[Array, "N K"]]:
    """Project data and read off the K-dimensional Poincaré ball coordinates.

    Horospherically projects each point (default distance version), maps the projections to
    the Poincaré ball, and reads the K ball coordinates as the component-frame coefficients
    ``y @ q_orthoᵀ`` (an isometry onto the K-ball, since the projected spatial parts lie in
    the span of the orthonormal rows).

    Args:
        x_NA: Hyperboloid points, shape (N, A).
        q_ortho_KD: Row-orthonormal components, shape (K, D).
        c: Curvature (positive).

    Returns:
        Tuple ``(proj_NA, ball_NK)``: the projected hyperboloid points (N, A) and the
        low-dimensional Poincaré ball coordinates (N, K).
    """
    c = jnp.asarray(c, dtype=x_NA.dtype)  # the points' dtype decides, not a float64 `c`
    proj_NA = jax.vmap(horo_projection, in_axes=(0, None, None, None))(x_NA, q_ortho_KD, c, VERSION_DEFAULT)
    ball_ND = jax.vmap(hyperboloid_to_poincare, in_axes=(0, None))(proj_NA, c)  # (N, D) full ball coords
    ball_NK = jnp.matmul(ball_ND, q_ortho_KD.T, precision=MATMUL_PRECISION)  # (N, K) coordinates in the component frame
    return proj_NA, ball_NK

lift_ideals

lift_ideals(
    q_KD: Float[Array, "K D"],
) -> Float[Array, "K A"]

Lift spatial ideal directions to null vectors on the light cone.

Prepends a ones column: p_k = [1, q_k]. For unit q_k these are null vectors (⟨p_k, p_k⟩_L = -1 + ‖q_k‖² = 0), the ideal-point lifts used by the horospherical projection. Curvature-free (the null lift does not depend on c).

Args: q_KD: Spatial ideal directions (rows), shape (K, D). Assumed unit-norm.

Returns: Null lifts, shape (K, A) with A = D + 1.

Source code in hyperbolix/decomposition/horopca.py
def lift_ideals(q_KD: Float[Array, "K D"]) -> Float[Array, "K A"]:
    """Lift spatial ideal directions to null vectors on the light cone.

    Prepends a ones column: ``p_k = [1, q_k]``. For unit ``q_k`` these are null vectors
    (``⟨p_k, p_k⟩_L = -1 + ‖q_k‖² = 0``), the ideal-point lifts used by the horospherical
    projection. Curvature-free (the null lift does not depend on ``c``).

    Args:
        q_KD: Spatial ideal directions (rows), shape (K, D). Assumed unit-norm.

    Returns:
        Null lifts, shape (K, A) with A = D + 1.
    """
    ones_K1 = jnp.ones((q_KD.shape[0], 1), dtype=q_KD.dtype)
    return jnp.concatenate([ones_K1, q_KD], axis=1)

orthonormalize_rows

orthonormalize_rows(
    q_KD: Float[Array, "K D"],
) -> Float[Array, "K D"]

Orthonormalize the rows of q_KD via a reduced QR of its transpose.

Returns rows that are orthonormal in the Euclidean metric (needs D >= K). The QR sign is deterministic per input but frame-dependent (flipping a row flips the corresponding ideal point) — compare only geometric invariants across runs, never the components themselves.

Args: q_KD: Component directions (rows), shape (K, D) with D >= K.

Returns: Row-orthonormal directions, shape (K, D).

Source code in hyperbolix/decomposition/horopca.py
def orthonormalize_rows(q_KD: Float[Array, "K D"]) -> Float[Array, "K D"]:
    """Orthonormalize the rows of ``q_KD`` via a reduced QR of its transpose.

    Returns rows that are orthonormal in the Euclidean metric (needs ``D >= K``). The QR
    sign is deterministic per input but frame-dependent (flipping a row flips the
    corresponding ideal point) — compare only geometric invariants across runs, never the
    components themselves.

    Args:
        q_KD: Component directions (rows), shape (K, D) with D >= K.

    Returns:
        Row-orthonormal directions, shape (K, D).
    """
    q_ortho_DK, _ = jnp.linalg.qr(q_KD.T)  # reduced QR: (D, K) with orthonormal columns
    return q_ortho_DK.T

CO-SNE

Hyperbolic t-SNE (Guo et al. 2022): a low-dimensional Poincaré ball embedding that preserves both pairwise similarities (the t-SNE KL term) and each point's distance-to-origin — the hierarchy depth — via an added magnitude loss H = (1/N)·Σᵢ(‖xᵢ‖² − ‖yᵢ‖²)² (paper Eq. 10). A thin sklearn-style class over the functional core; being non-parametric it has fit / fit_transform but no out-of-sample transform (matching sklearn's TSNE). Poincaré input (N, D) embeds to (N, K) ball coordinates; Hyperboloid input (N, A) embeds to (N, K+1); ProperVelocity, Klein and HalfSpace input (N, D) embeds to (N, K) points of the same model (mapped onto the ball by the direct isometry; input is projected onto its model first, except ProperVelocity, which needs no projection).

Calibrated learning rate

The exact-autodiff gradients differ in scale from the reference's hand-derived gradients, so the reference learning rates do not transfer. The learning_rate default (0.5) is calibrated on a synthetic-cluster recovery test — see the class docstring.

hyperbolix.decomposition.cosne.CoSNE

CoSNE(
    manifold: Manifold,
    n_components: int = 2,
    *,
    perplexity: float = 30.0,
    gamma: float = 0.1,
    learning_rate: float = 0.5,
    learning_rate_h: float = 0.01,
    early_exaggeration: float = 12.0,
    n_iter: int = 1000,
    exploration_n_iter: int = 500,
    exact_cauchy: bool = False,
)

CO-SNE — hyperbolic t-SNE with magnitude preservation (Guo et al. 2022).

A thin sklearn-style wrapper over the functional core. Fits a low-dimensional Poincaré ball embedding of hyperbolic data that preserves both pairwise similarities (t-SNE KL term) and each point's distance-to-origin (the CO magnitude term). Input/output follow the manifold: Poincaré input (N, D) embeds to (N, K) ball coordinates; Hyperboloid input (N, A) embeds to (N, K+1) hyperboloid points; ProperVelocity, Klein and HalfSpace input (N, D) embeds to (N, K) points of the same model (the ball coordinates mapped back through the isometry). Klein and HalfSpace input is projected (proj_batch) before it is mapped onto the ball.

Being non-parametric (like sklearn's TSNE), it has no out-of-sample transform — only fit / fit_transform. For a precomputed-distance workflow (e.g. HycoCLIP), call :func:fit_cosne directly with the distance matrix and squared ball norms.

.. note:: Every step forms dense O(N²) matrices, so this shares the compute_pairwise_ distances caveat: budget memory carefully beyond a few thousand points. Fitting is most reliable in dtype=jnp.float64.

Args: manifold: A Poincare, Hyperboloid, ProperVelocity, Klein or HalfSpace instance (sets the I/O model and dtype). n_components: Embedding dimension K (default 2). perplexity: Target perplexity — the effective neighbor count (default 30.0, sklearn). Must be < N. gamma: Low-dimensional kernel scale gamma (default 0.1, paper). learning_rate: KL-gradient step size (default 0.5). Calibrated, not inherited: the exact-autodiff gradients differ in scale from the reference's buggy hand gradients (the missing 1/gamma² factor alone is ~100x at gamma = 0.1), so the reference learning rates do not transfer. Swept over {0.1, 0.5, 1, 5, 10} on the synthetic-cluster recovery test: values ≥ 1 overshoot (the final KL rises with lr and cluster recovery degrades); lr = 0.1 minimizes the KL best but makes the magnitude loss redundant (KL alone already preserves norms, so the CO ablation gap collapses into noise, ~+0.003 Spearman); lr = 0.5 is the balance point — stable KL, strong norm preservation (Spearman ~0.83), and a robust magnitude-loss ablation gap (~+0.10 to +0.17 Spearman) that shows the CO term doing its job. learning_rate_h: Magnitude-gradient step size (default 0.01, paper λ₂). Applied in the convergence stage only. early_exaggeration: Joint-P exaggeration factor during exploration (default 12.0, sklearn). n_iter: Total number of iterations (default 1000). exploration_n_iter: Exploration-stage length (default 500, reference / paper's "first 500 iterations"); clipped to n_iter. exact_cauchy: Use the paper Eq. 9 squared-distance kernel (1 + d²/gamma²)⁻¹ instead of the default author's-code plain-distance kernel (1 + d/gamma²)⁻¹ (default False).

Attributes (set after :meth:fit, sklearn trailing-underscore convention): embedding_: Low-dimensional embedding in the input's model — (N, K+1) hyperboloid points for Hyperboloid input, (N, K) coordinates otherwise. kl_divergence_: Final KL divergence on the unexaggerated P (scalar). losses_kl_: Per-step KL trace, shape (S,). Stage-1 entries use the exaggerated P (a discontinuity at the stage boundary is expected). losses_h_: Per-step magnitude-loss trace, shape (S,) (recorded in both stages; applied only in stage 2). c_: Curvature used at fit time.

Source code in hyperbolix/decomposition/cosne.py
def __init__(
    self,
    manifold: Manifold,
    n_components: int = 2,
    *,
    perplexity: float = 30.0,
    gamma: float = 0.1,
    learning_rate: float = 0.5,
    learning_rate_h: float = 0.01,
    early_exaggeration: float = 12.0,
    n_iter: int = 1000,
    exploration_n_iter: int = 500,
    exact_cauchy: bool = False,
) -> None:
    self._input_model = input_model(manifold, "CoSNE")

    self.manifold = manifold
    self.n_components = n_components
    self.perplexity = perplexity
    self.gamma = gamma
    self.learning_rate = learning_rate
    self.learning_rate_h = learning_rate_h
    self.early_exaggeration = early_exaggeration
    self.n_iter = n_iter
    self.exploration_n_iter = exploration_n_iter
    self.exact_cauchy = exact_cauchy

    # All embedding-space work runs on the ball at the I/O dtype.
    self._poincare = Poincare(dtype=manifold.dtype)

    # Fitted state (populated by fit()).
    self.embedding_: Array | None = None
    self.kl_divergence_: Array | None = None
    self.losses_kl_: Array | None = None
    self.losses_h_: Array | None = None
    self.c_: ScalarCurvature | None = None

fit

fit(
    x_ND: Float[Array, "N R"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
) -> CoSNE

Fit the embedding on x_ND at curvature c.

Args: x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models. c: Curvature (positive) — bound into the fitted state. key: PRNG key for the embedding init.

Returns: self.

Source code in hyperbolix/decomposition/cosne.py
def fit(self, x_ND: Float[Array, "N R"], c: ScalarCurvature, key: PRNGKeyArray) -> "CoSNE":
    """Fit the embedding on ``x_ND`` at curvature ``c``.

    Args:
        x_ND: Input points, shape (N, A) for Hyperboloid, (N, D) for the other models.
        c: Curvature (positive) — bound into the fitted state.
        key: PRNG key for the embedding init.

    Returns:
        ``self``.
    """
    if x_ND.ndim != 2:
        raise ValueError(f"Expected a 2D array (n_points, dim), got shape {x_ND.shape}.")
    n_points = x_ND.shape[0]
    if self.n_components < 1:
        raise ValueError(f"n_components must be >= 1, got {self.n_components}.")
    if n_points <= 1:
        raise ValueError(f"Need more than one point to embed, got {n_points}.")
    if self.perplexity >= n_points:
        raise ValueError(f"perplexity must be < n_points ({n_points}), got {self.perplexity}.")

    c_in = c
    # The manifold's dtype decides: a float64 `c` would otherwise promote the cleaned input, the
    # isometry maps and the embedding to float64. The fitted `c_` keeps the caller's value.
    c = self._poincare._cast_c(c)
    x_ball_ND = self._to_ball(x_ND, c)
    dist_NN = compute_pairwise_distances(x_ball_ND, self._poincare, c, VERSION_MOBIUS_DIRECT)
    x_sqnorms_N = jnp.sum(x_ball_ND**2, axis=1)

    y_NK, kl_trace_S, h_trace_S, final_kl = _fit_jit(
        dist_NN,
        x_sqnorms_N,
        c,
        key,
        n_components=self.n_components,
        perplexity=self.perplexity,
        gamma=self.gamma,
        learning_rate=self.learning_rate,
        learning_rate_h=self.learning_rate_h,
        early_exaggeration=self.early_exaggeration,
        n_iter=self.n_iter,
        exploration_n_iter=self.exploration_n_iter,
        exact_cauchy=self.exact_cauchy,
    )

    embedding = map_batch(self._input_model.from_ball, y_NK, c)  # (N, K+1) hyperboloid, else (N, K)

    self.embedding_ = embedding
    self.kl_divergence_ = final_kl
    self.losses_kl_ = kl_trace_S
    self.losses_h_ = h_trace_S
    self.c_ = c_in
    return self

fit_transform

fit_transform(
    x_ND: Float[Array, "N R"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
) -> Float[Array, "N out"]

Fit on x_ND then return its embedding (equivalent to fit(...).embedding_).

Source code in hyperbolix/decomposition/cosne.py
def fit_transform(self, x_ND: Float[Array, "N R"], c: ScalarCurvature, key: PRNGKeyArray) -> Float[Array, "N out"]:
    """Fit on ``x_ND`` then return its embedding (equivalent to ``fit(...).embedding_``)."""
    # `fit` assigns `embedding_` unconditionally on its last line, so the Optional is
    # only there for the not-yet-fitted state, which cannot be observed here.
    return cast(Float[Array, "N out"], self.fit(x_ND, c, key).embedding_)

Usage Example

import jax
import jax.numpy as jnp
from hyperbolix.manifolds import Poincare
from hyperbolix.decomposition import CoSNE

jax.config.update("jax_enable_x64", True)

manifold = Poincare(dtype=jnp.float64)
key = jax.random.PRNGKey(0)

# x: (N, D) points on the Poincaré ball (single-point proj, batched via vmap)
x = jax.vmap(manifold.proj, in_axes=(0, None))(0.3 * jax.random.normal(key, (200, 10), dtype=jnp.float64), 1.0)

model = CoSNE(manifold, n_components=2)
z = model.fit_transform(x, c=1.0, key=jax.random.PRNGKey(1))  # (200, 2) ball coordinates
print(model.kl_divergence_)                                   # final KL on the unexaggerated P

Functional core

The pure functions underneath CoSNE — independently usable and JIT-friendly. For a precomputed-distance workflow (e.g. HycoCLIP), call fit_cosne directly with the input distance matrix and squared ball norms.

hyperbolix.decomposition.cosne

CO-SNE — dimensionality reduction and visualization for hyperbolic data.

Port of CO-SNE (Guo, Guo, Yu — CVPR 2022) to JAX. CO-SNE is the hyperbolic analogue of t-SNE: high-dimensional similarities are the perplexity-calibrated conditional/joint probabilities of a hyperbolic normal on squared geodesic distances (paper Eq. 2), and low-dimensional similarities are a heavy-tailed Student-t / Cauchy kernel on geodesic distances in a low-dimensional Poincaré ball (paper Eq. 9 / the author's code). On top of the t-SNE KL divergence, CO-SNE adds a magnitude loss H = (1/N)·Σᵢ(‖xᵢ‖² - ‖yᵢ‖²)² (paper Eq. 10) that preserves each point's distance-to-origin — the hierarchy depth that a plain KL objective would otherwise wash out.

Optimization is projected gradient descent on the ball with momentum 0: the KL gradient is Riemannian-scaled by (1 - c‖y‖²)²/4 (paper §3.7 / reference), the magnitude gradient stays Euclidean, and the run is split into two fixed-length stages — an early-exaggeration KL-only exploration stage, then a KL + magnitude stage.

This module provides a pure functional core (independently usable and JIT-friendly) plus a thin sklearn-style :class:CoSNE wrapper. All embedding-space work runs on the Poincaré ball; Hyperboloid, ProperVelocity, Klein and half-space input/output is mapped through the exact isometries.

Deliberate deviations from the reference implementation
  • Exact autodiff gradients of the declared losses (jax.grad), not the reference's hand-derived gradients. The reference gradients are demonstrably buggy (an unsquared alpha = 1 - ‖y‖ where paper Eq. 13 needs 1 - ‖y‖²; a missing 1/gamma² chain factor; a magnitude gradient dropping the loss's own 1/N). We keep the reference's structure (Riemannian scaling on the KL gradient only, Euclidean magnitude gradient, projected GD, momentum 0, two-stage schedule) but with correct gradients. Consequence: the reference learning rates do not transfer — the defaults here are calibrated (see :class:CoSNE).
  • Ball re-projection via :func:hyperbolix.manifolds._gyrovector_core._proj (norm clip). The reference subtracts 1e-5 per coordinate, which can land outside the ball when Σyᵢ < 0.
  • Fixed-length lax.scan stages — no early stopping, progress checks, or per-point gains (the reference sets momentum 0 and never uses gains; fixed lengths are JIT-friendly).
  • Curvature-general: a single c for both spaces, passed at fit time (the reference hardcodes c = 1). Same-c balls have equal radius 1/√c, so the magnitude loss compares like for like.
  • No out-of-sample transform — t-SNE is non-parametric (sklearn's TSNE has none).

Dimension key: N: number of points D: input spatial dim K: number of components (embedding dim) S: number of iterations (n_iter)

References: Guo, Guo, Yu. "CO-SNE: Dimensionality Reduction and Visualization for Hyperbolic Data." CVPR 2022. van der Maaten, Hinton. "Visualizing Data using t-SNE." JMLR 2008.

conditional_probabilities
conditional_probabilities(
    dist_NN: Float[Array, "N N"],
    perplexity: Float[Array, ""] | float,
    *,
    n_steps: int = 100,
) -> Float[Array, "N N"]

Row-stochastic conditional similarities p_{j|i} (paper Eq. 2, t-SNE style).

Takes the plain hyperbolic distance matrix and squares it internally (matching the reference's square_distances=True flow), then per-row calibrates a precision βᵢ = 1/(2sigmaᵢ²) so the entropy of row i equals ln(perplexity) nats (the sklearn _binary_search_perplexity algorithm). The bisection is vectorized over all rows and carried through a fixed n_steps-iteration lax.fori_loop (no early-exit tolerance; 100 bisections ≫ converged). Degenerate all-equal-distance rows converge to the uniform distribution — acceptable.

Args: dist_NN: Plain (not squared) pairwise geodesic distance matrix, shape (N, N). perplexity: Target perplexity (effective number of neighbors); must be < N. n_steps: Number of bisection iterations (static; default 100).

Returns: Row-stochastic conditional similarities P, shape (N, N); rows sum to 1, diagonal is 0.

Source code in hyperbolix/decomposition/cosne.py
def conditional_probabilities(
    dist_NN: Float[Array, "N N"],
    perplexity: Float[Array, ""] | float,
    *,
    n_steps: int = 100,
) -> Float[Array, "N N"]:
    """Row-stochastic conditional similarities ``p_{j|i}`` (paper Eq. 2, t-SNE style).

    Takes the **plain** hyperbolic distance matrix and squares it internally (matching the
    reference's ``square_distances=True`` flow), then per-row calibrates a precision
    ``βᵢ = 1/(2sigmaᵢ²)`` so the entropy of row ``i`` equals ``ln(perplexity)`` nats (the sklearn
    ``_binary_search_perplexity`` algorithm). The bisection is vectorized over all rows and
    carried through a fixed ``n_steps``-iteration ``lax.fori_loop`` (no early-exit tolerance;
    100 bisections ≫ converged). Degenerate all-equal-distance rows converge to the uniform
    distribution — acceptable.

    Args:
        dist_NN: Plain (not squared) pairwise geodesic distance matrix, shape (N, N).
        perplexity: Target perplexity (effective number of neighbors); must be < N.
        n_steps: Number of bisection iterations (static; default 100).

    Returns:
        Row-stochastic conditional similarities ``P``, shape (N, N); rows sum to 1, diagonal
        is 0.
    """
    dtype = dist_NN.dtype
    eps = _MACHINE_EPS
    n_points = dist_NN.shape[0]
    d2_NN = dist_NN**2  # Eq. 2 uses squared hyperbolic distances
    offdiag_NN = ~jnp.eye(n_points, dtype=bool)
    log_perp = jnp.log(jnp.asarray(perplexity, dtype=dtype))  # target entropy (nats)

    inf = jnp.asarray(jnp.inf, dtype=dtype)
    beta_N = jnp.ones((n_points,), dtype=dtype)
    beta_min_N = jnp.full((n_points,), -inf, dtype=dtype)
    beta_max_N = jnp.full((n_points,), inf, dtype=dtype)

    def _row_entropy(beta_N: Float[Array, "N"]) -> tuple[Float[Array, "N N"], Float[Array, "N"], Float[Array, "N"]]:
        # Unnormalized similarities exp(-d²·β), diagonal masked to 0.
        p_NN = jnp.where(offdiag_NN, jnp.exp(-d2_NN * beta_N[:, None]), 0.0)
        sum_p_N = floor_at(jnp.sum(p_NN, axis=1), eps)
        # H(Pᵢ) = ln(Σ pᵢ) + βᵢ·Σ(d²·pᵢ)/Σ pᵢ  (Shannon entropy of the normalized row, nats).
        entropy_N = jnp.log(sum_p_N) + beta_N * jnp.sum(d2_NN * p_NN, axis=1) / sum_p_N
        return p_NN, sum_p_N, entropy_N

    def _body(_step: int, carry: tuple[Array, Array, Array]) -> tuple[Array, Array, Array]:
        beta_N, beta_min_N, beta_max_N = carry
        _, _, entropy_N = _row_entropy(beta_N)
        # Entropy too high ⇒ row too diffuse ⇒ sharpen by increasing β.
        too_high_N = entropy_N > log_perp
        new_beta_min_N = jnp.where(too_high_N, beta_N, beta_min_N)
        new_beta_max_N = jnp.where(too_high_N, beta_max_N, beta_N)
        # Clamp the doubling: with coincident points the target entropy can be unreachable from
        # above, so β doubles every step — unclamped it overflows to inf and 0·inf = NaN on the
        # zero-distance entries (float32 reaches inf at ~128 doublings).
        beta_capped_N = cap_at(beta_N * 2.0, jnp.asarray(jnp.finfo(dtype).max / 4.0, dtype=dtype))
        beta_up_N = jnp.where(jnp.isinf(beta_max_N), beta_capped_N, (beta_N + beta_max_N) / 2.0)
        beta_down_N = jnp.where(jnp.isinf(beta_min_N), beta_N / 2.0, (beta_N + beta_min_N) / 2.0)
        new_beta_N = jnp.where(too_high_N, beta_up_N, beta_down_N)
        return new_beta_N, new_beta_min_N, new_beta_max_N

    beta_N, _, _ = jax.lax.fori_loop(0, n_steps, _body, (beta_N, beta_min_N, beta_max_N))
    p_NN, sum_p_N, _ = _row_entropy(beta_N)
    return p_NN / sum_p_N[:, None]
joint_probabilities
joint_probabilities(
    dist_NN: Float[Array, "N N"],
    perplexity: Float[Array, ""] | float,
) -> Float[Array, "N N"]

Symmetric joint similarities P (paper Eq. 2, symmetrized t-SNE affinities).

Symmetrizes the conditional similarities (P = cond + condᵀ), normalizes them to sum to 1, and floors the off-diagonal at machine epsilon (the diagonal is forced to 0) — matching sklearn's _joint_probabilities including the eps floor.

Args: dist_NN: Plain (not squared) pairwise geodesic distance matrix, shape (N, N). perplexity: Target perplexity; must be < N.

Returns: Symmetric joint similarity matrix P, shape (N, N); ΣP ≈ 1, off-diagonal ≥ eps, diagonal 0.

Source code in hyperbolix/decomposition/cosne.py
def joint_probabilities(
    dist_NN: Float[Array, "N N"],
    perplexity: Float[Array, ""] | float,
) -> Float[Array, "N N"]:
    """Symmetric joint similarities ``P`` (paper Eq. 2, symmetrized t-SNE affinities).

    Symmetrizes the conditional similarities (``P = cond + condᵀ``), normalizes them to sum to
    1, and floors the off-diagonal at machine epsilon (the diagonal is forced to 0) — matching
    sklearn's ``_joint_probabilities`` including the eps floor.

    Args:
        dist_NN: Plain (not squared) pairwise geodesic distance matrix, shape (N, N).
        perplexity: Target perplexity; must be < N.

    Returns:
        Symmetric joint similarity matrix ``P``, shape (N, N); ``ΣP ≈ 1``, off-diagonal
        ``≥ eps``, diagonal 0.
    """
    eps = _MACHINE_EPS
    n_points = dist_NN.shape[0]
    cond_NN = conditional_probabilities(dist_NN, perplexity)
    p_NN = cond_NN + cond_NN.T
    p_NN = p_NN / floor_at(jnp.sum(p_NN), eps)
    offdiag_NN = ~jnp.eye(n_points, dtype=bool)
    return jnp.where(offdiag_NN, floor_at(p_NN, eps), 0.0)
low_dim_probabilities
low_dim_probabilities(
    y_NK: Float[Array, "N K"],
    gamma: Float[Array, ""] | float,
    c: ScalarCurvature,
    *,
    exact_cauchy: bool = False,
) -> Float[Array, "N N"]

Heavy-tailed low-dimensional similarities Q on the Poincaré ball (paper Eq. 9).

Computes pairwise ball distances (direct Möbius formula), forms a Student-t / Cauchy kernel (1 + u/dof)^(-(dof+1)/2) with dof = max(K-1, 1), and normalizes to a joint distribution. Two kernel forms select the argument u:

  • exact_cauchy=False (default, the author's-code form that produced the published figures and is used by HycoCLIP): u = d/gamma² (plain geodesic distance).
  • exact_cauchy=True (paper Eq. 9 Cauchy): u = d²/gamma² (squared distance).

At K = 2 (dof = 1) the kernel reduces to (1 + u)⁻¹. The diagonal is zeroed before normalization; the result is eps-floored off-diagonal for a stable log q in the KL divergence.

Args: y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K). gamma: Kernel scale gamma (paper default 0.1). c: Curvature (positive). exact_cauchy: Use the paper Eq. 9 squared-distance kernel instead of the default plain-distance kernel.

Returns: Symmetric low-dimensional similarity matrix Q, shape (N, N); off-diagonal ≥ eps, diagonal 0.

Source code in hyperbolix/decomposition/cosne.py
def low_dim_probabilities(
    y_NK: Float[Array, "N K"],
    gamma: Float[Array, ""] | float,
    c: ScalarCurvature,
    *,
    exact_cauchy: bool = False,
) -> Float[Array, "N N"]:
    """Heavy-tailed low-dimensional similarities ``Q`` on the Poincaré ball (paper Eq. 9).

    Computes pairwise ball distances (direct Möbius formula), forms a Student-t / Cauchy
    kernel ``(1 + u/dof)^(-(dof+1)/2)`` with ``dof = max(K-1, 1)``, and normalizes to a joint
    distribution. Two kernel forms select the argument ``u``:

    - ``exact_cauchy=False`` (default, the author's-code form that produced the published
      figures and is used by HycoCLIP): ``u = d/gamma²`` (**plain** geodesic distance).
    - ``exact_cauchy=True`` (paper Eq. 9 Cauchy): ``u = d²/gamma²`` (**squared** distance).

    At ``K = 2`` (``dof = 1``) the kernel reduces to ``(1 + u)⁻¹``. The diagonal is zeroed
    before normalization; the result is eps-floored off-diagonal for a stable ``log q`` in the
    KL divergence.

    Args:
        y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K).
        gamma: Kernel scale gamma (paper default 0.1).
        c: Curvature (positive).
        exact_cauchy: Use the paper Eq. 9 squared-distance kernel instead of the default
            plain-distance kernel.

    Returns:
        Symmetric low-dimensional similarity matrix ``Q``, shape (N, N); off-diagonal
        ``≥ eps``, diagonal 0.
    """
    dtype = y_NK.dtype
    eps = _MACHINE_EPS
    n_points, n_components = y_NK.shape

    dist_fn = functools.partial(_dist, c=c, version_idx=VERSION_MOBIUS_DIRECT)
    d_NN = jax.vmap(jax.vmap(dist_fn, in_axes=(None, 0)), in_axes=(0, None))(y_NK, y_NK)

    gamma2 = jnp.asarray(gamma, dtype=dtype) ** 2
    u_NN = d_NN**2 / gamma2 if exact_cauchy else d_NN / gamma2
    dof = jnp.asarray(max(n_components - 1, 1), dtype=dtype)  # Student-t dof (static shape ⇒ concrete)
    kernel_NN = (1.0 + u_NN / dof) ** (-(dof + 1.0) / 2.0)

    offdiag_NN = ~jnp.eye(n_points, dtype=bool)
    kernel_NN = jnp.where(offdiag_NN, kernel_NN, 0.0)  # zero diagonal BEFORE normalizing
    sum_kernel = floor_at(jnp.sum(kernel_NN), eps)
    return jnp.where(offdiag_NN, floor_at(kernel_NN / sum_kernel, eps), 0.0)
kl_divergence_loss
kl_divergence_loss(
    y_NK: Float[Array, "N K"],
    p_NN: Float[Array, "N N"],
    gamma: Float[Array, ""] | float,
    c: ScalarCurvature,
    *,
    exact_cauchy: bool = False,
) -> Float[Array, ""]

t-SNE KL divergence Σ_{i≠j} p·ln(p/q) between high- and low-dim similarities.

q is recomputed from y_NK via :func:low_dim_probabilities. The diagonal is masked out; both p and q are replaced by 1.0 on the diagonal inside the log so the log argument is strictly positive everywhere (the masked terms then contribute a hard zero with a finite — not 0·∞ — gradient). Off-diagonal p and q are already eps-floored by :func:joint_probabilities / :func:low_dim_probabilities.

During early exaggeration this is called with p = P·early_exaggeration (scaling the unnormalized joint P is the standard t-SNE exaggeration trick).

Args: y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K). p_NN: High-dimensional (possibly exaggerated) joint similarities, shape (N, N). gamma: Kernel scale gamma. c: Curvature (positive). exact_cauchy: Kernel-form flag forwarded to :func:low_dim_probabilities.

Returns: Scalar KL divergence.

Source code in hyperbolix/decomposition/cosne.py
def kl_divergence_loss(
    y_NK: Float[Array, "N K"],
    p_NN: Float[Array, "N N"],
    gamma: Float[Array, ""] | float,
    c: ScalarCurvature,
    *,
    exact_cauchy: bool = False,
) -> Float[Array, ""]:
    """t-SNE KL divergence ``Σ_{i≠j} p·ln(p/q)`` between high- and low-dim similarities.

    ``q`` is recomputed from ``y_NK`` via :func:`low_dim_probabilities`. The diagonal is
    masked out; both ``p`` and ``q`` are replaced by 1.0 on the diagonal *inside* the ``log``
    so the log argument is strictly positive everywhere (the masked terms then contribute a
    hard zero with a finite — not ``0·∞`` — gradient). Off-diagonal ``p`` and ``q`` are already
    eps-floored by :func:`joint_probabilities` / :func:`low_dim_probabilities`.

    During early exaggeration this is called with ``p = P·early_exaggeration`` (scaling the
    unnormalized joint P is the standard t-SNE exaggeration trick).

    Args:
        y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K).
        p_NN: High-dimensional (possibly exaggerated) joint similarities, shape (N, N).
        gamma: Kernel scale gamma.
        c: Curvature (positive).
        exact_cauchy: Kernel-form flag forwarded to :func:`low_dim_probabilities`.

    Returns:
        Scalar KL divergence.
    """
    n_points = y_NK.shape[0]
    q_NN = low_dim_probabilities(y_NK, gamma, c, exact_cauchy=exact_cauchy)
    offdiag_NN = ~jnp.eye(n_points, dtype=bool)
    p_safe_NN = jnp.where(offdiag_NN, p_NN, 1.0)  # 1.0 on the diagonal ⇒ log finite, gradient safe
    q_safe_NN = jnp.where(offdiag_NN, q_NN, 1.0)
    log_ratio_NN = jnp.log(p_safe_NN) - jnp.log(q_safe_NN)
    kl_NN = jnp.where(offdiag_NN, p_NN * log_ratio_NN, 0.0)
    return jnp.sum(kl_NN)
magnitude_loss
magnitude_loss(
    y_NK: Float[Array, "N K"], x_sqnorms_N: Float[Array, N]
) -> Float[Array, ""]

Magnitude (distance-to-origin) preservation loss (1/N)·Σᵢ(‖xᵢ‖² - ‖yᵢ‖²)² (Eq. 10).

The CO(-ordinate) term of CO-SNE: it pins each embedded point's squared Euclidean ball norm to the input point's squared ball norm, preserving the hierarchy depth that the KL term alone would discard. Includes the 1/N the reference gradient drops.

Args: y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K). x_sqnorms_N: Squared Euclidean ball norms ‖xᵢ‖² of the input points, shape (N,).

Returns: Scalar magnitude loss.

Source code in hyperbolix/decomposition/cosne.py
def magnitude_loss(
    y_NK: Float[Array, "N K"],
    x_sqnorms_N: Float[Array, "N"],
) -> Float[Array, ""]:
    """Magnitude (distance-to-origin) preservation loss ``(1/N)·Σᵢ(‖xᵢ‖² - ‖yᵢ‖²)²`` (Eq. 10).

    The CO(-ordinate) term of CO-SNE: it pins each embedded point's squared Euclidean ball
    norm to the input point's squared ball norm, preserving the hierarchy depth that the KL
    term alone would discard. Includes the ``1/N`` the reference gradient drops.

    Args:
        y_NK: Low-dimensional Poincaré ball coordinates, shape (N, K).
        x_sqnorms_N: Squared Euclidean ball norms ``‖xᵢ‖²`` of the input points, shape (N,).

    Returns:
        Scalar magnitude loss.
    """
    y_sqnorms_N = jnp.sum(y_NK**2, axis=1)
    return jnp.mean((x_sqnorms_N - y_sqnorms_N) ** 2)
fit_cosne
fit_cosne(
    dist_NN: Float[Array, "N N"],
    x_sqnorms_N: Float[Array, N],
    c: ScalarCurvature,
    key: PRNGKeyArray,
    *,
    n_components: int,
    perplexity: Float[Array, ""] | float,
    gamma: Float[Array, ""] | float,
    learning_rate: Float[Array, ""] | float,
    learning_rate_h: Float[Array, ""] | float,
    early_exaggeration: Float[Array, ""] | float,
    n_iter: int,
    exploration_n_iter: int,
    exact_cauchy: bool = False,
) -> tuple[
    Float[Array, "N K"],
    Float[Array, S],
    Float[Array, S],
    Float[Array, ""],
]

Fit a CO-SNE embedding from the two sufficient statistics of the input data.

Takes the input distance matrix and squared ball norms (the two statistics CO-SNE needs — the HycoCLIP flow) and runs two-stage projected gradient descent on the Poincaré ball:

  1. Exploration (length min(exploration_n_iter, n_iter)): early-exaggerated joint P (p = P·early_exaggeration), KL gradient only (magnitude learning rate 0).
  2. Convergence (remaining iterations): unexaggerated P, KL + magnitude gradients.

Each step (both stages) applies a single Euclidean update then re-projects onto the ball: the KL gradient is Riemannian-scaled by (1 - c‖y‖²)²/4 (via _egrad2rgrad), the magnitude gradient stays Euclidean (paper §3.7 / reference structure — deliberate).

Note: Stage-1 KL-trace entries are measured against the exaggerated P, so a visible discontinuity at the stage boundary is expected. final_kl re-evaluates the KL on the unexaggerated P (one extra eval inside JIT) for a clean final value even when n_iter ≤ exploration_n_iter.

Args: dist_NN: Input-space pairwise geodesic distance matrix (Poincaré ball), shape (N, N). x_sqnorms_N: Squared Euclidean ball norms of the input points, shape (N,). c: Curvature (positive), shared by input and embedding spaces. key: PRNG key for the 0.01·N(0, I) embedding init. n_components: Embedding dimension K (static). perplexity: Target perplexity for the high-dimensional similarities. gamma: Low-dimensional kernel scale gamma. learning_rate: KL-gradient step size. learning_rate_h: Magnitude-gradient step size (applied in stage 2 only). early_exaggeration: Exaggeration factor for the joint P during stage 1. n_iter: Total number of iterations S (static; the scan length). exploration_n_iter: Exploration-stage length (static; clipped to n_iter). exact_cauchy: Kernel-form flag forwarded to the low-dimensional similarities.

Returns: Tuple (y_NK, kl_trace_S, h_trace_S, final_kl): the embedding (N, K), the per-step KL and magnitude traces (each length S), and the final KL on the unexaggerated P.

Source code in hyperbolix/decomposition/cosne.py
def fit_cosne(
    dist_NN: Float[Array, "N N"],
    x_sqnorms_N: Float[Array, "N"],
    c: ScalarCurvature,
    key: PRNGKeyArray,
    *,
    n_components: int,
    perplexity: Float[Array, ""] | float,
    gamma: Float[Array, ""] | float,
    learning_rate: Float[Array, ""] | float,
    learning_rate_h: Float[Array, ""] | float,
    early_exaggeration: Float[Array, ""] | float,
    n_iter: int,
    exploration_n_iter: int,
    exact_cauchy: bool = False,
) -> tuple[Float[Array, "N K"], Float[Array, "S"], Float[Array, "S"], Float[Array, ""]]:
    """Fit a CO-SNE embedding from the two sufficient statistics of the input data.

    Takes the input distance matrix and squared ball norms (the two statistics CO-SNE needs —
    the HycoCLIP flow) and runs two-stage projected gradient descent on the Poincaré ball:

    1. **Exploration** (length ``min(exploration_n_iter, n_iter)``): early-exaggerated joint P
       (``p = P·early_exaggeration``), KL gradient only (magnitude learning rate 0).
    2. **Convergence** (remaining iterations): unexaggerated P, KL + magnitude gradients.

    Each step (both stages) applies a single Euclidean update then re-projects onto the ball:
    the KL gradient is Riemannian-scaled by ``(1 - c‖y‖²)²/4`` (via ``_egrad2rgrad``), the
    magnitude gradient stays Euclidean (paper §3.7 / reference structure — deliberate).

    Note:
        Stage-1 KL-trace entries are measured against the *exaggerated* P, so a visible
        discontinuity at the stage boundary is expected. ``final_kl`` re-evaluates the KL on
        the unexaggerated P (one extra eval inside JIT) for a clean final value even when
        ``n_iter ≤ exploration_n_iter``.

    Args:
        dist_NN: Input-space pairwise geodesic distance matrix (Poincaré ball), shape (N, N).
        x_sqnorms_N: Squared Euclidean ball norms of the input points, shape (N,).
        c: Curvature (positive), shared by input and embedding spaces.
        key: PRNG key for the ``0.01·N(0, I)`` embedding init.
        n_components: Embedding dimension K (static).
        perplexity: Target perplexity for the high-dimensional similarities.
        gamma: Low-dimensional kernel scale gamma.
        learning_rate: KL-gradient step size.
        learning_rate_h: Magnitude-gradient step size (applied in stage 2 only).
        early_exaggeration: Exaggeration factor for the joint P during stage 1.
        n_iter: Total number of iterations S (static; the scan length).
        exploration_n_iter: Exploration-stage length (static; clipped to ``n_iter``).
        exact_cauchy: Kernel-form flag forwarded to the low-dimensional similarities.

    Returns:
        Tuple ``(y_NK, kl_trace_S, h_trace_S, final_kl)``: the embedding (N, K), the per-step
        KL and magnitude traces (each length S), and the final KL on the unexaggerated P.
    """
    dtype = dist_NN.dtype
    n_points = dist_NN.shape[0]

    p_NN = joint_probabilities(dist_NN, perplexity)

    # Reference init: 0.01·randn projected onto the ball.
    y0_NK = 0.01 * jax.random.normal(key, (n_points, n_components), dtype=dtype)
    y0_NK = jax.vmap(_proj, in_axes=(0, None))(y0_NK, c)

    kl_loss_fn = functools.partial(kl_divergence_loss, exact_cauchy=exact_cauchy)

    def _make_step(p_eff_NN: Float[Array, "N N"], lr_h_eff: Float[Array, ""]):
        def step_fn(y_NK: Float[Array, "N K"], _: None) -> tuple[Array, tuple[Array, Array]]:
            kl, grad_kl_NK = jax.value_and_grad(kl_loss_fn)(y_NK, p_eff_NN, gamma, c)
            rgrad_kl_NK = jax.vmap(_egrad2rgrad, in_axes=(0, 0, None))(grad_kl_NK, y_NK, c)  # KL grad only
            h, grad_h_NK = jax.value_and_grad(magnitude_loss)(y_NK, x_sqnorms_N)  # Euclidean magnitude grad
            y_new_NK = y_NK - learning_rate * rgrad_kl_NK - lr_h_eff * grad_h_NK
            y_new_NK = jax.vmap(_proj, in_axes=(0, None))(y_new_NK, c)
            return y_new_NK, (kl, h)

        return step_fn

    explore = min(exploration_n_iter, n_iter)  # static

    # Stage 1: exaggerated P, magnitude off (lr_h = 0).
    step1_fn = _make_step(p_NN * early_exaggeration, jnp.asarray(0.0, dtype=dtype))
    y_NK, (kl1_S, h1_S) = jax.lax.scan(step1_fn, y0_NK, None, length=explore)

    # Stage 2: unexaggerated P, magnitude on.
    step2_fn = _make_step(p_NN, jnp.asarray(learning_rate_h, dtype=dtype))
    y_NK, (kl2_S, h2_S) = jax.lax.scan(step2_fn, y_NK, None, length=n_iter - explore)

    kl_trace_S = jnp.concatenate([kl1_S, kl2_S])
    h_trace_S = jnp.concatenate([h1_S, h2_S])
    final_kl = kl_loss_fn(y_NK, p_NN, gamma, c)  # unexaggerated P
    return y_NK, kl_trace_S, h_trace_S, final_kl

Fréchet mean

The Karcher fixed-point Fréchet (Riemannian center of mass) mean, used to center data before fitting. Manifold-generic — works for Hyperboloid, Poincare, ProperVelocity, Klein, HalfSpace, Euclidean and ProductManifold (pass the per-factor curvature sequence as c). The step is divided by the mean of a·coth(a) over the points (a = √c·d to the current estimate; for a product, c is the largest non-negative factor curvature), so it converges on widely spread batches where the plain Karcher step overshoots; step_size multiplies that step.

hyperbolix.decomposition.frechet.frechet_mean

frechet_mean(
    x_NR: Float[Array, "N R"],
    manifold: Manifold,
    c: ScalarCurvature,
    *,
    step_size: float = 1.0,
    tol: float = 1e-08,
    max_iters: int = 100,
    init_D: Float[Array, R] | None = None,
) -> Float[Array, R]

Compute the weighted-uniform Fréchet mean of x_NR via Karcher iteration.

Minimizes Σ_i d(μ, x_i)² over the manifold. Each iteration averages the log-map tangents at the current estimate and steps along the exponential map::

a_i = √c · ‖logmap(x_i, μ)‖_μ                 # scaled distance to each point
η   = step_size / mean_i(a_i · coth(a_i))     # curvature-aware step (a·coth(a) = 1 at a = 0)
v   = η · mean_i logmap(x_i, μ)               # tangent at μ
μ   ← proj(expmap(v, μ))
δ   = ‖v‖_μ                                   # Riemannian tangent norm

stopping when δ ≤ tol or max_iters is reached. The Hessian of ½d(·, x_i)² has eigenvalues between 1 (radial) and a_i·coth(a_i), so the fixed Karcher step η = 1 overshoots once the batch spreads past √c·d ≈ 2 (measured: no convergence in 100 iterations); dividing by the mean a_i·coth(a_i) avoids that and reduces to η = step_size for a tight batch (or c = 0). For a ProductManifold, c in a_i is c_max, the largest non-negative factor curvature. ½d² is a sum over factors, so its Hessian is block-diagonal with blocks bounded by a_f·coth(a_f), a_f = √c_f·d_f; since √c_f·d_f ≤ √c_max·d and x·coth(x) is increasing, a = √c_max·d bounds every block (conservative: Euclidean factors have eigenvalue 1, spherical ones ≤ 1). The loop is not differentiated (while_loop is not reverse-mode differentiable) — used purely as a numerical solver.

The initial estimate is dispatched by manifold type: Hyperboloid uses the closed-form Lorentz centroid (:func:lorentz_midpoint with uniform weights); Poincaré uses the projected Euclidean mean; every other manifold uses the first point. Pass init_D to override (a point in the manifold's representation space).

Not JIT-decorated here (the manifold argument is unhashable). To compile, wrap a closure::

fmean = jax.jit(functools.partial(frechet_mean, manifold=H, c=1.0))

Args: x_NR: Points on the manifold, shape (N, R). R is the ambient dim (d+1) for Hyperboloid, the spatial dim (d) for the other models. manifold: Manifold instance (satisfies the Manifold protocol). c: Curvature: a positive scalar for single manifolds, or the per-factor sequence for a ProductManifold (the step then uses the largest non-negative factor curvature). step_size: Multiplier on the curvature-aware step η (default 1.0). tol: Convergence tolerance on the Riemannian tangent-update norm (default 1e-8). max_iters: Maximum iterations (default 100). init_D: Optional explicit initial estimate, shape (R,), in representation space.

Returns: Fréchet mean, shape (R,), on the manifold.

Notes: In float32 the update norm stalls around ≈1e-6 (the boundary of f32 resolution), so a tol below that just runs the loop to max_iters — harmless, the estimate is already converged to f32 precision.

Source code in hyperbolix/decomposition/frechet.py
def frechet_mean(
    x_NR: Float[Array, "N R"],
    manifold: Manifold,
    c: ScalarCurvature,
    *,
    step_size: float = 1.0,
    tol: float = 1e-8,
    max_iters: int = 100,
    init_D: Float[Array, "R"] | None = None,
) -> Float[Array, "R"]:
    """Compute the weighted-uniform Fréchet mean of ``x_NR`` via Karcher iteration.

    Minimizes ``Σ_i d(μ, x_i)²`` over the manifold. Each iteration averages the log-map
    tangents at the current estimate and steps along the exponential map::

        a_i = √c · ‖logmap(x_i, μ)‖_μ                 # scaled distance to each point
        η   = step_size / mean_i(a_i · coth(a_i))     # curvature-aware step (a·coth(a) = 1 at a = 0)
        v   = η · mean_i logmap(x_i, μ)               # tangent at μ
        μ   ← proj(expmap(v, μ))
        δ   = ‖v‖_μ                                   # Riemannian tangent norm

    stopping when ``δ ≤ tol`` or ``max_iters`` is reached. The Hessian of ``½d(·, x_i)²`` has
    eigenvalues between 1 (radial) and ``a_i·coth(a_i)``, so the fixed Karcher step ``η = 1``
    overshoots once the batch spreads past ``√c·d ≈ 2`` (measured: no convergence in 100
    iterations); dividing by the mean ``a_i·coth(a_i)`` avoids that and reduces to
    ``η = step_size`` for a tight batch (or ``c = 0``).
    For a ProductManifold, ``c`` in ``a_i`` is ``c_max``, the largest non-negative factor curvature. ½d²
    is a sum over factors, so its Hessian is block-diagonal with blocks bounded by ``a_f·coth(a_f)``,
    ``a_f = √c_f·d_f``; since ``√c_f·d_f ≤ √c_max·d`` and ``x·coth(x)`` is increasing, ``a = √c_max·d``
    bounds every block (conservative: Euclidean factors have eigenvalue 1, spherical ones ≤ 1).
    The loop is not differentiated (``while_loop`` is not reverse-mode differentiable) — used
    purely as a numerical solver.

    The initial estimate is dispatched by manifold type: Hyperboloid uses the closed-form
    Lorentz centroid (:func:`lorentz_midpoint` with uniform weights); Poincaré uses the
    projected Euclidean mean; every other manifold uses the first point. Pass ``init_D`` to
    override (a point in the manifold's representation space).

    Not JIT-decorated here (the ``manifold`` argument is unhashable). To compile, wrap a
    closure::

        fmean = jax.jit(functools.partial(frechet_mean, manifold=H, c=1.0))

    Args:
        x_NR: Points on the manifold, shape (N, R). ``R`` is the ambient dim (d+1) for
            Hyperboloid, the spatial dim (d) for the other models.
        manifold: Manifold instance (satisfies the ``Manifold`` protocol).
        c: Curvature: a positive scalar for single manifolds, or the per-factor sequence for a
            ``ProductManifold`` (the step then uses the largest non-negative factor curvature).
        step_size: Multiplier on the curvature-aware step ``η`` (default 1.0).
        tol: Convergence tolerance on the Riemannian tangent-update norm (default 1e-8).
        max_iters: Maximum iterations (default 100).
        init_D: Optional explicit initial estimate, shape (R,), in representation space.

    Returns:
        Fréchet mean, shape (R,), on the manifold.

    Notes:
        In float32 the update norm stalls around ``≈1e-6`` (the boundary of f32
        resolution), so a ``tol`` below that just runs the loop to ``max_iters`` — harmless,
        the estimate is already converged to f32 precision.
    """
    x_NR = manifold._cast(x_NR)
    dtype = manifold.dtype
    num_points = x_NR.shape[0]

    # -- Initial estimate (Python-level dispatch on manifold type) -----------------------
    if init_D is not None:
        mean_R = jnp.asarray(init_D, dtype=dtype)
    elif isinstance(manifold, Hyperboloid):
        # Closed-form Lorentz centroid with uniform weights (M = N points → 1 midpoint).
        weights_1N = jnp.full((1, num_points), 1.0 / num_points, dtype=dtype)
        mean_R = lorentz_midpoint(x_NR, weights_1N, c)[0]
    elif isinstance(manifold, Poincare):
        # Projected Euclidean mean (the ball is convex, so the mean stays inside it).
        mean_R = manifold.proj(jnp.mean(x_NR, axis=0), c)
    else:
        # Euclidean / ProperVelocity / Klein / HalfSpace and any other manifold: first point is a valid start.
        mean_R = x_NR[0]

    # -- Karcher fixed-point iteration (lax.while_loop) ---------------------------------
    logmap_batched = jax.vmap(manifold.logmap, in_axes=(0, None, None))  # log_μ(x_i) for all i
    norm_batched = jax.vmap(manifold.tangent_norm, in_axes=(0, None, None))  # d(x_i, μ) for all i
    # Largest non-negative curvature: a scalar for a scalar c and for a ProductManifold's per-factor sequence.
    c_max = jnp.max(jnp.maximum(jnp.asarray(c, dtype=dtype), 0.0))
    sqrt_c = jnp.sqrt(c_max)

    def cond_fn(carry: tuple[Array, Array, Array]) -> Array:
        _, delta, it = carry
        return (delta > tol) & (it < max_iters)

    def body_fn(carry: tuple[Array, Array, Array]) -> tuple[Array, Array, Array]:
        mean, _, it = carry
        logs_NR = logmap_batched(x_NR, mean, c)  # (N, R) tangents at mean
        a_N = sqrt_c * norm_batched(logs_NR, mean, c)  # (N,) scaled distances √c_max·d(x_i, μ)
        # a·coth(a), with its series 1 + a²/3 below the seam (exactly 1 at a = 0, no 0/0).
        small_N = a_N < _ACOTH_SERIES_SEAM
        a_safe_N = jnp.where(small_N, 1.0, a_N)
        acoth_N = jnp.where(small_N, 1.0 + a_N**2 / 3.0, a_safe_N / tanh(a_safe_N))
        eta = step_size / jnp.mean(acoth_N)  # ≤ step_size: a·coth(a) ≥ 1
        v_R = eta * jnp.mean(logs_NR, axis=0)  # (R,) averaged tangent
        new_mean = manifold.proj(manifold.expmap(v_R, mean, c), c)
        new_delta = manifold.tangent_norm(v_R, mean, c)
        return new_mean, new_delta, it + 1

    delta0 = jnp.asarray(jnp.inf, dtype=dtype)  # force at least one iteration
    it0 = jnp.asarray(0, dtype=jnp.int32)
    mean_R, _, _ = lax.while_loop(cond_fn, body_fn, (mean_R, delta0, it0))
    return mean_R

Usage Example

import functools
import jax
import jax.numpy as jnp
from hyperbolix.manifolds import Hyperboloid
from hyperbolix.decomposition import frechet_mean

jax.config.update("jax_enable_x64", True)

manifold = Hyperboloid(dtype=jnp.float64)
x = manifold.proj_batch(jax.random.normal(jax.random.PRNGKey(0), (64, 6), dtype=jnp.float64), c=1.0)

mean = frechet_mean(x, manifold, c=1.0)

# To JIT, close over the (unhashable) manifold argument:
fmean = jax.jit(functools.partial(frechet_mean, manifold=manifold, c=1.0))
mean_jit = fmean(x)

References

  • Chami, Gu, Nguyen, Ré. "HoroPCA: Hyperbolic Dimensionality Reduction via Horospherical Projections." ICML 2021.
  • Guo, Guo, Yu. "CO-SNE: Dimensionality Reduction and Visualization for Hyperbolic Data." CVPR 2022.
  • van der Maaten, Hinton. "Visualizing Data using t-SNE." JMLR 2008.
  • Karcher, H. "Riemannian center of mass and mollifier smoothing." Comm. Pure Appl. Math. 1977.

See also:

  • Manifolds API: the underlying geometry (Hyperboloid.gyro_difference for centering, Hyperboloid.busemann).
  • Utilities API: compute_pairwise_distances and delta-hyperbolicity metrics.