Matryoshka Representations: Jointly Trained Nested Subspaces
One embedding whose every prefix is itself a usable representation — and the exact sense in which the linear version is just PCA
Overview & motivation
The PCA topic reduced an embedding cloud to dimensions by reading its covariance, and random projection reduced it with a fixed-width random map. Both produce a single target width: choose up front, and that is the representation you store. But a retriever often wants two widths at once — a short embedding to scan a billion candidates quickly, and a long one to score the survivors accurately — and re-encoding the whole corpus at a second width is exactly the cost we are trying to avoid.
Matryoshka Representation Learning answers this by training one embedding so that every prefix is itself a usable representation. Store the full -dimensional vector; retrieve with its first coordinates when speed matters and its full width when accuracy does, with no re-encoding, because the short representation is literally a slice of the long one. The name is the nesting dolls: , each a complete representation at its own resolution.
Before the algebra, drag the prefix-width slider and watch what nesting buys:
The first panel is the point of the whole method: the nested embedding’s recall holds up as you shrink the prefix, while a random rotation of the same embedding — identical full-width geometry — collapses to near chance at small widths. The second shows the geometric reason in the linear case: the nested basis sits exactly on the Eckart–Young optimum at every width. The third is the payoff — shortlist on a cheap prefix, rerank at full width, and recover almost all the recall for a fraction of the cost.
What we cover
- The Matryoshka objective: a weighted sum of per-granularity losses.
- The linear theorem — the jointly optimal nested basis is exactly PCA — and why.
- Weight invariance: PCA is the optimum for any granularity weighting.
- Why nesting must be trained, not assumed.
- Adaptive funnel retrieval, and the nonlinear contrastive case.
The Matryoshka objective
Fix an embedding dimension and a set of granularities — in practice the halving sequence . A Matryoshka model produces, for each input, one vector , and is trained so that every prefix is a good representation under a task loss . The objective is a weighted sum over the granularities,
The weights trade off the granularities; the single shared trunk producing is what forces the prefixes to nest, because the same early coordinates must serve every width at once. To see the geometry cleanly we specialize to linear reconstruction, where the answer is exact and familiar.
The linear theorem: Matryoshka is PCA
Let be the centered data and let the representation be a linear projection onto an orthonormal basis , so the prefix uses the first columns and reconstructs through the projector . Take to be the squared reconstruction error .
Theorem 1 (The linear Matryoshka optimum is PCA).
For the linear squared-reconstruction loss, the basis minimizing the joint objective , for any positive weights , is the PCA basis: the eigenvalue-ordered eigenvectors of the covariance , equivalently the right singular vectors of .
Proof.
Fix a single granularity . Minimizing over rank- orthonormal projectors is the Eckart–Young–Mirsky problem, whose minimizer is the top- PCA subspace and whose minimum value is the tail . Call that per-granularity minimum .
The decisive structural fact is nestedness: the top- principal subspace is contained in the top- principal subspace, because both are spanned by a prefix of the same eigenvalue-ordered list . So a single ordered basis has the property that its first columns span exactly the top- subspace, for every at once. Therefore attains at every granularity simultaneously, and
for any orthonormal , since termwise and . This is exactly what a non-nested basis cannot do: a tuned to be optimal at one width has, in general, suboptimal prefixes at the others, because its top- subspaces are not nested. Only the eigenvalue-ordered basis is optimal at all widths at once, so it is the joint minimizer.
∎The reading to keep is that PCA already is a nested representation — its top- subspaces are the original matryoshka dolls — and the linear Matryoshka objective simply rediscovers it. What Matryoshka adds, in the nonlinear case below, is the same nested structure for a representation optimized against a retrieval loss rather than reconstruction. The companion harness confirms the theorem to the decimal: the PCA prefix reconstruction error equals the Eckart–Young rank- optimum at every granularity, while a random orthonormal basis is far worse.
The optimum does not depend on the weighting
A natural worry is that the granularity weights should change the answer — favor short prefixes and surely the basis should tilt toward them. In the linear case they do not.
Proposition 1 (Weight invariance of the nested optimum).
Because the PCA basis attains the per-granularity optimum at every , the joint loss it achieves equals , which is the smallest value the weighted sum can take for those weights. Hence the PCA basis is the joint minimizer for every choice of positive weights — the optimal nested basis is weight-invariant.
Proof.
The quantity is a lower bound on for any , because each term is bounded below by . The PCA basis meets this lower bound exactly (Theorem 1), so it is optimal, and the bound — and the minimizer that meets it — do not depend on the beyond their positivity. The harness verifies this over randomly drawn weight vectors: the PCA joint loss equals the weighted sum of the per- optima every time.
∎This is a comforting sanity check and a warning at once. Comforting, because in the linear world you never have to tune the weights. A warning, because it is a symptom of the linear case being too easy: the weighting only starts to matter when the per-granularity optima cannot all be achieved by one basis, which is precisely the nonlinear regime where Matryoshka earns its keep.
Nesting must be trained
Here is the fact that keeps Matryoshka from being trivial, and it is best seen by trying to fake it. Take the nested embedding and apply a random rotation to produce . Rotation is an isometry, so it preserves every full-width distance exactly — at the two embeddings retrieve identically. But smears the information that lived in the early coordinates of across all of them, so its prefixes are arbitrary mixtures.
The retrieval consequence is stark. On the finance cloud, the nested embedding’s first coordinates retrieve at about recall@10; the rotated embedding’s first coordinates, with identical full-width geometry, retrieve at about — barely above chance. The “Prefix recall” panel shows the two curves: the nested one rises fast and plateaus near the intrinsic dimension of the cloud, while the rotated one crawls along the bottom until almost every coordinate is restored. Nesting is not a property an embedding has for free; it is a property the training must put there, by forcing the shared trunk to load the most useful directions into the earliest coordinates. In the linear case that loading is the eigenvalue ordering; in the nonlinear case it is what the multi-granularity loss trains.
Adaptive retrieval, and the nonlinear case
The practical reward is adaptive, or funnel, retrieval. Shortlist candidates cheaply using a short prefix, then rerank only the shortlist at full width. The first stage scores every document on dimensions and the second scores a handful on all , so the cost is a small fraction of an exhaustive full-width scan while the recall is nearly unchanged — the short prefix is good enough to retrieve the right candidates even when it is not good enough to order them, and the full-width rerank fixes the order. On the finance cloud, shortlisting on a -dimensional prefix and reranking at recovers of the exhaustive recall@10 at under of the scoring cost; the “Adaptive funnel” panel traces the recall-versus-cost frontier as the shortlist grows.
The version that matters in practice is nonlinear and contrastive. Real Matryoshka encoders replace the reconstruction loss with a contrastive objective — pull a query toward its relevant document and push it from negatives — applied at each prefix width and summed, . That contrastive loss is the subject of a forthcoming neural-retrieval topic; here we only note its role. With it, the headline empirical results hold — a nonlinear Matryoshka embedding matches a full-width model’s accuracy at a fraction of the dimensions, and the jointly trained prefixes beat heads trained independently at each width. We are careful to call these empirical: there is no general theorem that joint training dominates independent heads, and the clean optimality we proved is special to the linear case. What carries over is the geometry — coordinates ordered by usefulness, prefixes that nest — which the linear theorem shows is not magic but the natural generalization of PCA.
Finance case study
Honest caveats
Implementation
The companion module matryoshka_nested_representations.py owns every number this page and the laboratory cite. Its seven assertions encode the claims in order: the linear Matryoshka optimum is PCA (the prefix reconstruction equals the Eckart–Young rank- optimum at every granularity, to the decimal); weight invariance (the PCA joint loss equals the weighted sum of per- optima for random weightings); prefix-recall monotonicity; the trained-nesting gap (a random rotation preserves full-width recall but collapses the prefixes); funnel retrieval (near-full recall at a fraction of the cost); a scikit-learn cross-check of the nested basis; and the finance headline. A subtlety worth flagging, since it bit during development: the synthetic corpus must have more points than dimensions for PCA to return a full-width -dimensional basis, so the finance cloud uses . Both the module and the narrative notebook run in about five seconds and must exit cleanly before the topic ships.
Connections
- this topic generalizes PCA's central optimality from variance to an arbitrary task loss: PCA's nested top-k subspaces, each the Eckart-Young rank-k optimum proved there, are exactly the linear Matryoshka optimum, so the nested-subspace structure that PCA gives for reconstruction is the structure Matryoshka trains for retrieval, and in the linear case the two coincide pca-dimensionality-reduction
References & Further Reading
- paper Matryoshka Representation Learning — Kusupati, Bhatt, Rege, Wallingford, Sinha, Ramanujan, Howard-Snyder, Chen, Kakade, Jain & Farhadi (2022) The original method: train one embedding whose nested prefixes are each usable, via a summed multi-granularity loss
- paper The Approximation of One Matrix by Another of Lower Rank — Eckart & Young (1936) The rank-m reconstruction optimum that each Matryoshka granularity term inherits — the per-m half of the linear theorem
- book Matrix Analysis — Horn & Johnson (2013) Eckart-Young-Mirsky and the nestedness of the dominant invariant subspaces the joint optimality turns on
- paper Representation Learning with Contrastive Predictive Coding — van den Oord, Li & Vinyals (2018) The InfoNCE contrastive objective the nonlinear Matryoshka loss applies at each prefix width — the forthcoming neural-retrieval topic
- book Principal Component Analysis — Jolliffe (2002) Nested principal subspaces and component retention — the classical structure the linear theorem rests on
- documentation New Embedding Models and API Updates (text-embedding-3) — OpenAI (2024) Production Matryoshka: the embeddings expose a dimension parameter that truncates the nested representation
- paper Nomic Embed: Training a Reproducible Long Context Text Embedder — Nussbaum, Morris, Duderstadt & Mulyar (2024) An open Matryoshka-trained text embedder — the nested-prefix recipe applied to a real encoder