Build a Collaborative Filtering Recommender with Matrix Factorization


recommendation-systems ranking classical-ml model-evaluation
View full code for this problem

ML Problem & Solution

Collaborative Filtering with Matrix Factorization

The 99.964% of the matrix nobody touched is not missing data. It is most of the objective.

⏱ 29 min read 📐 Intermediate 🎯 Classical ML

An audiobook streaming service wants ten personalised titles on the home shelf, chosen per listener, refreshed nightly. There are 1,870,000 monthly active listeners, 142,000 titles, and 96,400,000 distinct listener-title listen events across eighteen months. That is 0.036% of the possible pairs, so 99.964% of the matrix is empty. The shelf call has a 45 ms p99 budget at a 2,400 QPS peak, and the current shelf is the bestseller list with a genre filter.

The data has no target column. There is no rating on 97.9% of events, and the 2.1% that do carry a star rating are the ratings people volunteered, which is a different population from the listens people made. What the log does have is a completion fraction: how much of an eleven-hour audiobook somebody actually got through. That number takes a median of nine days to stabilise after the first play, so the signal for anything listened to this week is not yet trustworthy.

The naive translation of this into an ML problem is the one almost everybody writes first, and it is wrong in a specific, measurable way. You have a sparse matrix with some numbers in it, so you factorise it: minimise squared error between the observed entries and the dot product of a user factor and an item factor, the way the Netflix Prize papers do. Fit it, measure RMSE on held-out entries, ship. That model scores NDCG@10 of 0.041 on this data, and a ranking by raw global play count scores 0.094. A 128-factor latent model, correctly implemented and converged, loses to value_counts() by a factor of 2.3.

The reason is not a bug and it is not underfitting. A squared loss summed over observed entries only never mentions the 99.964% of the matrix that is empty, so nothing in the objective ever pushes an unlistened title down. Every target is positive, every residual is a residual on something the user already played, and the model’s score for the 141,988 titles a listener has not touched is whatever the factor geometry happens to extrapolate there. The analogy: it is like training a spam filter on nothing but spam. The model will learn the structure of spam beautifully and has been told nothing about what it is supposed to separate spam from.

What makes the problem genuinely hard is that the absences carry the information. An unplayed title is not a dislike, and it is not missing at random either: it is some mixture of “never shown”, “shown and ignored”, and “actively avoided”, and the log cannot tell those apart. The fix has to encode a belief about the empties without pretending to know which kind each one is, and it has to do that over 265 billion cells.

Given a listener’s history of implicit interactions on a 142,000-title catalog at 99.964% sparsity, produce a ranked list of ten unlistened titles, optimising for NDCG@10 and recall@200 on a leave-one-out temporal split, under a 45 ms p99 shelf budget, a nightly retrain window, and a guardrail that catalog coverage of the served shelves must not fall below 2.0%.

Framing the Problem

This is a ranking problem, specifically top-N item retrieval from implicit feedback, and calling it that rather than “rating prediction” is the single decision that determines whether the rest of the project works. The input is a listener’s set of past interactions. The output is an ordered list. There is no scalar to regress.

The target needs defining carefully because there are three candidates and two of them are traps.

  • The star rating exists on 2.1% of events. It is missing not at random: a listener who finished a title rates it 4.7x more often than one who abandoned it, so the rated subset is a sample of titles the listener already liked. Modelling it answers “how much would you enjoy a title you have already chosen”, which is not the shelf’s question.
  • The completion fraction is dense and graded, which makes it tempting as a regression target. It is not one. Setting p(u,i) = 0.2 for a title somebody abandoned after two chapters tells the model that two chapters is 20% of a preference, which is a rating-prediction claim about an unrated item. The completion fraction belongs in the objective as a weight, never as a target.
  • The binary indicator, 1 if any listen happened, is the target. It is crude and it is correct: the thing being predicted is whether this listener will start this title, and the graded signal expresses how confident we are that the observed 1 reflects a real preference.

The label lag is nine days. A title started on Monday has an unstable completion fraction until the following Wednesday, so the most recent nine days of data carry a signal that will change. For a nightly retrain this matters less than it would for a classifier, because the binary indicator is known immediately and only the confidence weight is unsettled, but it rules out using completion-based features computed on the trailing week.

Constraints, and the last two decided more of the design than the accuracy numbers did:

  • 45 ms p99 for the shelf call at 2,400 QPS peak, of which the recommender gets about 15 ms. That rules out scoring 142,000 titles per request with anything but a dot product plus an approximate nearest-neighbour index.
  • Nightly retrain on eighteen trailing months, on CPU, inside a four-hour window.
  • New listeners must be served within 90 seconds of their first play. A nightly retrain cannot do that, so there has to be an inference-time path that produces a factor vector from a history without refitting the model.
  • 24,000 new titles per quarter, with a median of six days from catalog ingest to first impression. A pure factorization model has nothing to say about a title with zero interactions, so a cold-item path is part of the system and not an enhancement.
  • Catalog coverage of served shelves at or above 2.0%. Stated as a hard constraint because without it the optimiser’s answer is “show everyone the top 200 titles”, which is both accurate and the end of the catalog.
Key Insight

Calling this a ranking problem rather than a rating-prediction problem is not terminology, it is the decision that determines whether anything downstream works, and the reason is that the two framings have different training sets. Rating prediction can only be fitted on the 2.1% of events that carry a rating, which is 2.0 million rows. Ranking from implicit feedback is fitted on all 96.4 million, a factor of 48. Requiring an explicit label does not merely add noise or reduce sample size, it selects a sub-population: a listener rates a title they finished 4.7x more often than one they abandoned, so the rated subset is the set of titles the listener already liked, and a model fitted on it answers "how much would you enjoy something you already chose". The shelf's question is which of 141,989 unchosen titles to put in front of somebody. Those two questions are evaluated on datasets that barely overlap, which is why the explicit model's held-out RMSE of 0.861 is a perfectly good number about the wrong thing, and why it scores NDCG@10 0.038 against a non-personalised 0.094.

Metric That Matters

The optimisation metric is **NDCG@10** on a leave-one-out temporal split, scored against the **full 142,000-title catalog** with already-played titles masked. Three qualifiers in that sentence are each load bearing. Against the full catalog, because scoring the held-out title against 100 sampled negatives inflates NDCG@10 by about 0.30 and, worse, compresses the gap between candidate models from 0.009 to 0.002, after which the winner is decided by the negative-sampling seed. With played titles masked, because without masking every model's top slot is a title the listener already finished and the metric measures memorisation of the training set, worth about +0.4 NDCG@10 of pure fiction. And leave-one-out temporal rather than random, because a random held-out interaction leaks the listener's own future and it leaks it unequally: +0.053 NDCG@10 to implicit ALS and -0.001 to the popularity baseline. The secondary metric is **recall@200**, which is the retrieval ceiling: a candidate generator that does not put the right title in the top 200 cannot be rescued by any reranker downstream, so recall@200 bounds the whole system at 0.571. **RMSE is deliberately absent.** Across 24 explicit-MF configurations the Spearman correlation between held-out rating RMSE and NDCG@10 is +0.31, and on the convention where RMSE is lower-better, a positive correlation means the two metrics disagree. The RMSE-best configuration scores 0.861 RMSE and 0.038 NDCG@10; the NDCG-best scores 0.934 and 0.072. Selecting on RMSE forfeits 0.034 NDCG@10, which is 47% of what the explicit family could reach, and the entire explicit family sits under a non-personalised popularity ranking. The guardrails are **catalog coverage@10**, floored at 2.0%, **head slot share**, the fraction of served slots going to the top 1% of titles, capped at 65%, and **started-listen rate on the home shelf**, which is the business metric the offline numbers are a proxy for and which moved +2.4% relative where a naive reading of the offline lift predicted +11%.

Out of scope: sequence models and session-based recommendation, which are a better fit when the next-item signal is strongly order-dependent and are a different post; two-tower neural retrieval, which is in the alternatives table and is the right answer once side features matter; and the reranking stage that sits downstream of candidate generation, including diversity and business rules.

Data and Features

There is almost no feature engineering in this problem, and that is the interesting part. A pure collaborative-filtering model takes three columns: who, what, and how much. Everything else is either a confidence weight or a leak.

The archive is 96.4 million rows of (listener_id, title_id, first_play_at, completion_fraction), deduplicated to one row per listener-title pair. Shape and shape alone:

Property Value
Listeners 1,870,000
Titles 142,000
Interactions 96,400,000
Density 0.036%
Interactions per listener, median 11
Interactions per listener, mean 51.5
Listeners with fewer than 5 interactions 38%
Share of interactions on the top 1% of titles 31.4%
Events carrying a star rating 2.1%
New titles per quarter 24,000

The two matrices that matter are built from that frame, and keeping them as two matrices rather than one is the whole of implicit-feedback preprocessing.

# Build the preference and confidence matrices. The only non-obvious thing here
# is that one observation produces TWO numbers, and merging them is the most
# common implementation error in this model family.
import numpy as np
import pandas as pd
from scipy import sparse

def build_interactions(frame: pd.DataFrame, n_users: int, n_items: int,
                       alpha: float = 40.0) -> tuple:
    """Return (p, c_minus_one) as aligned CSR matrices.

    p(u,i) = 1 if the listener played the title at all, 0 otherwise.
    c(u,i) = 1 + alpha * completion_fraction, the CONFIDENCE in that 1.

    The completion fraction weights the residual. It is never the target. If you
    put it into p and fit squared loss, you have told the model that a title
    abandoned after two chapters is 0.2 preferred, which is a rating-prediction
    statement about something nobody rated.
    """
    u = frame["listener_idx"].to_numpy()
    i = frame["title_idx"].to_numpy()
    r = frame["completion_fraction"].to_numpy().astype(np.float64)
    shape = (n_users, n_items)

    pref = sparse.csr_matrix((np.ones(len(u)), (u, i)), shape=shape)
    conf = sparse.csr_matrix((alpha * r, (u, i)), shape=shape)
    pref.sum_duplicates()
    # A duplicate (listener, title) pair is summed silently by the COO to CSR
    # conversion, handing one cell preference 2 and double the confidence. That
    # is a leak toward popular titles and it raises nothing.
    assert pref.data.max() <= 1.0 + 1e-9, (
        "duplicate (listener, title) pairs reached build_interactions")
    return pref, conf

alpha is the most important hyperparameter in the model and it is not a regularizer. It sets how much more a fully-consumed title counts than an untouched cell: at alpha=40 a 100%-completed listen carries confidence 41 against the confidence 1 carried by each of the 141,989 cells that listener never touched. Measured on this archive, with everything else pinned at 128 factors:

alpha NDCG@10
1 0.142
10 0.176
40 0.188
100 0.181
400 0.149

The shape is the point and so is the reason for it. alpha controls the ratio of observed mass to unobserved mass in the objective, which means its optimum moves with density. The companion codebase runs at 1.56% density, 43x denser, and peaks at alpha=15. Any alpha you read in a paper is relative to that paper’s sparsity, and copying the number without the density is how a model ends up either ignoring the signal or memorising the head.

Leakage, which looks different here than in a classifier

There is no feature matrix to leak through, so the leaks all live in the split and in the evaluation.

  • The listener’s own future. Holding out a random interaction instead of the chronologically last one puts the listener’s later plays into their training history. Taste drifts, so later plays are informative about earlier ones in a way no deployed model can exploit.
  • The catalog’s future. A random split also trains on the catalog composition of the prediction moment. The popularity prior the model learns is the one that was true when the held-out play happened, not the one that was true at the last timestamp it would really have had.
  • Already-played titles. If the evaluation does not mask the training history, the metric rewards re-recommending finished audiobooks.
  • The k-core filter. Dropping listeners with fewer than k interactions before splitting is standard, invisible in write-ups, and worth more than most modelling changes. On this archive a 3-core filter removes the 24% of evaluated listeners with one or two training interactions and raises reported NDCG@10 from 0.188 to 0.221, a change of +0.033 against a 0.009 gap between the two models the scorecard exists to compare.

The split, and why a random interaction split leaks

The earlier tracks in this series used grouped, time-ordered folds, and a recommender cannot use them. The reason is structural rather than stylistic. A grouped time fold holds out whole entities, but every listener in the test window needs an existing history to personalise from, and every title needs existing factors to be scored at all. So the unit of held-out evidence is neither a listener nor a time window: it is one interaction per listener, the chronologically last one, with that listener’s earlier interactions kept in training.

# Leave-one-out temporal split, and the random variant that leaks. The two are
# constructed to differ in exactly one respect: which interaction is held out.
# Same train size, same test size, same masking.
import numpy as np
import pandas as pd

def leave_one_out_temporal(frame: pd.DataFrame, min_train: int = 1):
    """Last interaction per listener to test, second-to-last to validation.

    min_train is the number of interactions a listener must retain in training
    to be eligible for a test item. Keep it at 1. Raising it to 4 is the
    standard k-core filter and it removes the cold-start cohort from the
    evaluation, which moves the reported metric by +0.033 here.
    """
    frame = frame.sort_values(["listener_idx", "first_play_at"], kind="stable")
    rank_from_end = frame.groupby("listener_idx").cumcount(ascending=False)
    size = frame.groupby("listener_idx")["title_idx"].transform("size")
    is_test = (size >= min_train + 1) & (rank_from_end == 0)
    is_valid = (size >= min_train + 2) & (rank_from_end == 1)
    return (frame[~(is_test | is_valid)], frame[is_valid], frame[is_test])

def split_report(train: pd.DataFrame, test: pd.DataFrame) -> dict:
    """The diagnostic that makes a leaky split visible before any model runs.

    `future_in_train` is the share of test interactions for which the SAME
    listener has a training interaction with a later timestamp. A deployed model
    never has that, so any value above 0.000 is a number you cannot reproduce in
    production. It is 0.000 for the temporal scheme and 0.76 for the random one.
    """
    last = train.groupby("listener_idx")["first_play_at"].max()
    aligned = last.reindex(test["listener_idx"]).to_numpy()
    future = np.nan_to_num(aligned, nan=-np.inf) > test["first_play_at"].to_numpy()
    seen_items = set(train["title_idx"].to_numpy().tolist())
    cold = np.array([i not in seen_items for i in test["title_idx"].to_numpy()])
    return {"future_in_train": float(future.mean()),
            "cold_test_items": float(cold.mean())}

Measured on this archive, with the training and test set sizes held bit-identical between the two schemes so that nothing but the choice of held-out row differs:

Model Temporal leave-one-out Random leave-one-out Leak
Popularity 0.094 0.093 -0.001
Item-item cosine kNN 0.131 0.179 +0.048
Implicit ALS 0.188 0.241 +0.053
BPR-MF 0.179 0.220 +0.041
Key Insight

The random split does not inflate every model equally, and that asymmetry is what turns a measurement error into a wrong decision. It is worth -0.001 to the non-personalised baseline, which has no listener-specific parameters to overfit, and +0.041 to +0.053 to every personalised model. So the quantity actually being estimated, the benefit of personalisation over showing everyone the bestseller list, inflates from 0.094 to 0.148, a 57% overstatement. A uniform inflation would be annoying and harmless: everyone's number is too high, the ranking survives, you ship the right model and brag about the wrong figure. An unequal inflation is a different failure, because the thing it inflates most is the thing the decision depends on. This is the same shape as the leakage asymmetry in the bagging-versus-boosting comparison, where a random K-fold cost the booster 0.063 and the forest 0.047, and the general rule is identical: when a leak favours the more flexible model, the leak is not noise on the estimate, it is a bias on the comparison.

The Naive Baseline

Four baselines, and the two that matter are the first and the last, for opposite reasons.

# The four baselines. Popularity is not a straw man: it is a strong competitor
# on any metric computed over a popularity-biased test set, which is every
# metric computed over a real log.
import numpy as np
from scipy import sparse

def popularity_scores(pref: sparse.csr_matrix, users: np.ndarray) -> np.ndarray:
    """Global play count, tiled. Zero personalisation, four lines, hard to beat."""
    counts = np.asarray(pref.sum(axis=0)).ravel()
    return np.tile(counts, (len(users), 1))

def item_knn_scores(pref: sparse.csr_matrix, users: np.ndarray,
                    top_k: int = 200, shrink: float = 100.0) -> np.ndarray:
    """Cosine item-item neighbourhood on the binary matrix.

    Truncating to each title's top_k neighbours is not an optimisation. Without
    it the similarity matrix is dense noise, the model collapses toward
    popularity, and you get the classic result where a kNN baseline matches
    value_counts() to three decimals.
    """
    P = pref.tocsc().astype(float)
    co = np.asarray((P.T @ P).todense())
    norms = np.sqrt(np.diag(co))
    sim = co / (np.outer(norms, norms) + shrink + 1e-9)
    np.fill_diagonal(sim, 0.0)
    cut = np.partition(sim, -top_k, axis=1)[:, -top_k]
    sim[sim < cut[:, None]] = 0.0
    return np.asarray(pref[users] @ sim)

def observed_only_mf_step(target: sparse.csr_matrix, Y: np.ndarray,
                          reg: float) -> np.ndarray:
    """One ALS half-step for squared loss over OBSERVED entries only.

    This is the wrong objective and it is here to be measured. Compare it to the
    HKV kernel below and note the single difference: there is no Y.T @ Y term,
    which is exactly the contribution of every cell the listener did not touch.
    """
    f = Y.shape[1]
    out = np.zeros((target.shape[0], f))
    indptr, indices, data = target.indptr, target.indices, target.data
    for row in range(target.shape[0]):
        s, e = indptr[row], indptr[row + 1]
        if s == e:
            continue
        Yi = Y[indices[s:e]]
        out[row] = np.linalg.solve(Yi.T @ Yi + reg * np.eye(f),
                                   Yi.T @ data[s:e])
    return out

On the temporal leave-one-out split, scored against all 142,000 titles with played titles masked:

  • Random ranking: NDCG@10 0.00003. The true zero, worth printing once so the rest of the table has a floor.
  • Popularity: NDCG@10 0.094, MAP@10 0.061, recall@200 0.412.
  • Item-item cosine kNN: NDCG@10 0.131, recall@200 0.487.
  • Explicit biased MF on the 2.1% rated subset, RMSE-tuned: NDCG@10 0.038, held-out RMSE 0.861.
  • Observed-only squared-loss MF, 128 factors: NDCG@10 0.041, recall@200 0.188.

The last two lines are the reason this post exists. Both are correctly implemented matrix factorizations with 128 latent factors, both converged, and both lose to a ranking by global play count. The explicit model loses because it was fitted on a biased 2.1% sample and because its item-bias term is the mean rating among people who chose to rate, which for a niche title with four five-star reviews is 5.0. The implicit model loses because its objective never mentions the empties.

Key Insight

Popularity is the floor that matters, and most published recommender numbers do not clear it by enough to justify the system. The reason it is strong has nothing to do with the model and everything to do with the test set: a held-out interaction drawn from a popularity-biased log is, by construction, usually a popular title, so a non-personalised ranking by play count scores well on it without knowing anything about anybody. Three practical consequences follow. First, a model that beats popularity by 0.01 NDCG@10 has probably learned the popularity prior and nothing else, which you can confirm by checking whether its head slot share is near the log's own 31.4%. Second, the right comparison for any new architecture is popularity, not the previous model, because the previous model may also have been measuring the prior. Third, and least comfortable: popularity is the worst model in the whole scorecard on an unbiased measure of relevance. Against the exposure-free oracle in the companion codebase it captures 0.421 of achievable relevance against a uniformly random ranking's 0.468. It is 3,100x better than random on the logged metric and slightly worse than random on the real one, which is the clearest single statement of what a popularity-biased log does to an offline evaluation.

The Solution

Pipeline from a 96.4 million event implicit listen log at 99.964 percent sparsity, through confidence construction where p is binary and c equals one plus alpha times completion with alpha 40, a leave-one-out temporal split whose random variant leaks 0.053 NDCG at 10 to implicit ALS and minus 0.001 to popularity, two factorization objectives where confidence-weighted all-pairs ALS reaches NDCG at 10 of 0.188 and BPR reaches 0.179 while observed-only squared loss reaches only 0.041 against a popularity floor of 0.094, HNSW candidate generation over 142,000 item vectors returning the top 500 in 3.2 milliseconds p99 inside a 45 millisecond shelf budget, ranking metrics against the full catalog rather than 100 sampled negatives, and a decision gate that is a band rather than an argmax because offline to online Spearman is 0.29 and four of seven offline-accepted changes failed in A/B

The approach has three parts: an objective that accounts for the empty cells, a second objective that optimises the ranking directly, and an evaluation that can tell them apart.

The implicit-feedback objective, stated properly

The analogy first. A squared loss over observed entries is a teacher who only ever shows the class correct answers and then grades them on spotting wrong ones. The confidence-weighted objective is a teacher who also says, quietly and with low confidence, that everything not on the list is probably wrong, and who is willing to be overruled by enough evidence.

Formally, Hu, Koren and Volinsky’s 2008 formulation replaces one observation with two quantities. The preference p(u,i) is 1 if the listener interacted and 0 otherwise. The confidence c(u,i) = 1 + alpha * r(u,i) is how much the model should trust that indicator, where r is the graded signal. The objective sums over every cell:

minimise   sum over all (u, i) of  c(u,i) * ( p(u,i) - x_u . y_i )^2
         + lambda * ( sum_u ||x_u||^2 + sum_i ||y_i||^2 )

Three things that sum does which the observed-only version does not. It assigns p = 0 to every untouched cell, so there is now something pushing unlistened titles down. It assigns c = 1 there rather than 0, which is the claim being made: we weakly believe you would not have played it, and a single confident observation at c = 41 outweighs forty weak zeros. And it is over 265 billion terms, which is why the next paragraph exists.

The all-pairs sum is tractable because of one identity. For listener u the normal equations are (Y' C_u Y + lambda I) x_u = Y' C_u p_u, and since C_u = I + diag(alpha * r_u) is the identity everywhere the listener did not interact,

Y' C_u Y  =  Y'Y  +  Y_u' diag(alpha * r_u) Y_u

where Y_u is only the rows the listener did touch. Y'Y is computed once per iteration and shared across all 1.87 million listeners, so one listener’s solve costs O(f^2 * nnz_u + f^3) instead of O(f^2 * n_items), and the total per iteration is linear in the number of observed interactions. That identity is the entire reason implicit ALS runs at catalog scale.

# Implicit ALS, the Hu/Koren/Volinsky objective. The whole method is the Gram
# matrix on line 3 of the loop: it is the contribution of every cell this
# listener did NOT touch, and removing it is the observed-only model above.
import numpy as np
from scipy import sparse

def als_half_step(pref: sparse.csr_matrix, conf: sparse.csr_matrix,
                  Y: np.ndarray, reg: float) -> np.ndarray:
    """Solve for every row of `pref` against fixed factors Y.

    `pref` rows are the binary indicators, `conf` rows are alpha * r, i.e.
    c - 1. The two must share a sparsity pattern; a mismatch raises nothing and
    silently reweights the wrong cells, so it is asserted rather than assumed.
    """
    f = Y.shape[1]
    base = Y.T @ Y + reg * np.eye(f)          # shared by all 1.87M listeners
    out = np.zeros((pref.shape[0], f))
    for row in range(pref.shape[0]):
        s, e = pref.indptr[row], pref.indptr[row + 1]
        if s == e:
            continue      # no history: the solve returns zero, correctly
        idx = pref.indices[s:e]
        cminus = conf.data[s:e]
        assert np.array_equal(idx, conf.indices[s:e])
        Yi = Y[idx]
        A = base + (Yi * cminus[:, None]).T @ Yi
        b = ((1.0 + cminus)[:, None] * Yi).sum(axis=0)
        out[row] = np.linalg.solve(A, b)
    return out

def fit_implicit_als(pref, conf, n_factors=128, reg=0.08, n_iters=15, seed=23):
    """Alternate until the budget runs out. ALS is monotone non-increasing in
    the regularised objective, so there is no early stopping decision to make.
    """
    rng = np.random.default_rng(seed)
    X = 0.01 * rng.standard_normal((pref.shape[0], n_factors))
    Y = 0.01 * rng.standard_normal((pref.shape[1], n_factors))
    pi, ci = pref.T.tocsr(), conf.T.tocsr()
    for _ in range(n_iters):
        X = als_half_step(pref, conf, Y, reg)
        Y = als_half_step(pi, ci, X, reg)
    return X, Y

def all_pairs_objective(pref, conf, X, Y, reg) -> float:
    """The real objective, without enumerating 2.65e11 pairs.

    sum over all (u,i) of (x.y)^2 is trace((X'X)(Y'Y)), which is f^2 work. The
    observed cells then get a correction. Print this every iteration: ALS is
    monotone by construction, so a value that RISES means the two sparsity
    patterns are misaligned or the regulariser is negative.
    """
    all_pairs = float(np.sum((X.T @ X) * (Y.T @ Y)))
    coo = pref.tocoo()
    pred = np.einsum("ij,ij->i", X[coo.row], Y[coo.col])
    c = np.asarray(conf[coo.row, coo.col]).ravel() + 1.0
    observed = float(np.sum(c * (1.0 - pred) ** 2 - pred ** 2))
    penalty = reg * (float(np.sum(X ** 2)) + float(np.sum(Y ** 2)))
    return all_pairs + observed + penalty

The hyperparameters that moved the number, in order:

Parameter Value NDCG@10 at the extremes
alpha 40 0.142 at 1, 0.149 at 400
n_factors 128 0.161 at 32, 0.190 at 256
reg 0.08 0.172 at 0.01, 0.166 at 1.0
n_iters 15 0.181 at 5, 0.188 at 15, 0.188 at 40

Two readings. 256 factors buys 0.002 NDCG@10 and doubles the artifact from 1.03 GB to 2.06 GB, so 128 is the operating point. And the regularizer is far larger than an explicit model would tolerate, which is a direct consequence of the Y'Y term: every item row receives gradient from every listener, so the normal equations are well conditioned and the live risk is overfitting the observed cells rather than underdetermining the rest.

Pairwise ranking instead of pointwise regression

Implicit ALS still asks a pointwise question: what value does this cell have. Rendle’s 2009 Bayesian Personalised Ranking asks the question the shelf actually poses: for this listener, is observed title i ranked above unobserved title j.

maximise   sum over (u, i, j) in D_S  ln sigma( x_u . y_i  -  x_u . y_j )
         - lambda * ( ||x_u||^2 + ||y_i||^2 + ||y_j||^2 )

where D_S is the set of triples with i observed for u and j not. The derivative of ln sigma(d) with respect to d is sigma(-d), which is near 1 when the pair is currently ranked wrong and near 0 when it is already correct, so training concentrates itself on the pairs that are still broken. That is the structural reason BPR is sharper at the very top of a list than a squared-loss model: a pointwise objective keeps spending gradient on cells it already predicts well. The expectation of the objective is AUC, which is also why BPR optimises depth better than it optimises the first slot.

# BPR-MF. Three np.add.at calls, and they are the subtle part: a listener or a
# title appears many times inside a 4,096-triple batch, and plain fancy-index
# assignment keeps only the last write, which silently discards most of the
# gradient and still trains to something that looks plausible.
import numpy as np
from scipy import sparse

def fit_bpr(pref: sparse.csr_matrix, n_factors=128, lr=0.03, reg=0.008,
            n_epochs=40, batch_size=4096, seed=23):
    rng = np.random.default_rng(seed)
    n_users, n_items = pref.shape
    X = 0.1 * rng.standard_normal((n_users, n_factors))
    Y = 0.1 * rng.standard_normal((n_items, n_factors))
    coo = pref.tocoo()
    pos_u, pos_i = coo.row.astype(np.int64), coo.col.astype(np.int64)
    indptr, indices = pref.indptr, pref.indices

    for _ in range(n_epochs):
        order = rng.permutation(len(pos_u))
        for start in range(0, len(order), batch_size):
            sel = order[start:start + batch_size]
            u, i = pos_u[sel], pos_i[sel]
            j = rng.integers(0, n_items, size=len(u))
            # Two rejection rounds, not a while loop. At 99.964% sparsity the
            # expected collisions after two rounds are under one in a million,
            # and an unbounded loop in a hot path is how training hangs on a
            # listener with 4,000 plays.
            for _round in range(2):
                bad = np.array([np.isin(jj, indices[indptr[uu]:indptr[uu + 1]])
                                for uu, jj in zip(u, j)])
                if not bad.any():
                    break
                j[bad] = rng.integers(0, n_items, size=int(bad.sum()))
            d = np.einsum("ij,ij->i", X[u], Y[i] - Y[j])
            g = 1.0 / (1.0 + np.exp(np.clip(d, -30, 30)))   # sigmoid(-d)
            np.add.at(X, u, lr * (g[:, None] * (Y[i] - Y[j]) - reg * X[u]))
            np.add.at(Y, i, lr * (g[:, None] * X[u] - reg * Y[i]))
            np.add.at(Y, j, lr * (-g[:, None] * X[u] - reg * Y[j]))
    return X, Y

The negative sampler is uniform over the catalog, which is the paper’s default and is not obviously the best choice. A uniformly drawn negative from a 142,000-title catalog is almost always a long-tail title the listener would never have been shown, so the pair is easy and the gradient is small. Popularity-proportional sampling draws harder negatives and converges in 24 epochs instead of 40; it also raises the model’s head slot share from 66.1% to 74.8%, so it is a speed-for-popularity-bias trade and it belongs in the traps section rather than the tuning section.

The two models land in different places, and the difference is consistent rather than noise:

Model NDCG@10 MAP@10 recall@50 recall@200 Coverage@10
Implicit ALS, 128 factors, alpha 40 0.188 0.121 0.402 0.571 2.8%
BPR-MF, 128 factors 0.179 0.112 0.371 0.604 6.4%

ALS wins at the top of the list and BPR wins at depth 200 and on coverage. That is exactly what the two objectives predict: a confidence-weighted pointwise loss concentrates its effort on the cells it is most confident about, which are the popular ones, and a pairwise loss with uniform negatives spends most of its gradient distinguishing a positive from the tail. For a ten-slot shelf, ALS. For the retrieval stage of a two-stage system where a reranker will reorder the top 200 anyway, BPR.

The cold-start path, which is a solved problem and a separate problem

A new listener’s factor vector does not need a retrain. With item factors frozen, one listener’s normal equations are an f x f solve, 128 by 128 here, which runs in 0.04 ms.

# Fold-in: a factor vector from a history, against frozen item factors. This is
# the 90-second SLA for new listeners, and it is the same kernel as training.
def fold_in(pref_row, conf_row, Y, reg: float = 0.08):
    """Score a listener who was not in the nightly training run.

    Note what happens at nnz = 0: the equations reduce to (Y'Y + lambda I) x = 0
    and the answer is the zero vector, which ranks the catalog arbitrarily. A
    factorization model has nothing to say about a listener with no history, so
    the fallback is part of the design rather than a patch.
    """
    return als_half_step(pref_row.tocsr(), conf_row.tocsr(), Y, reg)

Cold items are harder and the asymmetry is worth naming. A new title with zero interactions has an untrained factor row, and no amount of folding in helps because there is nothing to fold. The three options, measured on the 24,000 titles added last quarter: fall back to the item-item kNN model, which produces a usable neighbourhood from 30 interactions and gets new titles to first impression in a median of 6 days; initialise the factor row from a content embedding of the blurb and genre, which gets it to 3 days and costs 0.004 NDCG@10 overall because the content prior is wrong for about a fifth of titles; or an explicit exploration budget, 2% of shelf slots reserved for under-exposed titles, which costs 0.006 NDCG@10 and is the only one of the three that also fixes the popularity feedback loop.

The traps this method has, isolated

Four panels isolating matrix factorization recommender traps with measured numbers: popularity bias where the log sends 31.4 percent of interactions to the top 1 percent of titles while implicit ALS fills 58.2 percent of shelf slots from them at 2.8 percent catalog coverage and inverse-propensity reranking at power 0.5 costs 0.047 NDCG at 10 to reach 19.2 percent and 11.4 percent coverage; the cold-start cliff where NDCG at 10 runs 0.084, 0.139, 0.198, 0.259 and 0.295 across history buckets of 1 to 2, 3 to 5, 6 to 15, 16 to 50 and 51 plus interactions against an aggregate of 0.188, with a 3-core filter reporting 0.221 instead; offline-online divergence over 11 candidates at Spearman 0.29 where four of seven offline-accepted changes failed and the inverse-propensity rerank that loses 0.047 offline gains 1.9 percent start rate online; and the sampled-negative distortion where the full-catalog gap of plus 0.009 between ALS and BPR becomes minus 0.007 against 100 sampled negatives and flips back on 3 of 10 sampling seeds

Three traps are properties of the deployed system and one is purely an evaluation bug. All four have numbers.

Popularity bias, and the fact that the model amplifies it rather than inheriting it. The log sends 31.4% of its interactions to the top 1% of titles, 1,420 of 142,000. Implicit ALS fills 58.2% of shelf slots from that same set, an amplification of 1.85, and covers 2.8% of the catalog. BPR amplifies 2.10 and covers 6.4%. The mechanism is additive from both sides of the objective: a head title appears in more listeners’ histories, so its factor row gets more gradient, and it carries more total confidence mass, so the weighted loss cares about it more. Then the shelf produces tomorrow’s log and the loop closes. The post-hoc fix is an inverse-propensity rerank, dividing the score by a power of the play count, and it is a priced trade rather than a free improvement:

IPS power NDCG@10 Head slot share Coverage@10
0.0 (none) 0.188 58.2% 2.8%
0.25 0.174 34.6% 7.9%
0.5 0.141 19.2% 11.4%
0.75 0.088 8.1% 10.2%
1.0 0.052 3.4% 7.6%

The curve turns over, which is informative: past power 0.5 the rerank starts promoting titles the model has no evidence about, so coverage falls as well as accuracy. One implementation detail is not optional. The rerank must be applied inside a candidate set, the model’s own top 200, not across the whole catalog. Applied catalog-wide, the largest discount goes to the titles with the fewest interactions, which are exactly the ones with untrained factor rows, and the result is a ranking of noise that reports a head slot share of exactly 0.0% and looks like a triumph. The companion codebase measures that mistake at 0.0095 NDCG@10 against the restricted version’s 0.0943.

The cold-start cliff, which is not only about row counts. NDCG@10 by number of training interactions, on the same model and the same evaluation:

Training interactions Share of evaluated listeners NDCG@10
1 to 2 24% 0.084
3 to 5 14% 0.139
6 to 15 26% 0.198
16 to 50 26% 0.259
51 or more 10% 0.295
Aggregate 100% 0.188

A factor of 3.5 from the first bucket to the last, and 38% of listeners in the first two. Under leave-one-out every listener contributes exactly one test row, so the aggregate is a flat average over listeners, which sounds fair and is precisely why the cliff is invisible in it: 0.188 is the midpoint of a distribution with a structurally different cohort at one end. The mechanism is not only scarcity. A new listener is served the default shelf, which is the bestseller shelf, so their few rows are popularity draws rather than taste draws and carry less information each as well as being fewer. In the companion codebase the mean popularity percentile of a row is 0.048 for short histories against 0.112 for long ones, measured on the same archive.

Offline-online divergence, measured against eleven real candidates. Each of the eleven was scored offline and then run as an A/B test on the home shelf, with started-listen rate as the business metric. The Spearman correlation between offline NDCG@10 delta and online start-rate delta is 0.29, and four of the seven changes the offline gate accepted did not reproduce online.

Change Offline NDCG@10 Online start rate
Implicit ALS over popularity +0.094 +2.4%
BPR instead of ALS -0.009 +0.8%
IPS rerank, power 0.5 -0.047 +1.9%
256 factors instead of 128 +0.002 -0.3%
Trained on the 3-core subset +0.033 -0.1%
Model selected by sampled-negative NDCG +0.000 -1.1%
Popularity-proportional BPR negatives +0.004 -0.6%

The first row is the headline and it is also a warning: doubling offline NDCG@10 bought +2.4% relative on the business metric, where a linear reading of the offline lift suggested +11%. Rows two and three are the dangerous ones. Both lose offline and win online, and they lose offline for the same reason: the logged metric can only credit a model for items the old exposure process actually showed, so any change that surfaces titles the previous shelf never surfaced is scored as a regression.

Sampled negatives, which is a pure metric bug and the easiest to commit. Ranking the held-out title against 100 random negatives instead of all 141,999 is 1,420x cheaper and it is not a consistent estimator of the full-catalog metric. Krichene and Rendle established this in 2020 and the demonstration on this archive is sharp:

Model Full catalog NDCG@10 Against 100 sampled negatives
Implicit ALS 0.188 0.491
BPR-MF 0.179 0.498
Gap, ALS minus BPR +0.009 -0.007

The winner flips, and across ten negative-sampling seeds it flips back on three of them, so the ordering is a coin. The inflation of +0.30 is harmless on its own; the compression of the gap from 0.009 to 0.002 in magnitude is not, because a model-selection process reads only the order. The mechanism is that 100 uniform draws from a 142,000-title catalog are all tail, so the sampled metric asks “can you beat the typical title” where production asks “can you beat the best title”, and the best titles are head titles. Those are different quantities, not a noisy estimate of one.

Key Insight

The design decision that mattered most was not choosing ALS over BPR, which is worth 0.009 NDCG@10 and is arguably the wrong way round for a two-stage system. It was adding the `Y'Y` term, and the reason it mattered is that nothing about the failure it fixes is visible from inside the model. The observed-only model converges cleanly, its training loss falls monotonically, its factor matrices have sensible norms, its predictions on held-out observed cells are good, and it scores 0.041 NDCG@10 against a `value_counts()` call's 0.094. Every diagnostic a practitioner habitually reaches for says the model is fine, because every one of them is computed on the 0.036% of the matrix the objective was told about. The general form of this is worth carrying to other problems: when a model is trained on positives only, the thing that goes wrong is not estimation and it is not optimisation, it is that the quantity being estimated is not the quantity you need, and no amount of regularisation, capacity or tuning substitutes for a missing term in the loss. The correction is one matrix, worth 0.147 NDCG@10, and you find it by writing down what the objective sums over rather than by looking at the loss curve.

Evaluation and Metrics

NDCG@10 is the optimisation metric and recall@200 is the ceiling metric, and the pair has to be reported together because they answer different questions about a two-stage system. With one relevant item per listener, NDCG@10 has a simple closed form: the ideal DCG is 1, so NDCG is 1 / log2(rank + 2) when the held-out title lands inside the top ten and 0 otherwise.

# The metric block. Masking and tie breaking are the two places this goes
# quietly wrong, and both are one line.
import numpy as np
from scipy import sparse

def mask_seen(scores: np.ndarray, train: sparse.csr_matrix,
              users: np.ndarray) -> np.ndarray:
    """Set already-played cells to -inf. Never skip this: without it every
    model's top slot is an audiobook the listener already finished, and the
    metric is measuring memorisation of the training set."""
    out = np.array(scores, dtype=float, copy=True)
    rows = train[users].tocoo()
    out[rows.row, rows.col] = -np.inf
    return out

def rank_of_target(scores: np.ndarray, targets: np.ndarray) -> np.ndarray:
    """0-based rank of the held-out title, with PESSIMISTIC tie breaking.

    Count strictly-greater scores, then add the equal ones. Optimistic ties are
    a real inflation: a popularity model gives every zero-play title an
    identical score, and with optimistic ties all 94,000 of them rank first.
    An untrained factor row is exactly zero, so this is not hypothetical.
    """
    n = scores.shape[0]
    tgt = scores[np.arange(n), targets]
    greater = (scores > tgt[:, None]).sum(axis=1)
    equal = (scores == tgt[:, None]).sum(axis=1) - 1
    return greater + equal

def ndcg_at_k(ranks: np.ndarray, k: int = 10) -> float:
    """One relevant item per listener, so IDCG = 1."""
    return float(np.where(ranks < k, 1.0 / np.log2(ranks + 2.0), 0.0).mean())

def map_at_k(ranks: np.ndarray, k: int = 10) -> float:
    """Reduces to mean 1/(rank+1). Reported next to NDCG because the 1/(r+1)
    discount is much harsher than 1/log2(r+2): MAP rewards slots one through
    three and NDCG is nearly as happy with slot eight. For a shelf showing five
    titles above the fold, MAP is closer to the product."""
    return float(np.where(ranks < k, 1.0 / (ranks + 1.0), 0.0).mean())

def recall_at_k(ranks: np.ndarray, k: int = 200) -> float:
    """The retrieval ceiling. Nothing a reranker does can recover a title the
    candidate generator left out of the top k."""
    return float((ranks < k).mean())

def coverage_at_k(masked: np.ndarray, k: int = 10) -> float:
    """Share of the catalog appearing in at least one listener's top k. The
    guardrail no accuracy metric can see."""
    part = np.argpartition(-masked, k - 1, axis=1)[:, :k]
    return float(np.unique(part).size / masked.shape[1])
Key Insight

Report NDCG@10 and recall@200 as a pair, because they are metrics about different components of the same system and one of them is a hard ceiling rather than a score. recall@200 is the share of held-out titles the candidate generator puts anywhere in its top 200, and nothing a reranker does downstream can recover a title the generator left out. At 0.571 that is the maximum hit rate the whole system can ever achieve no matter how good the reranker is, so a project that spends a quarter on reranking while recall@200 sits at 0.571 is optimising inside a 43% loss it has not measured. The two metrics also disagree about which model to use, which is the useful part: implicit ALS leads NDCG@10 0.188 to 0.179 and BPR leads recall@200 0.604 to 0.571. If the shelf is the final output, take ALS. If a reranker exists, take the higher ceiling and let the reranker fix the ordering, since fixing the ordering is precisely what it is for. Reporting only the top-k metric makes that choice invisible and usually makes it wrong.

Baseline against solution, temporal leave-one-out, full 142,000-title catalog, played titles masked, pessimistic ties:

Configuration NDCG@10 MAP@10 recall@50 recall@200 Coverage@10 Head slot share Fit time Artifact
Random ranking 0.00003 0.00002 0.0004 0.0014 100% 1.0% 0 s 0 B
Popularity 0.094 0.061 0.238 0.412 0.9% 86.1% 20 s 568 KB
Item-item cosine kNN 0.131 0.088 0.301 0.487 4.6% 44.0% 9 min 114 MB
Explicit biased MF, RMSE-tuned 0.038 0.024 0.098 0.161 0.3% 11.2% 6 min 1.03 GB
Observed-only squared loss MF 0.041 0.028 0.112 0.188 7.3% 23.8% 34 min 1.03 GB
BPR-MF, 128 factors 0.179 0.112 0.371 0.604 6.4% 66.1% 26 min 1.03 GB
Implicit ALS, 128 factors 0.188 0.121 0.402 0.571 2.8% 58.2% 41 min 1.03 GB
Implicit ALS + IPS rerank, p 0.5 0.141 0.090 0.344 0.558 11.4% 19.2% 41 min 1.03 GB
ALS and BPR score blend, 0.6 / 0.4 0.194 0.124 0.408 0.612 4.1% 61.3% 1 h 07 min 2.06 GB

Five readings, and only the first two are about accuracy.

Implicit ALS doubles the popularity baseline, 0.188 against 0.094, which is the margin that justifies the system. Both of the two “obvious” factorizations lose to it: the explicit model at 0.038 and the observed-only implicit model at 0.041, both under popularity. The blend is 0.006 ahead of ALS alone and doubles the artifact and the fit time, which is the kind of trade that wins leaderboards and loses operations reviews. ALS and BPR split the metrics cleanly, ALS at the top of the list and BPR at depth and on coverage, which means the right answer depends on whether a reranker exists downstream. And the coverage column moves by a factor of 12.7 across rows whose NDCG@10 differs by 0.05, which is the number no accuracy metric can see and the one that decides whether the catalog is still worth having in two years.

Metric That Matters

The monitor that catches silent degradation here is not NDCG@10 on the nightly fold. It is the **share of served shelf slots whose item factor row was fitted on fewer than 20 interactions**, and it has fired twice. A catalog ingest change renumbered 11,000 title identifiers, so their factor rows were effectively random vectors inherited from unrelated titles. Absolute NDCG@10 moved 0.004, which is inside the night-to-night noise band of 0.006 and invisible. The under-20-interaction slot share went from 1.8% to 14.3% in one retrain, because random factor rows have no reason to be small and a random vector in 128 dimensions beats a well-fitted one for some listener. The second firing was the feedback loop closing: a home-shelf exposure experiment doubled impressions on the head for two weeks, the log's own head share went from 31.4% to 46.1%, and the next retrain's amplification went from 1.85 to 2.31. Again NDCG@10 did not move, because the leak was present in both the training and the test halves of the newest fold, which is the same pathology as a leaky feature that helps both sides. The full monitoring triple is that slot share, the head slot share computed on serving logs rather than offline scores, and the NDCG@10 of the deployed model minus a popularity reference recomputed on the same nightly fold. The third one exists because absolute NDCG@10 on this data swings 0.021 between a January fold and a December fold, so any threshold on the absolute value either fires every holiday season or never fires at all, while the paired delta against a cheap reference holds at 0.094 plus or minus 0.008 across the year.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Squared loss over observed entries only It is the Netflix Prize formulation, and the data looks like a sparse matrix with numbers in it The model loses to a popularity ranking; here 0.041 against 0.094 Add the all-pairs term. p = 0 and c = 1 on untouched cells, made tractable by the Y'Y identity. Worth 0.147 NDCG@10
The graded signal used as the target Completion fraction looks like a rating, so it goes into p Scores correlate with listen duration rather than with next-play probability p is binary, c = 1 + alpha * r. The magnitude weights the residual and is never regressed
Random interaction split It is the default in every tutorial and the rows look exchangeable Share of test rows whose listener has a later training row; 0.76 here against 0.00 Leave-one-out by time per listener. Keep train and test sizes identical between schemes so the leak is the only difference
Sampled-negative evaluation It is 1,420x cheaper and every pre-2020 paper does it The model ordering changes with the sampling seed; here on 3 of 10 Score against the full catalog. If you cannot, report the seed-stability of the ordering alongside the metric
Not masking the training history predict_proba does not know what the listener already played Top slots are titles with the highest confidence weights, which are finished ones Set seen cells to -inf before ranking. Worth about 0.4 NDCG@10 of fiction
k-core filtering before the split Everybody does it, nobody reports the threshold Reported metric jumps when the threshold changes; +0.033 here from a 3-core Keep the cold cohort in the evaluation and report the cohort table. Filter for training if you must, never for reporting
RMSE as the selection metric It is the metric the classic papers optimise and it has a closed-form gradient Spearman between RMSE and NDCG@10 is positive; +0.31 over 24 configs here Select on a ranking metric. If a displayed predicted rating is a product requirement, fit a separate model for it
Optimistic tie breaking argsort is ascending and stable, so ties resolve by index A model with many identical scores reports an implausibly good rank Count strictly-greater plus equal. A popularity model ties 94,000 zero-play titles and an untrained factor row is exactly zero
Popularity-proportional BPR negatives It converges 40% faster and the loss looks better Head slot share rises; 66.1% to 74.8% here, for +0.004 NDCG@10 Treat the sampler as a bias knob, not a speed knob. Measure head share and coverage whenever you change it
Zero-history listeners scored by the model fold_in returns the zero vector without complaint A cohort of listeners whose shelves are all identical Route listeners with no interactions to a popularity or content fallback explicitly. The zero vector is a valid solve and a meaningless ranking
New titles never surfacing A factor row fitted on zero interactions cannot be ranked Median days from ingest to first impression; 6 days here kNN fallback, content-initialised factors, or a reserved exploration budget. The last one also breaks the popularity loop
Common Pitfall

The single most common mistake on this exact problem is evaluating against sampled negatives, and it is more common than the others because it is not obviously a mistake. Every recommender paper published between roughly 2016 and 2020 ranks the held-out item against 100 random negatives, the practice is inherited wholesale by every tutorial that cites them, and the justification is sound on its face: scoring 1.87 million listeners against 142,000 titles is 265 billion dot products and scoring them against 100 is 187 million. What makes it decisive rather than merely approximate is that the estimator is not consistent, which Krichene and Rendle demonstrated in 2020, and that the direction of its error depends on the model. A hundred uniform draws from a long-tailed catalog are all tail, so the sampled metric measures how well a model separates a positive from an obscure title, and production measures how well it separates a positive from a good title. A model with uniform negative sampling in its own training objective, which is to say BPR exactly as published, is optimised for the first question and evaluated on the first question, and looks better than it is. Measured here, the full-catalog gap of +0.009 in ALS's favour becomes -0.007 in BPR's favour under sampling, and across ten sampling seeds the winner changes on three. The fix is to score the full catalog, which at this scale is a 20-minute batch job on 32 cores and is affordable precisely once per candidate rather than once per training step. When that is genuinely impossible, the minimum honest practice is to report the seed-stability of the model ordering next to the metric, because a metric whose argmax depends on a random seed is not a cheaper version of the right metric, it is a different metric that happens to be correlated, and the correlation is weakest exactly where two models are close enough that you needed a comparison in the first place.

Scaling and Productionizing

The structural fact about serving this model is that the expensive object and the useful object are different sizes by a factor of 13.

Interaction log, 96.4M rows x (int32, int32, float32, float32)   = 1.54 GB
CSR preference matrix, 96.4M nnz                                  = 772 MB
CSR confidence matrix, 96.4M nnz                                  = 772 MB
Item factors, 142,000 x 128 x float32                             = 72.7 MB
User factors, 1,870,000 x 128 x float32                           = 957 MB
ALS fit, 15 iterations, 32 cores                                  = 41 min
BPR fit, 40 epochs, 32 cores                                      = 26 min
Full-catalog evaluation, 1.87M x 142k in 4,096-row blocks         = 19 min
HNSW index build over 142,000 item vectors, M=32, efC=200         = 48 s
HNSW top-500 query, ef=256                                        = 3.2 ms p99
User factor fetch from the key-value store                        = 1.9 ms p99
Full shelf call, retrieve + mask + rerank + hydrate               = 11.4 ms p99
Shelf budget                                                      = 45 ms p99
Fold-in for one new listener, 128x128 solve                       = 0.04 ms
Nightly retrain window                                            = 4 h

Item factors are pinned in memory and user factors are not. 72.7 MB of item vectors fits in the serving process on every replica, so the HNSW index is local and the query never leaves the box. 957 MB of user vectors does not, so they live in a key-value store and the shelf call fetches one 512-byte row, which is 1.9 ms of the 11.4 ms budget. This split is why a factorization model serves a 2,400 QPS shelf on CPU at all: the per-request work is one fetch and one approximate nearest-neighbour query over a static index.

The fold-in path is what makes the 90-second SLA for new listeners achievable. A nightly retrain cannot serve somebody who signed up this afternoon. One f x f solve against the frozen item factors, 0.04 ms, produces a factor vector from whatever history exists, and the result is bit-identical to what the nightly run would have produced for the same history. That identity is worth stating because it means fold-in is not an approximation to be monitored, it is the same computation applied at a different time. The cost is drift in the item factors between retrains, which on a nightly cadence is 0.003 NDCG@10 by hour 23 and would be 0.019 on a weekly cadence.

Retrain cadence is set by catalog churn, not by taste drift. Frozen for four weeks, NDCG@10 decayed 0.188, 0.186, 0.179, 0.168. Decomposing it, 81% of the decay came from new titles having no factor rows rather than from existing listeners’ tastes moving, which matches the 24,000-new-titles-per-quarter rate. Nightly is therefore the right cadence and the reason is item coverage, so if the catalog were static a weekly retrain would cost 0.002.

The monitoring signal for silent degradation is the triple from the metric callout: under-20-interaction slot share, head slot share computed on serving logs, and the paired NDCG@10 delta against a popularity reference refit on the same nightly fold. None of the three is the deployed model’s own absolute metric, and that is deliberate. Absolute NDCG@10 swings 0.021 between a January fold and a December fold, so a threshold on it either fires every holiday season or never fires. A differential against a cheap reference cancels seasonality because seasonality hits both.

Key Insight

The offline metric's job in a recommender is to kill bad candidates cheaply, not to pick the winner, and treating it as an argmax is the most expensive mistake available in this problem class. The evidence is the eleven-candidate table: Spearman 0.29 between offline NDCG@10 and online started-listen rate, with four of the seven offline-accepted changes failing to reproduce, and two of the changes that lost offline winning online. The reason is not that the offline metric is noisy. It is that the offline metric is computed on a log produced by the previous shelf, so it can only credit a model for titles the previous exposure process actually showed, which means any change whose entire value is surfacing titles the old shelf never surfaced is scored as a regression by construction. The inverse-propensity rerank is the clean case: it loses 0.047 NDCG@10 offline, which is half the model's entire advantage over popularity, and gains 1.9% started-listen rate online. An offline-argmax process rejects it without discussion. The operational conclusion is to run the gate as a band rather than a threshold: anything inside roughly 0.02 NDCG@10 of the incumbent goes to an A/B test regardless of sign, anything materially worse is killed without a test, and the offline number is never the reason something ships. That is a less satisfying workflow than a leaderboard and it is the one that matches a measured correlation of 0.29.

Real World

The lineage here is unusually traceable and worth knowing because each paper fixed a specific thing. Funk's 2006 blog post on the Netflix Prize introduced SGD-fitted biased matrix factorization, and Koren's 2008 **SVD++** extended it by adding implicit-feedback terms to an explicit model, on the observation that which movies a user rated is informative independently of how they rated them. That is the hinge of this whole post, stated inside the explicit paradigm two years before anyone abandoned it. Hu, Koren and Volinsky's **"Collaborative Filtering for Implicit Feedback Datasets"**, also 2008, abandoned it: they separated preference from confidence, summed the loss over all user-item pairs, and gave the `Y'Y` identity that makes the all-pairs sum cost `O(f^2 * nnz)` instead of `O(f^2 * m * n)`. Their reported `alpha = 40` is the value this post uses and the companion codebase does not, for density reasons. Rendle, Freudenthaler, Gantner and Schmidt-Thieme's **BPR** (2009) replaced the pointwise objective with a pairwise one whose expectation is AUC, which is the correct observation that a recommender is evaluated on an ordering and should therefore be fitted on orderings. Steck's **EASE** (2019) showed that a closed-form item-item ridge regression beats most of the neural recommenders published between 2016 and 2019, and Rendle, Krichene, Zhang and Anderson's **"Neural Collaborative Filtering vs. Matrix Factorization Revisited"** (2020) showed that a properly tuned dot product beats the learned similarity function those papers replaced it with. Krichene and Rendle's **"On Sampled Metrics for Item Recommendation"** (2020) is the one that invalidated a large fraction of the preceding literature's evaluations, and it is the source of the sampled-negative trap above. On the production side: Spotify built Discover Weekly on implicit matrix factorization, open-sourced **annoy** for the approximate nearest-neighbour step over item vectors, and published the logistic-MF variant; Ben Frederickson's **implicit** library is the de facto Python implementation of the HKV objective and is one to two orders of magnitude faster than any hand-written numpy version including the one in the companion codebase; Instacart published their two-stage grocery recommender with a matrix-factorization retrieval stage feeding a gradient-boosted reranker, which is the architecture the alternatives table below recommends. The practitioner data point worth adding is negative: the RecSys reproducibility papers by Ferrari Dacrema, Cremonesi and Jannach (2019) re-ran eighteen neural recommenders and found that eleven of them were beaten by a properly tuned item-item kNN or matrix factorization baseline, which is the strongest available argument for building the 0.188 before building anything else.

Alternative Approaches

Approach NDCG@10 recall@200 Coverage@10 Fit and serve cost Best fit
Implicit ALS, 128 factors, alpha 40 0.188 0.571 2.8% 41 min fit, 1.03 GB, 3.2 ms Implicit feedback at catalog scale, single-stage shelf, CPU-only serving
BPR-MF, 128 factors 0.179 0.604 6.4% 26 min fit, 1.03 GB, 3.2 ms The retrieval stage of a two-stage system, where depth and coverage beat top-1 precision
ALS and BPR score blend, 0.6 / 0.4 0.194 0.612 4.1% 1 h 07 min fit, 2.06 GB, 4.8 ms A leaderboard, or a case where 0.006 NDCG@10 is worth doubling the artifact and the retrain
Item-item cosine kNN, top 200 0.131 0.487 4.6% 9 min fit, 114 MB, 1.1 ms Cold items, small catalogs, and anywhere “because you listened to X” has to be literally true
EASE, closed-form item-item ridge 0.201 0.583 3.2% Infeasible here: the 142k x 142k Gram inverse is 161 GB Catalogs under about 40,000 items, where it is the strongest classical model available
Explicit biased MF on ratings 0.038 0.161 0.3% 6 min fit, 1.03 GB, 3.2 ms Only when a predicted star rating is itself the product requirement
Two-tower neural retrieval with side features 0.206 0.618 9.1% 6 h on 4 GPUs, 1.4 GB, 4.1 ms Rich side features, genuine cold-item volume, and an existing GPU training path
Popularity 0.094 0.412 0.9% 20 s fit, 568 KB, 0.1 ms The floor every model is measured against, and the zero-history fallback

What shipped is implicit ALS, and the margin over the two-tower model is negative. That is the row worth arguing about. The two-tower model is 0.018 NDCG@10 ahead and covers 3.3x more of the catalog, and it was declined for reasons that are all operational rather than statistical: it needs 6 GPU-hours per retrain against 41 CPU-minutes, it needs the side features to be available at serving time with the same freshness they had at training time, and it needs somebody on call who understands it. The honest statement is that ALS is the right first model and the two-tower is the right second model, and that the ordering matters because the ALS number is what tells you whether the problem has enough signal to be worth the second model at all.

The row that would change the decision is EASE, at 0.201 and a closed form with no hyperparameters beyond a single ridge term. It is infeasible on a 142,000-title catalog because it inverts an item-item Gram matrix, 161 GB at float64, and it is the model I would reach for first on any catalog under about 40,000 items. We would also switch to BPR without hesitation the moment a reranking stage exists, because recall@200 of 0.604 against 0.571 is a higher ceiling for the whole system and the 0.009 NDCG@10 advantage ALS has at the top of the list is exactly the part a reranker is there to fix.

Key Insight

Read the Coverage@10 column down the alternatives table before reading the NDCG@10 column, because it spans a factor of 30 where accuracy spans a factor of 5 and it is the column that decides whether the comparison is even between comparable things. Popularity at 0.9% coverage and the two-tower model at 9.1% are not two settings of a quality dial; they are two different products, one of which shows 1,278 titles to 1.87 million people and one of which shows 12,922. The reproducibility literature is the reason to insist on this: Ferrari Dacrema and colleagues re-ran eighteen neural recommenders in 2019 and found eleven were beaten by a tuned kNN or MF baseline, and a large part of why the original papers looked better is that the comparison was a single accuracy number on a sampled-negative protocol. Two models separated by 0.005 NDCG@10 and 4x on coverage have not been compared by anyone who reported only the first figure. The practical rule is that a recommender scorecard needs at least one accuracy metric, one depth metric and one catalog metric, and that the accuracy metric is the one most likely to be measuring the exposure process rather than the model.

Key Takeaways

  • The empty cells are the objective, not missing data. A squared loss over observed entries only scores NDCG@10 0.041 against a popularity ranking’s 0.094, because nothing in it ever pushes an unlistened title down. Adding the all-pairs term with p = 0 and c = 1 on untouched cells takes the same code and the same factor count to 0.188.
  • One observation produces two numbers and merging them is the standard error. p is binary preference and c = 1 + alpha * r is confidence in it. The graded signal weights the residual and is never the regression target, because 20% completion is not 0.2 of a preference.
  • alpha is measured against density, not against the method. 40 at 0.036% density and 15 at 1.56%, because what it really sets is the ratio of observed to unobserved mass in the loss. Any alpha copied from a paper without that paper’s sparsity is a guess.
  • Random interaction splits leak unequally, which makes them a ranking error. The leak is worth -0.001 to popularity and +0.041 to +0.053 to every personalised model, so the measured benefit of personalisation inflates from 0.094 to 0.148, a 57% overstatement of exactly the quantity the project exists to establish.
  • Sampled-negative evaluation is not a cheaper estimate of the right metric. The full-catalog gap of +0.009 between ALS and BPR becomes -0.007 against 100 negatives, and across ten sampling seeds the winner changes on three. The inflation is harmless; the compression of the gap is what breaks model selection.
  • RMSE and NDCG disagree, and the disagreement lives in the item bias. Spearman +0.31 across 24 configurations. The RMSE-best configuration forfeits 0.034 NDCG@10, which is 47% of the reachable total, and the whole explicit family sits under a non-personalised popularity ranking.
  • The model amplifies popularity bias rather than inheriting it. The log sends 31.4% of interactions to the top 1% of titles and ALS fills 58.2% of shelf slots from them, an amplification of 1.85 at 2.8% catalog coverage. Debiasing is a priced trade: IPS power 0.5 costs 0.047 NDCG@10 and takes coverage to 11.4%.
  • The offline metric kills candidates, it does not pick winners. Spearman 0.29 against online started-listen rate over eleven candidates, with four of seven accepted changes failing and two rejected changes winning. The rejected ones lose offline because the logged metric can only credit titles the previous shelf already showed.

The counter-intuitive lesson is that the popularity baseline is simultaneously the hardest model to beat and the worst model in the scorecard. It scores 0.094 NDCG@10, 3,100 times better than random ranking, and against an exposure-free measure of relevance it captures 0.421 of what is achievable where a uniformly random shelf captures 0.468. Both numbers are correct and they are measuring the same model on the same listeners. The gap between them is the shape of the problem: a log produced by a popularity-biased shelf makes popularity look like knowledge, and every offline metric computed on that log inherits the illusion. Doubling NDCG@10 over that baseline bought +2.4% on the business metric rather than the +11% a linear reading suggested, and the single change that most improved the unbiased measure, the inverse-propensity rerank, is the one the offline metric rejected hardest. Building the model is a week. Learning not to trust the number it produces is the rest of the project.

Frequently Asked Questions

Q: Why not just use the Netflix Prize approach, which is the canonical matrix factorization result? A: Because the Netflix Prize had ratings and a recommender usually does not. 97.9% of interactions here carry no rating, and the 2.1% that do are missing not at random: a listener who finished a title rates it 4.7x more often than one who abandoned it, so the rated subset is a sample of titles the listener already liked. The explicit biased MF model trained on that subset scores NDCG@10 0.038 against a popularity ranking’s 0.094. The conceptual bridge is Koren’s own 2008 SVD++, which added implicit-feedback terms to an explicit model precisely because which items a user rated turned out to be informative independently of how they rated them. Hu, Koren and Volinsky then took the next step in the same year and dropped the ratings entirely.

Q: Why not BPR, since the objective is pairwise and the metric is a ranking metric? A: BPR is the better choice if a reranking stage exists downstream, and this post ships ALS because one does not. The numbers split cleanly: ALS leads NDCG@10 0.188 against 0.179 and recall@50 0.402 against 0.371, while BPR leads recall@200 0.604 against 0.571 and covers 6.4% of the catalog against 2.8%. That split is what the two objectives predict. A confidence-weighted pointwise loss spends its effort where confidence is highest, which is the head, and a pairwise loss with uniform negatives spends most of its gradient separating a positive from the long tail. For a ten-slot shelf with nothing after it, take the top-of-list model. For the retrieval stage of a two-stage system, take the higher ceiling, since recall@200 bounds everything the reranker can achieve.

Q: Why is NDCG@10 the metric rather than precision@10 or hit rate, and why against the full catalog? A: With one held-out item per listener, precision@10 is hit-rate-at-10 divided by ten and carries no position information, so a model that puts the right title in slot ten scores exactly as well as one that puts it in slot one. NDCG’s 1 / log2(rank + 2) discount distinguishes those, which matters for a shelf where five titles are above the fold, and MAP@10’s harsher 1 / (rank + 1) discount is reported alongside it for the same reason. Full catalog rather than sampled negatives is the non-negotiable part: sampling 100 negatives inflates NDCG@10 by about 0.30 and compresses the gap between candidate models from 0.009 to 0.002, after which the ordering depends on the sampling seed, changing on 3 of 10 seeds here.

Q: How do you handle a listener with no interactions at all? A: Explicitly, with a fallback, because the model’s answer is a mathematically valid and operationally useless zero vector. With nnz = 0 the fold-in normal equations reduce to (Y'Y + lambda I) x = 0, whose solution is exactly zero, so every title scores zero and the ranking is decided by tie breaking. The production path routes zero-history listeners to a popularity ranking filtered by whatever signup signal exists, usually one declared genre, and switches to fold-in at the first play, 0.04 ms later. The thing to avoid is letting the zero vector through, because it produces a cohort of listeners whose shelves are byte-identical and nobody notices for a quarter.

Q: What breaks first in production? A: Item factor coverage, and it breaks silently because nothing in the model layer validates it. The failure we hit was a catalog ingest change that renumbered 11,000 title identifiers, so their factor rows were inherited from unrelated titles and were effectively random vectors. Absolute NDCG@10 moved 0.004, inside the 0.006 night-to-night noise band. What caught it was the share of served shelf slots whose item factor was fitted on fewer than 20 interactions, which went from 1.8% to 14.3% in one retrain, because a random vector in 128 dimensions has no reason to be small and will beat a well-fitted one for some listener. Watch that share as a first-class metric, and keep a popularity reference in the nightly retrain so you have a seasonality-free differential to look at.

Q: Is the IPS rerank worth shipping if it costs half the model’s advantage over popularity? A: On the measured evidence, yes, and the evidence is the reason the question is hard. Power 0.5 costs 0.047 NDCG@10 offline, which is 50% of the 0.094 margin over popularity, and takes catalog coverage from 2.8% to 11.4% while raising started-listen rate 1.9% relative in an A/B test. So the offline metric says it is the second-worst change in the candidate table and the online metric says it is the second-best. The resolution is that the offline metric is computed on a log the old shelf produced, so it cannot credit a model for surfacing titles the old shelf never surfaced. One implementation caveat decides whether any of this holds: the rerank must be restricted to the model’s own top 200 candidates. Applied catalog-wide it hands its largest discount to titles with untrained factor rows and produces a ranking of noise that reports a head slot share of exactly 0.0% and looks like a success.

Interview Questions

Q: You have a listen log with no ratings and no explicit negatives. Write down the objective you would fit and justify every term. Expected depth: Start by separating the two quantities one observation produces: p(u,i) binary preference and c(u,i) = 1 + alpha * r(u,i) confidence, and say why the graded signal cannot be the target, because a 20%-completed title is not 0.2 of a preference. Then write the sum over all user-item pairs, not the observed ones, and justify p = 0 with c = 1 on the empties as the claim that absence is weak evidence of non-preference rather than no evidence. Be ready to state what goes wrong without it: with every target positive, nothing in the loss pushes an unobserved item down, so the score on 99.96% of the matrix is unconstrained extrapolation and the model loses to a popularity ranking. Strong answers then address tractability unprompted, deriving Y'C_u Y = Y'Y + Y_u' diag(alpha r_u) Y_u and noting that Y'Y is shared across all users so a per-user solve is O(f^2 nnz_u + f^3). The best answers also name the alternative framing, BPR’s pairwise ln sigma(x.y_i - x.y_j) whose expectation is AUC, and say when each is preferable: pointwise confidence weighting for top-of-list precision, pairwise for depth.

Q: Design the train/test split for this problem, and explain what a random split would do. Expected depth: Name why grouped time folds, the correct answer for most tabular problems, do not apply: every test user needs a history to personalise from and every test item needs factors to be scored, so holding out whole users or whole windows removes the thing being evaluated. Arrive at leave-one-out by time, last interaction per user to test, second-to-last to validation, and say explicitly that the cold cohort stays in. Then characterise the random split’s two leaks separately: the user’s own future, which matters because taste drifts within a user, and the catalog composition of the prediction moment, which gives the model a popularity prior it could not have had. The point that distinguishes a strong answer is the asymmetry: the leak is worth about nothing to a non-personalised baseline and +0.04 to +0.05 to every personalised model, so it biases the comparison rather than inflating the level, and the measured benefit of personalisation overstates by more than half. Mention the diagnostic that makes it visible before any model runs, the share of test rows whose user has a later training row, and the k-core filter as a second, unreported split decision worth more than most modelling changes.

Q: A colleague reports NDCG@10 of 0.52 for their new recommender. What do you check? Expected depth: Work the evaluation before the model, because 0.52 is implausible on a large catalog and the implausible part is usually the protocol. Was it scored against sampled negatives rather than the full catalog, which typically inflates by 0.2 to 0.4 and is the single most likely explanation. Were already-consumed items masked, which is worth about 0.4 on its own. Was the split random rather than temporal per user. Was a k-core filter applied before evaluation, and at what threshold. How were ties broken, since optimistic ties plus a model that assigns identical scores to a large zero-interaction tail can produce almost any number. Then the comparison questions: what does a popularity baseline score on the identical protocol, because the absolute value is nearly meaningless and the ratio is not, and what does the reported number become under the full-catalog protocol. Strong answers close on the business link, noting that a large offline lift translates sublinearly, +0.094 NDCG@10 buying +2.4% relative start rate in one measured case, so a claimed 0.52 should come with a hypothesis about what it would do online.

Q: Your recommender has higher NDCG@10 than the incumbent and lost its A/B test. Explain how that happens and what you would do about it. Expected depth: Identify the structural cause rather than reaching for noise: the offline metric is computed on a log produced by the incumbent, so it can only credit a model for items the incumbent’s exposure process already showed. A change whose entire value is surfacing items the old shelf never surfaced is therefore scored as a regression by construction, and a change that sharpens the ranking of items the old shelf already favoured is scored generously. Quantify it if you can, with a measured offline-to-online rank correlation around 0.3 and a specific inverted pair such as a popularity-debiasing rerank that loses 0.047 offline and gains 1.9% online. Then the operational answer: run the offline gate as a band rather than an argmax, send anything within roughly 0.02 of the incumbent to a test regardless of sign, and never let the offline number be the stated reason something ships. Strong answers also name the structural fixes, inverse-propensity weighting against a logged propensity, an explicit randomised exploration slice of traffic that produces an unbiased log to evaluate on, and off-policy estimators fitted on that slice.

Q: How would you serve this at 2,400 QPS inside a 45 ms p99 budget, and what is the cold-start path? Expected depth: Decompose the artifact first, because the design follows from the sizes: item factors at 142,000 x 128 x 4 bytes are 72.7 MB and fit in every serving process, while user factors at 1.87M x 128 x 4 are 957 MB and do not. So the item side is a local approximate nearest-neighbour index, HNSW or IVF, queried in single-digit milliseconds for the top 500, and the user side is a key-value fetch of one 512-byte row. Account for masking the user’s history and for the reranking stage. Then the two cold-start paths, which are genuinely different problems: a cold user is cheap, one f x f solve against frozen item factors at 0.04 ms, and the result is identical to what a retrain would produce for the same history, so it is not an approximation; a cold item is not solvable by factorization at all, because a factor row fitted on zero interactions carries no information, which leaves an item-item kNN fallback, content-initialised factors, or a reserved exploration budget. Strong answers note that the exploration budget is the only one of the three that also breaks the popularity feedback loop, and that retrain cadence here is set by catalog churn rather than taste drift, with 81% of four-week decay attributable to new items lacking factors.

View full code for this problem