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
- 25Riemannian metric and geodesicsSmooth manifolds and tangent spacesEncoder-decoder framework for node embeddingsGCN propagation ruleKnowledge graph as relational multigraphNetwork statistics
- 24Optimization on manifolds via retraction
- 06Stochastic gradient descentAdam
- 02Quadratic formInner product
- 09Floating-point representationSubnormals, infinities and NaNIEEE 754 and deep learning formats
When a hierarchy runs out of space
A binary tree of depth has leaves. In fixed Euclidean dimension the volume of a radius- ball grows as ; in the hyperbolic plane of curvature , a radius- circle has length . 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 , a packing argument bounds the number of sufficiently separated points by a power of , 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 in different coordinates. In ball , the metric is with . Distance is
In particular, . 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.
In Lorentz we use and upper hyperboloid , . Its distance is . Coordinates convert via
For , with , the exponential map is , with continuous limit at zero. For , . The vector is tangent because its Lorentz product with vanishes. At the ball origin, and , with limits at zero. Riemannian norm at the origin is ; 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 , order the three sums , and as . The quadruple value is and is the maximum over quadruples. A tree with path distances has . 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 also multiplies . 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 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 , one multiplicative measure is . 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- tree has nodes at depth ; in the Euclidean plane a radius- circumference grows proportionally to . In the hyperbolic plane of curvature that length is and grows approximately as . 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.
For radial distance , disk coordinate has radius and . Boundary margin decreases exponentially: representing that margin near one needs approximately significand bits, plus constants and safety margin. Depth alone does not fix : it depends on chosen edge length and construction. In Lorentz, coordinates grow as 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 is expressed in ball coordinates, its Riemannian gradient is . 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 , the differential satisfies . In the ball, , so the vector satisfying that equality is the coordinate gradient multiplied by . 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.
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 , applies a transformation or sum there, and returns via . Aggregation in 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 ; 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.
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.
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 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.
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.
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.
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)))for kind in ('euclid','poincare'):
emb,clip=train_embedding(2,kind)
print(kind, 'MAP',round(reconstruction_map(emb,kind),4),'proyecciones',clip)for kind in ('euclid','poincare'):
emb,clip=train_embedding(5,kind)
print(kind, 'MAP',round(reconstruction_map(emb,kind),4),'proyecciones',clip)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.
Links and precision in two families
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 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 to every neighbor, aggregates those vectors and returns to the ball using . 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
Step 1 of 2. What happens to the Lorentz product?
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