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
fit ¶
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
transform ¶
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
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
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-projectxontospan(p_k)using the closed-form inverse of the null-lift GramI - 𝟙𝟙ᵀ(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 lengthd(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_kthenc_k = by_k + Σ_j by_j/(1 - K)cancel anO(x₀)term against anO(x₀)term to leave anO(1)result. Combined analytically they arec_k = x₀/(K - 1) + r·(g_k - Σ_j g_j/(K - 1)), which at the origin is exactly1/(√c·(K - 1)). -
Spine normalizer.
n = x - mpis Minkowski-orthogonal tospan(p_k), son₀ = ⟨q_k, n_s⟩for every k and the component ofn_soutside the span is the component ofx_soutside 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
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
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
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
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
lift_ideals ¶
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
orthonormalize_rows ¶
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
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
fit ¶
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
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
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 unsquaredalpha = 1 - ‖y‖where paper Eq. 13 needs1 - ‖y‖²; a missing1/gamma²chain factor; a magnitude gradient dropping the loss's own1/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 subtracts1e-5per coordinate, which can land outside the ball whenΣyᵢ < 0. - Fixed-length
lax.scanstages — 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
cfor both spaces, passed at fit time (the reference hardcodesc = 1). Same-cballs have equal radius1/√c, so the magnitude loss compares like for like. - No out-of-sample
transform— t-SNE is non-parametric (sklearn'sTSNEhas 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
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
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
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
magnitude_loss ¶
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
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:
- Exploration (length
min(exploration_n_iter, n_iter)): early-exaggerated joint P (p = P·early_exaggeration), KL gradient only (magnitude learning rate 0). - 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
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
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
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
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_differencefor centering,Hyperboloid.busemann). - Utilities API:
compute_pairwise_distancesand delta-hyperbolicity metrics.