Skip to content

Distributions API

Probability distributions on hyperbolic manifolds.

Overview

Hyperbolix provides wrapped normal distributions (Poincaré ball, hyperboloid) and a Riemannian-uniform distribution on a Poincaré geodesic ball, as plain functions. Uses include:

  • Variational Autoencoders (VAEs) with hyperbolic latent spaces
  • Bayesian neural networks on manifolds
  • Uncertainty quantification in hyperbolic embeddings

Riemannian Uniform Distribution

Poincaré Uniform

hyperbolix.distributions.uniform_poincare

Riemannian-uniform distribution on a geodesic ball in the Poincaré model.

Samples points uniformly (w.r.t. the Riemannian volume element) within a geodesic ball B(center, R) of finite radius R. Uses geodesic polar coordinates: sample a direction on S^{n-1}, sample a radius from the hyperbolic radial density, form a tangent vector, and map to the ball.

The radial density is p(r) ∝ sinh^{n-1}(√c·r) on [0, R]. A substitution u = cosh(√c·r) - 1 = 2·sinh²(√c·r/2) (evaluated in the half-angle form, and inverted as r = 2·asinh(√(u/2))/√c, so small radii do not round away) simplifies sampling: - n = 2: u is uniform on [0, cosh(√c·R) - 1] (closed-form) - n ≥ 3: rejection sampling with acceptance ∝ (u·(u+2))^{(n-2)/2}. Where the loop cannot accept a draw (u_max is not a normal float, or u_max·(u_max+2) overflows), the radius is drawn in closed form instead, from V ~ U(0, 1]: the flat limit r = R·V^{1/n}, or the exponential tail.

Dimension key: S: sample dimensions (from sample_shape) D: spatial/manifold dimension (n) Q: quadrature points (64 for GL) T: total flattened points (rejection sampling, and log_prob's flattened leading axes)

volume
volume(
    c: float, n: int, R: float, dtype=None
) -> Float[Array, ""]

Riemannian volume of a geodesic ball B^n_c(R) in n-dim hyperbolic space.

Vol = ω_{n-1} / c^{(n-1)/2} · ∫₀ᴿ sinh^{n-1}(√c·r) dr

where ω_{n-1} is the surface area of the unit (n-1)-sphere.

Computed via 64-point Gauss-Legendre quadrature.

Args: c: Positive curvature parameter. n: Ambient dimension of the Poincaré ball. R: Geodesic radius of the ball. dtype: Working/output dtype. Default: JAX's default float dtype.

Returns: Scalar volume, of dtype dtype.

Source code in hyperbolix/distributions/uniform_poincare.py
def volume(c: float, n: int, R: float, dtype=None) -> Float[Array, ""]:
    """Riemannian volume of a geodesic ball B^n_c(R) in n-dim hyperbolic space.

    Vol = ω_{n-1} / c^{(n-1)/2} · ∫₀ᴿ sinh^{n-1}(√c·r) dr

    where ω_{n-1} is the surface area of the unit (n-1)-sphere.

    Computed via 64-point Gauss-Legendre quadrature.

    Args:
        c: Positive curvature parameter.
        n: Ambient dimension of the Poincaré ball.
        R: Geodesic radius of the ball.
        dtype: Working/output dtype. Default: JAX's default float dtype.

    Returns:
        Scalar volume, of dtype ``dtype``.
    """
    working_dtype = jnp.dtype(dtype) if dtype is not None else _default_float_dtype()

    # ω_{n-1} = 2 π^{n/2} / Γ(n/2)
    half_n = jnp.asarray(n / 2.0, dtype=working_dtype)
    omega = 2.0 * jnp.asarray(jnp.pi, dtype=working_dtype) ** half_n / jnp.exp(jax.lax.lgamma(half_n))

    sqrt_c = jnp.sqrt(jnp.asarray(c, dtype=working_dtype))
    R_arr = jnp.asarray(R, dtype=working_dtype)

    # Map GL nodes from [-1, 1] to [0, R]: r = R/2 · (t + 1)
    nodes_Q = jnp.asarray(_GL_NODES, dtype=working_dtype)
    weights_Q = jnp.asarray(_GL_WEIGHTS, dtype=working_dtype)
    r_nodes_Q = (R_arr / 2.0) * (nodes_Q + 1.0)
    # safe_sinh: expm1-form accuracy fix over XLA's CPU jnp.sinh (up to ~17-496 ulps off for
    # |x| >= 16), plus its overflow clip for free.
    integrand_Q = safe_sinh(sqrt_c * r_nodes_Q) ** (n - 1)
    integral = (R_arr / 2.0) * jnp.sum(weights_Q * integrand_Q)

    vol = omega / sqrt_c ** (n - 1) * integral
    return vol
sample
sample(
    key: PRNGKeyArray,
    n: int,
    c: float,
    R: float,
    sample_shape: tuple[int, ...] = (),
    center: Float[Array, n] | None = None,
    dtype=None,
    manifold_module: Manifold | None = None,
) -> Float[Array, "... n"]

Sample uniformly from a geodesic ball in the Poincaré model.

Draws points that are Riemannian-uniform within B(center, R).

Algorithm: 1. Sample direction u ~ Uniform(S^{n-1}) 2. Sample geodesic radius r ~ p(r) ∝ sinh^{n-1}(√c·r) on [0, R] 3. Form tangent vector t = (r/2)·u (the /2 accounts for λ(0)=2) 4. Map to ball: x₀ = expmap_0(t, c) 5. Move to center: x = center ⊕ x₀ (Möbius addition)

Args: key: JAX PRNG key. n: Dimension of the Poincaré ball. c: Positive curvature parameter. R: Geodesic radius of the ball. sample_shape: Batch shape of samples. Default: () → single sample. center: Center of the geodesic ball, shape (n,). Default: origin. dtype: Output dtype. Default: inferred, in order of preference, from center, then manifold_module, then JAX's default float dtype. manifold_module: Optional Manifold instance. Default: Poincare(dtype).

Returns: Samples on the Poincaré ball, shape sample_shape + (n,).

Examples: >>> import jax >>> import jax.numpy as jnp >>> from hyperbolix.distributions import uniform_poincare >>> >>> key = jax.random.PRNGKey(0) >>> x = uniform_poincare.sample(key, n=2, c=1.0, R=1.0, sample_shape=(100,)) >>> x.shape (100, 2)

Source code in hyperbolix/distributions/uniform_poincare.py
def sample(
    key: PRNGKeyArray,
    n: int,
    c: float,
    R: float,
    sample_shape: tuple[int, ...] = (),
    center: Float[Array, "n"] | None = None,
    dtype=None,
    manifold_module: Manifold | None = None,
) -> Float[Array, "... n"]:
    """Sample uniformly from a geodesic ball in the Poincaré model.

    Draws points that are Riemannian-uniform within B(center, R).

    Algorithm:
        1. Sample direction u ~ Uniform(S^{n-1})
        2. Sample geodesic radius r ~ p(r) ∝ sinh^{n-1}(√c·r) on [0, R]
        3. Form tangent vector t = (r/2)·u  (the /2 accounts for λ(0)=2)
        4. Map to ball: x₀ = expmap_0(t, c)
        5. Move to center: x = center ⊕ x₀  (Möbius addition)

    Args:
        key: JAX PRNG key.
        n: Dimension of the Poincaré ball.
        c: Positive curvature parameter.
        R: Geodesic radius of the ball.
        sample_shape: Batch shape of samples. Default: () → single sample.
        center: Center of the geodesic ball, shape (n,). Default: origin.
        dtype: Output dtype. Default: inferred, in order of preference, from ``center``,
            then ``manifold_module``, then JAX's default float dtype.
        manifold_module: Optional Manifold instance. Default: Poincare(dtype).

    Returns:
        Samples on the Poincaré ball, shape ``sample_shape + (n,)``.

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> from hyperbolix.distributions import uniform_poincare
        >>>
        >>> key = jax.random.PRNGKey(0)
        >>> x = uniform_poincare.sample(key, n=2, c=1.0, R=1.0, sample_shape=(100,))
        >>> x.shape
        (100, 2)
    """
    # Resolve the working dtype the same way the wrapped-normal siblings do: an explicit
    # ``dtype`` wins, otherwise it is inferred from the caller's own array (``center`` here,
    # ``mu`` there). Only when the caller supplies neither does a default apply — the manifold's
    # dtype if one was passed, else JAX's default float dtype. Hardcoding float64 here silently
    # upcast float32 pipelines and warned whenever ``jax_enable_x64`` was off.
    if dtype is not None:
        dtype = jnp.dtype(dtype)
    elif center is not None:
        dtype = jnp.dtype(center.dtype)
    elif manifold_module is not None:
        dtype = jnp.dtype(manifold_module.dtype)
    else:
        dtype = _default_float_dtype()

    if manifold_module is not None:
        manifold = manifold_module
    else:
        from ..manifolds.poincare import Poincare

        manifold = Poincare(dtype=dtype)

    k1, k2 = jax.random.split(key)

    # 1. Direction on S^{n-1}
    directions_SD = _sample_uniform_direction(k1, n, sample_shape, dtype)

    # 2. Geodesic radii
    radii_S = _sample_radial(k2, c, n, R, sample_shape, dtype)

    # 3. Tangent vectors: t = (r/2) · u
    # The /2 compensates for expmap_0 mapping ||v|| → geodesic distance 2·||v||
    tangents_SD = (radii_S[..., None] / 2.0) * directions_SD  # (*S, 1) * (*S, D)

    # 4-5. Map to ball and translate to center
    def _map_single(t_D):
        x0_D = manifold.expmap_0(t_D, c)
        if center is not None:
            return manifold.addition(center, x0_D, c)
        return x0_D

    # vmap over all sample dimensions. With an empty ``sample_shape`` the loop leaves
    # ``mapped_fn is _map_single``, so the single-sample case needs no branch of its own.
    mapped_fn = _map_single
    for _ in sample_shape:
        mapped_fn = jax.vmap(mapped_fn)

    return mapped_fn(tangents_SD)
log_prob
log_prob(
    x: Float[Array, "... n"],
    c: float,
    R: float,
    center: Float[Array, n] | None = None,
    manifold_module: Manifold | None = None,
) -> Float[Array, ...]

Log-probability of the Riemannian-uniform distribution on B(center, R).

Returns -log Vol(B^n_c(R)) for points inside the geodesic ball, -∞ outside.

Args: x: Point(s) on the Poincaré ball, shape (..., n). c: Positive curvature parameter. R: Geodesic radius of the ball. center: Center of the geodesic ball, shape (n,). Default: origin. manifold_module: Optional Manifold instance. Default: Poincare(x.dtype).

Returns: Log-probability, shape (...), in x's dtype.

Source code in hyperbolix/distributions/uniform_poincare.py
def log_prob(
    x: Float[Array, "... n"],
    c: float,
    R: float,
    center: Float[Array, "n"] | None = None,
    manifold_module: Manifold | None = None,
) -> Float[Array, "..."]:
    """Log-probability of the Riemannian-uniform distribution on B(center, R).

    Returns -log Vol(B^n_c(R)) for points inside the geodesic ball, -∞ outside.

    Args:
        x: Point(s) on the Poincaré ball, shape (..., n).
        c: Positive curvature parameter.
        R: Geodesic radius of the ball.
        center: Center of the geodesic ball, shape (n,). Default: origin.
        manifold_module: Optional Manifold instance. Default: Poincare(x.dtype).

    Returns:
        Log-probability, shape (...), in ``x``'s dtype.
    """
    if manifold_module is not None:
        manifold = manifold_module
    else:
        from ..manifolds.poincare import Poincare

        manifold = Poincare(dtype=x.dtype)

    n = x.shape[-1]
    leading_shape = x.shape[:-1]

    def _dist_single(x_D):
        if center is not None:
            return manifold.dist(x_D, center, c)
        return manifold.dist_0(x_D, c)

    # ``manifold.dist``/``dist_0`` are single-point ops, so one vmap covers exactly one leading
    # axis. Flattening every leading axis into a single one (and restoring the shape afterwards)
    # is what makes the documented ``(..., n) -> (...)`` contract hold for ndim > 2 as well; the
    # old two-branch form raised a dot_general shape error there.
    x_flat_TD = x.reshape(-1, n)
    d_flat_T = jax.vmap(_dist_single)(x_flat_TD)
    d_S = d_flat_T.reshape(leading_shape)

    # Quadrature at ``x``'s precision: a float64 log-volume would upcast the whole result and
    # hand a float32 caller a float64 array. In log space, because the volume itself overflows
    # float32 (n = 11, R = 10) long before its log does.
    log_vol = _log_volume(c, n, R, dtype=x.dtype)

    # -log(vol) inside ball, -inf outside
    inside_S = d_S <= R
    return jnp.where(inside_S, -log_vol, jnp.asarray(-jnp.inf, dtype=x.dtype))

Samples uniformly with respect to the Riemannian volume measure within a geodesic ball \(B(\text{center}, R)\) on the Poincaré ball. Uses geodesic polar decomposition: direction from \(S^{n-1}\) (Muller method), radial component from \(p(r) \propto \sinh^{n-1}(\sqrt{c}\,r)\).

  • For \(n=2\): closed-form radial sampling via \(u = \cosh(\sqrt{c}\,r) - 1\)
  • For \(n \geq 3\): rejection sampling with jax.lax.while_loop (JIT-compatible); for radii too small or too large for the loop, the radius is drawn in closed form.

Usage:

from hyperbolix.distributions import uniform_poincare
from hyperbolix.manifolds import Poincare
import jax
import jax.numpy as jnp

poincare = Poincare()
key = jax.random.PRNGKey(42)

# Sample 100 points uniformly from geodesic ball B(origin, R=1.0) in 2D
# (n is the manifold dimension; the sample count goes in sample_shape)
samples = uniform_poincare.sample(key, n=2, c=1.0, R=1.0, sample_shape=(100,))
print(samples.shape)  # (100, 2)

# All samples inside the geodesic ball
inside = jax.vmap(poincare.dist_0, in_axes=(0, None))(samples, 1.0) <= 1.0
print(inside.all())  # True

# Volume of geodesic ball (2D closed-form: 2π(cosh R - 1)/c)
vol = uniform_poincare.volume(c=1.0, n=2, R=1.0)
print(vol)  # ~3.412 = 2π(cosh 1 − 1)

# Log probability (constant inside ball, -inf outside); batches natively over leading axes
log_p = uniform_poincare.log_prob(samples, c=1.0, R=1.0)
print(jnp.allclose(log_p, log_p[0]))  # True — uniform

Use cases: uniform priors for hyperbolic VAEs, and test points spread evenly over a geodesic ball.

Wrapped Normal Distribution

The wrapped normal distribution extends the Gaussian distribution to hyperbolic manifolds by wrapping Euclidean Gaussians via the exponential map.

Poincaré Wrapped Normal

hyperbolix.distributions.wrapped_normal_poincare

Wrapped normal distribution on Poincaré ball.

Simpler implementation than hyperboloid: sample needs no parallel transport, just the exponential map at the origin and a Möbius addition. log_prob still parallel-transports the log-map back to the origin, exactly as the hyperboloid version does.

Dimension key: S: sample dimensions (from sample_shape) B: batch dimensions (from mu batch shape) D: spatial/manifold dimension (n)

References: Mathieu et al. "Continuous Hierarchical Representations with Poincaré Variational Auto-Encoders" NeurIPS 2019. https://arxiv.org/abs/1901.06033

sample
sample(
    key: PRNGKeyArray,
    mu: Float[Array, "... n"],
    sigma: Float[Array, ...] | float,
    c: float,
    sample_shape: tuple[int, ...] = (),
    dtype=None,
    manifold_module: Manifold | None = None,
) -> Float[Array, ...]

Sample from wrapped normal distribution on Poincaré ball.

Simpler than hyperboloid version - no parallel transport needed!

Algorithm: 1. Sample v ~ N(0, Σ) ∈ R^n (directly in tangent space, no embedding) 2. Map to ball at origin: z_0 = exp_0(v) 3. Move to mean: z = μ ⊕ z_0 (Möbius addition)

Args: key: JAX random key mu: Mean point on Poincaré ball, shape (..., n) sigma: Covariance parameterization. Can be: - Scalar: isotropic covariance sigma^2 I (n x n) - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2) - 2D array (n, n): full covariance matrix (must be SPD) c: Curvature (positive scalar) sample_shape: Shape of samples to draw, prepended to output. Default: () dtype: Output dtype. Default: infer from mu manifold_module: Optional Poincare instance. Default: Poincare(dtype)

Returns: Samples from wrapped normal distribution, shape sample_shape + mu.shape

Examples: >>> import jax >>> import jax.numpy as jnp >>> from hyperbolix.distributions import wrapped_normal_poincare >>> >>> # Single sample with isotropic covariance >>> key = jax.random.PRNGKey(0) >>> mu = jnp.array([0.0, 0.0]) # Origin in Poincaré ball >>> sigma = 0.1 # Isotropic >>> z = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0) >>> z.shape (2,) >>> >>> # Multiple samples with diagonal covariance >>> sigma_diag = jnp.array([0.1, 0.2]) # Diagonal >>> z = wrapped_normal_poincare.sample(key, mu, sigma_diag, c=1.0, sample_shape=(5,)) >>> z.shape (5, 2) >>> >>> # Batch of means >>> mu_batch = jnp.array([[0.0, 0.0], [0.1, 0.1]]) # (2, 2) >>> z = wrapped_normal_poincare.sample(key, mu_batch, 0.1, c=1.0) >>> z.shape (2, 2)

Source code in hyperbolix/distributions/wrapped_normal_poincare.py
def sample(
    key: PRNGKeyArray,
    mu: Float[Array, "... n"],
    sigma: Float[Array, "..."] | float,
    c: float,
    sample_shape: tuple[int, ...] = (),
    dtype=None,
    manifold_module: Manifold | None = None,
) -> Float[Array, "..."]:
    """Sample from wrapped normal distribution on Poincaré ball.

    Simpler than hyperboloid version - no parallel transport needed!

    Algorithm:
    1. Sample v ~ N(0, Σ) ∈ R^n (directly in tangent space, no embedding)
    2. Map to ball at origin: z_0 = exp_0(v)
    3. Move to mean: z = μ ⊕ z_0 (Möbius addition)

    Args:
        key: JAX random key
        mu: Mean point on Poincaré ball, shape (..., n)
        sigma: Covariance parameterization. Can be:
            - Scalar: isotropic covariance sigma^2 I (n x n)
            - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2)
            - 2D array (n, n): full covariance matrix (must be SPD)
        c: Curvature (positive scalar)
        sample_shape: Shape of samples to draw, prepended to output. Default: ()
        dtype: Output dtype. Default: infer from mu
        manifold_module: Optional Poincare instance. Default: Poincare(dtype)

    Returns:
        Samples from wrapped normal distribution, shape sample_shape + mu.shape

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> from hyperbolix.distributions import wrapped_normal_poincare
        >>>
        >>> # Single sample with isotropic covariance
        >>> key = jax.random.PRNGKey(0)
        >>> mu = jnp.array([0.0, 0.0])  # Origin in Poincaré ball
        >>> sigma = 0.1  # Isotropic
        >>> z = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0)
        >>> z.shape
        (2,)
        >>>
        >>> # Multiple samples with diagonal covariance
        >>> sigma_diag = jnp.array([0.1, 0.2])  # Diagonal
        >>> z = wrapped_normal_poincare.sample(key, mu, sigma_diag, c=1.0, sample_shape=(5,))
        >>> z.shape
        (5, 2)
        >>>
        >>> # Batch of means
        >>> mu_batch = jnp.array([[0.0, 0.0], [0.1, 0.1]])  # (2, 2)
        >>> z = wrapped_normal_poincare.sample(key, mu_batch, 0.1, c=1.0)
        >>> z.shape
        (2, 2)
    """
    # Use provided manifold module or default class instance
    if manifold_module is not None:
        manifold = manifold_module
    else:
        from ..manifolds.poincare import Poincare

        _dtype = dtype if dtype is not None else mu.dtype
        manifold = Poincare(dtype=_dtype)

    # Determine output dtype
    if dtype is None:
        dtype = mu.dtype

    # Extract dimension
    n = mu.shape[-1]  # Dimension of Poincaré ball

    # Determine batch shape from mu (all dims except the last one)
    # mu.shape = batch_shape + (n,)
    mu_batch_shape = mu.shape[:-1]

    # Step 1: Sample v ~ N(0, Σ) ∈ R^n (directly in tangent space at origin)
    # Full noise shape: sample_shape + mu_batch_shape + (n,) = (*S, *B, D)
    cov_DD = sigma_to_cov(sigma, n, dtype)
    full_sample_shape = sample_shape + mu_batch_shape
    v_SBD = sample_gaussian(key, cov_DD, sample_shape=full_sample_shape, dtype=dtype)

    # Scale Euclidean tangent vector to Riemannian tangent space coordinates.
    # At origin, the conformal factor λ(0) = 2/(1 - c·0) = 2, so Riemannian
    # coordinates require dividing by λ(0). This matches the reference (Mathieu et al.
    # 2019) which does v = v / lambda_x(zero) before the exponential map.
    v_SBD = v_SBD / 2.0

    # Step 2: Map to ball at origin: z_0 = exp_0(v)
    # Step 3: Move to mean: z = μ ⊕ z_0

    def transform_single(v_D, mu_D):
        """Transform a single (v, mu) pair."""
        z_0_D = manifold.expmap_0(v_D, c)
        z_D = manifold.addition(mu_D, z_0_D, c)
        return z_D

    return _batched_transform(transform_single, v_SBD, mu, sample_shape, mu_batch_shape)
log_prob
log_prob(
    z: Float[Array, "... n"],
    mu: Float[Array, "... n"],
    sigma: Float[Array, ...] | float,
    c: ScalarCurvature,
    manifold_module: Manifold | None = None,
) -> Float[Array, ...]

Compute log probability of wrapped normal distribution on Poincaré ball.

Implements Algorithm 2 from the paper adapted for Poincaré ball: 1. Map z to u = log_μ(z) ∈ T_μB^n (logarithmic map) 2. Move u to v = PT_{μ→0}(u) ∈ T_0B^n (parallel transport to origin) 3. Calculate log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)

Args: z: Sample point(s) on Poincaré ball, shape (..., n) mu: Mean point on Poincaré ball, shape (..., n). z and mu broadcast against each other: mu's batch axes pair with z's trailing batch axes, and any further leading axes of z are sample axes that share the mean. sigma: Covariance parameterization. Can be: - Scalar: isotropic covariance sigma^2 I (n x n) - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2) - 2D array (n, n): full covariance matrix (must be SPD) c: Curvature (positive scalar) manifold_module: Optional Poincare instance. Default: Poincare(z.dtype)

Returns: Log probability, shape (...) (spatial dimension removed)

Examples: >>> import jax >>> import jax.numpy as jnp >>> from hyperbolix.distributions import wrapped_normal_poincare >>> >>> # Compute log probability of samples >>> key = jax.random.PRNGKey(0) >>> mu = jnp.array([0.0, 0.0]) >>> sigma = 0.1 >>> z = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0) >>> log_p = wrapped_normal_poincare.log_prob(z, mu, sigma, c=1.0) >>> log_p.shape () >>> >>> # Batch computation >>> z_batch = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0, sample_shape=(10,)) >>> log_p_batch = wrapped_normal_poincare.log_prob(z_batch, mu, sigma, c=1.0) >>> log_p_batch.shape (10,)

Source code in hyperbolix/distributions/wrapped_normal_poincare.py
def log_prob(
    z: Float[Array, "... n"],
    mu: Float[Array, "... n"],
    sigma: Float[Array, "..."] | float,
    c: ScalarCurvature,
    manifold_module: Manifold | None = None,
) -> Float[Array, "..."]:
    """Compute log probability of wrapped normal distribution on Poincaré ball.

    Implements Algorithm 2 from the paper adapted for Poincaré ball:
    1. Map z to u = log_μ(z) ∈ T_μB^n (logarithmic map)
    2. Move u to v = PT_{μ→0}(u) ∈ T_0B^n (parallel transport to origin)
    3. Calculate log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)

    Args:
        z: Sample point(s) on Poincaré ball, shape (..., n)
        mu: Mean point on Poincaré ball, shape (..., n). ``z`` and ``mu`` broadcast against
            each other: mu's batch axes pair with z's trailing batch axes, and any further
            leading axes of ``z`` are sample axes that share the mean.
        sigma: Covariance parameterization. Can be:
            - Scalar: isotropic covariance sigma^2 I (n x n)
            - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2)
            - 2D array (n, n): full covariance matrix (must be SPD)
        c: Curvature (positive scalar)
        manifold_module: Optional Poincare instance. Default: Poincare(z.dtype)

    Returns:
        Log probability, shape (...) (spatial dimension removed)

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> from hyperbolix.distributions import wrapped_normal_poincare
        >>>
        >>> # Compute log probability of samples
        >>> key = jax.random.PRNGKey(0)
        >>> mu = jnp.array([0.0, 0.0])
        >>> sigma = 0.1
        >>> z = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0)
        >>> log_p = wrapped_normal_poincare.log_prob(z, mu, sigma, c=1.0)
        >>> log_p.shape
        ()
        >>>
        >>> # Batch computation
        >>> z_batch = wrapped_normal_poincare.sample(key, mu, sigma, c=1.0, sample_shape=(10,))
        >>> log_p_batch = wrapped_normal_poincare.log_prob(z_batch, mu, sigma, c=1.0)
        >>> log_p_batch.shape
        (10,)
    """

    # Use provided manifold module or default class instance
    if manifold_module is not None:
        manifold = manifold_module
    else:
        from ..manifolds.poincare import Poincare

        manifold = Poincare(dtype=z.dtype)

    # Determine dtype
    dtype = z.dtype
    # The manifold's dtype decides: a float64 `c` must not promote the log-det to float64.
    c = jnp.asarray(c, dtype=manifold.dtype)

    # Extract dimension
    n = mu.shape[-1]  # Dimension of Poincaré ball

    # Batching layout: z is (*S, *B, D) and mu is (*B, D). The mean's batch axes pair with z's
    # trailing axes; the leading sample axes broadcast the mean. Steps 1 and 2 must use the
    # *same* layout — vmapping u and mu together over axis 0 (as step 2 used to) pairs a sample
    # axis with a batch axis and fails on sample()'s own output whenever both are present.
    # Both are first broadcast to that layout: a `z` with fewer leading axes than `mu` (one point
    # against a batch of means) would otherwise have its coordinate axis vmapped against mu's
    # batch axis, which is silently wrong when the batch size equals the dimension.
    full_shape = jnp.broadcast_shapes(z.shape, mu.shape)
    z = jnp.broadcast_to(z, full_shape)
    mu = jnp.broadcast_to(mu, full_shape[len(full_shape) - mu.ndim :])
    n_sample_dims = z.ndim - mu.ndim
    n_batch_dims = mu.ndim - 1

    # Step 1: Map z to tangent space at mu: u = log_μ(z), shape (..., D)
    def _logmap_single(z_D, mu_D):
        return manifold.logmap(z_D, mu_D, c)

    u_SBD = _vmap_sample_and_batch(_logmap_single, n_sample_dims, n_batch_dims)(z, mu)

    # Step 2: Parallel transport from mu to origin: v = PT_{μ→0}(u)
    mu_0_D = jnp.zeros(n, dtype=dtype)

    def _ptransp_single(u_D, mu_D):
        return manifold.ptransp(u_D, mu_D, mu_0_D, c)

    v_SBD = _vmap_sample_and_batch(_ptransp_single, n_sample_dims, n_batch_dims)(u_SBD, mu)

    # Step 3: Compute log p(v) where v ~ N(0, Σ)
    # Scale to Riemannian coordinates: v_riem = λ(0) · v_euclid = 2 · v
    v_riem_SBD = v_SBD * 2.0
    log_p_v_SB = gaussian_log_prob(v_riem_SBD, sigma, n, dtype)

    # Step 4: Compute log det Jacobian
    # Riemannian norm r = λ(0) · ||v||_E = 2 · ||v||_E, via `safe_norm`. It supplies exactly what
    # the old `sqrt(floor_at(sum(v**2), MIN_NORM))` was there for — a finite (zero) gradient at
    # z == mu, where sqrt'(0) is infinite — without the floor's side effect: flooring the *squared*
    # norm at 1e-15 pinned r at 2·3.16e-8 for every tangent vector shorter than that, and
    # `sum(v**2)` overflowed float32 past ||v|| = 1.8e19. `_log_det_jacobian_from_r` is already
    # NaN-free and stationary at r = 0 (double-`where` plus the Taylor branch), so r = 0 is safe.
    # The Taylor branch reads the un-rooted `sum(v**2)`, which keeps the log-det's second derivative
    # at z == mu.
    r_SB = 2.0 * safe_norm(v_SBD)
    r_sq_SB = 4.0 * jnp.sum(v_SBD**2, axis=-1)
    log_det_jac_SB = _log_det_jacobian_from_r(r_SB, c, n, r_sq=r_sq_SB)

    # Step 5: log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)
    log_p_z_SB = log_p_v_SB - log_det_jac_SB

    return log_p_z_SB

Hyperboloid Wrapped Normal

hyperbolix.distributions.wrapped_normal_hyperboloid

Wrapped normal distribution on hyperboloid manifold.

Implementation of the wrapped normal distribution that wraps a Gaussian from the tangent space at the origin onto the hyperboloid via parallel transport and exponential map.

Dimension key: S: sample dimensions (from sample_shape) B: batch dimensions (from mu batch shape) D: spatial dimension (n) A: ambient dimension (n+1, hyperboloid time+space)

References: Mathieu et al. "Continuous Hierarchical Representations with Poincaré Variational Auto-Encoders" NeurIPS 2019. https://arxiv.org/abs/1901.06033

sample
sample(
    key: PRNGKeyArray,
    mu: Float[Array, "... n_plus_1"],
    sigma: Float[Array, ...] | float,
    c: float,
    sample_shape: tuple[int, ...] = (),
    dtype=None,
    manifold_module: Hyperboloid | None = None,
) -> Float[Array, ...]

Sample from wrapped normal distribution on hyperboloid.

Implements Algorithm 1 from the paper: 1. Sample v_bar ~ N(0, Σ) ∈ R^n 2. Embed as tangent vector v = [0, v_bar] ∈ T_{μ₀}ℍⁿ at origin 3. Parallel transport to mean: u = PT_{μ₀→μ}(v) ∈ T_μℍⁿ 4. Map to manifold: z = exp_μ(u) ∈ ℍⁿ

Args: key: JAX random key mu: Mean point on hyperboloid, shape (..., n+1) in ambient coordinates sigma: Covariance parameterization in spatial coordinates. Can be: - Scalar: isotropic covariance sigma^2 I (n x n) - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2) - 2D array (n, n): full covariance matrix (must be SPD) c: Curvature (positive scalar) sample_shape: Shape of samples to draw, prepended to output. Default: () dtype: Output dtype. Default: infer from mu manifold_module: Optional Hyperboloid instance. Default: Hyperboloid(dtype)

Returns: Samples from wrapped normal distribution, shape sample_shape + mu.shape

Examples: >>> import jax >>> import jax.numpy as jnp >>> from hyperbolix.distributions import wrapped_normal_hyperboloid >>> >>> # Single sample with isotropic covariance >>> key = jax.random.PRNGKey(0) >>> mu = jnp.array([1.0, 0.0, 0.0]) # Origin in H^2 >>> sigma = 0.1 # Isotropic >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0) >>> z.shape (3,) >>> >>> # Multiple samples with diagonal covariance >>> sigma_diag = jnp.array([0.1, 0.2]) # Diagonal >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma_diag, c=1.0, sample_shape=(5,)) >>> z.shape (5, 3) >>> >>> # Batch of means >>> mu_batch = jnp.array([[1.0, 0.0, 0.0], [1.0, 0.1, 0.1]]) # (2, 3) >>> z = wrapped_normal_hyperboloid.sample(key, mu_batch, 0.1, c=1.0) >>> z.shape (2, 3)

Source code in hyperbolix/distributions/wrapped_normal_hyperboloid.py
def sample(
    key: PRNGKeyArray,
    mu: Float[Array, "... n_plus_1"],
    sigma: Float[Array, "..."] | float,
    c: float,
    sample_shape: tuple[int, ...] = (),
    dtype=None,
    manifold_module: Hyperboloid | None = None,
) -> Float[Array, "..."]:
    """Sample from wrapped normal distribution on hyperboloid.

    Implements Algorithm 1 from the paper:
    1. Sample v_bar ~ N(0, Σ) ∈ R^n
    2. Embed as tangent vector v = [0, v_bar] ∈ T_{μ₀}ℍⁿ at origin
    3. Parallel transport to mean: u = PT_{μ₀→μ}(v) ∈ T_μℍⁿ
    4. Map to manifold: z = exp_μ(u) ∈ ℍⁿ

    Args:
        key: JAX random key
        mu: Mean point on hyperboloid, shape (..., n+1) in ambient coordinates
        sigma: Covariance parameterization in spatial coordinates. Can be:
            - Scalar: isotropic covariance sigma^2 I (n x n)
            - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2)
            - 2D array (n, n): full covariance matrix (must be SPD)
        c: Curvature (positive scalar)
        sample_shape: Shape of samples to draw, prepended to output. Default: ()
        dtype: Output dtype. Default: infer from mu
        manifold_module: Optional Hyperboloid instance. Default: Hyperboloid(dtype)

    Returns:
        Samples from wrapped normal distribution, shape sample_shape + mu.shape

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> from hyperbolix.distributions import wrapped_normal_hyperboloid
        >>>
        >>> # Single sample with isotropic covariance
        >>> key = jax.random.PRNGKey(0)
        >>> mu = jnp.array([1.0, 0.0, 0.0])  # Origin in H^2
        >>> sigma = 0.1  # Isotropic
        >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0)
        >>> z.shape
        (3,)
        >>>
        >>> # Multiple samples with diagonal covariance
        >>> sigma_diag = jnp.array([0.1, 0.2])  # Diagonal
        >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma_diag, c=1.0, sample_shape=(5,))
        >>> z.shape
        (5, 3)
        >>>
        >>> # Batch of means
        >>> mu_batch = jnp.array([[1.0, 0.0, 0.0], [1.0, 0.1, 0.1]])  # (2, 3)
        >>> z = wrapped_normal_hyperboloid.sample(key, mu_batch, 0.1, c=1.0)
        >>> z.shape
        (2, 3)
    """
    # Use provided manifold module or default class instance
    if manifold_module is not None:
        manifold = manifold_module
    else:
        # Determine output dtype first for class instantiation
        _dtype = dtype if dtype is not None else mu.dtype
        manifold = Hyperboloid(dtype=_dtype)

    # Determine output dtype
    if dtype is None:
        dtype = mu.dtype

    # Extract spatial dimension
    n = mu.shape[-1] - 1  # Spatial dimension (n for H^n in R^(n+1))

    # Determine batch shape from mu (all dims except the last one)
    # mu.shape = batch_shape + (n+1,)
    mu_batch_shape = mu.shape[:-1]

    # Step 1: Sample v_bar ~ N(0, Σ) ∈ R^n
    # Full noise shape: sample_shape + mu_batch_shape + (n,) = (*S, *B, D)
    cov_DD = sigma_to_cov(sigma, n, dtype)
    full_sample_shape = sample_shape + mu_batch_shape
    v_spatial_SBD = sample_gaussian(key, cov_DD, sample_shape=full_sample_shape, dtype=dtype)

    # Step 2: Embed as tangent vector v = [0, v_bar] ∈ T_{μ₀}ℍⁿ at origin
    # Shape: (*S, *B, A) where A = n+1
    v_SBA = manifold.embed_spatial_0(v_spatial_SBD)

    # Step 3 & 4: Parallel transport and exponential map

    def transform_single(v_A, mu_A):
        """Transform a single (v, mu) pair."""
        u_A = manifold.ptransp_0(v_A, mu_A, c)  # Step 3: parallel transport to mu
        z_A = manifold.expmap(u_A, mu_A, c)  # Step 4: exponential map at mu
        return z_A

    return _batched_transform(transform_single, v_SBA, mu, sample_shape, mu_batch_shape)
log_prob
log_prob(
    z: Float[Array, "... n_plus_1"],
    mu: Float[Array, "... n_plus_1"],
    sigma: Float[Array, ...] | float,
    c: ScalarCurvature,
    manifold_module: Hyperboloid | None = None,
) -> Float[Array, ...]

Compute log probability of wrapped normal distribution.

Implements Algorithm 2 from the paper: 1. Map z to u = exp_μ⁻¹(z) ∈ T_μℍⁿ (logarithmic map) 2. Move u to v = PT_{μ→μ₀}(u) ∈ T_{μ₀}ℍⁿ (parallel transport to origin) 3. Calculate log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)

Args: z: Sample point(s) on hyperboloid, shape (..., n+1) mu: Mean point on hyperboloid, shape (..., n+1). z and mu broadcast against each other: mu's batch axes pair with z's trailing batch axes, and any further leading axes of z are sample axes that share the mean. sigma: Covariance parameterization. Can be: - Scalar: isotropic covariance sigma^2 I (n x n) - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2) - 2D array (n, n): full covariance matrix (must be SPD) c: Curvature (positive scalar) manifold_module: Optional Hyperboloid instance. Default: Hyperboloid(z.dtype)

Returns: Log probability, shape (...) (manifold dimension removed)

Examples: >>> import jax >>> import jax.numpy as jnp >>> from hyperbolix.distributions import wrapped_normal_hyperboloid >>> >>> # Compute log probability of samples >>> key = jax.random.PRNGKey(0) >>> mu = jnp.array([1.0, 0.0, 0.0]) >>> sigma = 0.1 >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0) >>> log_p = wrapped_normal_hyperboloid.log_prob(z, mu, sigma, c=1.0) >>> log_p.shape () >>> >>> # Batch computation >>> z_batch = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0, sample_shape=(10,)) >>> log_p_batch = wrapped_normal_hyperboloid.log_prob(z_batch, mu, sigma, c=1.0) >>> log_p_batch.shape (10,)

Source code in hyperbolix/distributions/wrapped_normal_hyperboloid.py
def log_prob(
    z: Float[Array, "... n_plus_1"],
    mu: Float[Array, "... n_plus_1"],
    sigma: Float[Array, "..."] | float,
    c: ScalarCurvature,
    manifold_module: Hyperboloid | None = None,
) -> Float[Array, "..."]:
    """Compute log probability of wrapped normal distribution.

    Implements Algorithm 2 from the paper:
    1. Map z to u = exp_μ⁻¹(z) ∈ T_μℍⁿ (logarithmic map)
    2. Move u to v = PT_{μ→μ₀}(u) ∈ T_{μ₀}ℍⁿ (parallel transport to origin)
    3. Calculate log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)

    Args:
        z: Sample point(s) on hyperboloid, shape (..., n+1)
        mu: Mean point on hyperboloid, shape (..., n+1). ``z`` and ``mu`` broadcast against
            each other: mu's batch axes pair with z's trailing batch axes, and any further
            leading axes of ``z`` are sample axes that share the mean.
        sigma: Covariance parameterization. Can be:
            - Scalar: isotropic covariance sigma^2 I (n x n)
            - 1D array of length n: diagonal covariance diag(sigma_1^2, ..., sigma_n^2)
            - 2D array (n, n): full covariance matrix (must be SPD)
        c: Curvature (positive scalar)
        manifold_module: Optional Hyperboloid instance. Default: Hyperboloid(z.dtype)

    Returns:
        Log probability, shape (...) (manifold dimension removed)

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> from hyperbolix.distributions import wrapped_normal_hyperboloid
        >>>
        >>> # Compute log probability of samples
        >>> key = jax.random.PRNGKey(0)
        >>> mu = jnp.array([1.0, 0.0, 0.0])
        >>> sigma = 0.1
        >>> z = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0)
        >>> log_p = wrapped_normal_hyperboloid.log_prob(z, mu, sigma, c=1.0)
        >>> log_p.shape
        ()
        >>>
        >>> # Batch computation
        >>> z_batch = wrapped_normal_hyperboloid.sample(key, mu, sigma, c=1.0, sample_shape=(10,))
        >>> log_p_batch = wrapped_normal_hyperboloid.log_prob(z_batch, mu, sigma, c=1.0)
        >>> log_p_batch.shape
        (10,)
    """
    # Use provided manifold module or default class instance
    if manifold_module is not None:
        manifold = manifold_module
    else:
        manifold = Hyperboloid(dtype=z.dtype)

    # Determine dtype
    dtype = z.dtype
    # The manifold's dtype decides: a float64 `c` must not promote the result to float64.
    c = manifold._cast_c(c)

    # Extract spatial dimension
    n = mu.shape[-1] - 1  # Spatial dimension

    # Batching layout: z is (*S, *B, A) and mu is (*B, A). The mean's batch axes pair with z's
    # trailing axes; the leading sample axes broadcast the mean. Steps 1 and 2 must use the
    # *same* layout — vmapping u and mu together over axis 0 (as step 2 used to) pairs a sample
    # axis with a batch axis and fails on sample()'s own output whenever both are present.
    # Both are first broadcast to that layout: a `z` with fewer leading axes than `mu` (one point
    # against a batch of means) would otherwise have its coordinate axis vmapped against mu's
    # batch axis, which is silently wrong when the batch size equals the dimension.
    full_shape = jnp.broadcast_shapes(z.shape, mu.shape)
    z = jnp.broadcast_to(z, full_shape)
    mu = jnp.broadcast_to(mu, full_shape[len(full_shape) - mu.ndim :])
    n_sample_dims = z.ndim - mu.ndim
    n_batch_dims = mu.ndim - 1

    # Steps 1 and 2 as one map: v = PT_{μ→μ₀}(log_μ(z)) = log_0((⊖μ) ⊕ z), the identity in
    # `_gyro_difference`'s docstring, shape (..., A). The composition `logmap` -> transport it replaces
    # stored u = log_μ(z) in the ambient chart at μ, whose components are cosh(a) times the vector's
    # length (a = scaled radius of the mean), so float32 lost eps·cosh(a) of v.
    # `close_pairs=True` reads a close pair off z_s - μ_s; the public `gyro_difference` leaves that
    # branch off because of its cost in the stacked layers, and here only correctness counts.
    def _origin_tangent_single(z_A, mu_A):
        centred_A = _hyperboloid_gyro_difference(manifold._cast(mu_A), manifold._cast(z_A), c, close_pairs=True)
        return manifold.logmap_0(centred_A, c)

    v_SBA = _vmap_sample_and_batch(_origin_tangent_single, n_sample_dims, n_batch_dims)(z, mu)

    # Step 3: Extract spatial components: v = [0, v_bar] at origin
    v_spatial_SBD = v_SBA[..., 1:]

    # Step 4: Compute log p(v) where v ~ N(0, Σ)
    log_p_v_SB = gaussian_log_prob(v_spatial_SBD, sigma, n, dtype)

    # Step 5: Compute log det Jacobian
    # Minkowski norm at origin: r = ||v_spatial|| (since v = [0, v_bar]). `safe_norm` gives the
    # finite (zero) gradient at z == mu that the old `floor_at(sum(v**2), MIN_NORM)` was there
    # for, without flooring r at 3.16e-8 and without `sum(v**2)` overflowing float32.
    # `_log_det_jacobian_from_r` is already NaN-free and stationary at r = 0. Its Taylor branch reads
    # the un-rooted `sum(v**2)`, which keeps the log-det's second derivative at z == mu.
    r_SB = safe_norm(v_spatial_SBD)
    r_sq_SB = jnp.sum(v_spatial_SBD**2, axis=-1)
    log_det_jac_SB = _log_det_jacobian_from_r(r_SB, c, n, r_sq=r_sq_SB)

    # Step 6: log p(z) = log p(v) - log det(∂proj_μ(v)/∂v)
    log_p_z_SB = log_p_v_SB - log_det_jac_SB

    return log_p_z_SB

Usage Examples

Basic Sampling (Poincaré)

from hyperbolix.distributions import wrapped_normal_poincare
from hyperbolix.manifolds import Poincare
import jax
import jax.numpy as jnp

poincare = Poincare()

# Mean on Poincaré ball
mean = jnp.array([0.2, 0.3])
mean_proj = poincare.proj(mean, c=1.0)

# Standard deviation
std = 0.1

# Sample
key = jax.random.PRNGKey(42)
samples = wrapped_normal_poincare.sample(
    key, mean_proj, std, c=1.0, sample_shape=(100,), manifold_module=poincare
)
print(samples.shape)  # (100, 2)

# Samples lie on Poincaré ball
norms = jnp.linalg.norm(samples, axis=-1)
print(jnp.all(norms < 1.0 / jnp.sqrt(1.0)))  # True

Log Probability

# Compute log probability of samples
log_probs = jax.vmap(
    lambda x: wrapped_normal_poincare.log_prob(x, mean_proj, std, c=1.0, manifold_module=poincare)
)(samples)
print(log_probs.shape)  # (100,)

# Higher probability near mean
point_near_mean = poincare.proj(jnp.array([0.21, 0.29]), c=1.0)
point_far = poincare.proj(jnp.array([0.7, 0.7]), c=1.0)

print(f"Log prob (near): {wrapped_normal_poincare.log_prob(point_near_mean, mean_proj, std, c=1.0, manifold_module=poincare):.4f}")
print(f"Log prob (far): {wrapped_normal_poincare.log_prob(point_far, mean_proj, std, c=1.0, manifold_module=poincare):.4f}")

Hyperboloid Distribution

from hyperbolix.distributions import wrapped_normal_hyperboloid
from hyperbolix.manifolds import Hyperboloid
import jax.numpy as jnp

hyperboloid = Hyperboloid()

# Mean on hyperboloid (ambient coordinates)
mean_space = jnp.array([0.2, 0.3, -0.1])
mean_ambient = jnp.concatenate([
    jnp.array([jnp.sqrt(jnp.sum(mean_space**2) + 1.0)]),
    mean_space
])

# Sample
key = jax.random.PRNGKey(123)
samples = wrapped_normal_hyperboloid.sample(
    key, mean_ambient, sigma=0.15, c=1.0, sample_shape=(50,), manifold_module=hyperboloid
)

# Compute log probabilities
log_probs = jax.vmap(
    lambda x: wrapped_normal_hyperboloid.log_prob(x, mean_ambient, 0.15, c=1.0, manifold_module=hyperboloid)
)(samples)

VAE Example

A sketch of a Poincaré VAE: the encoder gives a tangent vector that expmap_0 puts on the ball as the mean, a second head gives the log standard deviation, the latent code is drawn with wrapped_normal_poincare.sample, and the KL term is a one-sample Monte Carlo estimate from log_prob.

import jax
import jax.numpy as jnp
import optax
from flax import nnx
from hyperbolix.distributions import wrapped_normal_poincare
from hyperbolix.manifolds import Poincare

poincare = Poincare()
c = 1.0


class HyperbolicVAE(nnx.Module):
    def __init__(self, in_dim, latent_dim, rngs):
        self.encoder = nnx.Linear(in_dim, 128, rngs=rngs)
        self.mean_head = nnx.Linear(128, latent_dim, rngs=rngs)  # tangent vector at the origin
        self.log_std_head = nnx.Linear(128, latent_dim, rngs=rngs)  # trained with the rest
        self.decoder = nnx.Linear(latent_dim, in_dim, rngs=rngs)

    def __call__(self, x, key):
        h = jax.nn.relu(self.encoder(x))
        mean = jax.vmap(poincare.expmap_0, in_axes=(0, None))(self.mean_head(h), c)  # on the ball
        std = jnp.exp(self.log_std_head(h))  # per-axis standard deviation
        # A vector sigma is a per-axis std, so vmap over the batch (a 2-D sigma is a covariance)
        keys = jax.random.split(key, x.shape[0])
        z = jax.vmap(lambda k, m, s: wrapped_normal_poincare.sample(k, m, s, c))(keys, mean, std)
        recon = self.decoder(jax.vmap(poincare.logmap_0, in_axes=(0, None))(z, c))
        # One-sample Monte Carlo KL(q(z|x) || p(z)), prior = wrapped normal at the origin, sigma = 1
        log_q = jax.vmap(lambda z_, m, s: wrapped_normal_poincare.log_prob(z_, m, s, c))(z, mean, std)
        log_p = wrapped_normal_poincare.log_prob(z, jnp.zeros(z.shape[-1]), 1.0, c)
        return recon, log_q - log_p


def loss_fn(model, x, key):
    recon, kl = model(x, key)
    return jnp.mean(jnp.sum((x - recon) ** 2, axis=-1) + kl)


model = HyperbolicVAE(in_dim=784, latent_dim=2, rngs=nnx.Rngs(0))
optimizer = nnx.Optimizer(model, optax.adam(1e-3), wrt=nnx.Param)


@nnx.jit
def train_step(model, optimizer, x, key):
    loss, grads = nnx.value_and_grad(loss_fn)(model, x, key)
    optimizer.update(model, grads)
    return loss


x = jax.random.uniform(jax.random.PRNGKey(1), (32, 784))  # stand-in for a data batch
print(train_step(model, optimizer, x, jax.random.PRNGKey(2)))

Mathematical Background

Wrapped Normal Definition

Given a mean \(\mu \in \mathcal{M}\) and scale σ (a scalar or per-axis standard deviation, or an \((n, n)\) covariance matrix \(\Sigma\)), a sample is drawn as follows:

  1. Sample \(v \sim \mathcal{N}(0, \Sigma)\) in the tangent space at the origin
  2. Carry it to \(\mu\) and wrap it onto the manifold: \(x = \exp_\mu(\mathrm{PT}_{0\to\mu}(v))\)

The log probability is:

\[ \log p(x) = \log \mathcal{N}(v;\,0,\Sigma) - (n-1)\log\frac{\sinh(\sqrt{c}\,r)}{\sqrt{c}\,r},\qquad v = \mathrm{PT}_{\mu\to 0}(\log_\mu x),\ r = \|v\| \]

where \(n\) is the manifold dimension and \(r\) the Riemannian norm of \(v\).

Numerical Considerations

In float32, log_prob stays within ~1e-4 relative of float64 down to σ ≈ 1e-4; below that the float32 rounding of the stored sample is a noticeable fraction of σ, so use float64.

Curvature

For a fixed σ, the geodesic distance of a sample from μ has the same distribution for every \(c\). The curvature changes only the ball coordinates (the ball has radius \(1/\sqrt{c}\)) and the volume correction in log_prob.

References

Wrapped distributions on manifolds are discussed in:

  • Nagano, Y., et al. (2019). "A Wrapped Normal Distribution on Hyperbolic Space for Gradient-Based Learning"
  • Mathieu, E., et al. (2019). "Continuous Hierarchical Representations with Poincaré Variational Auto-Encoders." NeurIPS.

See also: