Picture a video app with a billion videos in its catalogue, and a user named Maya who opens it on her phone one weeknight evening. She has watched a lot of cooking videos lately. The app has to fill her screen with videos she'll want, and it has about 30 milliseconds to do it before the page starts to feel slow. Software that picks, from a large catalogue, the few items a particular person is most likely to want is a recommender system, and the catalogue it picks from is called the corpus.
Why is that hard? The most accurate thing we could build would be a model that reads Maya's profile and one video's details together and outputs a score. Running that model once for each of a billion videos is far beyond 30 milliseconds. So production systems narrow the field first and score later. A cheap first stage retrieves about a thousand candidates, an expensive model then ranks them, and a last pass reranks the top few for variety and business rules. We'll see that the cheap stage has to be built as two separate encoders, called a two-tower model, and that this one engineering constraint dictates the architecture.
A second difficulty has nothing to do with speed. Every model here learns from what users clicked, but users could only click on what the previous version of the system chose to show them. So a click tells us what Maya picked out of what she was shown, and only indirectly what she wanted. That loop, with a model's own choices turning into its next training data, is the hardest problem in the chapter.
You should know what an embedding is, a list of numbers whose geometry carries meaning (chapter 09), and how dense retrieval compares such lists (chapter 11). We'll build up from the oldest recommendation idea, matrix factorization, to the two towers, then to the ranker and how it's trained. After that we look at the three ways the data misleads us, what to do about new users and new items, and how a billion vectors get searched in about a millisecond.
01The funnel
Let's start with what Maya's request looks like from the system's side. Her phone sends a request, and somewhere a service has to turn "this user, right now" into an ordered list of ten or so videos. We met the constraint in the opening: every video can't be examined carefully, and the model that examines carefully gives the best answers. One way out is to spend effort unevenly, with a little on every video and a lot on the few that survive. Below is the resulting shape for one request, and the numbers on it are what force the design.
First comes retrieval, also called candidate generation. It reduces a billion videos to about a thousand, taking roughly a millisecond, and its work has to be sublinear in the size of the corpus, which means doubling the catalogue must not double the work. That rules out anything that looks at Maya and a video together, because we'd have to do that once per video. Retrieval therefore gets the cheapest possible test, a single dot product between a vector for Maya and a vector for a video. Next, ranking scores the survivors precisely. It can afford a full pass of a large model per candidate, with rich features that see the pair together, because a thousand or so is a small number. Last, reranking looks at the finished list as a whole. Scoring each video on its own can't notice that three of the top five are near-identical, that nothing published this week made it in, or that one video breaks a policy, so reranking fixes those with whole-list logic.
This two-stage split was set out in the 2016 YouTube paper listed under "Go deeper", and the shape has barely changed since. What has changed is what sits inside each box, and the next few sections open them one at a time, starting with the oldest idea in the retrieval box: how can we guess what Maya wants if we know nothing about the videos themselves?
02Collaborative filtering: the idea everything else refines
Here's a surprising fact about recommendation: you don't need to know what a video is in order to recommend it. Suppose Maya and two other people have all watched the same five cooking videos, and the other two also loved a sixth one that Maya hasn't seen. Maya will probably like it too, and nothing in that guess used a title, a genre or a description. Collaborative filtering is this idea turned into a method. It uses only the record of who touched what, on the assumption that users who agreed in the past will agree again.
To make it precise, write the record as a table with one row per user and one column per item, where each cell holds a rating or a watch. Such a table is enormously sparse, since a typical user has touched a vanishing fraction of the catalogue, so most cells are blank and the job is to fill them in. Matrix factorization does this by assuming the table is secretly low-rank, meaning it can be rebuilt from a small number of hidden tastes. Each user gets a short vector, each item gets a short vector of the same length, and the prediction for a cell is the dot product of the two:
Here is the number of users, the number of items, and the length of each vector, the number of hidden factors we allow. Every user and every item becomes a -dimensional vector, and a prediction is one dot product. Nobody tells the model what the factors mean. They're whatever directions of taste make the known cells come out right.
It's easier to believe once you see it work. Our code builds a tiny table of 6 users and 6 items. Users 0 to 2 like items 0 to 2, users 3 to 5 like items 3 to 5, and nobody says so. A 0 means the user never interacted with that item, so the mask on the line mask = R > 0 hides those cells from the loss, and the model learns from observed entries only. It uses k = 2, so every user and item is squeezed through two numbers. Each loop pass computes the error on observed cells and nudges U and V to shrink it, with a small .05 pull toward zero (weight decay) to keep the vectors modest. After training it predicts four cells the model never saw.
Try it Factorize a tiny ratings matrix and watch the blanks fill in
import numpy as np
# 6 users x 6 items. 0 = never interacted, so the model never sees it.
# Users 0-2 like items 0-2. Users 3-5 like items 3-5. Nobody says so.
R = np.array([[5., 0., 4., 1., 1., 0.],
[4., 5., 5., 1., 1., 1.],
[5., 4., 5., 1., 0., 1.],
[1., 1., 1., 5., 0., 5.],
[1., 1., 1., 4., 5., 5.],
[0., 1., 1., 5., 5., 4.]])
mask = R > 0 # learn from observed entries only
k = 2 # two latent factors -- the bottleneck
rng = np.random.default_rng(0)
U = rng.normal(0, .1, (6, k)) # user vectors (6, 2)
V = rng.normal(0, .1, (6, k)) # item vectors (6, 2)
for _ in range(6000): # plain SGD, with weight decay
err = mask * (R - U @ V.T)
U += .02 * (err @ V - .05 * U)
V += .02 * (err.T @ U - .05 * V)
P = U @ V.T
print("shapes:", U.shape, "@", V.T.shape, "->", P.shape, "\n")
for (u, i) in [(0, 1), (3, 4), (2, 4), (5, 0)]:
print(f"user {u}, item {i}: unseen -> predicted {P[u, i]:.1f}")
4.2 and user 3 on item 4 at 5.5, but user 2 on item 4 at 1.0. It has worked out which group each user belongs to and predicts accordingly, though nothing in the input said there were two groups. That fell out of forcing every user and item through k=2 numbers.Look at those four predictions. Every one is a cell the model never saw. It puts user 0 on item 1 at 4.2 and user 3 on item 4 at 5.5, yet user 2 on item 4 comes out at 1.0. It has worked out which group each user belongs to and predicts accordingly, even though nothing in the input mentioned groups.
Why does squeezing through two numbers help?
If were large enough, could reproduce exactly, blanks excluded, and we'd have learned nothing, because the model would have stored each rating individually. That bottleneck is what forces it to find structure. Pushing millions of users through 64 numbers means the model has nowhere to keep the specifics, so the only way to explain the data is with patterns that carry over to cells it hasn't seen. This is the bottleneck argument from the autoencoder on page 03: compression forces generalisation.
So collaborative filtering gives every user and item a vector, and similar tastes end up as nearby vectors. That's probably most of what retrieval needs. What's left is making it work for a billion items and for users who aren't in the training table, and that brings us to the design where the user and item vectors come from two separate models.
03Two-tower retrieval, and the constraint that shapes it
Matrix factorization gives each user and item a vector, maybe 64 numbers long, that was looked up by its ID. We'd like to compute those vectors from features instead, such as Maya's device, language and recent watches, or a video's text and category, so that a user or video outside the training table still gets a vector. Using features the obvious way means is one big model that reads a user and an item together and outputs a score, with cross-attention between them and rich interaction features. That model would be far more accurate than a dot product. For retrieval it's also, perhaps surprisingly, banned, because at a billion items it would need a billion forward passes per request.
So retrieval accepts a hard rule: the user and the item must never meet until the final dot product. We use two separate encoders, one for users and one for items, and a single score:
Here is the user tower and the item tower, each a neural network with its own parameters, and the two have no interaction until the end. That separation buys a great deal. Because doesn't depend on the user, every item vector can be computed offline, once, and loaded into an index. At request time we embed Maya with the user tower and search the index for the item vectors closest to hers, a job called approximate nearest neighbour search, which we'll get to in section 08. None of the billion gets touched.
Training needs positive examples, which are pairs of a user and an item they clicked, and it needs negatives, items the user didn't pick. Sampling negatives is awkward, so the common trick is to take them from the same batch. Our code builds two small towers, each a two-layer network (nn.Sequential) that turns raw features, 64 for users and 48 for items, into a 32-number vector. It then normalizes each vector to length 1 so the dot product behaves like cosine similarity. With a batch of B = 8 pairs, where item i is the one user i clicked, the line u @ v.T scores every user against every item at once, giving an 8 by 8 table of scores called logits. Dividing by 0.05 sharpens the differences, and the loss is ordinary cross-entropy that asks each row to put its highest score on the diagonal.
Try it A two-tower model, in-batch negatives, and the shapes at every step
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
D = 32 # embedding width
user_tower = nn.Sequential(
nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, D))
item_tower = nn.Sequential(
nn.Linear(48, 128), nn.ReLU(), nn.Linear(128, D))
B = 8
user_feats = torch.randn(B, 64) # (B, 64)
item_feats = torch.randn(B, 48) # (B, 48) item i is user i's +ve
u = F.normalize(user_tower(user_feats), dim=-1) # (B, D)
v = F.normalize(item_tower(item_feats), dim=-1) # (B, D)
logits = u @ v.T / 0.05 # (B, B) every user vs every item
labels = torch.arange(B) # the diagonal is the positive
loss = F.cross_entropy(logits, labels)
print("u", tuple(u.shape), "v", tuple(v.shape))
print("logits", tuple(logits.shape), "loss", round(loss.item(), 3))
u and v are both (8, 32), and logits is (8, 8). Each row is one user scored against every item in the batch. The diagonal is the item they clicked, and the other B-1 are free negatives you didn't have to sample. The untrained model prints a loss of 6.252.Notice the shape of logits, (B, B). Each row is one user scored against every item in the batch. Its diagonal entry is the item they clicked, and the other B-1 items are negatives that cost nothing extra, because they were already encoded for their own users. This is in-batch negative sampling.
Why does batch size matter so much for a two-tower model?
In ordinary supervised training, batch size mostly affects speed and gradient noise. Here it also sets how many negatives each positive is compared against, since the negatives are the other items in the batch. A bigger batch gives a harder, more informative comparison for every example.
Free negatives come with a bias, though. They're drawn from your traffic, so popular videos appear as negatives far more often than rare ones, and the model learns to push popular videos down, exactly backwards. A standard fix is a logQ correction: subtract the log of each item's sampling probability from its logit, so frequently sampled items aren't unfairly penalised. It comes from the 2019 Google two-tower paper linked at the end of the chapter, and skipping it is a common and quietly expensive mistake.
Retrieval now hands the ranker about a thousand candidates for Maya, and since the towers are done, the ranker can use everything retrieval was denied.
04Ranking: where the expensive model earns its keep
A thousand candidates is small enough to score extravagantly, and this stage decides what Maya sees. Retrieval couldn't let her profile and a video interact, but the ranker can, so it receives cross features (facts about the pair), her long watch history, the video's recent click-through rate (the fraction of people shown it who clicked), and the time of day.
Here's the difficulty: useful signals are usually combinations. "Maya likes cooking videos" is a weak signal, while "Maya likes cooking videos, on a phone, in the evening" is a strong one. A plain multilayer perceptron can in principle learn such combinations, but on sparse categorical features, where most inputs are one-hot IDs, it does so slowly and badly. Two families of architecture attack this directly.
Wide & Deep (Google, 2016) runs two paths side by side. Its wide path is a linear model over hand-crafted cross features, which memorises specific combinations known to matter. Its deep path is a neural network that generalises to combinations it has never seen. Their outputs are summed and the two are trained jointly. DeepFM (2017) removes the hand-crafting. A factorization machine component (the dot-product idea from section 02 applied to features) learns every pairwise feature interaction automatically and shares its embeddings with a deep component, so no feature engineer has to write the crosses.
It's tempting to read the wide path as a legacy part that deep learning should have replaced. But some facts are arbitrary and have to be memorised: this user buys this brand of coffee, for no reason the features explain. A deep path can't store that without overfitting everything else, and the wide path can, so Wide & Deep accepts that a recommender needs both memorising and generalising.
Sequence matters, and modelling it changes the answer
So far we've treated Maya's history as a set. It is ordered, and the order carries information. If she watched three episodes of one series in a row, she wants the fourth, and a bag of her all-time favourites doesn't say that. SASRec (2018) applied a causal self-attention stack to the interaction sequence, predicting the next item from the ones before it. That's a language model over items instead of tokens, using the same architecture as page 08 with a different vocabulary.
We now have a model that scores each candidate for Maya, and what's left is how to train it. Its output is a list, and an ordered list is a different target from a single score.
05Learning to rank: three ways to phrase the loss
You're producing an ordered list, but the obvious loss functions score one item at a time, and that mismatch has three standard answers. They differ in how much of the list the loss gets to see.
| Approach | What the loss sees | Optimises | Cost |
|---|---|---|---|
| Pointwise | one item | predicted score vs. label | cheapest, ignores order entirely |
| Pairwise | two items | is the better one ranked higher? | matches the task, quadratic pairs |
| Listwise | the whole list | a ranking metric directly | closest to the goal, hardest to optimise |
Pointwise treats ranking as regression or classification. Predict a click probability for each video, then sort by it. It's simple, and it's what most production rankers do, because sorting by a well-calibrated probability is a strong baseline. Its weakness is in the table: it ignores order entirely.
Pairwise asks a narrower and better-posed question. Given a video Maya clicked and one she saw but skipped, does the model score the clicked one higher? BPR (Bayesian Personalized Ranking) is the canonical version for implicit feedback, meaning feedback inferred from behaviour such as clicks, with no star ratings. It models the chance that the clicked video outranks the skipped one as the sigmoid of the score gap, and it minimises the negative log of that chance. Here it is applied to three pairs, each with a score for the clicked item and a score for the skipped one.
Try it The BPR loss, which is three lines and one good idea
import torch, torch.nn.functional as F
# For one user: an item they clicked, and one they saw but skipped.
s_pos = torch.tensor([2.10, 1.80, 1.50]) # scores for clicked items
s_neg = torch.tensor([1.30, 1.10, 1.90]) # scores for skipped items
# BPR maximises P(positive above negative) = sigmoid(s_pos - s_neg).
margin = s_pos - s_neg
per_pair = -F.logsigmoid(margin)
print("margins: ", [round(m, 2) for m in margin.tolist()])
print("per-pair: ", [round(x, 3) for x in per_pair.tolist()])
print("total: ", round(per_pair.mean().item(), 4))
0.913 against 0.371 and 0.403 for the two correct pairs. Nothing in the loss mentions a target value. BPR only claims that the clicked item belongs above the skipped one.Only the difference between the two scores appears. The third pair is ranked wrong, because the skipped item scores higher, so its margin is negative and its loss is 0.913, against 0.371 and 0.403 for the two correct pairs. Notice what's absent: any target value. BPR never claims a video deserves a 4.2, only that it belongs above another one, and when no ratings exist that's the only honest thing to ask.
Listwise goes after the ranking metric itself. Trouble is, ranking metrics are step functions of the ordering. Swap two items and the score jumps, so there's no usable gradient. LambdaRank sidesteps this by defining the gradient directly, weighting each pair by how much swapping it would move the metric NDCG, which we define next.
The metrics, and what each one refuses to tell you
Three metrics come up constantly, and each answers a different question. Recall@k asks, of the items the user wanted, how many made the top . It's the right metric for the retrieval stage, where the only goal is not losing anything good. MRR (mean reciprocal rank) is one over the rank of the first relevant hit, averaged over queries, which suits cases with one correct answer such as a navigational search. NDCG@k discounts each item's gain logarithmically by its position, then normalises by the best possible ordering, so a perfect list scores 1. It's the standard ranking metric because it knows position 1 beats position 10.
All three are offline metrics, computed against logged data, and that's their catch. Logs record what users did with the results of the old ranker. A new model that surfaces something better gets no credit for it, because nobody ever clicked a video the old system never showed. Serious recommender teams therefore treat offline metrics as a filter and decide with an online A/B test, in which two versions run on live traffic and real behaviour is compared. Page 24 covers the experimentation machinery. And that observation, that the log is a record of the old model's choices, is where the real trouble starts.
06The data lies, and it lies in a specific direction
If you take one thing from this chapter beyond the funnel, make it this section. It separates people who have run a recommender from people who have read about one. A click isn't a statement that Maya wanted a video. It's a statement that she wanted it out of what she was shown, and what she was shown was chosen by the previous version of your model. Three problems follow from that, and they compound.
First there's position bias. Videos at the top of the screen get clicked because they're at the top, so if you train naively you learn that whatever you ranked first is good, and that's circular. Next comes exposure bias. A video that was never shown has no clicks, so it looks bad, so it stays unshown, and the set of videos you can learn anything about shrinks over time. Last is popularity feedback. Popular videos get recommended, which makes them more popular, which makes the model more certain about them, and the catalogue quietly collapses toward a small head.
Why isn't this just ordinary distribution shift?
Usually distribution shift means the world changed underneath the model. Here the model changed the world. Your system chooses the impressions, the impressions become the training data, and the training data trains the next system. It's a closed loop with your own model inside it. A better architecture doesn't break that loop, so the fixes concern data collection and leave the model alone.
Practical mitigations are unglamorous, and they work. One is to model position explicitly: feed the displayed position in as a feature during training, then fix it to a constant at serving time, so the model has to attribute some of each click to the slot and not only to the video. Another is inverse propensity weighting: weight each logged example by one over its probability of having been shown, so rarely shown videos count for more. A third is deliberate exploration, spending a small slice of traffic on videos the model is uncertain about, specifically to generate data you wouldn't otherwise get.
That last one is a genuine cost, because you're knowingly showing some users something worse now to have a better system later. How much to spend is the subject of the next section, which also covers a closely related problem, the users and videos with no history at all.
07Cold start and exploration
Collaborative filtering needs interaction history, and new users and new items have none. Every real system faces this daily, and it comes in three cases, only two of which have good answers. A new video is tractable: use content features such as text, images and category, so the item tower can produce a vector on day zero without any interactions. A new user is probably harder, since nothing about their taste is known yet. Fall back to popularity and context such as locale, device and referrer, then adapt quickly, because the first session matters disproportionately. A new system has no data at all, so it has to be content-based or rule-based until enough interactions accumulate, so the first version of a recommender is usually not a recommender.
Exploration is the systematic version of the same problem. At every request you can exploit what you know, showing what the model thinks Maya likes best, or explore to learn more, showing something whose value is uncertain, maybe a cooking video from a channel she's never watched. Epsilon-greedy shows a random item some fraction of the time. Thompson sampling is better behaved: it samples from the posterior over each item's value, meaning the model's current spread of beliefs about how good it is, and shows the highest sample, so uncertainty drives exploration and not a coin flip. Page 15 covers the bandit machinery properly.
One piece of the funnel is still unexplained, the search through a billion item vectors that we promised in section 03.
08Making retrieval fast: ANN indexes
Our user tower gives us a vector for Maya, and finding its neighbours among a billion others is a separate engineering problem with its own literature. Exact nearest-neighbour search compares the query with every vector, so it's linear in corpus size, which defeats the point. Approximate nearest neighbour (ANN) search gives up a small amount of recall for orders of magnitude of speed. Two families dominate.
Graph-based indexes such as HNSW build a navigable small-world graph over the vectors, in which each vector links to some near ones and a few distant ones, and then walk it greedily toward the query. This gives an excellent recall-latency tradeoff at a high memory cost. Partition-and-quantise indexes such as IVF-PQ, as implemented in FAISS, cluster the vectors, search only the nearest clusters, and compress each vector into a compact code. Their memory footprint is far smaller, and the price is some accuracy lost to the compression.
Does a 98% recall index mean 98% good recommendations?
No, and the difference is a common way for retrieval work to stall. An ANN index is measured against the exact nearest neighbours of the same embedding model, so 98% recall means you found 98% of what your model would have ranked highest. It says nothing about whether the model was right. Tuning the index to 99.5% while the embedding model is mediocre is effort in the wrong place.
That completes the funnel from request to list, and the recurring theme is that the model is rarely what fails. To believe the feedback loop from section 06, watch it happen, as the project below lets you do.
09Summary
- You can't score a billion items in 30 ms, so the system narrows first. It retrieves about a thousand candidates, ranks them with an expensive model, then reranks the top few for diversity and business rules.
- Each stage is about 10 times smaller and 100 times more expensive per item than the one before, which keeps total latency flat.
- Collaborative filtering uses only who touched what. Matrix factorization fills the blanks by giving every user and item a short vector, and the low rank is what forces it to generalise.
- Retrieval is a two-tower model because the item tower doesn't depend on the user, so every item vector is computed offline and indexed. User and item never meet until the final dot product.
- In-batch negatives are free but biased. Popular items appear as negatives too often, and a logQ correction fixes it.
- The ranker gets everything retrieval was denied, such as cross features and history. Wide & Deep memorises and generalises, DeepFM learns interactions on its own, and SASRec models the order of the history.
- Pointwise, pairwise and listwise losses differ in how much of the list they see. BPR asks only whether the clicked item beats the skipped one.
- Offline metrics are measured on the old ranker's logs, so they reward agreeing with it. Use them as a filter and decide with an A/B test.
- The data is a record of your own earlier decisions. Position bias, exposure bias and popularity feedback compound, and the fixes are in data collection: model position, weight by inverse propensity, and explore.
- Cold start has content-based answers for new items and popularity and context for new users. Thompson sampling lets uncertainty drive exploration.
- ANN recall is measured against your own model, so a high-recall index can still serve poor recommendations if the embeddings are mediocre.
10Build this
The feedback loop in section 06 is the one thing here you should not take on trust. You can watch it happen in an afternoon, with no data and no GPU.
Build a synthetic world where you know the true user preferences, then train a recommender on its own logged clicks, repeatedly. You are not measuring accuracy. You are watching how fast the system stops being able to see most of its own catalogue.
- Create 1,000 users and 500 items with known latent vectors. True preference is the dot product. This is ground truth that you never show the model.
- Round one: show each user 10 random items. Simulate clicks by sampling from the true preference. Log the impressions and the clicks, not just the clicks.
- Train matrix factorization on the logged clicks only. Use it to pick each user's next 10 impressions, simulate again, and repeat for 20 rounds.
- Each round, record two things: what fraction of the 500 items has been shown to anyone at all, and mean true preference of what was shown.
- Now rerun the whole thing with 10% of slots filled randomly, and plot both curves against the pure-exploitation run.
11What breaks
Recommender failures are rarely a bad model. They are a metric that stopped meaning what you thought.
- Offline metrics improve, the A/B test does not. The single most common outcome. Your offline set was generated by the old ranker, so it rewards agreeing with it.
- The filter bubble closes. Coverage drops quietly while engagement looks stable, until the catalogue is effectively a few hundred items.
- Popularity masquerades as personalisation. A model that just predicts global popularity can score respectably. Always compare against that baseline explicitly — it is embarrassing how often it wins.
- Training and serving features drift apart. The ranker was trained on a feature computed one way in the warehouse and served one computed another way. Page 24 calls this training-serving skew; it is endemic here because there are so many features.
- In-batch negatives punished popular items. No logQ correction, so the model systematically suppresses exactly the items most people want.
- The index degraded. Recall@k of the ANN index drifts as the corpus grows and nobody re-tunes it. Measured end to end, this looks like the model getting worse even though the model has not changed.
- Delayed feedback. A click arrives in seconds, a purchase or a cancellation in days. Train on the fast signal alone and you optimise for clickbait.
12Where you meet this in the wild
Same funnel, very different weightings.
Enormous corpus, implicit feedback only, strong sequence signal. Watch time is the target, which immediately raises the question of whether watch time is the thing you want to maximise.
Two-tower retrieval, sequential ranker, heavy diversity reranking.
The query is an explicit statement of intent, which is a luxury a feed does not have. Relevance and revenue pull in different directions, and resolving that tension is a product decision as much as a modelling one.
Hybrid lexical plus semantic retrieval, then a learned ranker over both.
Repeat consumption is normal and desirable, which breaks the usual assumption that a consumed item should be suppressed. Sessions have a shape: a workout playlist is not a sleep playlist.
Session-based models, strong context features.
The market is two-sided, so a recommendation is only good if both parties want it, and one side has finite capacity — a job can be filled, a person can only reply so often.
Reciprocal objectives plus congestion control.
Not a standard one-sided ranker.
13Interview questions
BeginnerWhy do recommender systems use a multi-stage funnel instead of one model?
Because cost per item and number of items cannot both be large. Scoring a billion items with a rich model inside a 30-millisecond budget is impossible, so the system narrows first with something cheap and scores later with something expensive. Retrieval reduces roughly a billion candidates to a thousand using a single dot product per item against a precomputed index. Ranking then scores that thousand with a full model that can afford cross features and long histories. A final reranking stage fixes list-level properties such as diversity and freshness that pointwise scoring cannot see. Each stage is about an order of magnitude smaller and two orders more expensive per item, which is what keeps total latency roughly flat.
BeginnerWhat is collaborative filtering, and what does matrix factorization add?
Collaborative filtering recommends using only the interaction matrix of who engaged with what, with no content features at all, on the assumption that users who agreed before will agree again. Matrix factorization implements that by assuming the sparse user-item matrix is approximately low-rank, factorizing it into a user matrix and an item matrix of some small dimension k, so a prediction becomes a dot product between a user vector and an item vector. The low rank is the essential part: forcing millions of users through a few dozen dimensions means the model cannot memorise individual entries and must find structure that generalises, which is what lets it predict the blanks.
IntermediateWhy must a retrieval model keep user and item towers separate?
So that item vectors can be computed offline. If the architecture lets user and item features interact before the final score, every item's representation depends on the user, and you would have to run the model once per item per request — a billion forward passes. Restricting interaction to a single dot product at the end means the item tower can be evaluated once per item, ahead of time, and stored in an approximate nearest neighbour index. At request time you embed only the user and query the index, which is sublinear in corpus size. The accuracy cost is real, since no cross features are possible, and that is precisely what the ranking stage exists to recover on the surviving thousand candidates.
IntermediateWhat are in-batch negatives, and what bias do they introduce?
In a batch of B user-item positive pairs, you score every user against every item in the batch, giving a B×B matrix whose diagonal holds the true positives and whose off-diagonal entries serve as negatives. It is efficient because the negatives are already encoded, and it makes batch size effectively the negative count. The bias is that negatives are sampled from your traffic distribution, so popular items appear as negatives far more often than rare ones and the model learns to suppress them — exactly backwards. The standard correction is logQ: subtract the log sampling probability of each item from its logit so frequently sampled items are not penalised for being frequent.
IntermediateCompare pointwise, pairwise and listwise learning to rank.
Pointwise treats each item independently, predicting a score or click probability and sorting by it. It is simple, calibrated and ignores the fact that ranking is about relative order, yet it remains a strong production baseline. Pairwise looks at two items at a time and asks only whether the better one is scored higher, which matches the real task better and suits implicit feedback where absolute relevance labels do not exist; BPR is the canonical example. Listwise optimises a ranking metric over the whole list, which is closest to the goal but hardest to train, because metrics like NDCG are step functions of the ordering with no usable gradient. LambdaRank works around this by defining the gradient directly, weighting each pair by the NDCG change that swapping it would cause.
DeepYour offline NDCG improves by 8% but the A/B test is flat. What is going on?
The most likely explanation is that offline evaluation rewards agreement with the system that produced the logs. Your evaluation set records impressions chosen by the current ranker, so a new model can only be credited for items that were already shown; anything genuinely better that the old system never surfaced has no click to be right about. Related causes are position bias, where the model learns that whatever was ranked first gets clicked and so learns the old ranker's ordering, and a train-serve feature mismatch that only manifests online. Diagnose by checking whether the gain persists on a small randomly-ranked exploration slice, which is unbiased by construction, by inspecting how much of the improvement is concentrated in top positions, and by verifying feature parity between training and serving. The general rule is that offline metrics filter candidates for an online test rather than substituting for one.
DeepExplain the feedback loop in a deployed recommender and how you would mitigate it.
The model chooses impressions, impressions generate clicks, clicks become training data, and that data trains the next model, so the system is learning from a world it created. Three effects compound: position bias, where clicks reflect placement rather than preference; exposure bias, where unshown items accumulate no evidence and therefore stay unshown; and popularity amplification, where recommending popular items makes them more popular and shrinks effective catalogue coverage. This is not ordinary distribution shift, because the model caused it, so no architectural change escapes it. Mitigations act on data collection rather than the model: include displayed position as a training feature and hold it constant at serving so the model attributes some click probability to the slot, weight logged examples by inverse propensity so rarely-shown items count for more, and reserve a slice of traffic for deliberate exploration that produces unbiased data. Exploration has a genuine short-term cost, which is the point — you are paying now for data you cannot otherwise obtain.
DeepHow would you handle cold start for a brand-new item in a two-tower system?
Make the item tower depend on content rather than on an ID embedding. If the tower consumes text, images, category and other metadata, it can produce a usable vector the moment the item is created, with no interactions at all, and that vector can be indexed immediately. A pure ID embedding cannot: it is randomly initialised and stays random until interactions arrive, which they will not, because an unindexed item is never shown. In practice you blend the two, learning an ID embedding that gradually takes over as evidence accumulates while the content vector carries the early period. Alongside that, reserve some exploration traffic specifically for new items so they accumulate evidence at all, and expect that without it the system has no mechanism to ever discover them.