How Good Is the Best Key in a Cluster? Apple Amortizes Vector Search with Support Functions
IVF routes queries using centroids, which really compares the average inner product inside each cluster. Apple's ICML 2026 paper frames 'how good is the best key in a cluster' as a support function—using SupportNet for routing and KeyNet for query rewriting to pay search cost up front in offline training.
1. Which Step This Paper Tries to Save
The definition of Maximum Inner Product Search (MIPS) fits in one line: given a query vector and a set of keys , find the key with the largest inner product with .
This is the retrieval step in RAG: questions are encoded into , document passages into , and the passages with the highest inner products get stitched into the prompt. Brute force costs , which stops being viable per request once you have millions of passages and hundreds of dimensions—hence approximate indexes. The most common is the Inverted File Index (IVF): run k-means to partition keys into clusters, compare an incoming query against the centroids, pick the most promising clusters, and scan them exactly.
On November 5, the Apple Machine Learning Research blog published Faster Retrieval for Better, More Efficient RAG, summarizing their ICML 2026 paper Amortizing Maximum Inner Product Search with Learned Support Functions (by Theo X. Olausson, João Monteiro, Michal Klein, and Marco Cuturi; the first author is now at MIT and did this work during an internship at Apple), with code at apple/ml-amips.
After reading it, I think what's genuinely new here isn't "using neural networks to accelerate retrieval"—people have been doing that for years. What's new is first giving MIPS a name from convex analysis, and then letting both the network architecture and the training objective follow directly from that object's mathematical properties. It also puts front and center a premise that many indexing methods leave on the table: in production, the query distribution is usually stable, sampleable, and noticeably different from the key distribution. As the official blog puts it, RAG queries come from "short user-generated questions," whereas keys are "long, informative, and curated pieces of text."
"Amortized" means shifting search cost that would otherwise be paid repeatedly across many queries into a one-time offline training phase. The paper applies this in two places: IVF cluster selection, and the query vector itself.
2. Why Centroid Routing Picks the Wrong Cluster
Look at what IVF's cluster-selection rule actually compares. The centroid of cluster is . By linearity of the inner product,
In other words, the centroid score is the average inner product across the cluster. An average can never exceed the maximum—it's a lower bound, not an upper bound. What we actually want to know is "how good is the best key in this cluster?" Ranking clusters by their average only works reliably when the gap between the average and the maximum is roughly uniform across clusters. Yet that gap depends on how far a cluster stretches along the query direction: a compact cluster has a small gap, while an elongated cluster with one end reaching toward the query has a huge gap.
I wrote a quick 2D toy example to illustrate this. Two clusters: A is compact; B is elongated, with most points in the bottom-right and a single point reaching up. The query points straight up.
import numpy as np
# Two clusters: A is compact; B is elongated, mostly bottom-right with one point reaching up
A = np.array([[0.68, 0.48], [0.72, 0.52], [0.70, 0.46], [0.66, 0.54]])
B = np.array([[1.00, -0.40], [0.90, -0.30], [0.95, -0.35], [0.20, 0.85]])
q = np.array([0.0, 1.0]) # Query direction: straight up
def support(Y, x):
"""σ_Y(x) = max_y <x, y>"""
return (Y @ x).max()
for name, Y in [("A", A), ("B", B)]:
c = Y.mean(axis=0)
print(f"{name}: centroid={c.round(4)} <q,c>={q @ c:+.4f} "
f"σ(q)={support(Y, q):+.4f} gap={support(Y, q) - q @ c:.4f}")
# Centroid routing picks the cluster with largest <q,c>; exact routing picks the one with largest σ(q)
print("centroid routing ->", "AB"[np.argmax([q @ A.mean(0), q @ B.mean(0)])])
print("exact routing ->", "AB"[np.argmax([support(A, q), support(B, q)])])
# The gradient of σ is the optimal key: verify with central differences
allY, eps = np.vstack([A, B]), 1e-6
grad = np.array([(support(allY, q + eps * e) - support(allY, q - eps * e)) / (2 * eps)
for e in np.eye(2)])
print("numeric grad of σ at q:", grad.round(4), " argmax key:", allY[np.argmax(allY @ q)])Actual output on numpy 2.5.4:
A: centroid=[0.69 0.5 ] <q,c>=+0.5000 σ(q)=+0.5400 gap=0.0400
B: centroid=[ 0.7625 -0.05 ] <q,c>=-0.0500 σ(q)=+0.8500 gap=0.9000
centroid routing -> A
exact routing -> B
numeric grad of σ at q: [0.2 0.85] argmax key: [0.2 0.85]Cluster A has a gap of just 0.04; cluster B's gap is 0.90. Ranked by centroid, A wins in a landslide (0.50 vs. −0.05). Ranked by cluster maximum, B's 0.85 is the true answer. If you only probe one cluster, you miss the optimal key for this query. The last line is a small spoiler for Section 3: numerically differentiating the maximum inner product over the entire key set gives a gradient that equals the optimal key itself.
Of course, this 2D example is deliberately contrived. Real embeddings have hundreds of dimensions and k-means clusters aren't that extreme, but the underlying issue is the same: in high-dimensional space, cluster shapes vary widely, the gap between average and max changes with both query direction and cluster, and the centroid score is a biased estimator whose bias isn't even uniform. As the official blog states, the centroid alone "cannot account for the spread of its cluster."
Production systems have long used the simplest workaround: probe more clusters—i.e., crank up nprobe. The price is scanning proportionally more keys. What this paper aims to do is pick the right clusters without scanning more.
3. Support Functions: Writing "How Good Can a Cluster Get" as a Function
Treat the maximum inner product as a function of the query :
In convex analysis, this is the support function of the set . Geometrically, imagine pushing a line perpendicular to (a hyperplane in higher dimensions) along the direction of until it just grazes the convex hull of . The position where it makes contact corresponds to , and the vertex it touches is . The two horizontal dashed lines in the figure above are the supporting lines of the two clusters along . And precisely because only vertices of the convex hull can ever be touched, keys strictly inside the convex hull can never be the top match for any query.
The paper relies on three properties of , ordered here by how central they feel to me.
First, its gradient is the optimal key. Wherever the is unique,
This follows immediately from the envelope theorem: in a neighborhood of , coincides with the linear function , whose gradient is . That's what the numpy central-difference check above verified. Where the isn't unique (a tie between two or more keys), the function is non-differentiable and its subgradients are convex combinations of the tied keys. The function as a whole is piecewise linear, with each piece corresponding to the region where a particular key "wins." Figure 2 in the paper plots this: level sets on the left, and which key each query maps to on the right.
Second, it is convex. It is the pointwise maximum of linear functions, and taking a pointwise maximum preserves convexity. That means we can fit it with a class of networks that are convex by construction.
Third, it is positively 1-homogeneous. For any , : scaling the query by 2 doubles the maximum inner product without changing the best key. Homogeneous functions obey Euler's theorem:
Substitute the first property and the left-hand side becomes , so the identity holds trivially. This identity reappears later as a loss term for KeyNet.
Put all three together, and the neatest part is this: "score" and "optimal key" are no longer two separate targets to learn—they are the value and the gradient of the exact same function. Learn accurately enough, and you use its value for routing and its gradient to locate the key.
The paper also notes a connection to optimal transport: the map is the gradient of a convex function, making it a Brenier map by Brenier's theorem. Normally, when learning optimal transport maps, the convex potential is unknown and has to be inferred indirectly from samples. In MIPS, for any query you can exhaustively compute both the potential value and its gradient , so the authors frame it as a "supervised optimal transport learning problem." That lens doesn't change the engineering directly, but it explains why this research group (Cuturi is an optimal transport researcher) came at retrieval from this angle.
4. SupportNet: Why Input Convex Neural Networks
Since the target function is convex, pick a network architecture that can only represent convex functions. Input Convex Neural Networks (ICNNs, introduced by Amos et al. in 2017) fit that bill:
The hidden-to-hidden weights are required to be elementwise non-negative, and the activation is convex and non-decreasing. Taking non-negative weighted sums of convex functions and composing with a convex non-decreasing activation preserves convexity, so the entire network is convex with respect to its input . The direct input skip connections are left unconstrained to recover expressive power.
To me, using an ICNN buys two things. First, inductive bias: the hypothesis space is restricted to convex functions, so the network doesn't burn capacity learning "this thing is convex," and the gradient of a convex function is a monotone map—structurally the same kind of object as the true . Second, extrapolation behavior: on queries outside the training distribution, a convex network at least won't produce bizarre concave regions.
The paper isn't dogmatic about enforcing this as a hard constraint, though. Non-negativity is satisfied "loosely": instead of clipping weights, they add a penalty and use Hoedt and Klambauer's initialization so those weights start non-negative. Strictly speaking, a trained SupportNet is only "approximately convex." That feels like a pragmatic choice—hard clipping at hundreds of millions of parameters is likely painful to train—but it's worth keeping in mind when reading the results.
Two more details directly serve the properties from Section 3:
- Homogenization wrapper. For any base network , define , guaranteeing positive 1-homogeneity by construction. The paper notes this is more flexible than removing all biases and restricting to ReLU; SupportNet always uses this wrapper in their experiments.
- Activation function. Ground truth is piecewise linear, which points toward ReLU-like activations in theory; in practice, the paper uses a smooth leaky ReLU, with and , trading off between "sharp enough to look piecewise linear" and "clean gradient flow."
When used for routing, the network has outputs, where the -th output fits cluster 's support function . All clusters share a backbone, turning it into a multi-task regression problem over tasks. The training objective is a weighted sum of two losses:
Notice that the expectation is taken over —the actual query distribution—not over the entire ambient space. That is the crux of amortization: the network only needs to fit the support function accurately where queries actually show up. The paper's default weights are and , emphasizing gradient (key) reconstruction; ablations in Appendix A.6 show that adding a small score term noticeably reduces score error while leaving gradient error almost unchanged.
At query time, a single forward pass produces scores; you pick the top clusters and scan them exactly as usual. The routing question shifts from "how good is this cluster on average?" to "how good can the best key in this cluster be?"
Why use SupportNet for routing instead of KeyNet (coming up next)? The paper gives a concrete reason. KeyNet would have to output a -dimensional vector for every cluster, making the output layer ; by 128 clusters, the authors note KeyNet's output dimension becomes "too large to handle." SupportNet outputs just one scalar per cluster, so its output layer is . Conversely, extracting a key from SupportNet requires a backward pass to compute the gradient, which the paper says typically costs 1x to 2x a forward pass—so for predicting a single key over the whole set (), they switch to KeyNet.
5. KeyNet: Rewrite the Query, Leave the Index Alone
KeyNet takes a different tack: instead of learning the support function, directly regress the optimal key, . It uses the same MLP architecture with input skip connections as an ICNN, but drops all non-negativity constraints. Because its output is no longer guaranteed to be the gradient of a convex function, the paper adds a consistency loss derived from Euler's theorem:
What the second term says is: if truly is the gradient of some 1-homogeneous function, then its inner product with ought to equal that function's value. Without an explicit potential function, this identity nudges the network's output toward behaving like the gradient of a support function. Default weights are and .
How KeyNet gets deployed is, in my view, the most practical idea in the entire paper: take the predicted as a rewritten query and hand it straight to an off-the-shelf FAISS IVF index. No index rebuild, no changes to index code—just one forward pass sitting in front of it.
Why does this work? Here's how I think about it. When IVF builds an index, each key is assigned to a centroid according to the coarse quantizer's rule; at query time, the same rule runs again. So if a query happened to be one of the keys itself, the very first cell selected would be its own cell, and routing couldn't miss. The trouble is that queries aren't keys: short questions and long passages live in noticeably offset embedding distributions. Appendix A.10 of the paper checks this directly: on NQ and HotpotQA, the query distribution is visibly shifted relative to the keys, with several dense query regions lacking correspondingly dense key regions; on Quora (duplicate question retrieval), both queries and keys are short questions, so the two distributions sit close together. What KeyNet does is move the query into key territory—near the key it is most likely to match—and let IVF search from there. In the paper's words, is "by construction, closer to the true top key than x is."
This also explains a consistent pattern throughout the paper: the bigger the distribution shift, the more KeyNet helps. Gains are largest on NQ and HotpotQA, and saturate earliest on Quora. Appendix A.10 also reports the distribution of top-1 inner products: Quora has a mean of 0.86 and median of 0.88, while NQ and HotpotQA average 0.71 and 0.74. When the best match is already nearby, there's much less headroom to gain by moving the query.
There's one easy-to-miss detail that I marked with a dashed line in the diagram. The paper evaluates KeyNet with Recall@k, where ranges from 0.01% to 0.5% of the corpus size, checking whether the true optimal key shows up in the top neighbors of . That means it produces a candidate set. If I were putting this into production, I'd add an exact rescoring pass over those candidates using the original query . I added that step myself—the paper doesn't mention it—but without it, the final ranking criterion becomes "how close to the predicted point" rather than "how relevant to the question."
As for the numbers, I'll strictly relay what the sources report. On NQ (~2.6M passages), the official blog states that the largest KeyNet model reaches 99% recall in roughly one-eighth the time of raw queries (0.23 ms vs. 1.8 ms), and that latency includes KeyNet's own forward pass; measured by keys scanned, hitting 99% recall inspects roughly 11x fewer keys (0.009% vs. 0.10% of the corpus). The paper's appendix also pairs the same idea with ScaNN, SOAR, and LeanVec: the wins hold across medium budgets; in the very low-budget regime where the forward-pass cost isn't yet offset by index savings, raw queries stay competitive; and SOAR on Quora is largely saturated, with both curves overlapping.
On the SupportNet routing side, the official blog reports that on NQ with 128 clusters, a small SupportNet reaches 95% routing recall in 1.74 ms versus 3.36 ms for centroid routing (~1.9x faster). The main paper also uses NQ with 128 clusters, but with an 8-layer XS model trained on 1B samples and FLOPs on the x-axis: probing 1 cluster gets ~72% right versus ~56% for centroid routing, and probing 4 clusters hits ~95%, which takes centroid routing 16 clusters to match. These are all numbers from the paper and blog; I didn't run the benchmarks myself.
6. Does the Amortization Math Work Out?
Amortization means paying a large cost up front to save a little on every query. That raises three questions: how large is the upfront bill, under what conditions does it go stale, and do the savings actually pay it back?
What you pay offline. Every training query requires an exhaustive scan to find its optimal key in every cluster. The paper's data pipeline deduplicates and encodes queries, augments them with Gaussian noise (, re-normalized onto the unit sphere) to expand the query set 5x to 100x, and runs exact MIPS on each augmented query for labels. Training typically runs through 1B to 10B samples; Appendix A.7 sweeps training length on NQ and downstream metrics mostly level off after ~3B. I cross-checked the default config in the repo: trn_batch_size: 4096 times num_trn_steps: 732_421 comes out right around 3B, lining up with that finding. The paper doesn't report GPU-hours for training, so I can't estimate that part for them.
The models themselves aren't tiny either. The paper sizes parameter counts as a fraction of the corpus: , with XS through L at 1%, 5%, 10%, and 20%. Doing quick math for NQ (, ), , which puts XS at ~10M parameters and L at ~200M parameters. That's nothing dramatic for a GPU, but it means you now have a model sitting next to your index whose size scales with the corpus—when the corpus grows, the model has to grow with it. The paper's conclusion notes that small models (XS, S) give the best compute–recall tradeoff, while larger models only catch up when measured on wall-clock latency with GPU parallelism.
What happens when the corpus changes? This is what I care about most and what the paper says the least about—its stated setting is a "fixed key database." What follows is my own reasoning from the properties of support functions, not experimentally verified:
- Adding keys. Inserting a key into cluster changes the true support function to —it can only go up. A stale SupportNet will underestimate that cluster and might skip it. Fortunately, the fix is exact and cheap: hold newly added keys that haven't been trained into the model yet in a small buffer, and at query time score cluster as , paying only the cost of scanning the buffer. Retrain once the buffer reaches a size threshold.
- Deleting keys. The true support function can only go down, so a stale model overestimates. The consequence of overestimating is probing an extra cluster that wasn't worth probing—wasting a little compute—but since in-cluster scanning is exact, you won't return a deleted key and won't miss the real answer in another cluster (provided your probe budget has some slack). For routing, deletions are much safer than insertions.
- KeyNet is more fragile. It learns "where the optimal key for this question lives." If a newer, more relevant document gets added, KeyNet will still move the query near the old answer; if the new document happens to land in the same IVF cell you get lucky, otherwise it gets missed. On a fast-changing corpus, I'd lean toward SupportNet plus a buffer, or route only part of traffic through KeyNet while keeping the rest on raw queries.
What about query drift? Section 4.5 and Appendix A.2 test this by adding larger Gaussian noise to test queries ( from 0 to 0.06, versus 0.02 during training) before feeding them into FAISS IVF. Performance degrades, but it's "not catastrophic," and at it still outperforms raw queries across medium budgets. My take on that experiment: Gaussian noise is a gentle shift—it models "slightly different phrasing," not "a sudden wave of queries on brand-new topics." To their credit, the authors acknowledge in the appendix that data augmentation can mitigate this kind of degradation, but "would not render the model robust to other types of distribution shift," leaving online adaptation to query drift as future work.
One redeeming property is that the failure mode is graceful: when the model is wrong, you lose recall, not correctness, because final scoring is always exact. That makes monitoring straightforward. If I were running this, I'd sample a small batch of live queries each day, run offline exact search to measure routing recall and final recall against the launch baseline, and if they dip, bump up the number of probed clusters to hold the line while retraining on fresh queries.
When it isn't worth it. Judging from the paper's own numbers, three regimes see limited benefit: queries and keys drawn from the same distribution (like Quora); ultra-low budgets where a small network's forward pass isn't yet paid back by scanning fewer keys; and an underlying index that's already very strong (like SOAR on Quora). I'd add a fourth: small corpora or low query volume. Paying billions of training samples up front to save fractions of a millisecond per query won't break even if you don't have the traffic to amortize it.
7. How It Fits Alongside HNSW and Learned Routing
In its background section, the paper groups approximate MIPS methods into: inner-product-to-Euclidean reductions, quantization (product quantization, ScaNN, etc.), graph indexes (HNSW, etc.), learning-to-hash, and learned indexes. Its assessment is that these methods are largely "query-agnostic" at inference time, though a few incorporate partial query statistics during index construction. It cites two examples: RoarGraph (VLDB 2024), which from its title builds a projected bipartite graph for "cross-modal" nearest-neighbor search, and a KDD 2025 paper doing "query-aware repartitioning" in a tree-based learned vector index. I haven't read those two closely, so I'm simply passing along the paper's taxonomy.
Here's how I see the relationship with graph indexes. HNSW doesn't have a "cluster selection" step—it starts from an entry point and greedily walks the neighbor graph toward the query—so a SupportNet router doesn't have an obvious slot inside HNSW. KeyNet is different: it only rewrites the query vector, so in principle it's plug-and-play with any index. What the paper actually benchmarked is FAISS IVF, ScaNN, SOAR, LeanVec, and 15M-key BioASQ—it did not test HNSW. My hunch is that graph indexes also suffer when query and key distributions diverge (that's the exact problem work like RoarGraph targets), so moving the query onto the key manifold first might give greedy traversal a better starting point and direction. That's just speculation, though; graph recall also hinges on graph connectivity, entry points, and ef, so you'd have to measure it yourself.
Compared with other learned routing work, I noticed the paper cites a SIGIR 2024 paper that casts cluster selection in cluster-based ANN as a learning-to-rank problem. As I see it, learned routers are all ultimately learning "given a query, which clusters are worth probing," whether framed as classification or ranking. SupportNet's twist is that it regresses a quantity with an explicit mathematical meaning: each cluster's support function value. That gives you convexity, homogeneity, and gradient structure to exploit—and the scores themselves carry meaning. The official blog points out that SupportNet fits scenarios requiring a "calibrated score," such as thresholding or downstream reranking. Classification or ranking routers tell you "which to pick," but can't easily answer "what's the highest score I could possibly get if I pick this one?"
8. My Take
-
The one equation worth remembering from this paper. "The maximum inner product is a support function, and its gradient is the optimal key." Stated plainly, it's almost textbook convex analysis, yet it instantly unifies routing (which needs scores) and query rewriting (which needs keys) as the value and gradient of the exact same function. The architecture (ICNN), the losses (gradient matching, Euler consistency), and the homogenization wrapper all fall straight out of that function's properties rather than feeling like a pile of ad-hoc tricks. It's rare to read a paper where the design hangs together this cleanly.
-
Laying out the flaw in centroid routing clearly is valuable on its own. Centroid scores are averages—lower bounds whose looseness varies by cluster. Most vector-search practitioners know this intuitively (which is why they turn up
nprobe), yet rarely connect it to "what we actually want is each cluster's support function." Even if you never adopt this paper's models, that perspective clarifies existing techniques: making clusters more spherical, or assigning a key to multiple clusters like SOAR does, is fundamentally about shrinking the gap between the average and the maximum. -
KeyNet is much easier to ship than SupportNet. It doesn't touch the index—just sits in front of it—and if anything goes wrong you flip a switch to bypass it with minimal risk. If I were trying this out, I'd start with KeyNet on whichever workload has the widest gap between query and document distributions, and keep an exact rescoring pass with the original query over the returned candidates.
-
Treat the amortization assumptions as an ops problem, not a line in the paper. Corpus updates, query drift, retraining cadence, and monitoring: the paper only tested Gaussian noise for drift and never touched corpus updates. From support function properties, new keys can be covered exactly with a small buffer and deleted keys only waste a little probing, which makes me fairly optimistic about SupportNet routing on semi-static corpora; I'd be more cautious with KeyNet on indexes that churn frequently.
-
Training cost is the number I wanted most and the one the paper left out. Billions of samples, each exhaustively labeled, plus a model whose parameter count scales with corpus size. In return, it shaves milliseconds—or fractions of a millisecond—off each query. Whether that math pencils out depends entirely on query volume and update frequency. If someone eventually publishes those numbers from a real production RAG deployment, I'd love to read it.
References
- Faster Retrieval for Better, More Efficient RAG (Apple Machine Learning Research, 2026-11-05)
- Amortized Maximum Inner Product Search with Learned Support Functions (arXiv:2603.08001)
- Amortizing Maximum Inner Product Search with Learned Support Functions (PMLR v306, ICML 2026)
- Amortizing Maximum Inner Product Search with Learned Support Functions (Apple Paper Page)
- apple/ml-amips (Code)
- OTT-JAX: ICNN and KeyNet Implementation
- Input Convex Neural Networks (Amos, Xu, Kolter, ICML 2017)
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (Malkov, Yashunin)
- FAISS
- BEIR benchmark
Related Posts
Inside React 19.3's Runtime Primitives: ViewTransition-Suspense Coordination, FragmentInstance, and use(browser())
React 19.3 stabilizes <ViewTransition> and Fragment Refs, introduces use(browser()) for Suspense-native SSR opt-out, passes Trusted Types through without string coercion, allows Server Components to render Client <Context> directly, and decouples concurrent Transitions from entangling into a single render.
Repurposing GC Reachability to Catch Partial Deadlocks: Inside Go 1.27's goroutineleak Profiler
Go 1.27 ships the goroutineleak profiler in runtime/pprof and net/http/pprof. Rather than sampling stacks or guessing from goroutine counts, it adapts Go's tri-color mark-and-sweep GC to compute an inductive liveness fixpoint LIVE+(g)—pinpointing permanently blocked goroutines in production with near-zero false positives, while carrying sharp boundaries around memory overreach, O(n²) daisy-chains, and non-channel blocking.
Splitting encoding/json Into Two Layers and Putting It Back Together: Layering and Compatibility in Go's json/v2
Go 1.27 runs the old encoding/json package on top of v2: syntax (jsontext) and semantics (v2) are split apart, every behavioral difference is an option, and old and new code coexist in the same dependency graph without a flag day.