Suppose you're organising a product catalogue into categories and subcategories. Two items can be related because they share a category, while a broad category should also connect to many more specific ones below it. An embedding needs to preserve both kinds of relationship. Adding dimensions gives it more room, but choosing a geometry suited to a branching tree may let you represent the same hierarchy with far fewer coordinates.
We implement Nickel and Kiela's 2017 geometry to test how a hierarchy fits. Trees gain nodes exponentially with depth, and hyperbolic volume grows exponentially with radius, while fixed-dimensional Euclidean volume grows polynomially. The disc makes the fit inspectable. Refinement slows near its boundary. At radius 0.999, the update multiplier is 250,000 times smaller than at the centre.
On 1,170 WordNet mammal synsets, three hyperbolic dimensions beat 500 Euclidean ones under the same loss and budget. By five dimensions, mean rank reaches 1.15 and MAP 0.963. The hyperbolic fit then levels off while the Euclidean curve keeps improving. You will implement Riemannian SGD, plot the dimension comparisons and measure update and precision failures near the boundary.
Let's Build It
Open this in Google Colab and run it top to bottom.
Every point starts within a thousandth of the centre. Watch the tree push itself outward, fan into wedges, and then pile up against the rim. The view zooms out to follow it, and the caption on each frame gives the view radius, so the zoom is never silent.

The data is the standard benchmark: every synset under mammal.n.01 in WordNet, with the transitive closure of the hypernym relation as the training set. Every node is paired with each of its ancestors, all the way up to the root.
tree = mammals()
print(tree.summary())
# mammals: 1170 nodes, 6448 closure pairs, max depth 9
Start with the drawable case, two dimensions, 600 epochs, well under a minute:
cfg = TrainConfig(dim=2, geometry="hyperbolic", epochs=600, lr=2.0, batch_size=64)
fit, score = fit_and_score(tree, cfg)
print(f"mean rank {score.mean_rank:.2f} MAP {score.map_score:.3f}")
print(f"largest radius {float(fit.embeddings.norm(dim=1).max()):.6f}")
mean rank 3.13 MAP 0.727
largest radius 0.999990
Mean rank is the position of a true ancestor in the distance ranking against every node that is not an ancestor. Just over 3 out of 1,170 candidates, from two numbers per synset. Adding a third dimension takes it to 1.26, and a fifth to 1.15, which is where the geometry runs out of things to fix. Here is the two-dimensional case drawn twice.

Both panels hold the same numbers. The left panel plots the coordinates literally, and it is nearly useless, because a node at hyperbolic distance 8.7 from the centre and one at 12.2 both sit within a hundred-thousandth of the rim. The right one keeps every angle and replaces the drawn radius with hyperbolic distance, which is the quantity the model optimises. No point moved relative to any other. Nickel and Kiela's own Figure 2 shows the same thing happening to their embedding, and that distinction comes back below.
The wedges are the orders. Nothing told the model that carnivore.n.01 belongs closer to the middle than dog.n.01, and nothing told it that dogs and cats belong on the same side of the disc.
What Just Happened?
The mismatch between trees and flat space
Count the slots a tree needs, then count the room a geometry offers.
A ternary tree has nodes at depth . A circle of radius in the Euclidean plane has circumference , linear in . A circle of radius in the hyperbolic plane has circumference , exponential in .

Two of those three curves are the same shape. By depth 8 the tree needs 6,561 slots at that level, the hyperbolic circle offers about 9,366 units of circumference to spread them along, and the Euclidean circle offers 50. Push a tree into the plane and the level-8 nodes have to share, which in practice means cousins land on top of each other and the distances you wanted stop meaning anything.
Adding Euclidean dimensions buys room, but polynomially: a ball of radius in dimensions has volume proportional to . Against that is a losing race you can only postpone, and those 300-dimensional embeddings are postponing it.
The Poincaré disc
The model of hyperbolic space used here is the open unit disc, with a distance that is not the one your eyes report:
Where:
- is the ordinary squared distance you would measure with a ruler
- shrinks towards zero as approaches the rim
- dividing by two such terms makes the whole expression blow up near the edge
The rim is infinitely far from everywhere, so there is unlimited room out there. A point at Euclidean radius 0.5 is 1.10 units from the centre; at 0.99 it is 5.29; at 0.999 it is 7.60. Each factor-of-ten step towards the edge buys about 2.3 more units of distance, and the number of points you can place at that radius with a given separation grows with it.
def poincare_distance(u, v, eps=BALL_EPS):
sq_u = u.pow(2).sum(-1).clamp(max=1 - eps)
sq_v = v.pow(2).sum(-1).clamp(max=1 - eps)
sq_diff = (u - v).pow(2).sum(-1)
arg = 1 + 2 * sq_diff / ((1 - sq_u) * (1 - sq_v))
return torch.acosh(arg.clamp(min=1 + ACOSH_EPS))
The two clamp calls are not cosmetic. Without the first, a point that lands on the rim divides by zero. Without the second, floating-point error hands arcosh an argument below 1 and you get nan. Both failures show up within the first hundred steps.
Riemannian SGD in three lines
The gradient of the loss is a Euclidean object and the parameters live in a curved space, so a plain SGD step walks off the edge. Three lines fix it.
grad = table.grad
if cfg.geometry == "hyperbolic":
grad = grad * riemannian_rescale(table) # 1. rescale
table -= lr * grad # 2. step
if cfg.geometry == "hyperbolic":
table.copy_(project_to_ball(table, cfg.ball_eps)) # 3. project
The rescaling factor comes straight from the metric. The Poincaré metric is the Euclidean one multiplied by , so converting a Euclidean gradient into a Riemannian one divides by that:
That factor is 0.25 at the centre and 9.99e-7 at radius 0.999, so the geometry polices itself: the closer a point sits to the rim, the smaller its steps, and it takes a deliberate push to send anything over the edge. The projection is the backstop for when a large gradient manages it anyway.
Delete the rescaling and the first sizeable gradient throws points outside the disc, where is negative and the distance function returns nan. Delete the projection and the same thing happens more slowly. Both are one-line deletions worth making once, in the notebook, to see what the failure looks like.
The loss is the one from the paper: a softmax over negative distances, with one true ancestor against 50 sampled non-ancestors.
Nothing in it mentions depth, direction or the root. It only ever says "this pair is related and those fifty are not".
Depth, radius and the rim
The disc picture suggests a tidy story where radius reads off depth. The measurement is less tidy, and the gap is worth understanding.

The root sits at distance 0.06 and everything else is jammed against a ceiling of 12.21. That number is not a property of the tree. It is for the rim clamp , which is the largest distance from the centre the code allows. Correlation between depth and distance is 0.34, so the trained embedding carries the ordering as a weak trend rather than a readable coordinate.
It was not always this weak. Scoring every training snapshot shows a peak and a decline.

| Epoch | Mean rank | MAP | Depth against distance | Median distance |
|---|---|---|---|---|
| 50 | 121.58 | 0.135 | 0.29 | 2.30 |
| 100 | 65.93 | 0.182 | 0.31 | 4.33 |
| 200 | 8.15 | 0.441 | 0.62 | 8.73 |
| 350 | 3.33 | 0.703 | 0.47 | 11.77 |
| 600 | 3.13 | 0.727 | 0.34 | 12.21 |
Reconstruction improves monotonically. The radial ordering peaks at epoch 200 and then loses nearly half its strength, because the loss has no reason to stop pushing, since it only ever rewards separating related pairs from sampled unrelated ones, and moving further out is the cheapest way to keep doing that. Once the median node reaches the ceiling, radius stops distinguishing anything.
Nickel and Kiela's Figure 2 shows both ends of this without commenting on it. Their panel (a) is captioned "intermediate embedding after 20 epochs" and has structure spread through the disc; their panel (b) is "embedding after convergence" and has almost everything pressed onto the rim with the interior empty. The measurement above is what separates those two pictures, and it is why the intermediate one is the one everybody reproduces.
The mechanism behind the trend, while it lasts, is the argument for the whole method. A node with many descendants needs room around it for all of them, and the region near the rim has room, so a node is pushed outward in proportion to how much of the tree hangs below it. Being deep in the tree is the same thing as having little hanging below you.
The same logic explains the wedges, and the wedges survive the saturation. Two subtrees that share no members have every reason not to be near each other, since sharing a region means competing for the same room, so they settle on opposite sides of the disc. Angle keeps carrying the taxonomy long after radius has stopped carrying depth.
Going Deeper
Two dimensions against the ladder
Here is the comparison that decides whether any of this is worth the trouble. Same loss, same negatives, same epochs, same batch size, same learning rate, one line different: euclidean_distance in place of poincare_distance, and plain SGD in place of the Riemannian version. Three seeds at the low-dimensional hyperbolic points and either side of the crossover, one seed elsewhere.

| Geometry | Dimension | Mean rank | MAP |
|---|---|---|---|
| hyperbolic | 2 | 2.84 | 0.743 |
| hyperbolic | 3 | 1.26 | 0.949 |
| hyperbolic | 5 | 1.15 | 0.963 |
| hyperbolic | 10 | 1.11 | 0.965 |
| hyperbolic | 20 | 1.12 | 0.962 |
| Euclidean | 2 | 137.10 | 0.155 |
| Euclidean | 5 | 79.50 | 0.235 |
| Euclidean | 10 | 30.71 | 0.387 |
| Euclidean | 20 | 3.64 | 0.719 |
| Euclidean | 50 | 1.55 | 0.893 |
| Euclidean | 100 | 1.50 | 0.899 |
| Euclidean | 200 | 1.47 | 0.903 |
| Euclidean | 500 | 1.42 | 0.912 |
Three things fall out of that table, and the first is the headline.
Three hyperbolic dimensions beat five hundred Euclidean ones, 1.26 against 1.42 on mean rank and 0.949 against 0.912 on MAP. Both are seed-stable, the hyperbolic one to within 0.06 of mean rank across three seeds. Five hundred flat dimensions is more parameters than there are nodes in the tree, and it still loses to three.
The hyperbolic curve finishes and the Euclidean one does not. Hyperbolic reaches 1.15 at dimension 5 and then stops moving: 1.11 at 10, 1.12 at 20, all within seed noise of each other. Euclidean is still improving at 500 and the improvement has slowed to nothing useful, going 1.55, 1.50, 1.47, 1.42 across 50, 100, 200 and 500. One geometry solves the problem and stops, while the other buys diminishing returns for as long as you care to pay.
At matched dimension the gap is not close. Two against two is 2.84 versus 137.10. Five against five is 1.15 versus 79.50, a factor of 69. Ten against ten is 1.11 versus 30.71. The crossover only exists at all because Euclidean is allowed to spend ten to a hundred times the parameters.
Two comparisons anchor this against the literature. Nickel and Kiela's Figure 2 caption reports mean rank 1.26 and MAP 0.927 for a five-dimensional Poincaré embedding of this same mammals subtree; the implementation here reaches 1.15 and 0.963, so the from-scratch version lands slightly ahead of the published number on the same data. And their Table 1, on the full WordNet noun hierarchy of 82,115 nodes and 743,241 relations, records Euclidean at 200 dimensions on MAP 0.168 against Poincaré at 5 dimensions on 0.823. The shape here is theirs, compressed: at 1,170 nodes flat space stays in the race for longer than it does at 82,115, and it still never wins.
The one row worth hedging is the two-dimensional one. Averaged over three seeds it is ahead of Euclidean 20 and behind Euclidean 50, but it is the least stable measurement in the table, with mean rank spanning 1.02 across seeds, and the lead over Euclidean 20 swaps at a longer budget:
| Budget | 2-D hyperbolic | 20-D Euclidean |
|---|---|---|
| lr 2.0, 600 epochs | 2.84, MAP 0.743 | 3.64, MAP 0.719 |
| lr 1.0, 1,000 epochs | 2.94, MAP 0.729 | 4.24, MAP 0.691 |
| lr 2.0, 1,000 epochs | 3.14, MAP 0.729 | 2.38, MAP 0.800 |
Two dimensions is the drawable case, not the strong one. Reach for it when you want the picture, and for three or five when you want the embedding.
The gap as the tree deepens
Fixing the dimension and deepening the tree makes that dependence visible. Perfect binary trees from depth 4 to depth 9, which is 31 nodes up to 1,023, with the same training budget throughout.

| Tree depth | Nodes | Hyperbolic 2-D | Euclidean 2-D | Euclidean 10-D | Euclidean 50-D |
|---|---|---|---|---|---|
| 4 | 31 | 1.00 | 3.59 | 1.00 | 1.00 |
| 5 | 63 | 1.60 | 6.64 | 1.03 | 1.00 |
| 6 | 127 | 1.58 | 13.01 | 1.64 | 1.04 |
| 7 | 255 | 2.11 | 22.73 | 3.61 | 1.08 |
| 8 | 511 | 2.14 | 41.03 | 7.93 | 1.30 |
| 9 | 1,023 | 3.68 | 78.87 | 16.44 | 1.77 |
From depth 4 to depth 9, mean rank grows 3.7 times in two hyperbolic dimensions and 16 times in ten Euclidean ones. Ten flat dimensions start ahead and end well behind. Two flat dimensions were never in the race, which is the cleanest statement of the mismatch: the same two numbers per node buy a workable embedding in curved space and nothing at all in flat space.
Fifty flat dimensions hold up throughout, and that is the caveat worth carrying. If your hierarchy has a thousand nodes and you have fifty dimensions to spend, flat space will do the job. The argument for hyperbolic space gets stronger as the tree gets larger, deeper and more branching, and it is strongest of all when you want to look at the answer.
The rim
Two costs, both of them engineering problems, and the first has already shown up twice.

The step collapses. The rescaling that keeps points inside the disc falls off as the square of the gap to the rim, so each factor of ten closer costs two orders of magnitude of step size. At the centre it is 0.25; at radius 0.999 it is 9.99e-7, a factor of 250,000. Leaves settle early and then barely refine, which is why lr=2.0 here rather than the 0.1 you would use in flat space, and it is half the reason the radial ordering degrades after epoch 200.
float32 runs out of mantissa. The distance formula needs . In float32 the largest value below 1.0 is about 1 - 6e-8, so the term underflows for anything closer, and the function returns infinity:
| Gap to the rim | 1-r² in float32 | float32 distance | float64 distance | Exact |
|---|---|---|---|---|
| 1e-4 | 2.000e-4 | 19.8064 | 19.8069 | 19.8069 |
| 1e-6 | 2.027e-6 | 28.9909 | 29.0173 | 29.0173 |
| 1e-7 | 2.384e-7 | 33.2711 | 33.6225 | 33.6225 |
| 3e-8 | 1.192e-7 | 34.6574 | 36.0304 | 36.0304 |
| 1e-8 | 0 | inf | 38.2277 | 38.2277 |
The rim clamp defends against that, and it is not free. Loosening it buys real accuracy:
| Precision | Rim clamp | Mean rank | MAP | Largest radius reached |
|---|---|---|---|---|
| float32 | 1e-5 | 3.13 | 0.727 | 0.99999005 |
| float32 | 1e-7 | 2.50 | 0.808 | 0.99999923 |
| float64 | 1e-5 | 3.97 | 0.668 | 0.99999000 |
| float64 | 1e-9 | 3.01 | 0.775 | 0.99999988 |
Moving the clamp from the paper's to , which is as far as float32 goes, takes MAP from 0.727 to 0.808 on the identical model and the identical data. The two float64 rows say where that gain comes from. At the same clamp, float64 scores no better than float32, within the seed noise this model carries, and it only helps once the clamp moves out to . Precision is worth having because it lets the clamp move outward, and the extra room does the rest.
Sala et al. (2018) make the general version of this point. The bits needed to represent a hyperbolic embedding faithfully grow with the depth of the tree, so bit width is a resource you spend alongside dimensions, and two dimensions at float64 is not free the way two dimensions at float32 would be.
GPT-2's vocabulary as a tree
A tokeniser vocabulary carries a hierarchy nobody designed: the character prefix tree over its tokens, where every proper prefix is a node and a token's parent is the prefix one character shorter. The same code embeds it with no changes.
prefixes = gpt2_prefix_tree(1000) # the 1,000 commonest word-initial tokens
print(prefixes.summary())
# gpt2-prefixes: 1945 nodes, 8422 closure pairs, max depth 11

One wedge per initial letter, sub-wedges per second letter, whole words at the rim. Mean rank 3.80 and MAP 0.633 on a tree of 1,945 prefixes, from two numbers each, in 32 seconds.
The picture is the payoff here, and the metric is beside the point. A prefix tree is not a semantic hierarchy, so this particular embedding is not useful for anything downstream. What it shows is that the method needs no feature engineering and no notion of what the nodes mean: hand it a set of child-ancestor pairs and it will lay them out.
Four cases it does not fit
In rough order of how often they come up.
The data is not a hierarchy. The geometry encodes an assumption, and if the assumption is false you have paid for curvature and got nothing. A graph with cycles, a flat set of categories, a similarity matrix with no nesting: use Euclidean space. The cheap test is Gromov's -hyperbolicity, or checking whether a spanning tree explains most of the distances.
You need arithmetic on the embeddings. Averaging two Poincaré points is not the midpoint of the geodesic between them, dot products are not similarities, and standard cosine machinery does not apply. Ganea et al. (2018) rebuilt the layers you would need, and the reason that paper exists is that none of it comes for free.
Everything downstream expects Euclidean vectors. A vector index, a linear probe, a scikit-learn pipeline: all of them assume flat space. You can map out with the logarithmic map at the origin, and then you have flat vectors again with all the problems you started with.
The tree is deep and you are in float32. See the table above. Nickel and Kiela's own follow-up (2018) moves to the Lorentz model partly on these grounds, since it avoids the term entirely and stays well conditioned where the Poincaré ball does not.
Where This Comes From
Maximilian Nickel and Douwe Kiela introduced this in "Poincaré Embeddings for Learning Hierarchical Representations" (2017, arXiv:1705.08039), at Facebook AI Research. The framing in the abstract is the one worth keeping:
"we introduce a new approach for learning hierarchical representations of symbolic data by embedding them into hyperbolic space, or more precisely into an n-dimensional Poincaré ball. Due to the underlying hyperbolic geometry, this allows us to learn parsimonious representations of symbolic data by simultaneously capturing hierarchy and similarity."
Two words in that sentence do the work. Parsimonious is the dimension count, and it is the claim measured above. Simultaneously is the more interesting one: in the disc, the angle between two points carries similarity and the radius carries depth, so one embedding answers both questions without a second model. The measurements here bear out the angular half strongly and the radial half only up to a point, since a long run pushes almost everything to the same distance from the centre.
Their optimisation is the update reproduced here, from section 3.1:
with pulling any escaped point back to . Their is , which is the BALL_EPS used here, and their section 3.2 gives the rest of the recipe followed above: initialise uniformly in , then burn in at a tenth of the learning rate so the angular layout settles before the fast steps begin. Two deliberate departures: the burn-in runs for twenty epochs here rather than ten, and each positive pair is scored against 50 sampled negatives rather than the paper's 10, which is the setting their released implementation defaults to and which tightens the ranking the metrics measure.
Their reconstruction experiment is the one repeated above, on the full WordNet noun hierarchy rather than a corner of it. Table 1 records Euclidean at 200 dimensions on mean rank 1157.3 and MAP 0.168, against Poincaré at 5 dimensions on 4.9 and 0.823, and Poincaré barely moving from there to 200 dimensions (3.83 and 0.87). That flat Poincaré curve past dimension 5 is the same saturation measured above, seventy times larger.
The mammals subtree appears in their Figure 2 rather than as a row in Table 1, and its caption carries the one number this post can be checked against directly: mean rank 1.26 and MAP 0.927 at five dimensions.
Nickel and Kiela's follow-up, "Learning Continuous Hierarchies in the Lorentz Model of Hyperbolic Geometry" (2018, arXiv:1806.03417), swaps the Poincaré ball for the hyperboloid. The geometry is unchanged, and the arithmetic is better conditioned, which matters exactly where the float32 table above breaks.
Frederic Sala and colleagues wrote the analysis of what these embeddings cost in "Representation Tradeoffs for Hyperbolic Embeddings" (2018, arXiv:1804.03329). They give a combinatorial construction that needs no optimisation at all, and they quantify the precision requirement, which is bits in proportion to the tree's longest path. Read it before deploying any of this at scale.
Octavian Ganea, Gary Bécigneul and Thomas Hofmann built the rest of the toolkit in "Hyperbolic Neural Networks" (2018, arXiv:1805.09112): Möbius versions of matrix multiplication, bias addition, pointwise non-linearities and the softmax layer. If you want anything downstream of the embedding to stay in the disc, that paper is where the operators are.
Further reading
For a learned word-vector example, word2vec from scratch builds and inspects embeddings from a fixed corpus.
For searching embedding vectors, the HNSW Python tutorial measures the trade-off between recall and search cost.
The original: Nickel and Kiela (2017), sections 3 and 4 for the loss and the optimiser
The numerics: Nickel and Kiela (2018) for the Lorentz model, and Sala et al. (2018) for the precision analysis
The layers: Ganea et al. (2018), for building on top of the embedding without leaving the geometry
The reference implementation: facebookresearch/poincare-embeddings, the source of the burn-in and negative-sampling defaults used here
Next topic to learn: graph neural networks, for the case where the structure is a general graph with no tree in it
Interactive Tools
- Eigenvalue & SVD Visualiser: The flat-space version of the same question, where a matrix stretches the unit circle into an ellipse and the geometry stays Euclidean throughout
- Visual Sitemap Generator: Pulls a real hierarchy out of a website's URL structure, the kind of tree this method is built for
Related Posts
- PCA and SVD: The Linear Algebra You Actually Need: The standard route to a low-dimensional representation, and the flatness assumption this post drops
- LDA vs PCA: Supervised vs Unsupervised Reduction: Two more ways to choose the axes, both linear and both Euclidean
- Graph Neural Networks from Scratch: Message Passing: What to reach for when the structure is a general graph and the geometry cannot carry it
- Collaborative Filtering from Scratch in Python: Embeddings trained by the same recipe, negative sampling and all, on a relation with no hierarchy in it
- SVD for Recommender Systems: Matrix Factorisation in NumPy: The matrix-factorisation view of embedding a relation, for comparison with the geometric one





