Mental model
Recommendation systems rank a changing set of items for each user by separating broad candidate retrieval from context-rich ranking. A two-tower model embeds users and items so an approximate-nearest-neighbor index can retrieve a few thousand candidates cheaply; a DLRM-style ranker then combines sparse IDs and dense context to order a small slate under latency and product constraints.
Learning outcomes
- Trace a request through two-tower candidate generation, ranking, and constrained slate assembly.
- Calculate the storage cost of item embeddings and a sampled-softmax retrieval loss.
- Choose evaluation metrics that separate candidate recall, ranking quality, calibration, and online impact.
Theory
Candidate retrieval with two towers
A retrieval model maps a user context x_u to a query vector q_u and an item i to a vector v_i. Their inner product is a relevance score. The item tower can encode text, categories, and other item features, while the user tower summarizes recent interactions and context available at request time. Since the item vectors do not depend on the current user request, a service can compute them offline and place them in an approximate-nearest-neighbor (ANN) index. At request time it computes one query vector and retrieves a few hundred or thousand candidates from a catalog that may contain tens of millions of items.
Training often uses clicked or otherwise positive interactions and in-batch negatives: other items in the same minibatch act as plausible alternatives. With batch size B, temperature τ, user vector q_b, and the matching positive item vector v_b, the basic in-batch softmax objective is:
The objective is convenient because one matrix multiplication scores every user against every item in the batch. It also inherits the batch's sampling distribution. If popular items appear as negatives more often than long-tail items, the uncorrected denominator can teach the model to reject them too aggressively. Yi et al. study this sampling bias in two-tower retrieval and estimate item frequency from a stream to correct the sampled objective. In production, record the sampler version and sampling probabilities with the model; a correction computed from a different catalog or time window can create its own mismatch. Another trap is a false negative: a different user's positive item may also be relevant to the current user. Mask known positives or use a sampling design that reduces this contamination.
Ranking and feature interactions
Retrieval optimizes coverage at a bounded cost, not the final ordering. A separate ranker receives each candidate plus request-time features such as recent user activity, inventory, device, and position. DLRM represents categorical fields with embedding lookups, transforms dense fields with a bottom multilayer perceptron, computes pairwise interactions among feature vectors, then feeds the interactions and dense representation to a top MLP. This architecture captures useful crosses such as user-category affinity without allocating one parameter for every possible combination.
The ranker usually predicts a task tied to logged outcomes, such as click probability or conversion probability. That prediction is not automatically a causal estimate of what would happen if an item moved to another position: the logging policy already determines which items receive exposure. Keep candidate retrieval metrics separate from ranking metrics. Recall@K asks whether a known positive item survived retrieval; NDCG@K or MRR measures whether relevant items are placed near the top after ranking. Calibration, catalog coverage, diversity, and user-level slices reveal regressions hidden by an aggregate AUC or click-through rate.
Quantitative model
For a small score example, let a user vector be (0.6, 0.8). Candidate A has vector (0.9, 0.2) and scores 0.6 × 0.9 + 0.8 × 0.2 = 0.70; candidate B (0.4, 0.9) scores 0.24 + 0.72 = 0.96, so B ranks above A before business or safety constraints. The figures are dot-product scores, not probabilities. If the product needs calibrated click probabilities, fit and validate a calibration layer on a time-consistent held-out set rather than interpreting this raw score as a probability.
Embedding memory often dominates model size. A table for 30 million item IDs with 128 dimensions and two-byte values requires 30,000,000 × 128 × 2 = 7,680,000,000 bytes, or 7.68 GB (about 7.15 GiB) for raw vectors alone. The ANN structure, identifiers, replicas, and temporary rebuild copies add further capacity. This is why DLRM systems may shard large embedding tables separately from the dense layers, and why capacity estimates must include index overhead rather than only parameter count.
Trade-offs
A larger retrieval set can improve candidate recall, but it increases feature joins and ranking work. If retrieving 2,000 candidates instead of 500 raises Recall@2,000 from 0.91 to 0.96 while adding 18 ms to p95 ranking latency, decide whether that coverage is worth the added budget for the target surface. One option is to use a fast first-stage ranker before the expensive contextual model. Another is to cache item representations while versioning the ANN index and invalidating entries when item content or eligibility changes.
More categorical features can help the ranker model cross-field effects, but each high-cardinality feature increases embedding memory and network traffic. Hashing, pruning, quantization, and row-wise sharding reduce cost with different accuracy and operational trade-offs. Two-tower retrieval gives independent item encodings that are easy to precompute, but can miss pairwise context that only exists at request time; the ranker supplies that context, at the price of scoring candidates one by one or in a larger batch.
Offline replay is inexpensive and repeatable, but it evaluates the historical exposure policy. Online randomized experiments measure actual user response, yet they need guardrails for latency, inventory, safety, and subgroup outcomes. Set a primary outcome and non-inferiority checks before looking at a result. A model that increases clicks while overexposing a narrow item group or violating inventory constraints is not a successful release.
Failure modes and misconceptions
- Optimizing only ranker quality: The ranker cannot recover a relevant item omitted by the candidate generator. Track Recall@K before interpreting NDCG or click metrics.
- Treating every unclicked impression as a negative: Position, availability, and the logging policy affect whether an item could be seen. Preserve exposure data and evaluate selection bias before training.
- Mixing model and index versions: A query tower trained against one item-vector snapshot can be scored against another. Publish a versioned pair and switch the model and ANN index together.
- Ignoring feature freshness: A stale inventory or recent-history feature can rank unavailable items or make repeated events dominate. Add freshness checks and deduplicate event identities before aggregation.
- Calling embeddings a cold-start solution: A new item without content or interaction data may still have a poor vector. Use content features, explicit fallback candidates, and coverage metrics for new and low-traffic items.
- Reading click lift as user value: Position and popularity feedback can reinforce exposure. Keep randomized holdouts, calibrated outcomes, and diversity or quality constraints in the rollout review.
Decision scenario
A media service with 30 million items sees offline Recall@500 improve from 0.91 to 0.94 after retraining its item tower. During a 5% canary, click-through rate rises 1.8%, but the new ANN index is built from a catalog snapshot two days older than the ranker features; p95 latency also increases from 74 ms to 93 ms against an 85 ms budget. Hold the rollout. Compare timestamped item eligibility and embedding versions, inspect recall and ranking metrics by freshness and new-item cohort, and check exposure-adjusted outcomes. Promote only after the model and index are published as a matched version, stale or unavailable candidates are handled, and the latency target is met. If no matched rollback snapshot exists, restore the prior pair before further experimentation.
Implementation pattern
This training step uses each row's paired item as the positive and other items in the same batch as negatives. It is a compact retrieval baseline, not a production loss correction: measure item sampling frequencies and apply the correction appropriate to the sampler before using in-batch scores against a skewed catalog.
pythonimport torchfrom torch import nnfrom torch.nn import functional as Fclass TwoTower(nn.Module):def __init__(self, user_count: int, item_count: int, width: int = 128):super().__init__()self.user_table = nn.Embedding(user_count, width)self.item_table = nn.Embedding(item_count, width)def forward(self, user_ids: torch.Tensor, item_ids: torch.Tensor):users = F.normalize(self.user_table(user_ids), dim=-1)items = F.normalize(self.item_table(item_ids), dim=-1)return users, itemsmodel = TwoTower(user_count=100_000, item_count=250_000)optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3)user_ids = torch.tensor([12, 37, 54, 89])item_ids = torch.tensor([101, 208, 317, 422])users, items = model(user_ids, item_ids)logits = users @ items.T / 0.08targets = torch.arange(user_ids.numel(), device=user_ids.device)loss = F.cross_entropy(logits, targets)optimizer.zero_grad(set_to_none=True)loss.backward()optimizer.step()assert torch.isfinite(loss)