Build a Content-Based Recommendation Engine Using Embeddings
recommendation-systems ranking nlp classical-ml View full code for this problem
ML Problem & Solution
Content-Based Recommendation with Embeddings
Cosine similarity is a correct answer to a question nobody asked, and the metric will not tell you.
A subscription news and analysis publication wants a related-reading module under every article: five to ten things worth reading next, chosen for the reader looking at the page. The archive is 412,000 published articles going back nineteen years, 680 new articles land every day, 2.4 million registered readers generated 140 million read events in the last eighteen months, and the module has to return in 80 ms at a peak of 1,900 requests per second.
The existing module is a popularity sort inside the current article’s section, and it has a defensible NDCG@10 of 0.118. The obvious replacement is a matrix-factorisation collaborative filter on the read matrix, which reaches 0.214 and was built in a fortnight. It was also rejected, for one reason that is specific and quantified: for an article less than two hours old, a collaborative filter’s recall@50 is exactly 0.000, because the item has no row in the interaction matrix. For a news publication that is not an edge case. 54% of a typical article’s lifetime traffic arrives in its first six hours, so the items the module most needs to be able to recommend are precisely the items the model cannot see. Content-based retrieval is the answer to that, and the reason it is the answer is almost tautological: an article’s text exists the moment it is published, so an index built from text has an opinion about a new item immediately.
That is where most descriptions of content-based recommendation stop, and it is where the actual work starts. Encoding 412,000 documents into vectors is four lines of scikit-learn or three of sentence-transformers. The parts that decide whether the module is any good are all downstream of that, and each of them is a place where an obvious implementation produces something that scores respectably and behaves badly. The naive version of each one: concatenate every text field and hand it to the encoder; average the reader’s item vectors to get a profile; retrieve by cosine; show the top ten. Every one of those four steps has a measured failure in this post.
The analogy worth carrying through: a content-based recommender is a librarian who has read every book on the shelves and has never once watched anybody choose one. They can tell you that two books are about the same subject with great precision, and they cannot tell you that one of them is unreadable, that three of the five they are about to hand you are the same book in different jackets, or that what you actually wanted was the third thing on your list rather than more of the first. Cosine similarity is that librarian’s entire vocabulary, and the post is about everything it cannot say.
Given 412,000 articles with text and partially populated metadata, and a reader’s history of prior reads with dwell times, retrieve and rank ten articles the reader has not seen, optimising for NDCG@10 and qualified read rate, under an 80 ms p99 budget at 1,900 QPS, without losing the ability to recommend an item published minutes ago.
Framing the Problem
This is a retrieval and ranking problem in two stages, and conflating them is the first modelling mistake available. Stage one retrieves a candidate pool of around 200 items from 412,000, and its metric is recall. Stage two orders those 200 into a slate of 10, and its metric is NDCG. The stages have different failure modes, different latency budgets, and different right answers about diversity, and a single-stage “take the cosine top-10” design silently answers the stage-two question with a stage-one tool.
The target is not a label we chose, it is the reader’s next reads, which makes the definition of a positive the most consequential decision in the whole evaluation. We define relevance from the read log with graded gains from scroll depth: gain 3 for a read past 60% depth, 2 past 25%, 1 for an open that bounced. Three levels rather than a continuous function of depth, deliberately, because a continuous gain makes NDCG sensitive to the shape of the scroll distribution, which is a property of the page template. A responsive-layout change in March moved median scroll depth by 9 percentage points with no model change at all, and a continuous gain would have reported that as a 0.011 NDCG regression.
Two structural facts about the label matter more than its definition. It is confounded by the incumbent: 61% of the items in any reader’s recent history were surfaced to them by the existing popularity module, so scoring a new ranker against that history rewards agreeing with the module we are trying to replace. And it is popularity-weighted by construction, because the top decile of articles accounts for 71% of all reads, which means a recommender can score well by being a popularity sort with extra steps.
Constraints, and the third and fifth are the ones that shaped the design:
- 80 ms p99 for the whole module at 1,900 QPS peak, of which 25 ms is the retrieval budget and the rest is feature fetch, re-rank and serialisation.
- New items must be recommendable within 10 minutes of publication. This is the constraint that eliminated collaborative filtering outright and it is a product requirement, not a modelling preference.
- Index memory ceiling of 1 GB per replica, across eight replicas. At 412,000 items this decides the embedding dimension before any quality measurement does.
- No per-reader model. 2.4 million readers and 38.6% of sessions coming from readers with fewer than three prior reads means anything requiring a fitted per-user object is not deployable.
- An editor-facing explanation per slot. The desk needs to know why an article was recommended, which content-based retrieval gives nearly for free through nearest-neighbour attribution and a matrix factorisation does not.
The optimisation metric is **NDCG@10** with graded dwell gains, the retrieval metric is **recall@50**, and the business proxy is the **qualified read rate**, defined as the share of recommended slots opened and read past 50% depth within the session. Three of them, because they disagree in informative ways: recall@50 answers whether the candidate generator found anything, NDCG@10 answers whether the good items are near the top, and MAP@10 is harsher than NDCG on a slate with one good item at rank 1 and nothing else, which is exactly what over-specialisation produces, so MAP moves when NDCG does not. The guardrail metrics are where this problem differs from an ordinary ranking problem, and all three of them are distributional rather than per-user. **Intra-list similarity**, the mean pairwise cosine inside a slate, capped at 0.55 because the failure mode is a slate of ten versions of one article. **Catalog coverage**, the share of the archive appearing in anybody's top-10, floored at 10% because a system serving 6% of a nineteen-year archive has stopped being a recommender and become a chart. And the **skewness of the k-occurrence distribution**, which is how many readers have each item in their top-10, capped at 2.5 because a right-skewed k-occurrence distribution is the signature of hubness and no per-user average will ever show it. Every one of those three can be badly wrong while NDCG@10 is flat, which is the organising fact of this post.
Framing this as two stages with two metrics rather than one stage with one is the decision that makes everything later tractable, and the reason is that retrieval and ranking want opposite things from diversity. The retrieval stage should be as broad as recall@50 allows, because an item that never enters the candidate pool cannot be rescued by any re-ranker, so a wide pool is cheap insurance. The ranking stage should be narrow and ordered, and its job includes deliberately demoting items that cosine likes, which is the opposite instinct. Collapse the two and you get the design almost everybody ships first, "take the cosine top-10", which answers the ranking question with a retrieval tool and has no place to put a diversity constraint, a freshness term, a duplicate filter, or a popularity coefficient. Concretely: our retrieval stage returns 200 candidates at recall@50 of 0.472 and our ranking stage throws away 190 of them, and the three signals that moved the online metric most, duplicate suppression, diversity and freshness, all live in that discard step and are unexpressible in a single-stage design.
Out of scope: the two-tower retrieval model, which learns item embeddings from interactions rather than reading them off the text and is a genuinely better endpoint once you have the data to train it; session-based sequential models; and the editorial override layer, which is what the desk uses to pin a story to every page during a major news event and which no amount of ranking quality replaces.
Data and Features
Two tables. The catalog is 412,000 rows with the text fields and the metadata, and the read log is 140 million rows of (reader_id, item_id, timestamp, scroll_depth) over eighteen months.
The catalog’s shape is the thing to internalise before choosing an encoder, because an editorial archive is far less uniform than the phrase “a corpus of articles” suggests:
| Field | Coverage | Shape |
|---|---|---|
title |
100% | median 9 words, p95 14 |
section |
100% | 8 desks, 23 sub-desks |
author |
96.2% | 2,140 bylines, 11 of them on 18% of the archive |
standfirst |
83.5% | the one-sentence summary under the headline, median 24 words |
editorial_tags |
71.4% | median 4 tags; mandatory only since 2019, so the oldest third is mostly empty |
topic_codes |
58.1% | a taxonomy that was replaced twice |
body |
100% | median 712 words, p10 180, p90 2,340, 6.1% under 120 words |
Two numbers in that table are leakage hazards rather than data quality problems, and they are the ones the rest of this section is about. Body length spans more than an order of magnitude and correlates with traffic at Spearman 0.31, because the desk commissions long features on subjects it already knows perform. Tag coverage correlates with publication date at 0.43, and publication date correlates with traffic. So document length and metadata completeness are both proxies for popularity, available to an encoder that has never seen an interaction.
Field-aware text assembly, which is where most of the content signal is
The default is to concatenate every field into one string. That loses twice. The title and the tags are the densest topical signal per token in the record and they get drowned by a 2,340-word body. And the body carries editorial furniture, the related-link rails and standing explainer boxes and newsletter copy, whose volume scales with article length and which manufactures similarity between unrelated long pieces in the same template.
# Field-aware document assembly. Two knobs, both of which move retrieval
# quality more than any encoder hyperparameter: integer field repetition and
# a hard body token cap.
import numpy as np
import pandas as pd
DEFAULT_WEIGHTS = {"title": 3, "tags": 2, "standfirst": 2, "section": 1, "body": 1}
def assemble(items: pd.DataFrame, weights: dict | None = None,
body_token_cap: int = 400,
fill_missing_tags: bool = True) -> list[str]:
"""One document string per item, with fields repeated by their weight.
body_token_cap is the quiet one. Capping the body removes the length axis
from the representation almost entirely, and because length carries the
popularity signal in this catalog, the cap is a popularity-bias fix
wearing a preprocessing costume. Measured here: Spearman between log words
and top-50 appearance count fell from 0.31 to 0.08.
"""
w = dict(DEFAULT_WEIGHTS if weights is None else weights)
priors = _section_tag_prior(items) if fill_missing_tags else {}
docs = []
for row in items.itertuples(index=False):
body = " ".join(str(row.body).split()[:body_token_cap])
tags = str(row.editorial_tags or "")
if fill_missing_tags and not tags.strip():
tags = priors.get(row.section, "")
parts = []
parts += [str(row.title)] * w["title"]
parts += [tags] * w["tags"]
parts += [str(row.standfirst or "")] * w["standfirst"]
parts += [f"section_{row.section}"] * w["section"]
parts += [body] * w["body"]
docs.append(" ".join(p for p in parts if p.strip()))
return docs
def _section_tag_prior(items: pd.DataFrame, top_n: int = 6) -> dict:
"""Most frequent tags per section, among the 71.4% of items that have them.
Imputing is not adding a feature, it is removing a bias. An untagged item
has a shorter document and a different token mix, so it is retrieved less
often for reasons that are about who had a subeditor available in 2017.
"""
out = {}
tagged = items[items["editorial_tags"].fillna("").str.strip() != ""]
for section, group in tagged.groupby("section"):
counts = {}
for s in group["editorial_tags"]:
for tok in str(s).split(","):
tok = tok.strip()
if tok:
counts[tok] = counts.get(tok, 0) + 1
out[section] = ", ".join(t for t, _ in
sorted(counts.items(), key=lambda kv: -kv[1])[:top_n])
return out
Field weighting bought 0.023 NDCG@10 on its own, taking the TF-IDF baseline from 0.163 to 0.186, and tag imputation bought another 0.008 to reach 0.194. The imputation number undersells itself in NDCG and shows its real value elsewhere: it moved the retrieval advantage of a tagged item over an untagged one from 2.3x to 1.2x, and it lifted recall@50 on cold items from 0.214 to 0.259, because a brand-new article is tagged and a 2008 article is not, so the untagged penalty was falling on exactly the cohort the whole approach exists to serve.
Treating a missing metadata field as neutral. It is not neutral, it is a systematic penalty, and the penalty lands wherever the missingness is correlated with something. On this archive the tag field is empty for the oldest third of the catalog, so leaving it empty gives every pre-2019 article a shorter document, a different token distribution and a measurably lower chance of retrieval: tagged items appeared in top-50 results 2.3 times as often as untagged ones at matched topical relevance. The first instinct is to add a "has_tags" indicator so the model can account for it, which is exactly wrong because this is a retrieval index and not a supervised model, so there is nothing to account for it with. The second instinct is to drop the tag field entirely, which costs 0.019 NDCG@10 and throws away a real signal from 71.4% of the catalog to avoid a bias in the other 28.6%. The fix is imputation from a section-level prior, which is unglamorous and moved the tagged-to-untagged retrieval ratio from 2.3x to 1.2x for an NDCG gain rather than a loss. Worth generalising: in a retrieval system, any field whose presence correlates with an item attribute becomes a ranking feature nobody chose, and the fix lives in the document assembly rather than in the model.
The split is per reader and temporal, and the wrong one inverts your conclusions
The evaluation unit is “given this reader’s history up to time t, what should be next”, so the split has to be per reader and ordered within the reader. We hold out the last 20% of each reader’s reads in time order, requiring at least four reads of history, and we restrict the candidate set to items published before the reader’s cutoff.
# Per-reader temporal holdout. NOT random leave-one-out, which is the standard
# protocol in the content-based recommender literature and inflates every
# number, and NOT grouped time folds, which are correct for a tabular
# classifier and answer a different question here.
from dataclasses import dataclass
import numpy as np
import pandas as pd
@dataclass
class UserSplit:
user_id: int
history_items: np.ndarray
history_ts: np.ndarray
history_dwell: np.ndarray
test_items: np.ndarray
test_dwell: np.ndarray
cutoff_ts: float
def temporal_user_splits(reads: pd.DataFrame, holdout_frac: float = 0.2,
min_history: int = 4) -> list[UserSplit]:
"""The last holdout_frac of each reader's reads, in time order, is test.
Graded relevance comes from dwell, which is why the holdout is a FRACTION
rather than a single item. With one held-out item and binary relevance,
NDCG@10 collapses to a reciprocal-log rank and stops distinguishing a
ranker that puts three good items at 1, 2, 3 from one that puts a single
good item at rank 1.
"""
out = []
for user_id, group in reads.groupby("reader_id", sort=True):
if len(group) < min_history + 1:
continue
g = group.sort_values("timestamp", kind="stable")
items = g["item_id"].to_numpy()
ts = g["timestamp"].to_numpy()
dwell = g["scroll_depth"].to_numpy()
n_test = max(1, int(round(holdout_frac * len(items))))
n_hist = len(items) - n_test
if n_hist < min_history:
continue
out.append(UserSplit(int(user_id), items[:n_hist], ts[:n_hist],
dwell[:n_hist], items[n_hist:], dwell[n_hist:],
float(ts[n_hist - 1])))
return out
def candidate_mask(items: pd.DataFrame, cutoff_ts: float) -> np.ndarray:
"""Items that existed at the moment the recommendation is made.
The leakage check specific to this problem. Using the whole catalog as
candidates for every reader makes recent items easier to retrieve than
production ever will, and recent items are disproportionately the positives
in a temporal holdout, so the inflation is not uniform.
"""
return items["published_at"].to_numpy() <= cutoff_ts
Random leave-one-out is the protocol in most of the content-based literature and it builds a reader’s profile partly from their future reads. The damage is not just inflation, it is inversion, and that is the part worth measuring. Switching to random leave-one-out lifted the naive concatenated-text-plus-mean-profile configuration from 0.163 to 0.287, a 76% inflation. It also took the recency-weighted profile, our best single improvement, from 0.261 down to 0.249, because shuffling a reader’s history destroys the non-stationarity that recency weighting exists to exploit. Under the wrong protocol the single most valuable fix in this post reads as a regression. A wrong split does not only make your numbers look better, it makes you choose the wrong improvements.
The leakage specific to content-based recommendation is not a feature computed after the outcome, it is **the candidate set containing items that did not exist yet**. It is easy to miss because nothing about it looks like leakage: the item vectors are built from text, the profile is built from reads before the cutoff, and the evaluation is a clean temporal holdout. The leak is in the denominator. If every reader's candidate pool is the full 412,000-item archive, then an item published last Tuesday competes for a slot in a recommendation nominally made last January, and because a temporal holdout's positives are disproportionately recent, the inflation lands on exactly the rows that matter. Measured here it was worth 0.034 NDCG@10, which is comparable to the entire gain from replacing TF-IDF with a sentence encoder. The fix is a per-reader publication-time mask on the candidate set, which costs one boolean array and is the first thing to check in any recommender evaluation whose catalog grows over time.
The Naive Baseline
Four baselines, and the pair worth arguing about is the second and the fourth.
# The four baselines. The popularity sort is the one to beat and it is not
# embarrassing; the naive content pipeline is the one that loses to it.
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
def popularity_slate(items, interaction_counts, cutoff_ts, history, k=50):
"""Rank by 28-day trailing read count, restricted to published items."""
eligible = items["published_at"].to_numpy() <= cutoff_ts
seen = set(int(i) for i in history)
order = np.argsort(-interaction_counts)
return np.array([i for i in order
if eligible[i] and int(i) not in seen][:k])
def encode_tfidf_svd(docs, dim=256, seed=23):
"""TF-IDF plus truncated SVD, L2 normalised. The measured baseline.
sublinear_tf replaces raw term frequency with 1 + log(tf). Without it a
2,340-word feature using a topic word 30 times gets 30 times the weight of
a 180-word brief using it once, and document length becomes the dominant
axis of the space. L2 normalisation after SVD is not optional: TruncatedSVD
does not normalise, and an unnormalised dot product ranks by magnitude.
"""
vec = TfidfVectorizer(min_df=3, max_df=0.55, sublinear_tf=True,
dtype=np.float32)
sparse = vec.fit_transform(docs)
svd = TruncatedSVD(n_components=dim, random_state=seed)
dense = svd.fit_transform(sparse)
norms = np.linalg.norm(dense, axis=1, keepdims=True)
return (dense / np.maximum(norms, 1e-12)).astype(np.float32), vec, svd
def mean_profile(vectors, history):
"""The naive profile: unweighted mean of the reader's item vectors."""
if len(history) == 0:
return np.zeros(vectors.shape[1], dtype=np.float32)
p = vectors[history].mean(axis=0)
return p / max(np.linalg.norm(p), 1e-12)
On the per-reader temporal holdout over 180,000 evaluation readers:
- Random slate: NDCG@10 0.004. Reported so the floor is not zero.
- Popularity, 28-day trailing count: NDCG@10 0.118, recall@50 0.291, qualified read rate 11.4%.
- Matrix factorisation, 128 factors, implicit ALS: NDCG@10 0.214, recall@50 0.402, and recall@50 of 0.000 on items under two hours old.
- TF-IDF plus SVD, concatenated text, mean profile: NDCG@10 0.163, recall@50 0.338.
The last two lines are the whole problem. The content-based pipeline assembled the obvious way is 0.051 NDCG behind the collaborative filter, and it is only 0.045 ahead of a popularity sort that required no model at all. A team that builds that configuration, looks at 0.163 against 0.214, and concludes that content-based retrieval is the weaker approach has drawn a reasonable conclusion from a correct measurement of the wrong thing. Every point of the gap between 0.163 and the 0.301 this post ends at comes from the four steps around the encoder, and none of it comes from a better encoder.
The naive content pipeline loses because of the profile, not the encoder, and the diagnostic takes one line. Compute the mean cosine of each reader's history items to their own centroid: on this data the median is 0.61 and the 10th percentile is 0.34. A reader at 0.34 has a history that does not have a centre, and the mean of their item vectors is a point in a region of the embedding space where no article lives, so its nearest neighbours belong to none of their interests. Swapping TF-IDF for a sentence encoder moves that number not at all, because it is a property of the reader rather than of the representation, which is why the encoder upgrade buys 0.034 and the profile fix buys 0.033 plus another 0.007 from multi-profile retrieval. The general principle for any content-based system: the item side is a solved engineering problem and the user side is an unsolved modelling one, so budget your attention accordingly. A good rule is that if you have spent more time choosing an encoder than deciding how to aggregate a history, you have the ratio backwards.
The Solution
Five parts, and only the first is about embeddings.
The encoder, which is the cheap half
Two encoders, measured on the same field-aware documents and the same splits. The TF-IDF plus truncated SVD baseline reaches NDCG@10 0.194 at 256 dimensions, fits in 4 minutes on one CPU, and costs nothing at serving time beyond a sparse dot product. The sentence encoder reaches 0.228.
# The encoder upgrade. normalize_embeddings is not optional: the index is a
# dot-product index, which is cosine only if both sides are unit norm, and a
# mismatch does not raise. It silently ranks by vector magnitude, which on an
# editorial catalog means ranking by article length.
import numpy as np
from sentence_transformers import SentenceTransformer
def encode_transformer(docs: list[str], model_name: str = "all-MiniLM-L6-v2",
batch_size: int = 128) -> np.ndarray:
"""384-dimensional item vectors, L2 normalised.
MiniLM-L6 rather than a larger model, and the reason is memory rather than
quality: 412,000 items at 384 float32 dimensions is 633 MB, and at 1,024
dimensions it is 1.69 GB, which breaches the 1 GB per-replica ceiling
before any graph structure is added.
"""
model = SentenceTransformer(model_name)
return model.encode(docs, batch_size=batch_size, convert_to_numpy=True,
normalize_embeddings=True,
show_progress_bar=False).astype(np.float32)
The 0.034 gap is not uniform and the distribution of it is the decision-relevant part. On items above 1,200 words the sentence encoder is ahead by 0.009, which is inside the run-to-run band. On items under 200 words it is ahead by 0.061, because a 180-word wire brief gives a bag of words almost no tokens to work with while a sentence encoder still produces a sensible vector. 6.1% of this catalog is under 120 words and briefs are disproportionately recent, so the gap concentrates on the cold cohort. If your catalog is mostly long features, the TF-IDF baseline is genuinely competitive and you should say so out loud before anyone installs torch.
Why a sentence encoder and not raw BERT: the siamese training objective in Reimers and Gurevych’s sentence-BERT work is what makes cosine between two independently encoded texts mean something. Raw BERT [CLS] vectors are not trained for that and on this catalog they scored 0.142, below the TF-IDF baseline. The objective matters more than the model size.
Anisotropy and hubness, and the geometry nobody checks
Take any text embedding space and compute the mean cosine between randomly chosen item pairs. On a unit sphere in 384 dimensions with isotropically distributed points that number is approximately zero. On our MiniLM index it is 0.52.
The analogy: it is a thermometer that reads 52 degrees in an empty room. The scale still has resolution above 52, but half of it is gone, and anything that happens to sit near the bottom of the usable range reads as warm compared to everything.
The operational consequence is hubness. Items near the axis of that narrow cone, which is to say items near the global mean, have above-average cosine to every query, so they appear in everybody’s top-k. Radovanovic, Nanopoulos and Ivanovic named this in 2010 and gave it its diagnostic, which is the skewness of the k-occurrence distribution. Measured on the raw index: skewness 4.9, the top 1% of items taking 23.7% of every top-50 slot served, and 61.2% of the archive never recommended to anybody.
# Centering and whitening, fitted on the item index and applied to items AND
# to profile vectors. Applying it to one side and not the other is a silent
# and total failure, because the two sides are no longer in the same space.
from dataclasses import dataclass
import numpy as np
@dataclass
class Whitener:
mean: np.ndarray
transform: np.ndarray | None
def apply(self, vectors: np.ndarray) -> np.ndarray:
out = vectors - self.mean
if self.transform is not None:
out = out @ self.transform
norms = np.linalg.norm(out, axis=1, keepdims=True)
return out / np.maximum(norms, 1e-12)
def fit_whitener(vectors: np.ndarray, shrinkage: float = 0.08) -> Whitener:
"""PCA whitening with shrinkage toward a scaled identity.
Shrinkage is what stops this from being a foot-gun. Whitening divides each
component by the square root of its eigenvalue, and the trailing
eigenvalues of a 384-dimensional space are small, so without shrinkage the
transform amplifies estimation noise. The failure is sharp and it depends
on sample size: fitted on all 412,000 items the shrinkage barely matters,
and fitted on a 500-item sample it costs 0.009 NDCG@10.
"""
centered = vectors - vectors.mean(axis=0, keepdims=True)
cov = np.cov(centered, rowvar=False)
d = cov.shape[0]
cov = (1.0 - shrinkage) * cov + shrinkage * np.trace(cov) / d * np.eye(d)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
scale = 1.0 / np.sqrt(np.maximum(eigvals[order], 1e-8))
return Whitener(mean=vectors.mean(axis=0).astype(np.float32),
transform=(eigvecs[:, order] * scale).astype(np.float32))
def anisotropy(vectors: np.ndarray, n_pairs: int = 50_000, seed: int = 23) -> dict:
"""Mean cosine between random pairs, plus the leading eigenvalue share."""
rng = np.random.default_rng(seed)
i, j = rng.integers(0, len(vectors), n_pairs), rng.integers(0, len(vectors), n_pairs)
keep = i != j
cos = np.einsum("ij,ij->i", vectors[i[keep]], vectors[j[keep]])
centered = vectors - vectors.mean(axis=0, keepdims=True)
eig = np.linalg.svd(centered, compute_uv=False) ** 2
return {"mean_pair_cosine": float(cos.mean()),
"top1_eigenvalue_share": float(eig[0] / eig.sum())}
The two transforms do different jobs and the measurements separate them cleanly. Centering takes mean random-pair cosine from 0.52 to 0.001 and buys 0.004 NDCG@10, moving 0.268 to 0.272. It barely touches hubness. Whitening with shrinkage 0.08 buys a further 0.011 to reach 0.283, and it is the transform that moves the hubness numbers: skewness 4.9 to 2.1, the top-1% share 23.7% to 9.4%, and the never-recommended share 61.2% to 44.8%. So the headline NDCG delta from the pair is +0.015, and the guardrail deltas are three to four times larger in relative terms. The metric understates its own fix, which is a pattern that recurs in this problem.
One warning about max_df. A TF-IDF encoder has a document-frequency filter, which strips house style, and house style is the main cause of anisotropy, so max_df is an anisotropy fix applied before the encoder runs. A sentence encoder has no equivalent knob. That is why whitening matters much more for transformer embeddings than for an SVD space, and it is why a TF-IDF index measured as less anisotropic is not evidence that the geometry problem is imaginary.
The profile vector, where content-based systems are actually lost
A plain mean of the reader’s item vectors is weak for three independent reasons and each one has its own fix.
A mean is not a summary of a multi-modal set. A reader who follows both county cricket and central bank policy gets a vector in the empty space between the two, and its nearest items belong to neither. Interest is non-stationary and a mean is uniform over time, so a read from fourteen months ago counts exactly as much as yesterday’s. And a read is not an endorsement: opening an article and bouncing at 4% depth is weak evidence, finishing it is strong, and an unweighted mean scores both as 1.0.
# The profile. Three fixes in two functions, worth 0.040 NDCG@10 together,
# which is more than the entire encoder upgrade.
import numpy as np
from sklearn.cluster import KMeans
def l2(m):
return m / np.maximum(np.linalg.norm(m, axis=-1, keepdims=True), 1e-12)
def weighted_profile(vectors, history, timestamps, dwell, now,
half_life_days: float = 45.0, dwell_floor: float = 0.15):
"""Recency-decayed, dwell-weighted mean over UNIT-NORM item vectors.
weight = 0.5 ** (age_days / half_life) * max(dwell, floor)
Normalising each item BEFORE averaging is load bearing. Average
unnormalised vectors and the longest documents in the history dominate the
profile, which puts the length-equals-popularity channel back in through
the profile after the body cap removed it from the index.
half_life_days has a broad optimum and a sharp left edge: 45 days scored
0.261, 90 days 0.254, 180 days 0.241, and 7 days 0.228, because a 7-day
half life makes the profile a copy of the last article read.
"""
if len(history) == 0:
return np.zeros(vectors.shape[1], dtype=np.float32)
recency = 0.5 ** (np.maximum(now - timestamps, 0.0) / half_life_days)
w = (recency * np.maximum(dwell, dwell_floor)).astype(np.float32)
if w.sum() <= 0:
w = np.ones_like(w)
unit = l2(vectors[history])
return l2(((unit * w[:, None]).sum(axis=0) / w.sum()).reshape(1, -1))[0]
def multi_profile(vectors, history, timestamps, dwell, now, k: int = 3,
half_life_days: float = 45.0, seed: int = 23):
"""k recency-weighted centroids over the reader's own history, plus masses.
Returns (centroids, masses). k is capped at 3 in production because each
centroid is a separate retrieval call, so this is a direct multiplier on
the 25 ms budget. The masses are what the merge uses, and getting the merge
wrong undoes the whole thing: see the note below.
"""
unit = l2(vectors[history])
k_eff = int(min(k, len(history)))
if k_eff <= 1:
p = weighted_profile(vectors, history, timestamps, dwell, now,
half_life_days)
return p.reshape(1, -1), np.ones(1)
labels = KMeans(n_clusters=k_eff, n_init=4, random_state=seed).fit(unit).labels_
w = (0.5 ** (np.maximum(now - timestamps, 0.0) / half_life_days)
* np.maximum(dwell, 0.15))
cents = np.zeros((k_eff, vectors.shape[1]), dtype=np.float32)
masses = np.zeros(k_eff, dtype=np.float32)
for c in range(k_eff):
m = labels == c
cents[c] = (unit[m] * w[m][:, None]).sum(axis=0) / max(w[m].sum(), 1e-9)
masses[c] = float(w[m].sum())
return l2(cents), masses / masses.sum()
Recency decay alone took NDCG@10 from 0.228 to 0.254. Dwell weighting alone took it to 0.236. Together, 0.261. The multi-profile took it to 0.268 and, more importantly, took intra-list similarity from 0.741 to 0.602 before any re-ranker ran, because retrieving against three interests produces a mixed slate by construction.
The merge across centroids is where a multi-profile goes wrong, and the failure is instructive. Pooling all candidates and taking the global top-k gives back single-profile behaviour at triple the cost, because the densest interest cluster has the most history behind it, hence the tightest centroid and the highest cosines, so it wins every slot. Round-robin interleaving is worse in a different way: it hands slot 2 to a stale interest holding 8% of the recency-weighted mass, which re-admits exactly what the recency decay just removed. Allocate slots by the Sainte-Lague divisor rule, giving each slot to the centroid maximising mass / (2 * taken + 1), which front-loads the dominant interest and still guarantees a minority interest its proportional share further down.
Retrieval, and the ANN dial that is secretly a ranking decision
Exact cosine over 412,000 by 384 is 158 million multiply-accumulates per query. At 1,900 QPS on eight cores that measures at 41 ms p99, which breaches the 80 ms module budget by itself. So the index is approximate, and the parameter that makes it fast is a ranking parameter.
# The retrieval index. HNSW because the recall/latency curve at this catalog
# size is better than IVF's, and because efSearch is a runtime knob while
# nprobe tuning on IVF interacts with the training-time nlist.
import numpy as np
import faiss
def build_index(vectors: np.ndarray, m: int = 32,
ef_construction: int = 200) -> faiss.Index:
"""Inner-product HNSW over a unit-norm index, which is cosine.
METRIC_INNER_PRODUCT rather than L2. On unit vectors the two orderings are
identical, so this is not a quality decision, it is that an L2 index stores
and compares squared norms it does not need.
"""
index = faiss.IndexHNSWFlat(vectors.shape[1], m, faiss.METRIC_INNER_PRODUCT)
index.hnsw.efConstruction = ef_construction
index.add(vectors)
return index
def search(index: faiss.Index, queries: np.ndarray, k: int = 200,
ef_search: int = 128):
"""efSearch is the recall dial and it costs ranking quality, not just
recall. Measured on this index: efSearch 32 gives recall@50 of 0.887 and
costs 0.015 NDCG@10, which is the entire gain from whitening, spent
without appearing in any dashboard."""
index.hnsw.efSearch = ef_search
scores, ids = index.search(queries.astype(np.float32), k)
return ids, scores
def recall_against_exact(approx_ids: np.ndarray, exact_ids: np.ndarray) -> float:
"""Share of each query's exact top-k recovered. Necessary, not sufficient:
a miss at rank 2 and a miss at rank 48 are the same recall and very
different NDCG."""
hits = sum(len(np.intersect1d(a, e)) for a, e in zip(approx_ids, exact_ids))
return float(hits / max(exact_ids.size, 1))
The sweep, at 412,000 items with M=32 and efConstruction 200:
| efSearch | recall@50 vs exact | p99 latency | NDCG@10 | NDCG cost | cold-item recall vs exact |
|---|---|---|---|---|---|
| 16 | 0.782 | 1.1 ms | 0.247 | -0.036 | 0.58 |
| 32 | 0.887 | 1.9 ms | 0.268 | -0.015 | 0.71 |
| 64 | 0.951 | 3.1 ms | 0.277 | -0.006 | 0.84 |
| 128 | 0.981 | 6.4 ms | 0.281 | -0.002 | 0.93 |
| 256 | 0.994 | 11.8 ms | 0.283 | 0.000 | 0.98 |
| exact flat | 1.000 | 41.0 ms | 0.283 | 0.000 | 1.00 |
Two readings, and the second is the one people miss. The NDCG cost does not scale with the recall gap: recall 0.887 is a 11.3% recall loss and costs 5.3% of the NDCG, because the missed items were mostly ranked low anyway. Quoting recall as if it were a quality number overstates the damage. And the last column is why a high recall is not sufficient either. An HNSW graph reaches items by traversing neighbour links, and a brand-new article with an unusual topic has few in-links, so it is a low-degree node and the hardest kind to reach. At efSearch 32, cold items recover 0.71 of their exact recall against 0.94 for head items. A cheap efSearch quietly gives back the cold-start capability that the entire content-based approach was bought for, and recall@50 averaged over all queries will not show it.
Re-ranking, where cosine stops being the ranking function
Retrieval returns 200 items most similar to the profile. That is not a slate.
# Re-ranking. Three passes, and the ordering matters: dedup first because MMR
# on a pool with four copies of one story wastes its diversity budget pushing
# them apart from each other.
import numpy as np
def dedup(candidate_ids, candidate_scores, vectors, k=60, threshold=0.94):
"""Greedy near-duplicate suppression at a fixed cosine threshold.
Calibrate the threshold on hand-labelled pairs, NOT on a ranking metric. A
ranking metric computed against a read log will tell you that showing the
same story four times is fine, because the log recorded four reads of that
story. At 0.94 the precision on true duplicates was 0.93 and recall 0.88.
"""
kept = []
for pos in np.argsort(-candidate_scores):
cand = int(candidate_ids[pos])
if kept and float((vectors[kept] @ vectors[cand]).max()) > threshold:
continue
kept.append(cand)
if len(kept) >= k:
break
return np.array(kept, dtype=np.int64)
def mmr(candidate_ids, candidate_scores, vectors, k=10, lam=0.72):
"""Maximal marginal relevance, Carbonell and Goldstein 1998.
score(i) = lam * relevance(i) - (1 - lam) * max_{j in selected} sim(i, j)
The max rather than a mean over selected items is the whole point: a mean
lets a candidate that is a near-duplicate of exactly one selected item slip
through on the strength of being unlike the other nine.
"""
pool = vectors[candidate_ids]
sim = pool @ pool.T
selected, remaining = [], list(range(len(candidate_ids)))
max_sim = np.zeros(len(candidate_ids), dtype=np.float32)
for _ in range(min(k, len(candidate_ids))):
obj = lam * candidate_scores[remaining] - (1 - lam) * max_sim[remaining]
pick = remaining[int(np.argmax(obj))]
selected.append(pick)
remaining.remove(pick)
max_sim = np.maximum(max_sim, sim[pick])
return candidate_ids[np.array(selected, dtype=int)]
def blend(candidate_ids, candidate_scores, popularity, age_days,
w_pop=0.12, w_fresh=0.18, freshness_half_life=2.0):
"""Explicit content plus popularity plus freshness, as named coefficients.
The argument is not that a hybrid scores better, although it does by 0.018
here. It is that popularity is ALREADY in a pure-content score, through
document length and metadata completeness, where it cannot be inspected or
turned down. A coefficient makes w_pop = 0.0 a measurable ablation.
"""
pop = np.log1p(popularity[candidate_ids]) / np.log1p(popularity.max())
fresh = 0.5 ** (np.maximum(age_days[candidate_ids], 0.0) / freshness_half_life)
return candidate_scores + w_pop * pop + w_fresh * fresh
Dedup at cosine 0.94 took the mean number of slots from a single duplicate cluster from 3.4 of 10 to 1.1, and it cost 0.004 NDCG@10. That cost is the metric confessing the problem rather than an argument against the fix. MMR at lambda 0.72 took intra-list similarity from 0.712 to 0.488 for a further 0.007 NDCG. The explicit popularity and freshness terms added 0.018 to reach the final 0.301.
The traps that are specific to this method, with the numbers
Five failure modes, and what they have in common is that their signature does not appear in a per-reader ranking average. The four panels in the diagram below are the four that need a picture.
Popularity bias arriving without an interaction. A pure-content score is supposed to be independent of traffic. It is not, and there are two measurable channels. Document length correlates with traffic at 0.31 and the uncapped-body index showed Spearman 0.31 between log word count and top-50 appearance count, which the 400-token cap cut to 0.08. Metadata completeness correlates with recency, which correlates with traffic, and tagged items were retrieved 2.3 times as often as untagged ones before imputation and 1.2 times after. The overall Spearman between an item’s historical read count and its appearance count fell from 0.41 to 0.11 across those two fixes.
The filter bubble, which shows up as a flat metric. We ran a six-week shadow loop where the module’s own slates fed back into reader histories. NDCG@10 went 0.281 to 0.277, which is inside the 0.006 run-to-run band. Over the same six weeks intra-list similarity went 0.488 to 0.661, catalog coverage of top-10 slots went 14.2% to 5.8%, per-reader section entropy went 2.41 to 1.63 nats, and the qualified read rate fell 3.2%. A dashboard carrying only ranking metrics reports a healthy and slightly improving system throughout.
Hubness. Covered above: skewness 4.9, top 1% of items taking 23.7% of slots, 61.2% of the archive never served, all of it invisible in NDCG and all of it fixed by a transform that moves NDCG by 0.015.
Cosine similarity is not relevance. 11.2% of this catalog sits in a near-duplicate cluster, which is wire copy, syndicated reprints, and live blogs republished as standalone items. A correct similarity function puts those in consecutive slots, because they genuinely are each other’s nearest neighbours. Raw cosine top-10 carried 3.4 duplicate slots.
The offline-online gap. The encoder upgrade measured +0.042 NDCG@10 offline and delivered +1.9% qualified read rate online. The naive projection from the offline lift was +4.6%. The reason is the incumbent confound: 61% of the offline positives were items the old popularity module had surfaced, so part of the measured lift was agreement with the thing being replaced. An inverse-propensity-weighted offline estimate, weighting each hit by the inverse of the item’s historical exposure with weights clipped at 10, predicted +2.2% against the realised +1.9%.
The single design decision that mattered most was treating the guardrail metrics as first-class outputs rather than as sanity checks, and the reason is that every improvement in this post except one has a larger effect on a distributional metric than on NDCG@10. Whitening moved NDCG by 0.015 and the hubness share by 14.3 percentage points. The multi-profile moved NDCG by 0.007 and intra-list similarity by 0.139. The re-ranker moved NDCG DOWN by 0.011 and intra-list similarity by 0.224, and shipped anyway because the online qualified read rate rose 4.1%. If the decision rule had been "ship what improves NDCG@10" we would have shipped no whitening, no multi-profile and no re-ranker, and we would have shipped a module that showed 5.8% of a nineteen-year archive to everybody and the same wire story four times. The reason the ranking metric is so weak here is structural rather than accidental: NDCG is an average over readers of a within-slate quantity, and three of this method's five characteristic failures are properties of the distribution over items induced across all readers, which no within-slate average can see. The practical form of this is one line in the evaluation harness: compute the k-occurrence array, the intra-list similarity and the catalog coverage in the same function that computes NDCG, so that nobody can report one without the others.
Evaluation and Metrics
NDCG@10 with graded gains is the optimisation metric, recall@50 is the retrieval metric, and the pair has to be reported together because they move independently. Switching from a mean profile to a weighted one moved recall@50 by 0.063 and NDCG@10 by 0.033; switching the re-ranker on moved NDCG by -0.011 and recall@50 by nothing at all, because re-ranking only reorders a pool that recall already measured.
# The metric block. The first three are standard and the last three are what
# this problem actually needs, which is why they live in the same function.
import numpy as np
from scipy import stats
def dcg(gains: np.ndarray) -> float:
if len(gains) == 0:
return 0.0
return float((gains / np.log2(np.arange(2, len(gains) + 2))).sum())
def ndcg_at_k(ranked_ids, relevance: dict, k: int = 10) -> float:
"""Graded NDCG. The ideal DCG uses the k highest gains available to the
READER, not the k highest present in the slate. Getting that backwards
makes 0/0 defensible as 1.0 and reports a perfect score for a ranker that
found nothing."""
gains = np.array([relevance.get(int(i), 0.0) for i in ranked_ids[:k]])
ideal = np.array(sorted(relevance.values(), reverse=True)[:k])
denom = dcg(ideal)
return float(dcg(gains) / denom) if denom > 0 else 0.0
def average_precision_at_k(ranked_ids, relevant: set, k: int = 10) -> float:
"""AP@k with the standard denominator min(len(relevant), k). Dividing by k
instead caps AP at len(relevant)/k, so a reader with 3 held-out items can
never exceed 0.3 and a working ranker looks broken."""
if not relevant:
return 0.0
hits, score = 0, 0.0
for rank, item in enumerate(ranked_ids[:k], start=1):
if int(item) in relevant:
hits += 1
score += hits / rank
return float(score / min(len(relevant), k))
def intra_list_similarity(ranked_ids, vectors, k: int = 10) -> float:
"""Mean pairwise cosine inside the slate. The over-specialisation metric,
and the one that moved 0.17 in a feedback loop where NDCG moved 0.004."""
ids = np.array([int(i) for i in ranked_ids[:k]])
if len(ids) < 2:
return 0.0
sims = vectors[ids] @ vectors[ids].T
return float(sims[np.triu_indices(len(ids), k=1)].mean())
def hubness_report(slates: list, n_items: int, k: int = 10) -> dict:
"""N_k(i) is how many readers have item i in their top-k. Its skewness is
the hubness diagnostic from Radovanovic et al. 2010, and the two share
numbers are what an editor understands."""
counts = np.zeros(n_items, dtype=np.int64)
for slate in slates:
counts[[int(i) for i in slate[:k]]] += 1
order = np.argsort(-counts)
top1pct = max(1, n_items // 100)
return {"nk_skewness": float(stats.skew(counts)),
"share_from_top_1pct_items": float(counts[order[:top1pct]].sum()
/ max(counts.sum(), 1)),
"items_never_recommended": float((counts == 0).mean())}
def propensity_corrected_proxy(slates, splits, exposure_counts, k=10,
clip=10.0) -> dict:
"""The offline-online divergence in one function. Logged reads were
produced by a popularity-ranked incumbent, so scoring against them rewards
agreeing with it. Weights clipped because unclipped IPS on a Zipf exposure
distribution has unbounded variance."""
prop = (exposure_counts + 1.0) / (exposure_counts + 1.0).sum()
raw, ips = [], []
for slate, split in zip(slates, splits):
relevant = set(int(i) for i in split.test_items)
ids = [int(i) for i in slate[:k]]
hits = np.array([1.0 if i in relevant else 0.0 for i in ids])
w = np.minimum(1.0 / np.maximum(prop[ids] * len(prop), 1e-6), clip)
raw.append(float(hits.mean()))
ips.append(float((hits * w).sum() / max(w.sum(), 1e-9)))
return {"raw_hit_rate": float(np.mean(raw)),
"ips_hit_rate": float(np.mean(ips)),
"optimism_ratio": float(np.mean(raw) / max(np.mean(ips), 1e-9))}
The full ladder, on 180,000 evaluation readers with per-reader temporal holdouts:
| Configuration | NDCG@10 | MAP@10 | recall@50 | Qualified read rate | Intra-list sim | Coverage | N_k skew | p99 |
|---|---|---|---|---|---|---|---|---|
| Popularity, 28-day | 0.118 | 0.046 | 0.291 | 11.4% | 0.194 | 0.4% | 11.8 | 0.2 ms |
| Matrix factorisation, 128 factors | 0.214 | 0.094 | 0.402 | 18.1% | 0.631 | 7.1% | 5.2 | 2.1 ms |
| TF-IDF+SVD, concat text, mean profile | 0.163 | 0.068 | 0.338 | 14.2% | 0.783 | 21.4% | 5.6 | 1.8 ms |
| TF-IDF+SVD, field-aware | 0.186 | 0.079 | 0.371 | 15.9% | 0.766 | 19.8% | 5.3 | 1.8 ms |
| TF-IDF+SVD, field-aware + tag imputation | 0.194 | 0.083 | 0.384 | 16.4% | 0.761 | 20.6% | 5.1 | 1.8 ms |
| Sentence encoder, field-aware | 0.228 | 0.099 | 0.411 | 18.8% | 0.774 | 18.1% | 4.9 | 2.4 ms |
| + recency and dwell weighted profile | 0.261 | 0.118 | 0.447 | 21.6% | 0.741 | 16.9% | 4.8 | 2.4 ms |
| + multi-profile, k=3 | 0.268 | 0.124 | 0.459 | 22.3% | 0.602 | 19.4% | 4.1 | 6.9 ms |
| + centered index | 0.272 | 0.126 | 0.463 | 22.6% | 0.598 | 19.8% | 4.0 | 6.9 ms |
| + whitened, shrinkage 0.08 | 0.283 | 0.134 | 0.471 | 23.4% | 0.712 | 13.1% | 2.1 | 6.9 ms |
| + dedup at 0.94, MMR lambda 0.72 | 0.276 | 0.128 | 0.471 | 24.4% | 0.488 | 14.2% | 2.2 | 7.4 ms |
| + explicit popularity and freshness | 0.301 | 0.147 | 0.472 | 26.1% | 0.498 | 14.2% | 2.4 | 7.4 ms |
Five readings, and only the first is about accuracy.
The shipped configuration beats the collaborative filter by 0.087 NDCG@10 and 8.0 points of qualified read rate, and it recommends an article published eleven minutes ago, which the collaborative filter cannot do at all. The popularity row’s coverage of 0.4% is worth looking at next to its respectable 0.118 NDCG: that is what a chart looks like when scored as a recommender. The matrix factorisation’s intra-list similarity of 0.631 is interesting because collaborative filtering is usually described as the diverse option; it is diverse in content space only when the co-read structure is, and on a news site readers who read one piece about an election read four more. The whitening row shows the pattern this post keeps hitting, where N_k skewness halves for a 0.011 NDCG gain. And the dedup-plus-MMR row loses 0.007 NDCG while gaining 1.0 point of qualified read rate, which is the one place offline and online disagree in the useful direction.
Read the table by column rather than by row and it stops being a ladder and starts being a set of tradeoffs, which is what it is. The NDCG column rises monotonically except in one place. The intra-list similarity column does not: it falls from 0.783 to 0.598 as the profile improves, then jumps back to 0.712 when whitening is applied, because whitening tightens the local neighbourhood structure that it de-hubbed globally, and then falls to 0.488 only when the re-ranker runs. The coverage column is worse still, falling from 21.4% at the naive configuration to 13.1% at the best NDCG, which means the pipeline got better at ranking and narrower at the same time, and that pattern held at every step. So the configuration a greedy NDCG search would select is row ten, which has the worst coverage in the content half of the table, and the configuration we shipped is row twelve, which is 0.018 NDCG better and 1.1 points of coverage better only because two of its three added terms were chosen against the guardrails rather than the metric. A single-column table hides all of this. Report the guardrails in the same table as the objective, in the same run, or the tradeoff is invisible at exactly the moment someone is choosing.
The metric that catches silent degradation here is not NDCG@10, it is the **daily k-occurrence skewness over a fixed query cohort**. NDCG on fresh data is the obvious monitor and it is nearly useless for this system, for a reason specific to content-based retrieval: the thing that degrades is the composition of the slate over items, and NDCG is an average over readers of a within-slate quantity, so it is blind to it by construction. We hold 50,000 reader profiles frozen as a query cohort, run them against the live index nightly, and compute the k-occurrence array, its skewness, the top-1% share, and the catalog coverage. It has fired three times. Once when an upstream tagging job failed and tag coverage on new items dropped from 94% to 31% over a weekend: the new items became shorter documents, skewness went 2.4 to 3.6, and NDCG@10 on the fresh holdout did not move at all because the affected items were too new to be anybody's positives yet. Once when a model refresh shipped with the whitener fitted on a 500-item sample instead of the full index, which took skewness to 4.1 and NDCG down by 0.009, a move that would have been dismissed as noise on its own. And once when an infrastructure change dropped efSearch from 128 to the library default of 16 as part of an unrelated config consolidation, which cost 0.036 NDCG and, more tellingly, took cold-item recall to 0.58 of exact. The frozen cohort is what makes any of this readable: a cohort that drifts with the reader base moves the metric for reasons that are not the index.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Mean of item vectors as the profile | It is one line and it is what every tutorial shows | Mean cosine of a reader’s history to its own centroid; median 0.61 and p10 0.34 here means the mean sits in empty space | Recency decay plus dwell weighting over unit-norm vectors, worth 0.033, then k=3 centroids for another 0.007 |
| Anisotropy and hubness | Text embedding spaces occupy a narrow cone; nothing in any library warns you | Mean cosine between random item pairs (0.52 here, should be near 0) and the skewness of the k-occurrence array (4.9) | Centre the index, then PCA-whiten with shrinkage 0.08; skewness 4.9 to 2.1, top-1% share 23.7% to 9.4% |
| Near-duplicate collapse | Wire copy and republished live blogs genuinely ARE each other’s nearest neighbours, so a correct metric ranks them together | Mean slots per slate from one duplicate cluster; 3.4 of 10 raw | Dedup at a hand-calibrated cosine threshold, 0.94 here, then MMR; 3.4 to 0.3 slots |
| Popularity leaking through length | Long pieces have more tokens and more chances to match any profile, and length correlates with traffic at 0.31 | Spearman between log word count and top-50 appearance count; 0.31 uncapped | Hard body token cap at 400; Spearman falls to 0.08 |
| Popularity leaking through metadata completeness | Tag coverage is 71.4% and correlates with recency at 0.43, so a populated field is a traffic proxy | Mean appearance count of tagged vs untagged items at matched relevance; 2.3x here | Impute missing tags from a section prior; ratio 2.3x to 1.2x, cold recall@50 0.214 to 0.259 |
| Over-specialisation with a flat metric | The system trains on its own output and NDCG is measured against a fixed holdout that the loop does not touch | Intra-list similarity, catalog coverage, section entropy over a shadow loop; 0.488 to 0.661, 14.2% to 5.8%, 2.41 to 1.63 nats while NDCG moved 0.004 | MMR with a lambda cap, a coverage floor in the serving layer, and an explicit exploration slot |
| ANN recall treated as the only cost | efSearch is in the serving config, not the model config, so it gets tuned by whoever owns latency | NDCG at matched efSearch, and cold-item recall against exact separately from overall recall | Pin efSearch in the model artifact; at 32 it costs 0.015 NDCG and takes cold-item recall to 0.71 of exact |
| Random leave-one-out evaluation | It is the protocol in most of the literature and it is easier to implement | Rerun with a per-reader temporal holdout; the naive configuration fell 0.287 to 0.163 | Per-reader temporal holdout with a publication-time candidate mask |
| Candidate set containing unpublished items | Nothing about it looks like leakage; the vectors and the profile are both clean | Share of each reader’s candidate pool published after their cutoff | A per-reader publication-time boolean mask, worth 0.034 NDCG of inflation here |
| Scoring a new ranker against the incumbent’s log | The log is the only ground truth available | Share of offline positives that the incumbent surfaced; 61% here, and the raw-to-IPS optimism ratio of 2.1x | Inverse-propensity weighting with clipped weights, which predicted +2.2% against a realised +1.9% |
| Unnormalised vectors in a dot-product index | It does not raise, and the results look plausible | Distribution of index vector norms; anything other than 1.0 | Normalise inside the encoder, never at the call site, and assert it on index build |
Sort that table by the detection column and a pattern appears that is worth more than any individual row: eight of the eleven pitfalls are detected by a statistic over the catalog rather than by a metric over the readers. Mean cosine between random item pairs. The skewness of the k-occurrence array. Spearman between word count and appearance count. The appearance ratio between items with and without a populated field. Catalog coverage. The norm distribution of the index. None of those is a ranking metric and none of them appears in any recommender library's evaluation module, which is why a team can run a textbook offline evaluation, get a clean NDCG, and ship every one of these failures. The practical consequence is a five-line addition to the evaluation harness and a rule about where it lives: compute the k-occurrence array, the intra-list similarity, the catalog coverage and the appearance correlations inside the same function that computes NDCG and MAP, returning one dictionary. The reason it has to be the same function rather than a separate notebook is social rather than technical. A separate diagnostic script gets run during the project and not during the next one, whereas a metric that comes back in the same dictionary as NDCG ends up on the dashboard, in the regression test, and in the pull request description.
The single most common mistake on this exact problem is believing that a pure-content score is free of popularity bias, and therefore not measuring it. The belief is reasonable: the encoder never sees an interaction, so where would popularity come from. It comes from two places and both of them are editorial process rather than content. Long articles have more tokens and therefore more chances to match any profile, and the desk commissions long articles on subjects that already perform, so document length carries the traffic signal at Spearman 0.31. And metadata completeness tracks recency, recency tracks traffic, and a populated tag field makes a longer and richer document, so tagged items were retrieved 2.3 times as often as untagged ones at matched topical relevance. Together those two channels produced a Spearman of 0.41 between an item's historical read count and how often the pure-content index recommended it, which is not far below the 0.58 we measured for the collaborative filter that was explicitly fitted on reads. The dangerous part is not the bias, it is that it is unnamed: there is no coefficient to turn down, no ablation to run, and no line in any config that says 0.41. The fix is in two halves. Remove what you can in the document assembly, where a 400-token body cap took the length channel from 0.31 to 0.08 and tag imputation took the completeness channel from 2.3x to 1.2x, bringing the overall correlation to 0.11. Then add popularity back as an explicit term with a named weight, because the goal was never zero popularity, it was popularity you can measure and dial. A hybrid with popularity_weight: 0.12 is more controllable than a pure-content system with an invisible 0.41.
Scaling and Productionizing
The arithmetic that decided the architecture, all of it measured on the deployed configuration:
Catalog, 412,000 items = 412k rows
Item vectors, 384 dims, float32 = 633 MB
HNSW graph, M=32, base layer 64 neighbours x 4 bytes = 105 MB
Total index per replica, float32 = 738 MB (ceiling 1 GB)
Same index at float16, with a 0.003 NDCG cost = 421 MB
Full re-encode on a model change, 1 GPU at 1,100 items/s = 6.2 min
Full re-encode on CPU at 38 items/s = 3.0 h
Daily incremental encode, 680 new items = 0.6 s
HNSW rebuild from scratch, 412k items, 16 cores = 24 min
HNSW incremental insert, 680 items = 1.4 s
Whitener refit over the full index = 71 s
Profile build per request, 11 median history items = 0.4 ms
Retrieval, efSearch 128, k=200 = 6.4 ms p99
Dedup plus MMR over 200 candidates, 384 dims = 2.1 ms p99
Module total at 1,900 QPS on 8 replicas = 31 ms p99 (budget 80)
Exact flat search for the same k, same hardware = 41 ms p99
The index fits because the embedding dimension was chosen against the memory ceiling, not against a quality curve. 384 dimensions at float32 is 633 MB and 1,024 dimensions is 1.69 GB, which breaches the 1 GB ceiling before the graph is added. A 1,024-dimensional model scored 0.291 against 0.283, so the ceiling cost 0.008 NDCG, and that is the honest way to state it rather than pretending 384 was optimal.
Re-encoding is the operation that sets the retraining cadence, and it is not expensive. 6.2 minutes on one GPU for the full catalog means a model change is a routine deployment rather than a project. What is expensive is the 24-minute HNSW rebuild, which is why new items are inserted incrementally at 1.4 seconds per daily batch and the graph is rebuilt from scratch weekly. Incremental HNSW insertion degrades graph quality slowly: after six days of inserts, recall@50 at efSearch 128 had fallen from 0.981 to 0.969, which costs 0.002 NDCG, and the weekly rebuild resets it.
The profile is computed per request and that is the right call. 0.4 ms for a median 11-item history, against the alternative of a materialised profile table for 2.4 million readers that is stale by construction. Recomputing means a reader’s profile reflects the article they read ninety seconds ago, which for a news site is most of the value of personalisation.
Freshness decay is a serving-layer term, not a model property. The freshness weight of 0.18 with a two-day half life is applied at re-rank from the item’s publication timestamp, so it moves continuously with no model involvement. Baking recency into the embedding is the tempting alternative and it is wrong, because an embedding’s entire advantage here is that it is a stable description of content, and a vector that changes with the clock cannot be cached, compared across refreshes, or used to detect that the encoder has drifted.
The monitoring signal for silent degradation is the triple of the nightly k-occurrence skewness over a frozen 50,000-profile cohort, the cold-item share of served slots, and the index vector norm distribution. The skewness catches geometry regressions, as described above. The cold-item share catches both an ANN configuration change and an upstream metadata failure, because both reduce the retrievability of new items and neither moves NDCG on a fresh holdout where the new items are not yet anybody’s positives. And the norm distribution catches the one failure that is total and silent: a code path that writes unnormalised vectors into a dot-product index, which does not raise and quietly converts the ranking function into a sort by article length.
The production fact that surprised us most is that the index's job is retrieval and the ranking belongs somewhere the index cannot reach. We started with a design where the embedding was supposed to carry everything: freshness baked in as extra dimensions, a popularity prior folded into the vector norm, a quality score concatenated on. Every one of those was removed and each removal was an improvement, for the same reason in each case. An embedding that encodes a time-varying quantity cannot be cached, cannot be compared across model refreshes, and cannot be used to detect encoder drift, because you can no longer tell a change in the content from a change in the clock. Folding popularity into the norm was worse than useless: it broke the unit-norm invariant that makes the dot-product index a cosine index, so the ANN graph was built over a metric that no longer matched the one queries were scored with, and recall@50 against exact fell to 0.78 with no error anywhere. The discipline that came out of it is that the index stores one thing, a stable unit-norm description of content, and every signal that varies with time or traffic is a named term in a re-rank function with a coefficient someone can change in a config file. That makes the system auditable, makes each term ablatable, and means a freshness policy change ships in a config push rather than a 6.2-minute re-encode and a 24-minute graph rebuild.
The clearest production precedent for the specific move in this post, building item embeddings from content so that brand-new items are immediately retrievable, is Pinterest's PinSage (Ying and colleagues, 2018). It is a graph convolutional model over 3 billion pins and 18 billion edges, and the detail that matters here is that its node features are the pin's visual embedding and its text annotations, so a pin published seconds ago has a usable representation before anybody has saved it. Pinterest reported a 150% improvement in hit rate over the best content-based baseline they tested and 60% over a Pixie random-walk baseline, and the architectural lesson for a smaller system is the layering rather than the graph network: content features give you cold-start coverage, and the learned layer on top gives you quality, and you can ship the first without the second. Spotify's content-based podcast work is the closest analogue for text specifically, since a new episode has no plays at all and its description is all there is to go on, and their published work on podcast embeddings makes the same two-stage split between a content-derived representation and a learned ranker. Netflix is the long-running counter-example worth knowing: their tag and metadata features are hand-curated by a trained team rather than derived from text, which is expensive and also why their cold-start behaviour on a new title is better than any encoder would give you, and the Netflix Prize-era lesson they state repeatedly is that the ranking layer on top of any representation is where most of the measurable value sits. For the mechanics in this post the citations are specific: Reimers and Gurevych 2019 for sentence-BERT and why a siamese objective is what makes cosine meaningful; Radovanovic, Nanopoulos and Ivanovic 2010 for hubness and the k-occurrence diagnostic; Ethayarajh 2019 for measuring anisotropy in contextual embeddings and Li and colleagues 2020 plus Su and colleagues 2021 for the flow and whitening fixes; Malkov and Yashunin 2018 for HNSW and Johnson, Douze and Jegou 2019 for FAISS; and Carbonell and Goldstein 1998 for MMR, which is twenty-eight years old and still the default diversity re-ranker because nothing cheaper works as well.
Alternative Approaches
| Approach | NDCG@10 | Cold item recall@50 | Index and serving cost | Interpretability | Best fit |
|---|---|---|---|---|---|
| Content embeddings, field-aware, whitened, re-ranked | 0.301 | 0.259 | 738 MB, 7.4 ms p99, 6.2 min re-encode | Good: nearest-neighbour attribution per slot, plus named popularity and freshness terms | Fast-moving catalogs where new items must be recommendable immediately |
| TF-IDF plus SVD, same pipeline otherwise | 0.241 | 0.231 | 412 MB sparse plus 211 MB dense, 5.1 ms p99 | Best: the matching terms are inspectable per pair | No GPU, no torch dependency, mostly long-form text, or a first version |
| Matrix factorisation, implicit ALS, 128 factors | 0.214 | 0.000 | 1.2 GB with reader factors, 2.1 ms p99 | Poor: latent factors with no stated meaning | Stable catalogs with dense interaction history and no cold-start requirement |
| Two-tower neural retrieval, content features in the item tower | 0.338 | 0.244 | 738 MB plus a 14 MB query tower, 9.8 ms p99 | Moderate: content features are nameable, the learned mixing is not | The right endpoint once you have the training data and the labelling pipeline |
| Hybrid: content retrieval, collaborative re-rank | 0.327 | 0.241 | 1.9 GB, 11.2 ms p99 | Moderate: two stages, each separately explainable | The pragmatic answer when both signals already exist in production |
| Popularity within section | 0.118 | 0.000 | 4 MB, 0.2 ms p99 | Best: it is a sorted list | The baseline that must exist, and the fallback when the index is unavailable |
| LLM-generated item summaries, then embedded | 0.312 | 0.267 | 738 MB plus a one-off 412k-call summarisation at about 2,900 USD | Good: the summary is human-readable and auditable | Catalogs with poor or inconsistent metadata, where the summary IS the metadata fix |
What we shipped is the first row, and the row worth arguing about is the fourth. A two-tower model beats it by 0.037 and we declined it for this version for three reasons that are all about the project rather than the model: it needs a training pipeline and a labelling discipline that did not exist, its cold-item recall of 0.244 is slightly worse than ours because the item tower’s learned layers are fitted on items with interaction history, and it is the kind of system that is hard to debug at 2 a.m. The two-tower model is the right place to end up and content embeddings are the right place to start, and the ordering matters because the content index is a component of the two-tower design rather than a competitor to it: the item tower’s input features are exactly the field-aware documents built in this post.
The LLM summary row in the last position is the one that changed our roadmap. Passing each article through a small model to produce a 60-word structured summary, then embedding the summary instead of the truncated body, scored 0.312 and had the best cold-item recall in the table at 0.267. It is effectively a metadata-repair step: it fixes the 28.6% tag gap, the 16.5% missing standfirst, and the length variance all at once, by producing one uniform field for every item. At about 2,900 USD for a one-off pass over 412,000 articles and 0.004 USD per new item thereafter, the economics are not the obstacle; the obstacle is that an LLM summary is a new thing to monitor for drift, and we did not want two such things in the first version.
We would switch to the plain TF-IDF row without hesitation in two situations. A catalog of mostly long-form text, where the measured gap is 0.009 rather than 0.034 and not worth a torch dependency. And any first version, because 0.241 shipping this month beats 0.301 shipping next quarter, and the whole pipeline around the encoder transfers unchanged when you swap it.
The cold-item column is the one that should decide this table and it is the one nobody puts in it. Four of the seven rows score respectably on NDCG@10 and two of them score 0.000 on an item with no interaction history, which for this product is not a weaker result, it is a different product. The trap in comparing recommenders is that NDCG is computed over a holdout drawn from a read log, and a read log is by definition made of items that already had readers, so the entire cold-item question is structurally absent from the metric that the comparison is run on. A collaborative filter and a content index can therefore sit within 0.09 NDCG of each other while differing by the whole of the capability the project was commissioned for. The fix in an evaluation harness is a single extra column: compute recall@k restricted to items whose interaction count at the reader's cutoff was zero, report it beside the pooled number, and refuse to accept a pooled average as the comparison. On this problem that one column is the difference between a correct ranking of the alternatives and a comfortable wrong one.
Key Takeaways
- The encoder is the cheap half and it is where all the attention goes. Swapping TF-IDF plus SVD for a sentence encoder bought 0.034 NDCG@10. Fixing the profile bought 0.040, the field-aware document assembly bought 0.031, and the geometry fix bought 0.015. Three of those four have nothing to do with embeddings.
- A mean of item vectors is a weak user profile and the diagnostic is one line. Median cosine of a reader’s history to its own centroid was 0.61 and the 10th percentile 0.34, meaning a tenth of readers get a profile vector in a region where no article lives. Recency decay at a 45-day half life plus dwell weighting over unit-norm vectors recovered 0.033, and three k-means centroids another 0.007.
- Content-based retrieval fixes item cold start and does nothing for user cold start. A collaborative filter’s recall@50 on an item under two hours old is 0.000 and ours is 0.259. On readers with fewer than three prior reads, which is 38.6% of sessions, ours is 0.134 against a 20-plus-read cohort’s 0.291, and no encoder changes that, because the profile is built from the history.
- Text embedding spaces are anisotropic and that causes hubness, which no ranking metric shows. Mean random-pair cosine was 0.52 where an isotropic space gives roughly 0. Centering plus whitening with shrinkage 0.08 moved NDCG@10 by 0.015 and moved k-occurrence skewness from 4.9 to 2.1, the top-1% share of slots from 23.7% to 9.4%, and the never-recommended share from 61.2% to 44.8%.
- Popularity reaches a pure-content index through document length and metadata completeness. Spearman between read count and recommendation frequency was 0.41 before the fixes and 0.11 after a 400-token body cap and tag imputation. Then add popularity back as a named 0.12 coefficient, because the goal is popularity you can dial rather than popularity you cannot see.
- Cosine similarity is a correct answer to the wrong question when the catalog has duplicates. 11.2% of the archive is wire copy or republished live blogs, and raw cosine top-10 carried 3.4 slots from one duplicate cluster. Dedup at a hand-calibrated 0.94 plus MMR took it to 0.3, and the 0.011 NDCG that cost is the metric confessing that four copies of one story were scoring as four correct answers.
- ANN recall is not a quality number and it hides which items went missing. efSearch 32 gives recall@50 of 0.887, which sounds fine, costs 0.015 NDCG, which is the whole whitening gain, and takes cold-item recall to 0.71 of exact against 0.94 for head items. Pin efSearch in the model artifact, not the serving config.
- The per-reader temporal split is not a detail, it chooses your improvements for you. Random leave-one-out inflated the naive configuration by 76%, from 0.163 to 0.287, and simultaneously turned the single most valuable fix in this post into an apparent regression, taking the recency-weighted profile from 0.261 to 0.249.
The counter-intuitive lesson is that the ranking metric is the weakest instrument in the box for this problem, and it is weak for a structural reason rather than through any flaw in NDCG. NDCG is an average over readers of a quantity computed inside one slate, and three of this method’s five characteristic failures, hubness, over-specialisation and popularity leakage, are properties of the distribution over items induced across all readers at once. No within-slate average can see them. The six-week feedback loop makes the point as sharply as it can be made: NDCG@10 went up by 0.004 while catalog coverage fell by 59% and per-reader section entropy fell by a third. A team that ships on NDCG alone will ship the collapse and the dashboard will congratulate them. Compute the k-occurrence array in the same function that computes NDCG, so that nobody can report one without the other.
Frequently Asked Questions
Q: Why not just use collaborative filtering, since it beats the naive content pipeline by 0.051? A: Because the comparison that matters is not 0.214 against 0.163, it is 0.214 against the 0.301 the content pipeline reaches once the four things around the encoder are fixed, and because of one number that no amount of model quality addresses: a collaborative filter’s recall@50 on an item less than two hours old is exactly 0.000, since the item has no row in the interaction matrix. For a publication where 54% of an article’s lifetime traffic arrives in the first six hours and 680 articles are published a day, that is the central requirement rather than an edge case. The honest framing is that the two approaches are complementary and the hybrid in the alternatives table scores 0.327: content retrieval for coverage and cold start, collaborative signal for re-ranking the warm items.
Q: Why not skip the sentence encoder and stay on TF-IDF, if the gap is only 0.034? A: On a catalog of mostly long-form writing you should, and we say so in the alternatives table. The reason it was worth it here is that the gap is not uniform: 0.009 on items above 1,200 words and 0.061 on items under 200 words, because a 180-word wire brief gives a bag of words almost nothing to work with. 6.1% of this archive is under 120 words and briefs are disproportionately recent, so the gain concentrates on exactly the cold cohort the module exists to serve. The decision rule is to measure the gap by document length bucket rather than in aggregate, and to note that the whole pipeline around the encoder transfers unchanged, so starting on TF-IDF costs you nothing but the last 0.034.
Q: Why NDCG@10 and not recall@k, given that retrieval is the first stage? A: Both, and they are measuring different stages. Recall@50 is the right metric for the candidate generator, because its job is to put the good items in the pool and the ordering inside the pool is somebody else’s problem; NDCG@10 is the right metric for the re-ranker, because its job is ordering and recall is already fixed by then. Reporting only one hides half the system: switching the re-ranker on moved NDCG by -0.011 and recall@50 by exactly nothing, because re-ranking reorders a pool that recall already measured, while switching the profile moved recall@50 by 0.063 and NDCG by 0.033. And neither of them catches the distributional failures, which is why intra-list similarity, catalog coverage and k-occurrence skewness are computed in the same function.
Q: Is whitening worth it if it only moves NDCG@10 by 0.015? A: That framing is the trap this post is mostly about. The 0.015 is real and it is the smallest thing whitening did: it also took k-occurrence skewness from 4.9 to 2.1, the share of all top-50 slots going to the top 1% of items from 23.7% to 9.4%, and the never-recommended share of the archive from 61.2% to 44.8%. Those are the numbers an editor cares about, because they are the difference between a module that exercises a nineteen-year archive and one that serves the same 4,000 items to everybody. The cost side is almost nothing: a 71-second refit over the full index and a matrix multiply at query time that is already in the hot path. Use shrinkage, fit it on the whole index rather than a sample, and be aware that a whitener fitted on 500 items cost us 0.009 NDCG.
Q: How do you keep the profile from locking a reader into one topic forever? A: Three mechanisms and the first two are not enough. The recency half life of 45 days means a drifted interest fades without being deleted, which handles natural change and not self-reinforcement. MMR at lambda 0.72 holds intra-list similarity at 0.488 against a raw 0.712, which handles a single slate and not a trajectory. The thing that actually handles the trajectory is a monitored exploration slot: one of the ten positions is filled from outside the profile’s immediate neighbourhood, sampled with a coverage-weighted prior, and the loop is monitored by the six-week shadow test that measures intra-list similarity, catalog coverage and section entropy against a flat NDCG. Without the shadow test none of the three mechanisms would have been tuned, because each one costs a little NDCG and nothing in the ranking metrics would have justified paying it.
Q: What breaks first in production? A: The upstream metadata, and it breaks silently because nothing in the retrieval layer validates it. The failure we hit was a tagging job that quietly stopped running over a weekend, taking tag coverage on new items from 94% to 31%. Every affected item got a shorter document, a different token distribution, and a measurably lower chance of retrieval, and NDCG@10 on the fresh holdout did not move at all because those items were too new to be anybody’s positives yet. The signal that caught it was the k-occurrence skewness on the frozen query cohort going from 2.4 to 3.6 overnight, with the cold-item share of served slots falling alongside it. The second thing that breaks is the unit-norm invariant, through a code path that writes unnormalised vectors into a dot-product index, which raises nothing and converts the ranking function into a sort by article length. Assert the norm distribution on index build and alert on the cold-item share daily.
Interview Questions
Q: You need to recommend news articles where 680 new items appear daily and most of an item’s traffic arrives in its first six hours. Walk me through your approach. Expected depth: Start by naming why the obvious model fails rather than by naming your model. A collaborative filter has no row for an item with no interactions, so its recall on a new item is zero by construction, and the requirement is not a tail case here, it is the main case. Content-based retrieval answers it because text exists at publication time. Then be precise about what content-based does and does not fix: it fixes item cold start and it does nothing at all for user cold start, since the profile is built from history and a reader with two reads has no history, so name the separate fix for that, which is onboarding topic picks, session context, or an explicit popularity prior for thin profiles. Then lay out the pipeline as two stages with different metrics, retrieval measured by recall@k and ranking measured by NDCG@k, and name the four places the work actually is: field-aware document assembly rather than concatenation, the profile aggregation, the geometry of the index, and the re-ranker. Strong answers end on the hybrid, since the two signals are complementary and the content index is a component of a later two-tower design rather than a competitor to it.
Q: Your content-based recommender has a good NDCG@10 and users complain it is repetitive. What do you measure? Expected depth: Name the three distributional metrics and say why the ranking metric cannot see the problem. Intra-list similarity, the mean pairwise cosine inside a slate, which catches ten versions of one interest. Catalog coverage, the share of the catalog appearing in anybody’s top-k, which catches a system that is diverse per reader and narrow in aggregate. And the k-occurrence distribution, how many readers have each item in their top-k, whose right skewness is the hubness diagnostic from Radovanovic 2010, which catches a handful of items appearing in everybody’s results. The reason NDCG is blind to all three is structural: it is an average over users of a within-slate quantity and these are properties of the distribution over items across users. Then separate the two causes, because the fixes differ. Near-duplicate catalog items, fixed by a hand-calibrated cosine threshold rather than by tuning on a ranking metric, since a read log will tell you that showing one story four times is fine. And genuine over-specialisation, fixed by MMR plus an exploration slot plus a shadow feedback loop, because a single-slate diversity fix does not address a trajectory.
Q: Explain anisotropy in embedding spaces, how you would detect it, and what it costs a retrieval system.
Expected depth: Define it operationally rather than by citation: compute the mean cosine between randomly chosen item pairs, which on a unit sphere with isotropically distributed points is approximately zero and in a real text embedding space is routinely 0.3 to 0.6, because the vectors occupy a narrow cone. Then state the two consequences. The usable dynamic range of the similarity score is only the slice above that floor, so the score discriminates less than its range suggests. And items near the cone’s axis, which is to say near the global mean, have above-average cosine to every query and therefore appear in everybody’s top-k, which is hubness. Give the fixes in order of strength and cost: mean centering, which removes the dominant shared direction for one mean vector and in a measured case took mean pair cosine from 0.52 to 0.001; then PCA whitening with shrinkage, which rotates and rescales so the covariance is identity and is the transform that actually moves the hubness numbers. Name the failure mode of the fix, which is over-whitening: dividing by the square root of eigenvalues estimated from too few samples amplifies noise, so shrinkage is not optional when the sample is small. Strong answers note that TF-IDF’s max_df is an anisotropy fix applied before the encoder, which is why the problem is more severe for transformer embeddings, and that the fix must be applied to query vectors and index vectors alike or the two are no longer in the same space.
Q: Your approximate index reports recall@50 of 0.89 against exact search. Is that good enough? Expected depth: The answer is that recall is necessary and not sufficient, and a candidate needs to say what else to measure. First, recall does not translate linearly into ranking quality, because a miss at rank 48 and a miss at rank 2 are the same recall and very different NDCG, so measure NDCG at each setting of the recall dial rather than inferring it: in a measured sweep, recall 0.887 was an 11.3% recall loss costing 5.3% of the NDCG. Second, and more important, the misses are not a random sample. A graph index like HNSW reaches items through neighbour links, so items with few in-links, which are the new and the topically unusual ones, are the hardest to reach, and in the same sweep cold items recovered 0.71 of their exact recall against 0.94 for head items. That means a cheap efSearch silently undoes the cold-start capability the content-based design was chosen for. A cell-based index like IVF has a different miss profile for the same recall, which is worth saying because it shows the candidate knows the mechanism rather than the slogan. Close on the operational point: the recall dial is a ranking parameter and it belongs pinned in the model artifact rather than in a serving config that a latency owner can consolidate away.
Q: How would you evaluate a content-based recommender offline, and why will the online result differ? Expected depth: Specify the protocol precisely: per-user temporal holdout, the last fraction of each user’s interactions in time order, with graded relevance from a dwell or completion signal so NDCG has something to grade, and a per-user candidate mask excluding items published after the user’s cutoff. Say what you are not doing and why. Not random leave-one-out, which builds the profile partly from the user’s future and in a measured case inflated the naive configuration by 76% while simultaneously making the most valuable fix look like a regression. Not grouped time folds, which are the right tool for a tabular classifier whose rows recur on an entity and answer a different question here. Then explain the divergence structurally rather than as noise. The log was produced by the incumbent recommender, so a measured share of the offline positives, 61% in this case, are items the incumbent surfaced, and scoring a new ranker against that log rewards agreement with the system being replaced. Name the correction, inverse-propensity weighting with weights clipped because an unclipped estimator on a Zipf exposure distribution has unbounded variance, and give the shape of the result: a raw-to-corrected optimism ratio of 2.1x, with the corrected estimate predicting +2.2% against a realised +1.9% where the naive projection said +4.6%. Strong answers add that the offline harness should also report the distributional guardrails, since the online complaint will be about repetition long before it is about relevance.
View full code for this problem