Module contents
Lesson 28 of 30Advanced 105 min

Applied differential geometry II: hyperbolic spaces and curvature-aware embeddings

Study hyperbolic geometry, hierarchy distortion, Riemannian optimization and mixed-curvature models with explicit numerical and evaluation limits.

After this lesson you can

  • Compare Poincaré and Lorentz models and their distances.
  • Measure Gromov hyperbolicity and tree embedding distortion.
  • Derive Riemannian gradient scaling and distinguish update rules.
  • Evaluate hierarchy reconstruction and link prediction under controlled candidates.
  • Analyze curvature and floating-point precision tradeoffs.

Before you start

When a hierarchy runs out of space

A binary tree of depth hh has 2h2^h leaves. In fixed Euclidean dimension the volume of a radius-RR ball grows as RdR^d; in the hyperbolic plane of curvature −1-1, a radius-RR circle has length 2πsinh⁡R2\pi\sinh R. Thus more space is available to separate branches at large distances without increasing dimension. This is a geometric conclusion, not a guarantee that every graph is better represented in a hyperbolic ball.

If all distances of a deep binary tree must be preserved up to constant factors, leaves have separations proportional to their tree distance. In a Euclidean ball of radius proportional to hh, a packing argument bounds the number of sufficiently separated points by a power of hh, versus the exponential number of leaves. The bound depends on dimension, scale and allowed distortion: it does not claim a finite tree cannot be embedded in any Euclidean dimension.

Two models, one geometry

The Poincaré and Lorentz hyperbolic models represent the same space of curvature −1-1 in different coordinates. In ball Bd={x∈Rd:∥x∥<1}\mathbb{B}^d=\{\vb{x}\in\R^d:\norm{\vb{x}}<1\}, the metric is gx=λx2Ig_{\vb{x}}=\lambda_{\vb{x}}^2\mat{I} with λx=2/(1−∥x∥2)\lambda_{\vb{x}}=2/(1-\norm{\vb{x}}^2). Distance is

dB(x,y)=arcosh⁡(1+2∥x−y∥2(1−∥x∥2)(1−∥y∥2)).d_{\mathbb B}(\vb{x},\vb{y})=\operatorname{arcosh}\left(1+\frac{2\norm{\vb{x}-\vb{y}}^2}{(1-\norm{\vb{x}}^2)(1-\norm{\vb{y}}^2)}\right).

In particular, d(0,x)=2artanh⁡∥x∥d(\vb{0},\vb{x})=2\operatorname{artanh}\norm{\vb{x}}. The boundary is not part of the space and is infinitely distant. The ball is conformal: it preserves local angles, not Euclidean lengths. Geodesics are diameters or circular arcs orthogonal to the boundary.

InteractiveHyperbolic lines
  • geodesic
  • Euclidean segment
Hyperbolic distance2.284
Euclidean distance0.955
Drag the points: the magenta arc is the geodesic and the point on it is the hyperbolic midpoint. Move one point toward the boundary while holding the other fixed and observe distance. Interaction limits radius to avoid numerical overflow.

In Lorentz we use ⟨x,y⟩L=−x0y0+∑i=1dxiyi\langle\vb{x},\vb{y}\rangle_L=-x_0y_0+\sum_{i=1}^{d}x_i y_i and upper hyperboloid ⟨x,x⟩L=−1\langle\vb{x},\vb{x}\rangle_L=-1, x0>0x_0>0. Its distance is dL(x,y)=arcosh⁡(−⟨x,y⟩L)d_L(\vb{x},\vb{y})=\operatorname{arcosh}(-\langle\vb{x},\vb{y}\rangle_L). Coordinates convert via

z∈Bd⟼(1+∥z∥21−∥z∥2,2z1−∥z∥2),z=x1:dx0+1.\vb{z}\in\mathbb B^d\longmapsto\left(\frac{1+\norm{\vb{z}}^2}{1-\norm{\vb{z}}^2},\frac{2\vb{z}}{1-\norm{\vb{z}}^2}\right),\qquad \vb{z}=\frac{\vb{x}_{1:d}}{x_0+1}.

For v∈TxHd\vb{v}\in T_{\vb{x}}\mathbb H^d, with s=⟨v,v⟩Ls=\sqrt{\langle\vb{v},\vb{v}\rangle_L}, the exponential map is exp⁡x(v)=cosh⁡(s)x+sinh⁡(s)v/s\exp_{\vb{x}}(\vb{v})=\cosh(s)\vb{x}+\sinh(s)\vb{v}/s, with continuous limit at zero. For x≠y\vb{x}\ne\vb{y}, log⁡x(y)=d(x,y)(y+⟨x,y⟩Lx)/sinh⁡d(x,y)\log_{\vb{x}}(\vb{y})=d(\vb{x},\vb{y})(\vb{y}+\langle\vb{x},\vb{y}\rangle_L\vb{x})/\sinh d(\vb{x},\vb{y}). The vector is tangent because its Lorentz product with x\vb{x} vanishes. At the ball origin, exp⁡0(v)=tanh⁡(∥v∥)v/∥v∥\exp_0(\vb{v})=\tanh(\norm{\vb{v}})\vb{v}/\norm{\vb{v}} and log⁡0(x)=artanh⁡(∥x∥)x/∥x∥\log_0(\vb{x})=\operatorname{artanh}(\norm{\vb{x}})\vb{x}/\norm{\vb{x}}, with limits at zero. Riemannian norm at the origin is 2∥v∥2\norm{\vb{v}}; do not confuse coordinate-vector norm with geometric length.

How tree-like is the graph?

Gromov hyperbolicity can be computed in a finite metric space using four points. For a,b,c,da,b,c,d, order the three sums d(a,b)+d(c,d)d(a,b)+d(c,d), d(a,c)+d(b,d)d(a,c)+d(b,d) and d(a,d)+d(b,c)d(a,d)+d(b,c) as S1≥S2≥S3S_1\ge S_2\ge S_3. The quadruple value is (S1−S2)/2(S_1-S_2)/2 and δ\delta is the maximum over quadruples. A tree with path distances has δ=0\delta=0. For large graphs quadruples are sampled: the sample maximum is a lower bound on the exhaustive maximum, not an unbiased estimate.

Scale matters: multiplying all lengths by cc also multiplies δ\delta. Compare with a characteristic length and inspect cycles, communities and distance distribution. A disconnected graph has infinite intercomponent distances; restrict measurement to a connected component or explicitly define another metric.

The four-point condition does not label each graph “hyperbolic” or “not hyperbolic” independently of scale. A four-edge cycle has two sums equal to two and one equal to four, so δ\delta is one in edge units. A tree has its two largest sums equal for every quadruple. Adding shortcuts or cycles can change that maximum, but a small sample of quadruples may omit the region attaining it. Report sample count, seed and a graph-size measure alongside the figure.

Distortion, scale and precision

Tree embedding distortion compares all pair distances after permitting a global scale. If rij=demb(i,j)/dT(i,j)r_{ij}=d_{\text{emb}}(i,j)/d_T(i,j), one multiplicative measure is max⁡rij/min⁡rij\max r_{ij}/\min r_{ij}. A combinatorial embedding of trees in the hyperbolic plane can achieve distortion arbitrarily close to one at the cost of scale and precision, as analyzed by De Sa and colleagues. This does not mean fixed-precision floats can represent arbitrary depth.

The geometric reason appears when comparing growth. A branching-b>1b>1 tree has bkb^k nodes at depth kk; in the Euclidean plane a radius-RR circumference grows proportionally to RR. In the hyperbolic plane of curvature −1-1 that length is 2πsinh⁡R2\pi\sinh R and grows approximately as πeR\pi e^R. If depth is represented by proportional radius, angular space accommodates many more descendants. This motivates a geometry choice but does not itself show a trained embedding achieves low distortion: branch separation and optimization also matter.

Multiplicative distortion divides maximum expansion by minimum. Uniform scale changes all ratios by the same factor and not their ratio. If distinct tree points collapse to one target point, the minimum ratio is zero and distortion becomes infinite. A reconstruction loss looking only at edges can bring neighbors close while collapsing distant branches; the figure therefore measures all pairs and the lab evaluates additional candidates.

InteractiveOne tree, two metrics
Euclidean planeHyperbolic disk
2
3
1.2
0.00
0.00
Nodes15
Euclidean distortion3.85
Hyperbolic distortion3.33
This explicit radial construction assigns angles by subtree and radii proportional to depth in each geometry. Compare all-pair distortion and shift the disk: the isometry does not change hyperbolic distances. Drawn edges are connecting segments, not geodesics; the construction is not intended to be optimal or implement Sarkar.

For radial distance RR, disk coordinate has radius tanh⁡(R/2)\tanh(R/2) and 1−tanh⁡(R/2)∼2e−R1-\tanh(R/2)\sim2e^{-R}. Boundary margin decreases exponentially: representing that margin near one needs approximately R/ln⁡2R/\ln 2 significand bits, plus constants and safety margin. Depth alone does not fix RR: it depends on chosen edge length and construction. In Lorentz, coordinates grow as eRe^R and other losses from cancellation and overflow appear; changing model does not remove all numerical difficulty.

Optimizing in the ball

Poincaré embeddings learn positions to bring related nodes together and separate negatives. A distance-based ranking loss can use positive neighbors and negative samples; sampling policy and candidate set are part of the result. Nickel and Kiela use Riemannian optimization for hierarchies.

If ff is expressed in ball coordinates, its Riemannian gradient is grad⁡Rf=λx−2∇Ef=((1−∥x∥2)2/4)∇Ef\operatorname{grad}_R f=\lambda_{\vb{x}}^{-2}\nabla_E f=((1-\norm{\vb{x}}^2)^2/4)\nabla_E f. An approximate Riemannian SGD step can use a retraction and project to radius less than one. Projection avoids invalid coordinates but changes the algorithm if frequently active; record its rate and use sufficient precision. The Lorentz model has other operations and stability problems; Nickel and Kiela compare both experimentally.

The formula follows directly from the gradient definition. For any tangent vector v\vb{v}, the differential satisfies  ⁣df(v)=∇Ef⊤v=gx(grad⁡Rf,v)\dd f(\vb{v})=\nabla_E f\T\vb{v}=g_{\vb{x}}(\operatorname{grad}_R f,\vb{v}). In the ball, gx=λx2Ig_{\vb{x}}=\lambda_{\vb{x}}^2 I, so the vector satisfying that equality is the coordinate gradient multiplied by λx−2\lambda_{\vb{x}}^{-2}. Near the boundary the factor decreases: a small Euclidean displacement represents a larger hyperbolic distance. Rescaling corrects the local metric but does not eliminate learning-rate choice or guarantee a discrete update remains inside the ball.

Distinguish two update forms. The exponential map advances along the geodesic from the chosen tangent vector and defines an exact geometric step. Adding coordinates and projecting into the domain is simpler and may approximate a small step, but active projection changes the trajectory. In both cases direction depends on the Riemannian gradient; a Euclidean update followed by clipping is not by itself the same rule. Also check near-zero distances, where a direct gradient formula may divide by a small quantity and needs its limit or numerical protection.

InteractiveTwo gradients, one loss
  • ordinary SGD
  • Riemannian SGD
0.12
5
Riemannian loss0.007
Ordinary SGDleft the ball
Optimize a minimal taxonomy of one root and two children; the largest point is the root. Ordinary SGD uses the coordinate gradient and stops if it leaves the disk; the other rescales by the metric and projects if needed. Lines connect positions; they are not geodesics.

The loss penalizes each root-child distance differing from 0.8 and sibling distance below 1.5. This is a deliberately small task, with all three points learnable and the same initialization for both optimizers. Each step uses full loss on three pairs: full-batch descent, a deterministic case of SGD without minibatch sampling. An additive step with radial projection when needed is used, not an exact exponential-map update. Trajectories use analytic gradients checked by finite differences; they do not represent the lab’s WordNet training.

Layers and products

Hyperbolic neural layers need to define operations on a manifold. One option maps features to tangent space with log⁡\log, applies a transformation or sum there, and returns via exp⁡\exp. Aggregation in TxT_{\vb{x}} depends on base point and parallel transport matters when combining vectors from different tangent spaces. Möbius addition is another geometric operation, not ordinary Euclidean addition. HNN constructs disk operations and HGCN uses the hyperboloid and learnable-curvature layers.

Mixed-curvature product spaces combine hyperbolic, Euclidean or spherical components. Under the product metric, squared distance sums squared distances in each factor. A deep taxonomy suggests trying negative curvature; dense communities may need other factors and a sensor mesh may be locally approximated well by flat geometry. These are hypotheses for comparison under the same protocol and budget, not an infallible classification rule.

For example, a product representation can reserve a hyperbolic component for hierarchy and a Euclidean one for continuous variation within each branch. Total distance combines both contributions, but the network may ignore a factor if its parameters or scales favor that. Measure each component’s norm, test single-factor ablations and match baseline parameter counts. Curvature, dimension and learning rate interact: changing only geometry without tuning the rest means an AUC difference does not identify one cause.

Precision also affects optimization. Near the ball boundary the distance denominator contains 1−∥x∥21-\norm{\vb{x}}^2; rounding a norm to one can make an operation nonfinite. Projecting to an interior radius avoids that invalid input but introduces a precision-dependent threshold. When comparing float32 and float64, use the same seeds and initializations before conversion, record projections and check finite values as well as final metric. Equal AUC does not imply gradients or distances match digit by digit.

Lab: distances and WordNet reconstruction

The following edge table is a breadth-first spanning tree of 120 noun synsets descending from animal.n.01 in WordNet 3.0. A taxonomy can have multiple hypernyms: here only the first encountered parent is retained to study a tree, so the task does not represent the full taxonomy. Download the table with identifiers and words and the WordNet license. Code reproduces all distances and trains both model types on the same edges and candidates.

[ ]Data and geometric functionsBrowser
import numpy as np
from scipy.special import expit
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import shortest_path

edges = np.array([[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[0,10],[0,11],[0,12],[0,13],[0,14],[0,15],[0,16],[0,17],[0,18],[0,19],[0,20],[0,21],[0,22],[0,23],[0,24],[0,25],[0,26],[0,27],[0,28],[0,29],[0,30],[0,31],[0,32],[0,33],[0,34],[0,35],[0,36],[0,37],[0,38],[0,39],[0,40],[0,41],[0,42],[0,43],[0,44],[0,45],[0,46],[0,47],[1,48],[10,49],[11,50],[11,51],[12,52],[12,53],[12,54],[12,55],[12,56],[12,57],[19,58],[20,59],[20,60],[20,61],[20,62],[21,63],[21,64],[21,65],[21,66],[23,67],[23,68],[23,69],[23,70],[23,71],[23,72],[33,73],[33,74],[33,75],[34,76],[34,77],[34,78],[35,79],[35,80],[35,81],[35,82],[35,83],[35,84],[35,85],[35,86],[35,87],[35,88],[35,89],[35,90],[35,91],[35,92],[35,93],[35,94],[35,95],[38,96],[40,97],[40,98],[43,99],[43,100],[43,101],[43,102],[43,103],[43,104],[43,105],[43,106],[43,107],[43,108],[43,109],[43,110],[43,111],[43,112],[43,113],[43,114],[43,115],[44,116],[44,117],[44,118],[50,119]], dtype=int)
n = 120
neighbors = [set() for _ in range(n)]
for a,b in edges:
    neighbors[a].add(int(b)); neighbors[b].add(int(a))
graph = coo_matrix((np.ones(2*len(edges)),
    (np.r_[edges[:,0],edges[:,1]],np.r_[edges[:,1],edges[:,0]])),shape=(n,n)).tocsr()
D = shortest_path(graph, directed=False, unweighted=True)

def lorentz_dot(x,y):
    return -x[...,0]*y[...,0] + np.sum(x[...,1:]*y[...,1:],axis=-1)

def to_lorentz(x):
    r2 = np.sum(x*x,axis=-1,keepdims=True)
    if np.any(r2 >= 1): raise ValueError('Fuera de la bola')
    return np.concatenate(((1+r2)/(1-r2),2*x/(1-r2)),axis=-1)

def distance_ball(x,y):
    x,y=np.asarray(x),np.asarray(y)
    a=1-np.sum(x*x,axis=-1); b=1-np.sum(y*y,axis=-1)
    if np.any(a<=0) or np.any(b<=0): raise ValueError('Fuera de la bola')
    return np.arccosh(np.maximum(1,1+2*np.sum((x-y)**2,axis=-1)/(a*b)))

x=np.array([0.9,0.0]); y=np.array([0.0,0.9])
print('distancias:', distance_ball(np.zeros(2),x), distance_ball(x,y))
print('Lorentz coincide:', np.allclose(distance_ball(x,y),np.arccosh(-lorentz_dot(to_lorentz(x),to_lorentz(y)))))

Four-point computation can enumerate everything for a small graph or sample for a larger one. Quadruples here use distinct indices and a sample result is a lower bound on the true maximum.

[ ]Four pointsBrowser
def gromov_delta(D, samples=None, seed=1):
    import itertools
    N=len(D)
    if not np.all(np.isfinite(D)): raise ValueError('La métrica debe ser finita')
    if samples is None:
        quads=itertools.combinations(range(N),4)
    else:
        rng=np.random.default_rng(seed)
        quads=(rng.choice(N,4,replace=False) for _ in range(samples))
    largest=0.0
    for a,b,c,d in quads:
        sums=sorted((D[a,b]+D[c,d],D[a,c]+D[b,d],D[a,d]+D[b,c]))
        largest=max(largest,(sums[2]-sums[1])/2)
    return largest

print('delta de la muestra del árbol:',gromov_delta(D,2000))
cycle = np.array([[min(abs(i-j),4-abs(i-j)) for j in range(4)] for i in range(4)],float)
print('delta del ciclo de cuatro:',gromov_delta(cycle))

Sarkar’s construction places each child at hyperbolic distance τ\tau from its parent. It moves the parent to the origin by a Möbius isometry, leaves the grandparent in one direction and distributes children in equally spaced directions relative to it; then it undoes the isometry. The root has no grandparent, so it distributes children around the origin. De Sa et al. describe this construction and its distortion-precision tradeoff.

[ ]Sarkar construction on the reduced taxonomyBrowser
def mobius(x,y):
    xx=x@x; yy=y@y; xy=x@y
    return ((1+2*xy+yy)*x+(1-xx)*y)/(1+2*xy+xx*yy)

def sarkar_tree(edges,tau):
    children=[[] for _ in range(n)]; parent=np.full(n,-1,int)
    for a,b in edges: children[a].append(int(b));parent[b]=int(a)
    if parent[0]!=-1 or np.any(parent[1:]<0): raise ValueError('Se necesita árbol enraizado en 0')
    X=np.zeros((n,2)); radius=np.tanh(tau/2)
    queue=[0]
    while queue:
        a=queue.pop(0); kids=children[a]
        if not kids:continue
        if a==0:
            angles=2*np.pi*np.arange(len(kids))/len(kids)
        else:
            z=mobius(-X[a],X[parent[a]])
            angle=np.arctan2(z[1],z[0]); degree=len(kids)+1
            angles=angle+2*np.pi*np.arange(1,len(kids)+1)/degree
        for child,theta in zip(kids,angles):
            X[child]=mobius(X[a],radius*np.array([np.cos(theta),np.sin(theta)]))
            queue.append(child)
    if np.any(np.linalg.norm(X,axis=1)>=1):raise FloatingPointError('La precisión agotó el margen al borde')
    return X

for tau in (1.0,2.0,4.0,6.0):
    Xs=sarkar_tree(edges,tau)
    i,j=np.triu_indices(n,1)
    embedded=distance_ball(Xs[i],Xs[j])
    ratio=embedded/D[i,j]
    lengths=distance_ball(Xs[edges[:,0]],Xs[edges[:,1]])
    print('tau',tau,'distorsión',round(ratio.max()/ratio.min(),4),
          'error máximo de arista',round(np.max(np.abs(lengths-tau)),10),
          'margen mínimo',round(np.min(1-np.linalg.norm(Xs,axis=1)),10))

The scale factor can improve global distortion while pushing points toward the boundary. The experiment computes all pairs of this tree; precision limits are specific to its depth and float64, not a guarantee for larger trees.

Train with logistic loss on a positive edge and a nonneighbor node as negative. Distance and gradient are calculated directly; ball gradient is rescaled by inverse metric before update. Boundary normalization is a numerical safeguard, not an exact solution of the geodesic equation. Seeds and step counts match for reproducible comparison, though they do not guarantee each method received the best hyperparameter search.

[ ]Gradients and optimizerBrowser
def pair_distance_grad(x,y,kind):
    diff=x-y
    sq=np.sum(diff*diff,axis=1)
    if kind=='euclid':
        dist=np.sqrt(np.maximum(sq,1e-12))
        gx=diff/dist[:,None]
        return dist,gx,-gx
    a=1-np.sum(x*x,axis=1); b=1-np.sum(y*y,axis=1)
    z=1+2*sq/(a*b)
    denom=np.sqrt(np.maximum(z*z-1,1e-12))
    gx=(4*diff/(a*b)[:,None]+4*sq[:,None]*x/(a*a*b)[:,None])/denom[:,None]
    gy=(-4*diff/(a*b)[:,None]+4*sq[:,None]*y/(a*b*b)[:,None])/denom[:,None]
    return np.arccosh(np.maximum(z,1)),gx,gy

def train_embedding(dim,kind,steps=1200,seed=17):
    rng=np.random.default_rng(seed)
    X=rng.normal(0,0.01,(n,dim))
    directed=np.vstack((edges,edges[:,::-1]))
    adjacent=graph.toarray().astype(bool)
    clipped=0
    for step in range(steps):
        batch=directed[rng.integers(len(directed),size=64)]
        i,j=batch[:,0],batch[:,1]
        k=rng.integers(n,size=len(i))
        invalid=(k==i)|adjacent[i,k]
        while invalid.any():
            k[invalid]=rng.integers(n,size=int(invalid.sum()))
            invalid=(k==i)|adjacent[i,k]
        dp,gpi,gpj=pair_distance_grad(X[i],X[j],kind)
        dn,gni,gnk=pair_distance_grad(X[i],X[k],kind)
        weight=expit(dp-dn+1)/len(i)
        grad=np.zeros_like(X)
        np.add.at(grad,i,weight[:,None]*(gpi-gni))
        np.add.at(grad,j,weight[:,None]*gpj)
        np.add.at(grad,k,-weight[:,None]*gnk)
        if kind=='poincare': grad*=((1-np.sum(X*X,axis=1))**2/4)[:,None]
        X-=0.15*grad
        if kind=='poincare':
            norms=np.linalg.norm(X,axis=1)
            clipped+=int(np.sum(norms>=0.999))
            X*=np.minimum(1,0.999/np.maximum(norms,1e-15))[:,None]
    return X,clipped

def reconstruction_map(X,kind):
    scores=[]
    for i in range(n):
        idx=np.array([j for j in range(n) if j!=i])
        dist,_gx,_gy=pair_distance_grad(np.repeat(X[i:i+1],len(idx),axis=0),X[idx],kind)
        order=idx[np.argsort(dist)]
        hits=np.array([j in neighbors[i] for j in order],dtype=float)
        scores.append(np.sum(np.cumsum(hits)*hits/np.arange(1,len(order)+1))/len(neighbors[i]))
    return np.mean(scores)

Before trusting the optimizer, compare both derivatives with central differences at interior points. This does not replace a proof but detects sign and factor errors in implementation.

[ ]Check the gradientBrowser
x=np.array([[0.2,-0.1]]); y=np.array([[-0.3,0.15]])
eps=1e-6
for kind in ('euclid','poincare'):
    _,g,_=pair_distance_grad(x,y,kind)
    numeric=np.zeros_like(x)
    for k in range(x.shape[1]):
        step=np.zeros_like(x); step[0,k]=eps
        numeric[0,k]=(pair_distance_grad(x+step,y,kind)[0][0]
                     -pair_distance_grad(x-step,y,kind)[0][0])/(2*eps)
    print(kind,'error máximo',np.max(np.abs(g-numeric)))
[ ]Dimension twoBrowser
for kind in ('euclid','poincare'):
    emb,clip=train_embedding(2,kind)
    print(kind, 'MAP',round(reconstruction_map(emb,kind),4),'proyecciones',clip)
[ ]Dimension fiveBrowser
for kind in ('euclid','poincare'):
    emb,clip=train_embedding(5,kind)
    print(kind, 'MAP',round(reconstruction_map(emb,kind),4),'proyecciones',clip)
[ ]Dimension tenBrowser
for kind in ('euclid','poincare'):
    emb,clip=train_embedding(10,kind)
    print(kind, 'MAP',round(reconstruction_map(emb,kind),4),'proyecciones',clip)

MAP measures reconstruction of those same observed edges, not unseen link prediction. All remaining nodes are candidates and the node itself is excluded. Generalization comparison requires splitting edges without leaking information into training, controlling connectivity and choosing negatives and seed according to the problem. Repeat training and tune both models with the same budget before attributing differences to curvature.

A node’s average precision is obtained by traversing its candidates sorted by distance and averaging cumulative precision at true-neighbor positions. MAP averages those precisions over nodes with at least one neighbor. A node with few neighbors and one with many each contribute once; another weighting answers another question. If the task requires retrieving transitive ancestors, this tree’s direct edges are not the correct label and positives and evaluation must both change.

In WordNet a synset may have multiple hypernyms. This tree retains the first parent encountered in search from the root and discards additional relations. That permits tree distances and unambiguous-parent Sarkar construction, but does not describe the full original taxonomy. Evaluation on the full graph must retain multiple relations and document how edges are held out without revealing their labels to the model.

Changing the hierarchy root or parent-selection criterion also changes the measured problem. Retain the node and edge manifest to compare runs on exactly the same structure.

hgcn_lab.py compares a Euclidean GCN with a simplified hyperbolic variant: it aggregates in the origin tangent space, projects with geoopt.PoincareBall.expmap0 and scores links by ball distance. Both are transductive, share a connected training graph and evaluate held-out edges against test nonedges. It requires PyTorch, NetworkX, NumPy and geoopt; it does not represent every HGCN layer or learnable curvature.

python hgcn_lab.py

In a geoopt 0.5.1 run on a tree with a leaf cycle and a grid, maximum δ\delta among 3000 sampled quadruples was 2.5 and 5.0 respectively. Link AUC on the former was 0.75 Euclidean, 0.71875 hyperbolic and 0.734375 for the hyperbolic-Euclidean product; on the grid it was approximately 0.9444, 0.8889 and 0.9444. Both cases repeated the same AUC in float32 and float64 with shared initialization, and test scores were finite. AUC ranks a small candidate set: equal AUC does not show numerical score equality. These are two synthetic graphs, one seed and one split, so they cannot decide when a geometry pays off in general.

The hgcn_manifold.py variant moves hyperbolic aggregation to each receiver’s tangent space: it applies log⁡xi(xj)\log_{\vb{x}_i}(\vb{x}_j) to every neighbor, aggregates those vectors and returns to the ball using exp⁡xi\exp_{\vb{x}_i}. Interlayer transformations are expressed in the origin tangent space. The mixed product combines this with a Euclidean factor; it remains a teaching version and does not reproduce every HGCN decision.

Run the variant with python hgcn_manifold.py; it saves each configuration in JSON and can resume pending ones. Argument --threads controls PyTorch parallelism and does not change update count.

With the same split and 250 updates, AUC on the tree with cycle was 0.75 for the Euclidean variant, 0.71875 in float32 and 0.703125 in float64 for local hyperbolic, and 0.765625 for mixed in both precisions. On the grid values were 0.94444, 0.83333 and 0.93056 respectively in both precisions. All evaluated scores were finite. The hyperbolic AUC difference on the first graph reminds us optimization trajectories can diverge when precision changes; it does not establish a specific cause. Values are one seed and few held-out links, not comparable to an extensive benchmark.

Exercises

ProofLorentz isometry
Prove: Prove hyperboloid distance invariance under a Lorentz transformation preserving its upper sheet.
0
Let A be linear, with AᵀJA = J and A(Hᵈ) = Hᵈ.

Step 1 of 2. What happens to the Lorentz product?

Numeric
In the ball of curvature −1, calculate the distance between the origin and (0.9, 0).
Numeric
Calculate the distance between (0.9, 0) and (0, 0.9) in the ball of curvature −1.
Numeric
A leaf is at radial distance R = 30 from the origin. If a uniform grid near the boundary has step 2⁻ᵖ, what is the minimum integer p such that the step does not exceed margin 1 − tanh(15)?
CodeMeasure hyperbolicity
Implement gromov_delta(D, quads) for a finite distance matrix and an iterable of distinct quadruples. Return the maximum half-difference between the two largest sums of the four-point condition; return zero if there are no quadruples.
import numpy as np

def gromov_delta(D, quads):
  pass
Shift+Enter to run
Quiz
Which statement on geometry choice is best justified?
Key idea
Curvature changes how available space grows. Using it requires correct geometric formulas together with explicit evaluation and numerical precision.