Build a Two-Tower Neural Network for Candidate Retrieval at Scale


recommendation-systems deep-learning ranking model-evaluation
View full code for this problem

ML Problem & Solution

Two-Tower Candidate Retrieval

Precomputable item vectors are worth more than the features you give up to get them

⏱ 36 min read 📐 Advanced 🎯 Deep Learning

The ranker is fine. It is a gradient-boosted model with 340 features, it was tuned over eighteen months, its NDCG@10 is 0.41 against a production baseline of 0.33, and nobody wants to touch it. The problem is upstream of it: the ranker scores a candidate set that a hand-written SQL query produces, that query returns the user’s last 200 viewed categories joined against the 5,000 most popular items in each, and the result is that 94% of the catalogue has never been scored for any user. Not ranked badly. Never scored at all.

This is the stage that posts 21 through 26 quietly assumed away. Every one of them evaluated by computing a score for every user against every item and sorting, which is a (n_users, n_items) matrix, and at 1,500 items that matrix is 3.6 million floats and takes milliseconds. At 20 million items and 200 million users it is 4 times 10 to the 15th cells, and the per-request version is not better: scoring one user against the full catalogue with a 340-feature GBDT is 20 million tree traversals inside a 30 millisecond budget, which is roughly four orders of magnitude past what the hardware will do. So the catalogue has to be cut to something scoreable before the ranker runs, and the cutting is its own modelling problem with its own metric and its own failure modes.

The naive fix is to make the ranker cheaper and run it on everything. This fails in a specific and instructive way: the thing that makes the ranker good is precisely the thing that makes it unservable at catalogue scale. Its best features are interaction features, functions of the (user, item) pair together: how many times this user has bought from this item’s publisher, the BM25 overlap between the query text and the item title, the co-click count. An interaction feature cannot be precomputed for an item, because its value depends on who is asking. So every item’s score has to be computed at request time, from scratch, and no amount of model compression changes the arithmetic.

The move that works is to give up those features on purpose, in exchange for a factorisation. Think of it as the difference between a locksmith and a key-cutting machine. The locksmith examines your lock and files a key to fit it, which is accurate and takes twenty minutes per lock. The key-cutting machine stamps out every key shape in advance, and then matching a lock to a key is a lookup. The machine’s keys fit worse. There are 20 million locks.

Formally: given a query context u and a catalogue of N items, return a set C of size k that maximises recall@k against the items the user will actually engage with, subject to |C| = 100, a p99 latency under 10 milliseconds for the retrieval stage, and the hard constraint that the item-side representation must be computable without u.

Framing the Problem

The ML problem type is extreme multi-class classification, and naming it that way rather than “retrieval” or “recommendation” is what makes the loss function obvious. Given a context, predict which of N items was engaged with. N is 20 million, so the softmax denominator has 20 million terms and cannot be computed, and every design decision downstream follows from that one fact.

The target is the next engaged item, where “engaged” is a product decision and not a modelling one. We define a positive as a play of at least 30 seconds, which excludes the accidental-tap traffic that is 11% of raw plays and whose inclusion moved our offline metric by 0.03 in the direction that looked like an improvement. The label lag is the 30 seconds plus a batch-ingest delay that runs between 4 and 90 minutes, which matters in the next section.

Constraints, in the order they actually bind:

  • Item-side representations must be precomputable. This is architectural, not a budget, and it forbids an entire feature class.
  • Retrieval p99 under 10 milliseconds, as part of a 30 millisecond end-to-end budget shared with the ranker and the business-logic layer.
  • The item index is rebuilt nightly and refreshed incrementally within the day, so an item’s vector is up to 24 hours stale and a brand-new item has no vector at all until the incremental path catches it.
  • 20 million items at 64 float32 dimensions is 5.1 GB of index, which has to fit in the memory of the serving fleet alongside everything else.
  • The candidate set is handed to a ranker that we do not control and must not starve.

The success metric is recall@100: the share of the user’s held-out engaged items that appear in the 100 candidates we return. The number 100 is not ours either; it is the ranker’s throughput budget, and if the ranker team changes it the retrieval metric changes with it.

Metric That Matters

Recall@k where k is what the next stage consumes, and NDCG is a guardrail rather than an objective. The retriever's only job is to not lose the answer before the ranker sees it; the order inside its 100 is the ranker's problem, and optimising it is spending the tuning budget on somebody else's metric. The companion codebase measures what happens when you forget this: across a temperature sweep from 0.02 to 1.00, recall@100 moves 21% and is NON-MONOTONE, while NDCG@10 moves 102%, from 0.0257 to 0.0518. The two agree on the best value, which is the comfortable result, and disagree completely about how much the choice matters. A team tuning on recall alone sees a nearly flat curve, concludes the temperature is unimportant, and picks between two settings whose ranking quality differs by a factor of two by coin flip. The guardrails are catalogue coverage and the share of served slots taken by the 100 most popular items: 1.000 and 0.123 for the shipped model against 0.146 and 0.487 for a popularity ranker. Neither is interpretable alone, and reporting coverage without an accuracy number next to it is how post 26's random fallback got to 61.4% coverage and was worthless.

Key Insight

Naming the problem "extreme multi-class classification over the catalogue" rather than "retrieval" is what makes every later decision follow rather than be chosen. Call it retrieval and the loss function is an open question with a dozen plausible answers: pairwise hinge, triplet with margin, BPR, a regression on engagement. Call it a 20 million way classification and the loss is cross-entropy with a softmax, full stop, and the only remaining question is how to approximate a denominator with 20 million terms, which is a sampling question with a known answer and a known bias. The framing also fixes the metric: a classifier's natural metric is top-k accuracy, which is recall@k, and not a graded ranking measure. This is the 2016 YouTube paper's framing and it is the single most useful sentence in it. The practical test of whether a team has internalised it: ask what the model's output layer is. If the answer is "a 32-dimensional embedding" the team is thinking about retrieval; if the answer is "a softmax over the catalogue, factorised so the denominator is a dot product" the team will get the negatives right.

Explicitly out of scope: the ranker itself, which post 24 covered; the sequence-aware query encoder, which post 25 covered and which slots into the query tower without changing anything structural; and the exploration problem of how an item that has never been retrieved gets its first impression, which is the subject of the next post and is not solvable inside a supervised objective.

Data and Features

The training data is the engagement log, 36,563 events in the companion codebase’s synthetic version and 1.1 billion in the real one, as (user, item, timestamp) triples. Two side tables: 34 item metadata columns, of which three are one-hot blocks because real catalogue metadata is mostly categorical; and 18 user context columns from signup and session.

The split is temporal and has three segments, the same shape posts 23 through 26 used. History fits the towers, tune fits the index parameters and the temperature, test reports.

# The three-segment temporal split, with every count snapshotted at the history cut.
import numpy as np
import pandas as pd


def temporal_split(events: pd.DataFrame, n_users: int, n_items: int,
                   history_frac: float, tune_frac: float) -> dict:
    t_hist = float(np.quantile(events["t"].to_numpy(), history_frac))
    t_tune = float(np.quantile(events["t"].to_numpy(), tune_frac))

    history = events[events["t"] <= t_hist].reset_index(drop=True)
    tune = events[(events["t"] > t_hist) & (events["t"] <= t_tune)].reset_index(drop=True)
    test = events[events["t"] > t_tune].reset_index(drop=True)

    def counts(frame, col, n):
        out = np.zeros(n)
        if len(frame):
            agg = frame.groupby(col).size()
            out[agg.index.to_numpy()] = agg.to_numpy().astype(float)
        return out

    return {
        "history": history, "tune": tune, "test": test,
        "item_counts": counts(history, "item", n_items),
        "user_counts": counts(history, "user", n_users),
    }

A random split would be wrong for the reason it is always wrong in a recommender, and for one extra reason specific to retrieval. The general reason is that the model will serve tomorrow’s queries having been trained on today’s log, so a random split measures a task nobody will ask it to do. The retrieval-specific reason is the item id embedding: a random split lets an item’s future popularity leak into the id vector that then sits in an index for 24 hours ranking that item. The leak is not a feature value you can audit, it is baked into a learned parameter.

Common Pitfall

Computing the item interaction count over the whole log instead of as of the history cut. Post 26 spent a section on this and in a retrieval model the stakes are higher, because the count is not just a feature the model reads, it is a feature the ITEM TOWER BAKES INTO A VECTOR that is then written to an index and serves every query for a day. There are three consequences and the third is the one that survives review. It inflates the offline metric, which is the expected failure and the least dangerous because it is the one people look for. It changes which items the tower learns to suppress, because an item that got 400 plays during the test window is no longer in the zero-count group during the test window when it had none. And it silently fixes the cold-item problem in the evaluation while leaving it broken in production: a title published yesterday has a full-log count of 400 and an as-of count of 0, so the offline run routes it through the warm path and reports a healthy number for a cohort that in production gets the cold path and a different vector entirely. The fix is that the count array is snapshotted into the model artifact alongside the weights, and the item tower, the feature standardiser and the evaluation all read that same array. The request-time delta comes from a streaming counter whose lag is itself a monitored metric, because post 23's project had a 31-hour counter stall that nobody noticed until a weekly report.

The constraint, enforced structurally

The factorisation constraint is the whole architecture, so it is worth making it impossible to violate rather than documenting it. In the companion codebase the query-feature builder is never handed the item metadata table and the item-feature builder is never handed the user table. The property that makes an index possible is visible as two function signatures.

# The two feature blocks. Note what is absent from each signature.
import numpy as np


def build_item_features(item_content: np.ndarray, item_counts: np.ndarray,
                        standardiser=None):
    """Item tower input: metadata plus two count-derived columns.

    No user argument exists, which is why g(item) is callable at index-build
    time. The count MUST be the as-of-history count.
    """
    X = np.concatenate([item_content,
                        np.log1p(item_counts)[:, None],
                        (item_counts == 0).astype(float)[:, None]], axis=1)
    if standardiser is None:
        standardiser = Standardiser()
        return standardiser.fit_transform(X), standardiser
    return standardiser.transform(X), standardiser


def build_query_features(user_context: np.ndarray, history_lists: list,
                         item_content: np.ndarray, standardiser=None):
    """Query tower input: context plus a mean-pooled bag of history metadata.

    Reading the item ids in the USER'S OWN HISTORY is permitted, because that
    is a property of the query. Reading anything about the candidate being
    scored is not.
    """
    n_users = user_context.shape[0]
    pooled = np.zeros((n_users, item_content.shape[1]))
    hist_len = np.zeros(n_users)
    for u in range(n_users):
        h = history_lists[u]
        hist_len[u] = len(h)
        if len(h):
            pooled[u] = item_content[h].mean(axis=0)

    X = np.concatenate([user_context, pooled,
                        np.log1p(hist_len)[:, None],
                        (hist_len == 0).astype(float)[:, None]], axis=1)
    if standardiser is None:
        standardiser = Standardiser()
        return standardiser.fit_transform(X), standardiser
    return standardiser.transform(X), standardiser

The item ids in the user’s own history are allowed. This sounds like a loophole and is not: the pooled history vector is a function of u alone, so f(u) is still computable without knowing which candidate we are about to score. The distinction is not “does this feature mention items” but “does this feature’s value change depending on which item I evaluate”.

Key Insight

The standardiser is fitted on the history segment and the floor on its scale is 1e-6 rather than a guard against zero variance, because a one-hot column that is all zeros in the history segment is a real and common case: it is a category that launched after the training cut. The general version of this is the most underrated line in a retrieval feature pipeline. Every statistic the model consumes, whether it is a mean, a scale, a count or a sampling probability, is a training-time artifact that has to travel with the weights into the serving path, and any one of them recomputed at serve time from fresher data is a train-serve skew that no offline evaluation can detect because the offline evaluation recomputes it the same wrong way. In the companion codebase there are four such statistics: the item count array, the two feature standardisers, and the sampling distribution the logQ correction reads. All four are snapshotted; the one that caused the most trouble was the fourth, for reasons in "The Solution" below.

The cohort shapes, measured on the synthetic log, because the whole argument about segmented reporting depends on them:

Cohort Share of the population Share of held-out rows Ratio
Users with zero history 10.95% of 1,753 test users 8.34% of 2,936 rows 1.31
Items with zero history 19.80% of 1,500 items 1.06% of rows 18.7
The top 1% of items 1% of items 28.06% of history events 0.036

The last row is not a cohort, it is the reason the loss function in the next section needs a correction. The top 1% of items hold 28.06% of events, so anything that samples items proportionally to events is sampling a wildly non-uniform distribution.

The Naive Baseline

Four baselines, because the final model differs from a naive one in four ways at once and a single “before” number cannot attribute anything. Three of the four are strong, which is the point: retrieval at large k is a problem where simple methods do well and the literature’s reported gains are frequently measured against a straw man.

# Two of the four baselines. Neither involves gradient descent.
import numpy as np
import pandas as pd


class Popularity:
    """log1p of the as-of count, identical for every user. Hard to beat at large k."""

    def __init__(self, item_counts: np.ndarray) -> None:
        self.scores_ = np.log1p(item_counts)

    def score(self, users: np.ndarray) -> np.ndarray:
        return np.repeat(self.scores_[None, :], len(users), axis=0)


class ItemKNN:
    """Cosine item-item co-occurrence, scored from the user's history.

    The normalisation IS the model. A raw co-occurrence count is dominated by
    the popularity of the co-occurring item, so the unnormalised version is a
    popularity model wearing a personalisation costume and scores within noise
    of `Popularity`. Dividing by sqrt(count_i * count_j) is what separates them.
    """

    def __init__(self, n_items: int, shrink: float = 10.0) -> None:
        self.n_items, self.shrink = n_items, shrink

    def fit(self, history: pd.DataFrame, n_users: int) -> "ItemKNN":
        H = np.zeros((n_users, self.n_items), dtype=np.float32)
        H[history["user"].to_numpy(), history["item"].to_numpy()] = 1.0
        co = H.T @ H
        cnt = np.diag(co).copy()
        np.fill_diagonal(co, 0.0)
        denom = np.sqrt(np.outer(cnt, cnt)) + self.shrink
        self.sim_ = co / np.maximum(denom, 1e-9)
        self.H_ = H
        return self

    def score(self, users: np.ndarray) -> np.ndarray:
        return self.H_[users] @ self.sim_
Baseline recall@100 recall@10 NDCG@10 Coverage Head share
Popularity 0.1921 0.0544 0.0327 0.146 0.487
Item-kNN 0.2236 0.0870 0.0562 0.833 0.208
Content cosine, post 22’s route 0.1099 0.0200 0.0107 1.000 0.073
ALS matrix factorisation, post 21 0.2219 0.0897 0.0556 0.824 0.169

Popularity at 0.1921 is the number to respect rather than the number to beat. It is one count table, it has no training cost, it has no index, and it retrieves 19% of what the user will engage with. Item-kNN at 0.2236 is the strongest baseline and the one teams routinely omit from the comparison table, which is how a neural retriever gets credited with a gain it did not make.

ALS is the most informative row, because ALS is a two-tower model with the towers removed. Its score is a dot product of a user vector and an item vector, so it factorises and it indexes, and it differs from what we are about to build only in that its vectors are learned per id with no feature inputs. Every claim about what the towers add has to be measured against this row and not against popularity.

Key Insight

Content cosine at 0.1099 looks like a broken model and is a necessary calibration row. The top 100 of a 1,500-item catalogue is 6.7% of it, so a uniformly random ranker scores 0.0667 on recall@100 and content cosine is 1.6 times random. At 20 million items the top 100 is 0.0005% of the catalogue, random scores effectively zero, and the same algorithm's absolute recall falls by a large factor that has nothing to do with the algorithm. This is the single most common error in reading a retrieval benchmark: recall@k is not comparable across catalogue sizes, not even approximately, and a paper reporting recall@100 of 0.85 on a 10,000-item academic dataset is not reporting a better system than one reporting 0.24 on 20 million. Compare within a catalogue; never carry the absolute number across one.

The Solution

Three parts, and they are separable: a pair of towers, a loss that makes a 20 million way softmax tractable, and an index. The towers are the least interesting of the three and the loss is where the real content is.

A two-tower retrieval pipeline over a 20 million item catalogue with 200 million users and a 30 millisecond p99 budget, where scoring the catalogue per request would be 6.7 times 10 to the 15 dot products a second: stage one is the factorisation constraint, a query tower reading a 16-wide id embedding plus a 24-wide pooled history embedding plus 18 context columns and nothing about the candidate, and an item tower reading a 16-wide id embedding plus 34 metadata columns plus an as-of-history log count and nothing about the query, with both outputs L2 normalised so the score is a dot product and the item tower is callable with no query at all; stage two measures what the constraint costs, an item-kNN interaction term at weight 1.0 lifting recall@100 from 0.2417 to 0.2802 and NDCG@10 from 0.0444 to 0.0738 with none of it servable; stage three is the loss, a B by B logit matrix where each row's negatives are the other rows' positives, biased because the top 1 percent of items hold 28.06 percent of history events, fixed by subtracting a log Q term clipped at 6 nats with a pseudo-count of 0.5 and a zero gradient, worth recall@100 0.1735 to 0.2417, head share 0.059 to 0.123, the head's own hit rate 0.0943 to 0.1999 and cold-user recall 0.1615 to 0.5382, but costing 0.1336 if also applied at serve time; stage four is the train-serve mismatch where batch 32 gives an in-batch loss of 1.8484 against a full-softmax 5.2318 for a gap of 3.3833 and recall 0.2258, batch 128 gives 3.0739 and 5.1832 and 2.1093 and 0.2417, batch 512 gives 0.8032 gap and 0.2280, and batch 1024 gives 0.1528 gap and 0.2205, so the estimator improves monotonically while the model peaks at 128; stage five is the index, HNSW with M 12 and 3 layers and mean degree 24.0 reaching index recall 0.9364 at 668 distance computations and 0.9916 at 1404, against IVF-PQ with 40 lists and 8 four-bit subvectors compressing 128 bytes to 4 for 32x and reaching 0.6249 at n_probe 6 but only 0.7585 at full probe, leaving 0.2415 of index recall permanently unreachable as the quantiser's own floor, with PQ on residuals scoring 0.2409 mean error against 0.3483 on raw vectors; and stage six is the metric, recall@100 moving 21 percent and non-monotonically across a temperature sweep while NDCG@10 moves 102 percent, ending at recall@100 0.2417 against item-kNN 0.2236 and ALS 0.2219 and popularity 0.1921, coverage 1.000 against 0.824, cold-user recall 0.5382 against 0.0634 and cold-item hit 0.1935 against 0.0000, but NDCG@10 0.0444 losing to item-kNN's 0.0562 and popularity winning the cold-user bucket outright at 0.6467

Model architecture

Each tower is an embedding lookup concatenated with a feature block, a two-layer MLP, and an L2 normalisation. That is the entire architecture and its simplicity is load-bearing: the 2016 YouTube deep candidate generation paper and the 2019 Google two-tower paper both use essentially this, and the depth that helps a ranker does not help here because the output is a single vector that has to be compared by dot product.

# One tower's forward pass. The absent argument is the architecture.
import numpy as np


def forward_tower(p, ids, feats, pool=None):
    """[id emb | pooled history emb | feature block] -> dense -> relu -> dense -> L2.

    There is no item argument. The history pool is indexed BY THE QUERY'S OWN
    id, so what it contributes is a property of the query.
    """
    blocks = [p.emb[ids]]
    if p.hist is not None and pool is not None:
        blocks.append(np.einsum("bl,bld->bd", pool.w[ids], p.hist[pool.idx[ids]]))
    blocks.append(feats)
    x = np.concatenate(blocks, axis=1)
    h = np.maximum(x @ p.w1 + p.b1, 0.0)
    z = h @ p.w2 + p.b2
    n = np.sqrt(np.maximum((z * z).sum(axis=1, keepdims=True), 1e-8))
    return z / n, n

Two decisions in there with measurable consequences.

The L2 normalisation makes the dot product a cosine, which removes the model’s ability to express “this item is popular” through vector magnitude. That sounds like a loss and is a deliberate one: the popularity signal reaching this model is already distorted by the negative sampler, so letting the model encode it in a norm means encoding a biased quantity in a channel the index cannot see. It also means the HNSW graph, built under 1 - cosine, returns exactly the ordering the model’s score defines. Mixing a cosine-trained model with an L2 index is a real and silent bug: the two agree for most pairs and disagree precisely where the norms differ.

The learned history embedding is a separate table from the item tower’s id embedding. The query tower mean-pools a 24-wide embedding over the items in the user’s history. Sharing that table with the item tower is tempting and couples the two towers during training, so the query tower’s output starts depending on the item tower’s current weights, which is an engineering cost rather than a modelling one. Setting hist_dim: 0 removes the table entirely and is a real alternative architecture in which the query tower sees only its context fields plus a mean of raw item metadata.

The loss function, which is the actual subject

The objective is a softmax over 20 million items and it cannot be computed. The standard answer is to estimate it from a sample, and the specific choice that makes two-tower training cheap is that the sample is the batch itself. For a batch of B positive pairs, build a B by B logit matrix: row a, column b is query a scored against item b. Row a’s label is a, so every other row’s positive serves as a negative for row a, and B positives have bought B times B - 1 training signals with no extra forward passes.

Which is elegant, and introduces a bias that is the single most consequential thing in this post. A batch is a sample of events, not a sample of items. The probability that item j appears somewhere in a batch is proportional to j’s share of events, so a head item is a negative in nearly every batch and the softmax denominator spends most of its effort pushing down exactly the items most users want.

# Sampled softmax over in-batch negatives, with the sampling-bias correction.
import numpy as np


def loss_and_grads(self, u_ids, i_ids, query_feats, item_feats):
    B = len(u_ids)
    qc = forward_tower(self.query, u_ids, query_feats[u_ids], self.pool)
    ic = forward_tower(self.item, i_ids, item_feats[i_ids])

    logits = (qc.out @ ic.out.T) / self.temperature

    if self.logq_correction:
        # The correction from Bengio and Senecal 2008, as used by Yi et al.
        # 2019: the in-batch softmax estimates P(item | query) under a
        # proposal of Q(item), so each logit is debiased by log Q.
        logits = logits - np.clip(self.log_q, -self.logq_clip,
                                  self.logq_clip)[i_ids][None, :]

    # Mask columns holding the same item as the row's own positive. Without
    # this the model is asked to rank one copy of an item above another and
    # the loss has a floor it can never reach.
    same = i_ids[None, :] == i_ids[:, None]
    np.fill_diagonal(same, False)
    logits = np.where(same, -1e9, logits)

    m = logits.max(axis=1, keepdims=True)
    ex = np.exp(logits - m)
    denom = ex.sum(axis=1, keepdims=True)
    loss = float(-(logits - m - np.log(denom))[np.arange(B), np.arange(B)].mean())

    g_logits = ex / denom
    g_logits[np.arange(B), np.arange(B)] -= 1.0
    g_logits = np.where(same, 0.0, g_logits) / B / self.temperature
    return loss, g_logits

The correction is one subtraction and three details that are each worth a paragraph.

log Q has zero gradient. It does not depend on the parameters, so subtracting it changes the logits, therefore the softmax probabilities, therefore every gradient, while contributing no term of its own. Adding a gradient for it is a bug that no loss curve can show.

The pseudo-count matters more than the clip. Q(j) is estimated as (count_j + 0.5) / sum(count + 0.5). An item with zero history events has Q = 0 and log Q of negative infinity, and clamping to a tiny float gives a correction term of around negative 30 that drowns the dot product entirely. The 0.5 is the Jeffreys-style choice and says: treat an unseen item as having been seen half a time.

It is a train-time term only. This one cost us a day and is in the companion codebase’s bug list with the number. The correction exists so that the trained score s satisfies s - log Q approximately equals the true log odds, which means s itself already carries the popularity term the ranking wants. Subtracting log Q again when scoring the catalogue removes it twice.

Configuration recall@100 NDCG@10 Head share Cold-user recall@100
logQ off 0.1735 0.0203 0.059 0.1615
logQ on, train only (shipped) 0.2417 0.0444 0.123 0.5382
logQ on at train and serve (the bug) 0.1336 0.0142 0.021 -
Common Pitfall

Reading a pooled recall number to decide whether the sampling-bias correction helped. The correction is a redistribution and slots are zero-sum, so any single pooled number is a half-truth in one direction or the other. Measured per held-out event and bucketed by the item's own history count, turning the correction on moves the 80-plus bucket from 0.0943 to 0.1999, which is more than double, and moves the zero-history bucket from 0.3871 to 0.1935, which is a halving. Both directions are real, both are consequences of the same change, and a report containing only the first is marketing while a report containing only the second is an argument to revert. The second trap in the same table is the double-application bug: it produces 0.1336, which is WORSE than never correcting at all, and 0.1336 is a perfectly plausible number for a reviewer to look at and conclude that sampling-bias correction does not help on this dataset. The same reviewer, with the correction applied in the one place it belongs, would see 0.2417. A correction worth 0.0682 of recall@100 gets deleted because it was applied in two places instead of one, and the only defence is structural: in the companion codebase `log_q` is readable only inside the loss function, and the two embedding methods have no access to it at all.

The hyperparameters that matter, in order

Temperature, 0.30. Divides the logits before the softmax. Too low and the loss is dominated by the single hardest negative in the batch; too high and every gradient is the same. It is the most consequential number in the config and the one whose effect the retrieval metric is worst at seeing, per the metric callout above.

Batch size, 128, and it is an accuracy hyperparameter here rather than a throughput one. B - 1 is the number of negatives per gradient step, so changing it changes the model. The measured table is the honest negative of this post.

Batch Negatives per row In-batch loss Full-softmax loss Gap recall@100
32 31 1.8484 5.2318 3.3833 0.2258
64 63 2.4477 5.2189 2.7712 0.2324
128 127 3.0739 5.1832 2.1093 0.2417
256 255 3.7246 5.1952 1.4707 0.2274
512 511 4.3837 5.1869 0.8032 0.2280
1024 1023 5.0478 5.2007 0.1528 0.2205

The gap column is monotone and does exactly what sampled-softmax theory says: the in-batch loss is an estimator of the full one over B - 1 negatives, it is biased low by construction, and the bias shrinks from 3.3833 to 0.1528 as the batch grows 32-fold. The recall column is not monotone and peaks at 128. We expected more negatives to be strictly better and it is not, for two reasons that we did not separate: at a fixed epoch count a larger batch takes fewer optimiser steps, 228 per epoch at 128 against 28 at 1024, so the large-batch runs are simply less trained; and a larger in-batch softmax contains more items the user was never offered, so a growing share of the denominator pushes down things that are not negatives in any useful sense. The loss-estimator argument for large batches is correct and is not by itself an argument for large batches.

Key Insight

The in-batch loss and the full-softmax loss are different quantities, which means a training curve and a validation curve plotted on the same axis are measuring different things and their crossing point means nothing. At batch 128 the gap is 2.1093 nats, and nothing about the shapes of the two curves announces that. This is the train-serve mismatch in its purest form: the objective optimised during training is a sampled estimate, the objective at serving is the real softmax over the catalogue, and the only honest way to compare runs is to compute the full-softmax loss on a held-out slice once at the end, which the companion codebase does and which is affordable only because its catalogue is 1,500 items. At 20 million the full softmax is unaffordable, which is the entire reason sampled softmax exists, and the practical consequence is that the quantity you actually care about is one you can never measure at production scale. The substitute is the retrieval metric itself: recall@100 on a held-out temporal slice is computable at any catalogue size, and it is the number to gate a release on.

The index

The model is useless without an index, and the index is where the recall the model earned gets given back. Two families, failing in different directions.

HNSW loses recall in one place: ef_search bounds the beam width of the graph walk, so a narrow beam misses neighbours it never visited. One dial, one loss, tunable without rebuilding.

IVF-PQ loses recall in two independent places. The inverted file loses neighbours in cells that n_probe did not open, which is the same kind of routing error as a small ef_search. And product quantisation loses precision in the distance itself, because every vector is replaced by 8 codebook indices, so the distance is computed between a real query and an approximate item and the ordering is wrong even among the items the probe did open.

Index Index recall@100 recall@100 NDCG@10 Distances per query Share of catalogue
Exact brute force 1.0000 0.2417 0.0444 1500 100%
HNSW, ef=128 0.9776 0.2229 0.0403 759 50.6%
HNSW, ef=640 0.9916 0.2329 0.0436 1404 93.6%
IVF-PQ, n_probe=6 0.6249 0.1843 0.0398 247 16.5%
IVF-PQ, n_probe=40 (all cells) 0.7585 0.2351 0.0377 1540 100%

The last row is the measurement that justifies the whole file. At n_probe equal to the list count, every cell is opened, the routing error is zero by construction, and the index recall is still 0.7585. So 0.2415 of index recall is permanently unreachable and is the product quantiser’s own floor. It is the price of compressing 128 bytes per vector to 4, a 32-fold reduction, and it is paid in recall rather than in time. One more detail worth a line because it is a one-line change: fitting the codebooks on the residual from the coarse centroid rather than on the raw vectors gives a mean reconstruction error of 0.2409 against 0.3483, so the coarse quantiser removes 30.8% of the error for free.

Metric That Matters

Report distance computations per query, not milliseconds, and never conflate index recall with accuracy. The millisecond column in the table above is dominated by the Python interpreter and would change by two orders of magnitude under faiss without the algorithm changing at all; the distance count is a property of the algorithm and survives both the reimplementation and the move from 1,500 items to 20 million. It is also the only column that shows why retrieval is worth doing: HNSW at ef=128 touches 50.6% of this catalogue, which is a terrible number and is why brute force is faster here, and the fraction falls as the catalogue grows because the graph walk is logarithmic where the scan is linear. At 20 million items the same graph parameters touch a few thousand vectors, or 0.01%. The second half of the callout is the more dangerous confusion: index recall is overlap with the MODEL'S OWN exact top-100, so an index at 1.0 reproduces the model perfectly including every mistake the model makes. It is not an accuracy metric. A team that tunes ef_search against a business metric is measuring a quantity dominated by the model and will conclude the index is unimportant.

Evaluation and Metrics

recall@k for a retriever is the share of the user’s held-out engaged items appearing in the top k, averaged over users. The denominator is the number of relevant items with no cap, which means a user with 30 held-out items cannot reach 1.0 at k = 10, so recall@10 for a retriever is not interpretable as a percentage of a reachable maximum and only recall@k at the k the ranker consumes should be read as a headline.

# The metrics, and the two functions whose names are deliberately similar.
import numpy as np


def recall_at_k(ranked: np.ndarray, relevant: set, k: int) -> float:
    """The model against the user's held-out items. The business-relevant one."""
    if not relevant:
        return float("nan")
    return sum(1 for i in ranked[:k] if int(i) in relevant) / len(relevant)


def index_recall(approx: np.ndarray, exact: np.ndarray, k: int) -> float:
    """The INDEX against the model's own exact top-k. Not an accuracy metric.

    An index at 1.0 reproduces the model including every mistake it makes.
    """
    if not len(exact):
        return float("nan")
    return len(set(map(int, approx[:k])) & set(map(int, exact[:k]))) / len(set(map(int, exact[:k])))


def head_share(all_ranked: list, k: int, item_counts: np.ndarray,
               head_n: int = 100) -> float:
    """Share of served slots taken by the head_n most popular items.

    This is the number the logQ correction is supposed to move, and the pooled
    recall is the number it is not supposed to move much. Reporting only the
    second is how a sampling-bias fix gets rejected for doing nothing.
    """
    head = set(int(i) for i in np.argsort(-item_counts)[:head_n])
    tot = inhead = 0
    for r in all_ranked:
        for i in r[:k]:
            tot += 1
            inhead += int(i) in head
    return inhead / tot if tot else float("nan")
Model recall@100 recall@10 NDCG@10 Coverage Head share Fit time
Popularity 0.1921 0.0544 0.0327 0.146 0.487 0.0s
Item-kNN 0.2236 0.0870 0.0562 0.833 0.208 0.3s
ALS matrix factorisation 0.2219 0.0897 0.0556 0.824 0.169 6.2s
Two towers, exact scoring 0.2417 0.0756 0.0444 1.000 0.123 11.2s
Two towers, HNSW ef=128 0.2229 0.0699 0.0403 0.991 0.126 11.2s + 0.8s

The towers win the metric they were built for, 0.2417 against 0.2236 for the strongest baseline, and lose NDCG@10 clearly, 0.0444 against 0.0562. A model that retrieves better and ranks worse is not a contradiction; it is the expected shape of something trained with a softmax over a hundred-odd sampled negatives and then evaluated at the top of the list. The system that ships uses it as the first of two stages and lets the ranker own the top.

The segmented tables carry the rest of the argument.

recall@100 by user history length Cold (0), n=192 1 to 4, n=283 5 to 19, n=686 20+, n=592
Popularity 0.6467 0.2975 0.1269 0.0697
Item-kNN 0.0634 0.4189 0.2490 0.1527
ALS matrix factorisation 0.0634 0.4174 0.2415 0.1571
Two towers 0.5382 0.3294 0.2165 0.1329
hit@100 per held-out event, by item history 0, n=31 1 to 4, n=149 5 to 19, n=407 20 to 79, n=748 80+, n=1601
Popularity 0.0000 0.0000 0.0000 0.1096 0.2773
ALS matrix factorisation 0.0000 0.0940 0.3907 0.3636 0.1649
Two towers 0.1935 0.3020 0.3489 0.2834 0.1999

The item-side table uses the held-out event as its unit rather than the user, for the grammatical reason post 26 established: “this account got a bad candidate set” is a statement about a user, but “this item was never retrieved” has no user to attribute it to.

Three readings, and the third is the one that should change what you build.

The towers are the only learned model with a nonzero cold column on either side: 0.5382 against 0.0634 for users with no history, and 0.1935 against 0.0000 for items with no history. The mechanism is not subtle. An ALS row with no interactions is the zero vector, its score is constant across the catalogue, and its ranking is whatever argsort does with ties. The towers read features, so they degrade to a content prior rather than to nothing. Catalogue coverage of 1.000 against 0.824 is the same mechanism measured a second way.

The towers lose the warm column, 0.1329 against ALS’s 0.1571, and win the pooled number anyway because the pooled number averages over users and the cold-leaning buckets hold 475 of 1,753 of them. Whether that trade is right is a product question, and a single pooled metric cannot be used to make it.

Key Insight

Popularity beats every learned model on cold users, 0.6467 against the towers' 0.5382, and it is not close. This is the most useful number here for anyone about to fund this work. A user with no history has no signal, so the best available prediction for them is the population prior, and a popularity ranker IS the population prior with zero estimation error on top of it. Every learned model pays a variance cost to produce an answer that a count table gets exactly right for free. The cold-start column is therefore NOT a reason to deploy a neural retriever, and a proposal that justifies one on cold-start grounds is making a claim the data does not support. The reasons to deploy it are the three in the table that popularity cannot touch: coverage of 1.000 against 0.146, a head share of 0.123 against 0.487, and the cold ITEM column where popularity scores a structural 0.0000 because an item with no plays has no popularity. Post 26 reached the same conclusion from the other direction and it is worth stating once more in the opposite polarity: the thing cold start needs is not a better model, it is a model that does not collapse to a constant, and there is more than one way to get that.

Metric That Matters

The signal that catches a silent retrieval regression in production is the head share of served slots, tracked per deploy, because it moves before recall does and it moves when nothing else does. Retrieval degrades in a characteristic way: the index goes stale, or a feature pipeline starts emitting a default value, or the count snapshot stops refreshing, and the model's output collapses toward the popularity prior. Recall@100 barely moves when that happens, because the head is genuinely what most users want and the pooled metric is dominated by warm users whose answers are in the head anyway. Head share moves immediately: the shipped model serves 0.123 and a collapse toward popularity's 0.487 is a four-fold change visible within an hour of traffic. The second signal, which catches the opposite failure, is the share of queries where the index returns fewer than k candidates after the exclude-seen filter. That number is 0.0000 at the shipped over-fetch factor and any nonzero value means the effective k is smaller than the ranker was promised, which the ranker's own metrics will report as a ranking regression.

Common Pitfalls and Failure Modes

Five retrieval traps with the number each one cost, all printed by the companion codebase on its synthetic log: trap one is tuning a retriever on a ranking metric, where a temperature sweep from 0.02 to 1.00 gives recall@100 of 0.2297 at 0.02 with NDCG@10 of only 0.0288, 0.2191 and 0.0257 at the published default of 0.07, 0.2381 and 0.0447 at 0.20, 0.2401 and 0.0518 at 0.40, and a collapsed 0.1979 at 1.00, so recall spans 21 percent non-monotonically while NDCG spans 102 percent and the two agree on the argmax while disagreeing completely on how much the choice matters; trap two is reading a pooled recall and calling the sampling fix a no-op, where turning logQ on moves the 80-plus item bucket from 0.0943 to 0.1999 and the zero-history bucket from 0.3871 down to 0.1935, with pooled recall going 0.1735 to 0.2417, head share 0.059 to 0.123 and cold-user recall 0.1615 to 0.5382, and applying it at serve time too giving 0.1336, worse than never applying it; trap three is a sweep whose rows are identical, where ef_search of 8, 16, 32 and 64 at k equal to 100 all read 0.9364 index recall and 668 distances per query because ef is floored at k, against a real curve from ef 100 at 0.9364 and 668 distances through ef 256 at 0.9867 and 1046 to ef 640 at 0.9916 and 1404 distances and 2.24 milliseconds; trap four is assuming n_probe can buy back all of IVF-PQ's lost recall, where n_probe 1 gives index recall 0.1738 at 70 distances, n_probe 6 gives 0.6249 at 247, n_probe 20 gives 0.7571 at 775, and n_probe 40 opens every cell for zero routing error and still reads 0.7585, leaving 0.2415 of index recall as the product quantiser's own unreachable floor; and trap five is trusting a metric to find a derivation bug, where dropping the projection term in the L2-normalise backward pass gave recall@100 0.1237 against 0.2417 with an in-batch loss plateauing at 5.1114 against 3.0739 and a gradient check max relative error of 1.0000 against 1.47e-06, using assignment instead of scatter-add discarded a third of the embedding gradient since 30.30 percent of item slots in a 128-row batch are duplicates yet cost only 0.0006 of recall and improved NDCG because Adam absorbs a constant rescale, and the double-applied logQ produced a plausible 0.1336 that argues for deleting a correction worth 0.0682
Pitfall Why It Happens How to Detect How to Fix
Interaction features sneak into the item tower A well-meaning feature PR adds “co-click count with the user’s last item” and offline metrics improve The item tower’s embed call needs a user argument; the index build breaks or silently indexes one user’s view Enforce structurally: the item-feature builder never receives the user table. Measured cost of obeying this: 0.0385 of recall@100
logQ applied at serve as well as train The correction looks like a scoring adjustment rather than a loss term recall@100 0.1336, below the 0.1735 you get with no correction at all, and head share collapses to 0.021 log_q is readable only inside the loss. The embedding methods have no access to it
Item count computed over the whole log The count is just another feature in a dataframe Zero-history item cohort shrinks; the cold-item bucket reports a healthy number offline and a broken one in production Snapshot the count array into the model artifact. Tower, standardiser and evaluation read the same array
Tuning the retriever on NDCG@10 It is the metric the team already has a dashboard for The chosen value is near-optimal on NDCG and arbitrary on recall@100, whose curve is flat and non-monotone Tune on recall at the k the ranker consumes; keep NDCG as a guardrail. Measured: recall spans 21% and NDCG spans 102% over the same sweep
ef_search swept below k ef is floored at k internally, so the rows are identical Four sweep rows reading exactly 0.9364 and 668 distances Sweep at or above k. Identical sweep rows are a bug in the sweep, never a finding
Expecting n_probe to recover IVF-PQ’s recall The routing loss is visible and the quantisation loss is not At n_probe = list count the routing error is zero and index recall is still 0.7585 Budget for the floor. 0.2415 of index recall is unreachable at 32x compression
Exclude-seen applied before the search It looks cheaper to filter the candidate pool first Nothing offline; in production the effective k is silently below the requested k Filter after the search and over-fetch. Track the short-of-k rate as a metric, not a constant
Index recall reported as accuracy Both are called recall An index at 1.0 is reported as a model improvement Report them in adjacent columns with different names, as the companion codebase does
Common Pitfall

Trusting a metric to find a derivation bug in a hand-written tower. Three real bugs from the companion codebase, with what each one did to the leaderboard. Dropping the projection term in the L2-normalisation backward pass cost 0.1180 of recall@100, halving the model, and the in-batch loss plateaued at 5.1114 against a correct 3.0739, which sounds like an obvious signal and is not, because the number you need in order to know 5.11 is wrong is 3.07 and you only have that if you already have the correct implementation. Using assignment instead of scatter-add on the embedding gradient discards a third of it every step, since 30.30% of item slots in a 128-row batch are duplicate ids, and cost 0.0006 of recall@100 while IMPROVING NDCG@10 from 0.0444 to 0.0499; Adam's m over sqrt(v) absorbs a constant rescale of a parameter's gradient, so the bug is invisible to the leaderboard and would not survive plain SGD or gradient-norm clipping. And the double-applied logQ produced 0.1336, a plausible number that argues for deleting a correction worth 0.0682. The pattern across all three is that the metric moved in a believable direction or did not move at all. A central-difference gradient check is the only diagnostic here that needs no correct baseline to interpret: the broken normalisation reported a max relative error of 1.0000 against 1.47e-06, it covers 78 parameter entries, it takes under a second, and in the companion codebase it runs in the default pipeline rather than behind a flag. The general lesson is the one that is hardest to act on: "the metric did not move" is not evidence that a derivation is correct.

Scaling and Productionizing

What changes between the notebook and the deployment, in order of how much trouble each one causes.

The embedding table stops fitting. 20 million items at 64 dimensions in fp32 is 5.1 GB for the output vectors and the id embedding table inside the tower is comparable, which does not fit on one accelerator alongside the activations. The table is sharded and the lookup becomes a collective operation. This is the point where a hand-written numpy version stops being a teaching tool, because the thing to reason about is the sharding and a single-process implementation has nothing to say about it.

In-batch negatives become per-replica. Each worker draws negatives from its own local batch, so 128 rows across 64 workers gives 127 negatives per row and not 8,191, unless a cross-replica gather is added. Given the batch-size table above, that is not obviously a problem, which is itself a useful thing to know before paying for the gather.

The index build becomes the critical path. Back of envelope, measured per-item and scaled:

item tower forward, 20M items, batched:        ~40s on one GPU
HNSW build, M=12, ef_construction=200:         ~55 min on 32 cores
  (from the measured 1,564,966 distance calls at 1,500 items,
   scaled by the n log n build complexity)
index serialise + ship to 400 serving pods:    5.1 GB x 400, ~25 min on a CDN
total nightly window:                           ~1h 40m
incremental path for items published today:    append to layer 0 only, ~2ms/item

The incremental path is where the cold-item story actually lives. A nightly full rebuild means an item published at 09:00 has no vector until the next build; appending to layer 0 of the existing graph gives it one in milliseconds at the cost of a graph that slowly degrades until the next full rebuild. We measure that degradation as index recall against brute force on a fixed query set, and rebuild when it falls below 0.95.

The monitoring signal for silent degradation is head share, per deploy, per hour. The reasoning is in the metric callout above: retrieval fails by collapsing toward the popularity prior, recall@100 barely moves when it does because the pooled metric is dominated by warm users whose answers are in the head anyway, and head share moves four-fold. The second signal is index recall against brute force on a fixed 10,000-query probe set, computed hourly, which catches a stale or corrupted index without needing any labels.

Real World

This architecture is the 2016 YouTube deep candidate generation paper (Covington, Adams and Sargin), which framed recommendation as extreme multi-class classification over the video corpus and used sampled softmax with several thousand negatives per example, then served with a nearest-neighbour lookup on the learned video vectors. The sampling-bias correction is Yi et al. 2019 at Google, "Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations", which is where the in-batch logQ term and the measurement that it matters most for head items both come from. The index side is Malkov and Yashunin 2016 for HNSW and Jegou, Douze and Schmid 2011 for product quantisation, with Guo et al. 2020's ScaNN adding the one genuinely better idea for a maximum-inner-product index: weight the quantisation error by how much it distorts the inner product rather than the L2 distance, which directly attacks the 0.2415 index-recall floor measured above. Pinterest's PinSage and Spotify's Annoy are the two most instructive production variants, Annoy specifically because it chose a different point on the memory-versus-recall curve (random projection trees, memory-mapped from disk) for a catalogue where the index had to be reloaded constantly.

Alternative Approaches

Approach recall@100 Serving cost per query Can precompute item side? Best-fit scenario
Popularity count table 0.1921 One array lookup Trivially Under 10k items, or as the cold-user fallback, where it WINS at 0.6467
Item-kNN co-occurrence 0.2236 Sparse row product, O(history x neighbours) Partly: needs the user’s history at request time Under ~40k items, where the item-item matrix fits. Strongest baseline here
ALS matrix factorisation 0.2219 One dot product plus an index Yes Pure collaborative signal, stable catalogue, no cold-item requirement
Two towers plus ANN 0.2417 One tower forward plus 759 distances Yes, which is the point Large catalogue, feature-rich items, real cold-item traffic
Cross-encoder over the catalogue 0.2802 20M forward passes No, structurally Never at retrieval. This is the ranker, over 100 candidates

The last row is the ablation and it is the honest framing of the whole design. Adding an item-kNN interaction term to the tower score lifts recall@100 from 0.2417 to 0.2802 and NDCG@10 from 0.0444 to 0.0738, and none of it is servable, because an interaction term is a function of the pair and an index holds a function of the item alone. That 0.0385 gap is not a modelling failure to be closed; it is the job description. The right comparison is not tower versus cross-encoder, it is tower-plus-ranker versus cross-encoder-over-the-whole-catalogue, and the second one has no latency budget it can meet.

Key Insight

Three of the five rows are within 0.0198 of each other on recall@100, and that compression is the real finding of the table rather than the ordering inside it. Popularity, item-kNN, ALS and the towers span 0.1921 to 0.2417, which is a 26% relative range across four methods whose implementation costs span from one count table to a sharded embedding table plus a nightly index build. Retrieval at large k is a forgiving problem: it only has to keep the answer in a set of 100, and most methods that capture any signal at all manage that for the warm majority. The decision therefore is not made on the headline metric, because the headline metric barely distinguishes the options. It is made on the columns that differ by factors rather than by percentages: coverage 0.146 against 1.000, head share 0.487 against 0.123, and the cold-item column 0.0000 against 0.1935. The general version, which applies past retrieval, is that when your candidate methods cluster on the primary metric, the primary metric has stopped being the decision input and continuing to optimise it is how a team spends six months moving 0.01 while the thing that actually differentiates the options goes unmeasured.

What we would actually pick: item-kNN, until the catalogue passes roughly 40,000 items or the cold-item traffic becomes a funded problem. It scores 0.2236 against the towers’ 0.2417, it beats them on NDCG@10, it has no training job, no index build, no embedding table and no sampling-bias subtlety, and the 0.0181 of recall it gives up is worth less than the four systems it does not require. The switch happens on one of two triggers: the item-item matrix stops fitting in memory, which is arithmetic rather than judgement; or the cold-item column starts mattering, where kNN’s structural 0.0000 against the towers’ 0.1935 is not a gap that tuning closes.

Key Takeaways

  • Retrieval is a stage, not a small ranker. Its metric is recall at the k the next stage consumes, its loss is an approximation to a softmax that cannot be computed, and its architecture is defined by what it is forbidden to see. Optimising its NDCG is spending the tuning budget on somebody else’s metric.
  • The factorisation constraint is the product, not a limitation. Giving up query-document interaction features costs a measured 0.0385 of recall@100 and buys an item vector that can be computed once a night for 20 million items. The cross-encoder that scores 0.2802 cannot be served and belongs in the second stage.
  • A batch is a sample of events, so in-batch negatives are biased toward the head. The top 1% of items hold 28.06% of events. Subtracting log Q(item) from the logits is worth 0.0682 of recall@100, more than doubles the head’s own hit rate from 0.0943 to 0.1999, and halves the zero-history item’s from 0.3871 to 0.1935. It is a redistribution and a pooled number cannot show it.
  • The sampling correction belongs to the loss and nowhere else. Applied at serve time as well it gives 0.1336, worse than never applying it, which is a plausible enough number to get a correction worth 0.0682 deleted.
  • Batch size is an accuracy hyperparameter when the batch is the negative sampler, and more negatives is not strictly better: the loss-estimator gap falls monotonically from 3.3833 to 0.1528 while recall@100 peaks at batch 128 and falls at 1,024.
  • Report distance computations, not milliseconds, and never call index recall accuracy. The distance count is a property of the algorithm and survives reimplementation and catalogue growth. An index at index-recall 1.0 reproduces the model including every mistake it makes.
  • IVF-PQ has two recall losses and only one is tunable. At n_probe equal to the list count the routing error is zero and 0.2415 of index recall is still gone, which is the quantiser’s floor and the price of 32x compression.
  • Segment every metric by both cold cohorts or the pooled number will lie to you. The towers’ 0.2417 against ALS’s 0.2219 is a 0.0198 pooled gain that hides a 0.5382-against-0.0634 cold-user gap and a 0.1329-against-0.1571 warm-user loss.

The counter-intuitive lesson is the cold-start one, and it runs against the way this work usually gets funded. A neural retriever with 34 metadata columns and a learned history embedding scores 0.5382 on users with no history. A count table scores 0.6467 on the same users, because a user with no history has no signal, the best available answer is the population prior, and a popularity ranker is the population prior with no estimation error on top. Every learned model pays variance to approximate something a count gets exactly right. The towers earn their place on coverage, on head share, and on the cold item column where popularity is structurally zero, and a proposal that justifies them on cold-start grounds is claiming something the measurement does not support.

Frequently Asked Questions

Q: Why not just use ALS, which also factorises and also indexes?

A: Because an ALS row with no interactions is the zero vector, so its score is constant across the catalogue and its ranking is a tie-break. Measured: 0.0634 against the towers’ 0.5382 on users with no history, 0.0000 against 0.1935 on items with no history, and catalogue coverage of 0.824 against 1.000. On warm users ALS is better, 0.1571 against 0.1329, and if you have no cold traffic and a stable catalogue it is the simpler choice.

Q: Why not skip retrieval and make the ranker fast enough to score everything?

A: The arithmetic does not close. A 340-feature GBDT over 20 million items inside a 30 millisecond budget is roughly four orders of magnitude past the hardware, and compression does not help because the binding constraint is not the model’s size but that its best features are functions of the (user, item) pair and so cannot be precomputed. The ablation in “Alternative Approaches” measures what those features are worth: 0.0385 of recall@100, which is real and unservable.

Q: Why recall@100 rather than NDCG@10, when NDCG is what the business cares about?

A: Because the retriever does not determine the order the user sees; the ranker does. Tuning the retriever on NDCG@10 optimises the top of a list that gets reordered immediately afterward. The companion codebase measures the cost of the confusion: over a temperature sweep, NDCG@10 moves 102% and recall@100 moves 21% non-monotonically, so a retriever tuned on NDCG picks a value the retrieval metric cannot distinguish from a much worse one, and a retriever tuned on recall sees a flat curve and concludes the parameter does not matter.

Q: Is the logQ correction worth the complexity on a catalogue that is not Zipf-skewed?

A: Its magnitude scales with the skew. Here the top 1% of items hold 28.06% of events and the correction is worth 0.0682 of recall@100; a flatter catalogue gets less, and a uniform one gets nothing because Q is then constant and the subtraction is a constant shift that the softmax ignores. Real catalogues are usually more skewed than this one rather than less, so the direction transfers and the number has to be re-measured. Measure your own: compute the share of events held by the top 1% of items before deciding.

Q: How do I evaluate a retriever when the log was generated by the incumbent system?

A: You largely cannot, and this is the honest limitation of every number in this post. The test events here came from a simulator where each item had an equal chance of being observed; a real log is the output of the deployed recommender, so an item it never retrieved has no positive events and its absence reads as evidence nobody wants it. That makes every cold-item number an upper bound. Off-policy estimators help for a ranking change and help much less for a retrieval change, because a retrieval change alters the candidate set itself and the logged propensities say nothing about items that were never candidates.

Q: What breaks first in production, and what is the signal?

A: Index staleness and feature-pipeline defaults, both of which collapse the model toward the popularity prior. The signal is head share of served slots, tracked hourly: the shipped model serves 0.123 and a collapse toward popularity’s 0.487 is a four-fold change, while recall@100 barely moves because the pooled metric is dominated by warm users whose answers are in the head anyway. Second signal is index recall against brute force on a fixed probe set, which needs no labels and catches a corrupted or stale index directly.

Interview Questions

Q: A candidate proposes adding a “number of times this user has purchased from this item’s brand” feature to improve a two-tower retriever. Walk through your response.

Expected depth: identify it as a query-document interaction feature; explain that it makes the item representation a function of the pair, so g(item) is no longer computable at index-build time and there is nothing to put in the index; distinguish this from features computed over the user’s own history, which are functions of the query alone and are fine; place the feature in the ranking stage instead; and quantify the tradeoff rather than asserting it, citing the measured 0.0385 of recall@100 and 0.0294 of NDCG@10 that obeying the constraint costs.

Q: Derive the in-batch sampled softmax loss and explain exactly why the logQ correction is needed and what its gradient is.

Expected depth: write the full softmax over N items and state why it is intractable; derive the importance-sampled estimate of the denominator, (1/m) sum exp(s_j) / Q(j) equals (1/m) sum exp(s_j - log Q(j)); identify Q(j) as proportional to item j’s event share because the batch samples events and not items; note that the correction’s gradient with respect to the parameters is zero since log Q is a constant, so it changes the softmax probabilities and every parameter gradient while contributing no term itself; explain that the correction applies at train time only because the trained score already absorbs the popularity term; and discuss the pseudo-count for zero-count items.

Q: Your IVF-PQ index has an index recall of 0.72. Your colleague proposes raising n_probe. What do you say?

Expected depth: separate the two independent recall losses, routing and quantisation; note that n_probe only addresses routing; propose the diagnostic of setting n_probe to the list count, which zeroes the routing error by construction and exposes the quantiser’s floor; interpret the result, in the measured case 0.7585 at full probe meaning 0.2415 is unreachable; discuss the actual levers for the quantisation loss, more subvectors, more bits, fitting codebooks on residuals rather than raw vectors (measured at 0.2409 against 0.3483 mean error), or an anisotropic loss as in ScaNN; and note the latency cost of full probe, 1,540 distances against 247 at n_probe 6.

Q: You increase the training batch size from 128 to 1024 and the validation loss improves while the offline recall gets worse. Explain.

Expected depth: identify that the in-batch loss and the full-softmax loss are different quantities and that a larger batch is a better estimator of the second, so “the loss improved” may be a statement about the estimator rather than the model; give the measured gap shrinking from 2.1093 at batch 128 to 0.1528 at 1,024; then give the two mechanisms working against recall, the drop from 228 to 28 optimiser steps per epoch at fixed epochs, and the growing share of the softmax denominator occupied by items that are not meaningful negatives; and conclude that the two must be disentangled by equalising steps rather than epochs before any conclusion about batch size is drawn.

Q: How would you tell whether a retrieval model has silently degraded in production, given that you only see clicks on what you served?

Expected depth: explain why recall-style metrics are insensitive to the dominant failure mode, which is collapse toward the popularity prior; propose distributional signals that need no labels, head share of served slots (0.123 shipped against popularity’s 0.487), catalogue coverage, and the entropy of the served-item distribution; propose index recall against brute force on a fixed probe set as a label-free correctness check on the index itself; propose the short-of-k rate after the exclude-seen filter; and address the feedback loop, that clicks on what you served cannot measure what you failed to retrieve, which is the argument for a small randomised holdout and the subject of bandit-based exploration.

View full code for this problem