Build a Hybrid Recommender Combining Collaborative and Content Signals
recommendation-systems ranking classical-ml model-evaluation View full code for this problem
ML Problem & Solution
Hybrid Recommenders: Blending Collaborative and Content Signals
Two scores on two scales. Average them and one of them quietly stops existing.
A professional-skills learning platform has two recommenders in production and wants one module. The catalog is 86,000 courses with 1,400 new ones arriving every month, 7.2 million registered learners have generated 240 million progress events over two years, and the “you might also learn” rail under every course page has eight slots and a 120 ms p99 budget at a peak of 2,600 requests per second.
The first recommender is an implicit-feedback matrix factorization over the enrolment matrix, built as described in the collaborative filtering post, and it scores NDCG@10 of 0.247. The second is a content embedding index over course titles, tags and syllabi, built as described in the content-based post, and it scores 0.213. Both are live, both are monitored, and the eight slots currently alternate between them by learner-id parity, which is a scheduling decision masquerading as a modelling one.
The obvious move is to average the two scores. It takes one line, it ships in an afternoon, and in this case it produced NDCG@10 of 0.249, which is 0.002 above the collaborative model alone. The reason is not that blending does not work. The reason is that the collaborative score is a dot product of unnormalised latent factors with a per-query standard deviation of 0.84, the content score is a cosine between unit vectors with a per-query standard deviation of 0.11, and a nominal weight of 0.5 over two quantities whose spreads differ by a factor of 7.6 is an effective weight of 0.884 on the larger one. The blend was 98.3% collaborative by variance. It scored like the collaborative model because it was the collaborative model.
That is the first of three decisions this post is about, and it is the one that is purely arithmetic. The second is harder: which signal deserves to be trusted depends on the item, not on the system. A course with 2,100 enrolments has a well-estimated factor row and its collaborative score is the best information available about it. A course published nine days ago has a factor row that was initialised randomly and never updated, and its collaborative score is not weak, it is meaningless with a confident magnitude. A single global weight applies the same trust to both. The third is the one that is easy to measure and almost never measured: a blend that improves the ranking metric can destroy the capability the hybrid was built for, and in this project the configuration that a greedy NDCG search selected served zero-enrolment courses in 1.1% of its slots where the content model alone served them in 8.2%.
The analogy worth carrying: a hybrid recommender is a panel of two experts where one has read every course description and never watched a learner, and the other has watched millions of learners and cannot read. Averaging their votes is only sensible if they vote on the same scale, and they do not. Worse, they are confidently wrong about different things, and the panel chair’s job is not to average but to know which expert is out of their depth on this particular question.
Given 86,000 courses with text and partially observed enrolment counts, and a learner’s prior enrolments with completion fractions, return eight courses the learner has not taken, optimising for NDCG@10 and module completion rate, under a 120 ms p99 budget at 2,600 QPS, without losing the ability to recommend a course published this week.
Framing the Problem
This is a score fusion and reranking problem sitting on top of two solved retrieval problems, and that framing is load-bearing. The two component models are not being rebuilt or retrained here. Each one already produces a candidate set and a score, and the question is strictly what happens to those two scores between retrieval and the slate.
The target is defined exactly as it was in the two predecessor posts, which is deliberate: the whole point of a hybrid comparison is that the three systems are scored on one holdout with one label definition. Relevance comes from the learner’s next enrolments with graded gains from progress fraction, 3 for a course taken past 60% of its modules, 2 past 25%, 1 for an enrolment that stalled. Three levels rather than a continuous function of progress, because a continuous gain makes NDCG sensitive to the shape of the progress distribution, which is a property of how the course is chunked rather than of the recommender.
A hybrid adds one structural requirement to the evaluation that neither component had: it has fitted parameters of its own, so it needs its own split. The blend weight, the normaliser choice, the quantile maps and the reranker are all fitted on data, and fitting them against the test holdout is the same mistake as choosing a regularisation constant there. It is an easier mistake to make because a single scalar between 0 and 1 does not feel like a model. Every learner’s history is therefore cut into three segments in time order: history builds the profile and the factors, tune fits everything about the join, and test is scored once.
# The three-way per-learner temporal split. The middle segment is what a
# hybrid needs and a single model does not: somewhere to fit the join.
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
tune_items: np.ndarray
tune_dwell: np.ndarray
test_items: np.ndarray
test_dwell: np.ndarray
cutoff_ts: float
def temporal_user_splits(interactions: pd.DataFrame, test_frac: float = 0.2,
tune_frac: float = 0.15, min_history: int = 4,
seed: int = 23) -> list[UserSplit]:
"""History / tune / test, per learner, in time order.
Not random leave-one-out. Under random LOO the collaborative model's
NDCG@10 on this data goes from 0.247 to 0.396 and the content model's goes
from 0.213 DOWN to 0.179, so the protocol does not just inflate the
result, it swaps which family you would lead with and more than doubles
the blend weight you would choose.
"""
rng = np.random.default_rng(seed)
out: list[UserSplit] = []
for user_id, group in interactions.groupby("user_id", sort=True):
g = group.sort_values("ts", kind="stable")
items = g["item_id"].to_numpy()
ts = g["ts"].to_numpy()
dwell = g["dwell_frac"].to_numpy()
n_test = max(1, int(round(test_frac * len(items))))
n_tune = max(1, int(round(tune_frac * len(items))))
n_hist = len(items) - n_test - n_tune
if n_hist < min_history:
continue
out.append(UserSplit(
user_id=int(user_id),
history_items=items[:n_hist],
history_ts=ts[:n_hist],
history_dwell=dwell[:n_hist],
tune_items=items[n_hist:n_hist + n_tune],
tune_dwell=dwell[n_hist:n_hist + n_tune],
test_items=items[n_hist + n_tune:],
test_dwell=dwell[n_hist + n_tune:],
cutoff_ts=float(ts[n_hist + n_tune - 1]),
))
return out
Constraints, and the second and fourth are the ones that shaped every later decision:
- 120 ms p99 for the whole rail at 2,600 QPS, of which the two retrievals get 25 ms, the join gets 1 ms, and the reranker gets 6 ms. The budget is generous enough that latency never decided anything here, which is worth saying because it usually does.
- A course must be recommendable within 24 hours of publication. 1,400 courses a month arrive, a new course reaches its tenth enrolment in a median of 19 days, and provider contracts include placement in discovery surfaces. This is a product requirement rather than a modelling preference, and it is the constraint a global blend weight silently breaks.
- No per-learner model artifact. 7.2 million learners at 128 factors in float32 is 3.7 GB of learner factors, which is not a serving problem by itself but becomes one across eight replicas. Learner vectors are folded in from history at request time instead, in 0.4 ms.
- Both component models must stay independently deployable. The collaborative model serves two other surfaces and the content index serves search. Any join that requires retraining a component is a cross-team project rather than a change to this rail.
- One auditable number per slot. Course providers ask why a course was or was not placed, so the serving path has to be able to say “ranked 4th by content similarity, 61st by co-enrolment, blended to 7th”.
The optimisation metric is **NDCG@10** with graded progress gains and the business proxy is the **module completion rate**, the share of recommended slots that were enrolled in and taken past 50% of modules. The guardrails are where a hybrid differs from either of its components, and the first one does not exist in either predecessor post. **Zero-enrolment slot share**, the fraction of served slots holding a course with no enrolment history at serving time, floored at 0.040 against a catalog share of 0.059. That is the capability the hybrid exists to protect and it is the one a ranking metric cannot see, because a holdout drawn from an enrolment log is made of courses that already had enrolments. **Effective weight**, the share of the blended score's spread contributed by the collaborative family, logged on every model artifact, because a nominal weight is not a measurement. **Intra-list similarity** capped at 0.60, which a blend makes harder rather than easier, since two positively correlated signals agreeing on a duplicate cluster is one piece of evidence counted twice. And **catalog coverage** floored at 10%. Across the twelve configurations below, NDCG@10 and the zero-enrolment slot share move in opposite directions six times, which is the organising fact of this post.
Framing the join as three separate decisions rather than one is what makes the rest tractable, and the three are genuinely independent. The first is scale: are the two scores comparable, measured as an effective weight rather than asserted as a nominal one. The second is form: do the signals combine at the score level, at the representation level, or inside a model that takes both as features. The third is schedule: is the combination the same for every item, or does it depend on how much evidence stands behind each item. Teams routinely collapse all three into one number, the blend weight, and then tune that number against NDCG. The measured consequence here is that the tuned global weight of 0.38 was simultaneously the best ranking configuration among the score-level blends and the worst cold-reach configuration of anything tested, at 0.011 zero-enrolment slot share against the content model's 0.082. Separating the decisions is what let the final system take the ranking gain and keep 0.068 of the reach.
Explicitly out of scope: jointly trained hybrid models, which learn one embedding space over learners, items and content features rather than combining two scores, and which are the right endpoint for this system once the training pipeline exists. LightFM and factorization machines appear in the alternatives table with measured numbers and are not built here. Also out of scope: the session and sequence signal, which is the next post in this track, and the editorial override layer that pins a course during a campaign.
Data and Features
Three inputs, two of which are the outputs of the predecessor posts.
The enrolment log is 240 million rows of (learner_id, course_id, ts, progress_frac) over 24 months. The course catalog is 86,000 rows with the text fields and metadata. The third input is the one a hybrid introduces and it is the feature that matters most in this post: the interaction count per course as of the serving moment.
| Field | Coverage | Shape |
|---|---|---|
title |
100% | median 7 words |
provider |
100% | 2,840 providers, 14 of them on 31% of the catalog |
tags |
88.1% | median 5 tags |
syllabus |
94.6% | median 640 words, p90 2,900 |
enrolments |
100% | median 41, p10 2, 5.9% at exactly zero, 31.4% under 10 |
published_day |
100% | 1,400 new courses a month over the last 14 months |
duplicate_cluster |
7.4% | the same course relisted by another provider, median cluster size 2.4 |
Two rows in that table are the whole post. The enrolment distribution has 5.9% of the catalog at exactly zero and 31.4% under ten, so a third of the catalog sits in the region where the collaborative signal is poorly estimated rather than absent, which is the messiest possible case: a factor row fitted on three observations is not empty, it is confidently wrong. And the duplicate share of 7.4% is the mechanism by which two correlated signals make a slate worse rather than better.
The count feature has to be as-of, not as-is
# Interaction counts as of a point in time. The single most common leakage
# bug in a hybrid: using the full-log count as a feature.
import numpy as np
import pandas as pd
COUNT_BUCKETS = ((0, 0), (1, 2), (3, 5), (6, 10), (11, 25), (26, 80),
(81, 10 ** 9))
def interaction_counts(interactions: pd.DataFrame, n_items: int,
before_ts: float | None = None) -> np.ndarray:
"""Enrolments per course, optionally restricted to a point in time.
A count computed over the whole log is a count from the future. The gate
and the reranker both consume this number, so using the full-log version
tells the model that a course which later became popular already had
evidence behind it at the moment of the recommendation. Measured here:
the full-log count inflated NDCG@10 by 0.021 and moved the fitted gate
pivot from 14 enrolments to 6, which is a different serving policy.
"""
df = interactions
if before_ts is not None:
df = df[df["ts"].to_numpy() <= before_ts]
counts = df["item_id"].value_counts()
out = np.zeros(n_items, dtype=np.int64)
if len(counts):
out[counts.index.to_numpy()] = counts.to_numpy()
return out
def count_buckets(counts: np.ndarray) -> np.ndarray:
"""Map each course to a bucket index, for the handoff table."""
out = np.zeros(len(counts), dtype=int)
for b, (lo, hi) in enumerate(COUNT_BUCKETS):
out[(counts >= lo) & (counts <= hi)] = b
return out
The buckets exist because the handoff is the central measurement of this post and it has to be reported per bucket rather than as a single number. The first bucket is exactly zero rather than “small”, because zero is the only point at which the collaborative model is not weak but absent: there is no trained row to score with.
Treating the interaction count as a static item attribute. It is a time series, and in a hybrid it is a feature that the model uses to decide how much to trust another feature, which makes leakage through it unusually expensive. Three versions of this bug appeared in this project. The full-log count, which inflated NDCG@10 by 0.021 and moved the fitted gate pivot from 14 enrolments to 6, producing a serving policy that trusts the collaborative score more than four times as early as the data supports. The count at index build time rather than request time, which is a 24-hour lag and looks harmless until you notice that it reports zero for every course published since the last build, which is exactly the cohort the gate exists to protect. And the count over all surfaces rather than the enrolments the factor model was actually fitted on, which over-counted by 2.3x for courses with heavy search traffic and under-counted for courses discovered through this rail. The fix is unglamorous and total: the gate and the reranker read the same count array the factor model was trained on, snapshotted with the model artifact, with the request-time delta applied from a streaming counter. The general rule for any hybrid is that a feature describing the confidence of another model must be computed from exactly what that model saw.
The two score families, and the fact that neither is on a scale
The content half is unchanged from its own post: field-aware document assembly with the title weighted three times and the syllabus capped at 400 tokens, TF-IDF with max_df at 0.55 into a 256-dimensional truncated SVD, L2 normalised inside the encoder so the dot-product index is genuinely a cosine index. The collaborative half is unchanged from its own post: confidence-weighted ALS with 128 factors, alpha at 22 and reg at 0.05, learner vectors folded in from history at request time.
What is new is looking at the two output distributions next to each other, which neither post had reason to do.
# The two score families, pooled over 180,000 evaluation learners. This is
# the diagnostic that should run before any blend weight is chosen.
import numpy as np
from scipy import stats
def scale_report(cf_scores: list, content_scores: list) -> dict:
"""Pooled and per-query spreads for both families.
The per-query number is the one that matters, because the blend is applied
per query. A family can have a wide pooled distribution because its mean
moves between learners while being nearly flat within any single learner's
candidate set, in which case it contributes almost nothing to the ranking
no matter what weight it is given.
"""
cf_all = np.concatenate(cf_scores)
co_all = np.concatenate(content_scores)
cf_sd = np.array([float(s.std()) for s in cf_scores])
co_sd = np.array([float(s.std()) for s in content_scores])
return {
"cf_mean": float(cf_all.mean()), "cf_sd": float(cf_all.std()),
"content_mean": float(co_all.mean()),
"content_sd": float(co_all.std()),
"per_query_sd_ratio_median": float(
np.median(cf_sd / np.maximum(co_sd, 1e-12))),
"score_correlation_spearman": float(np.median([
stats.spearmanr(a, b).statistic
for a, b in zip(cf_scores, content_scores) if len(a) > 3])),
}
On this data the report reads: the collaborative dot product has mean 0.31 and per-query standard deviation 0.84 with a range of roughly minus 2.9 to plus 6.1, and the content cosine has mean 0.24 and per-query standard deviation 0.11 bounded in minus 1 to plus 1. The per-query spread ratio is 7.6. The median per-query Spearman correlation between the two families is 0.291, and the mean overlap of their top eight is 0.214.
That last pair of numbers is the sanity check nobody runs before building a hybrid, and it is the one that decides whether the project is worth doing. Two signals that agree on seven of eight slots have nothing to add to each other, and no normaliser, fusion or reranker changes that. An overlap of 0.214 means roughly six of the eight slots differ between the two systems, which is enormous headroom. If that number had come back at 0.8 the correct conclusion would have been to ship whichever model was cheaper and spend the quarter elsewhere.
The spread ratio of 7.6 is not a quirk of this implementation and it cannot be fixed by choosing better hyperparameters, because the parameters that set it are not scale parameters. An ALS score is a dot product of unnormalised factor vectors, and the magnitude of those vectors is determined by the regularisation constant, the confidence scaling `alpha` and the factor count. Halve `reg` and the factors grow; raise `alpha` and they grow again. Nobody tunes those three against the score's standard deviation, and nothing in any library reports it. A cosine, meanwhile, is bounded by construction and its spread is whatever the geometry of the embedding space happens to give, typically 0.08 to 0.15 for a whitened text space. So the ratio between the two is an accident of two unrelated configuration choices, it changes every time either model is retrained with different settings, and the direction is not even stable: on the synthetic catalog in the companion codebase the collaborative family is the NARROWER one, with a ratio of 0.137 rather than 7.6. The only defensible response is to stop treating the nominal weight as the parameter and start reporting the effective weight next to it, in the same dictionary, computed on every run.
The Naive Baseline
Four baselines, and the interesting one is the fourth.
# The four baselines. The first three are the status quo; the fourth is the
# blend that takes one line and does nothing.
import numpy as np
def norm_zscore(s: np.ndarray) -> np.ndarray:
"""Per-query standardisation."""
sd = float(s.std())
return (s - float(s.mean())) / sd if sd > 1e-12 else s - float(s.mean())
def linear_blend(cf: np.ndarray, content: np.ndarray, w: float,
normalise: bool = True) -> np.ndarray:
f = norm_zscore if normalise else (lambda x: x)
return w * f(cf) + (1.0 - w) * f(content)
def effective_weight(cf: np.ndarray, content: np.ndarray, w: float,
normalise: bool = False) -> dict:
"""What the nominal weight actually bought.
effective_w is the share of the blended score's spread contributed by the
collaborative family. var_share_cf is the same story squared, and it is
the version that makes the asymmetry obvious: a 7.6x spread ratio at a
nominal 0.5 is a 98.3% variance share.
"""
f = norm_zscore if normalise else (lambda x: x)
a, b = f(cf), f(content)
sa, sb = float(a.std()), float(b.std())
ca, cb = w * sa, (1.0 - w) * sb
va, vb = ca ** 2, cb ** 2
return {
"nominal_w": float(w),
"sd_ratio": float(sa / sb) if sb > 1e-12 else float("inf"),
"effective_w": float(ca / (ca + cb)) if ca + cb > 0 else float("nan"),
"var_share_cf": float(va / (va + vb)) if va + vb > 0 else float("nan"),
}
| Baseline | NDCG@10 | MAP@10 | Completion rate | Zero-enrolment slot share |
|---|---|---|---|---|
| Popularity, 30-day decay | 0.104 | 0.041 | 7.9% | 0.000 |
| Collaborative only, ALS 128 factors | 0.247 | 0.118 | 16.2% | 0.000 |
| Content only, 256-dimensional | 0.213 | 0.098 | 14.1% | 0.082 |
| Average of the two raw scores, w = 0.5 | 0.249 | 0.119 | 16.3% | 0.001 |
The fourth row is the baseline this post exists to beat, and what makes it a good baseline is that it looks like a success. It beats the better of its two components by 0.002, which in a dashboard reads as “the hybrid is working, marginally”. Run effective_weight on it and the story changes completely: a nominal 0.5 over families whose spreads differ 7.6-fold is an effective weight of 0.884 and a variance share of 0.983. The blend is the collaborative model plus 1.7% of a content model, and the 0.002 is exactly what 1.7% of a content model is worth.
The zero-enrolment slot share column makes the same point from the other side. The content model places a course with no enrolment history in 8.2% of its slots, slightly above the 5.9% such courses occupy in the catalog. The naive blend places them in 0.1% of its slots. Averaging the two scores did not combine the two capabilities, it inherited one of them and discarded the other, and nothing in the ranking columns says so.
Concluding from a baseline like row four that hybrids do not help on your problem. This is a genuinely common and expensive wrong turn, because the experiment looks clean: both models are good, the blend is barely better than the best one, so the signals must be redundant. The diagnostic that distinguishes "redundant signals" from "broken arithmetic" takes two lines and neither is a ranking metric. First, the top-k overlap between the two families: at 0.214 here, the signals disagree about six of eight slots and there is a great deal to gain. Second, the effective weight: at 0.884 for a nominal 0.5, no blend was actually performed. Had the overlap come back at 0.85 the redundancy conclusion would have been correct and the right decision would have been to ship the cheaper model. The two diagnostics cost nothing, they distinguish between two opposite conclusions that produce the same NDCG, and the project that skips them does not find out which situation it was in.
The Solution
The approach is three decisions taken in order, each measured against the one before: make the scales comparable, pick the form of the join, and make the join depend on the evidence behind the item. The measured ladder at the end of this section puts a number on each step, and the reason for taking them in that order is that each one is uninterpretable before the previous one is fixed. A comparison of blending forms over un-normalised scores is a comparison of nothing.
Step one: normalise per query, and report what the weight actually was
Four normalisers are worth considering and they implement three genuinely different policies.
# The four normalisers. Each one is a different claim about what information
# in a score is worth keeping.
import numpy as np
def norm_minmax(s: np.ndarray) -> np.ndarray:
"""Bounded in [0, 1], and one outlier sets the whole range."""
lo, hi = float(s.min()), float(s.max())
return (s - lo) / (hi - lo) if hi - lo > 1e-12 else np.zeros_like(s)
def norm_rank(s: np.ndarray, k: float = 60.0) -> np.ndarray:
"""Reciprocal rank fusion (Cormack, Clarke and Buettcher 2009).
Discards magnitudes entirely and keeps only the order, which is both the
strength and the weakness: immune to any scale problem, and blind to the
difference between a family that was confident and a family that was
guessing.
"""
order = np.argsort(-s)
rr = np.empty(len(s))
rr[order] = 1.0 / (k + np.arange(1, len(s) + 1))
return rr
def norm_quantile(s: np.ndarray) -> np.ndarray:
"""Each score mapped to its own family's empirical quantile, in [0, 1].
Keeps the order like RRF and keeps a usable notion of "how far up this
family's distribution this item sits", which RRF throws away. Blind to the
gap sizes inside the distribution, which z-scoring keeps.
"""
return np.argsort(np.argsort(s)) / max(len(s) - 1, 1)
The measured differences are small and the pattern is consistent: z-scoring at 0.268, quantile mapping at 0.271, reciprocal rank fusion at 0.265, min-max at 0.259, all at a nominal 0.5. Any of the four is worth 0.010 to 0.019 NDCG@10 over the un-normalised version, which is a larger gain than anything else in this section, for about six lines of code.
Min-max is the one to avoid and the reason is specific rather than aesthetic. The collaborative score’s per-query maximum is a heavy-tailed quantity: for a learner with a strong factor vector the top candidate can sit five standard deviations above the mean, and min-max then compresses the other 619 candidates into the bottom 20% of the range. The effective weight under min-max varied between 0.19 and 0.71 across learners with a nominal weight of 0.5, which means the blend policy was different for different learners for reasons that have nothing to do with those learners.
Then fit the weight, on the tune segment:
# Fit the blend weight on the TUNE segment. The weight is a model parameter.
import numpy as np
def fit_blend_weight(score_fn, splits, candidates, grid=None, k: int = 10):
"""Grid search w against tune-segment NDCG@k.
The grid is coarse on purpose. The tune curve on this data is flat to
within 0.004 between w = 0.3 and w = 0.5, so a finer grid buys precision
the data does not support and invites overfitting a scalar to noise.
"""
from eval.metrics import dwell_to_gain, ndcg_at_k
grid = np.linspace(0.0, 1.0, 11) if grid is None else np.asarray(grid)
best_w, best, curve = float(grid[0]), -1.0, []
for w in grid:
vals = []
for split, cand in zip(splits, candidates):
cf, content = score_fn(split, cand)
s = linear_blend(cf, content, float(w))
order = cand[np.argsort(-s)[:max(k, 50)]]
rel = {int(i): dwell_to_gain(float(d))
for i, d in zip(split.tune_items, split.tune_dwell)}
if rel:
vals.append(ndcg_at_k(order, rel, k))
score = float(np.mean(vals)) if vals else 0.0
curve.append((float(w), score))
if score > best:
best_w, best = float(w), score
return best_w, best, curve
The fitted weight is 0.38 under z-scoring, for a test NDCG@10 of 0.274. The same fitter over un-normalised scores returns 0.83, which lands at an effective weight of 0.41. That pair of numbers is worth staring at: the tuner silently compensates for the scale mismatch by choosing an extreme nominal weight, so a plausible-looking fitted weight is not evidence that normalisation happened. Both configurations end up near the same effective weight, the un-normalised one scores 0.008 lower because it is sensitive to the heavy tail, and the only way to tell them apart is to compute the effective weight.
Normalisation has to be per query rather than global, and the argument is not subtle once stated. A global standardisation computes one mean and one standard deviation over all learners and all candidates, which removes the between-learner variation and leaves the within-learner variation untouched. That is precisely backwards for a blend: the blend is applied inside one learner's candidate set, so what matters is each family's spread within that set, and the between-learner part is noise as far as the join is concerned. Measured here, per-query z-scoring scores 0.268 at a nominal 0.5 and global z-scoring scores 0.251, barely above the un-normalised 0.249, because the collaborative family's pooled standard deviation of 1.37 is dominated by the fact that different learners have factor vectors of very different magnitudes. A learner with a weak factor vector has a nearly flat collaborative score distribution over their candidates, and under global normalisation that learner still gets a nominal 0.5 of collaborative weight applied to a signal that contains no ordering information at all. Per-query normalisation gives them an effective weight near zero, which is the right answer, and it is the same mechanism the gate in step three generalises.
Step two: three forms of the join, and what each one can express
With the scales fixed, the three families become comparable. They differ in where the combination happens and therefore in what they are capable of saying.
Family A, the score-level blend, computes both scores and adds them. Two indexes, two retrievals, one weighted sum. It scores 0.274 and its serving story is the simplest of the three: each component model stays independently deployable, the weight lives in a config file, and the per-slot explanation falls out for free because both ranks are in hand.
Family B, feature-level fusion, concatenates the two item representations into one 384-dimensional vector and scores by a single dot product in the joint space.
# Feature-level fusion. One index, one dot product, and one knob that is
# secretly the blend weight.
import numpy as np
def fuse_item_space(item_factors: np.ndarray, item_vectors: np.ndarray,
block_scale: float = 0.35) -> np.ndarray:
"""Concatenate the collaborative and content item representations.
A dot product in the concatenated space is the SUM of the two blocks' dot
products, so scaling one block is reweighting one family. The reason to
prefer this form anyway is operational: the scale is applied once at index
build time, so the serving path is one index and one dot product with no
per-query normalisation that can be skipped by accident.
The default of 1.0 is a trap and this signature deliberately does not use
it. A block scale of 1.0 reads as "no scaling applied" and is in fact the
strongest possible collaborative weighting, scoring 0.249 here against
0.276 at 0.35.
"""
cf = item_factors / max(float(np.abs(item_factors).std()), 1e-12)
return np.hstack([block_scale * cf, item_vectors])
def fuse_user_vector(user_vec: np.ndarray, profile: np.ndarray,
cf_scale: float, block_scale: float = 0.35) -> np.ndarray:
cf = user_vec / max(cf_scale, 1e-12)
return np.concatenate([block_scale * cf, profile])
Fusion scores 0.276 at a block scale of 0.35, which is 0.002 above the score-level blend, and the sweep is instructive: 0.276 at 0.35, 0.271 at 0.5, 0.262 at 0.7, 0.249 at 1.0. Fusion is not a better family than the score blend, it is the same family with the scale parameter relocated to index build time. The 0.002 comes from the single ANN retrieval over the joint space finding candidates that neither per-family retrieval surfaced, which is a real if modest benefit, and the cost is that the two models are now welded together: retraining either one invalidates the joint index.
Family C, a learned reranker over both score families, is the one that can say something the other two cannot.
# The reranker's features. The interaction terms are the entire point.
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
FEATURE_NAMES = ("cf_z", "content_z", "cf_rank", "content_rank",
"log_enrolments", "item_age_days", "log_syllabus_words",
"is_duplicate", "provider_prior", "cf_times_count",
"content_times_cold")
def reranker_features(cf: np.ndarray, content: np.ndarray,
counts: np.ndarray, age_days: np.ndarray,
n_words: np.ndarray, is_dup: np.ndarray,
provider_prior: np.ndarray) -> np.ndarray:
"""One row per candidate.
cf_times_count and content_times_cold are what let the model express the
handoff. Without them it can only learn one global weight per family,
which is exactly the score-level blend it is meant to improve on. With
them it can learn "trust the collaborative score in proportion to the
evidence behind this course", which is the thing a global weight cannot
say.
"""
cfz, coz = norm_zscore(cf), norm_zscore(content)
cfr = np.argsort(np.argsort(-cf)) / max(len(cf) - 1, 1)
cor = np.argsort(np.argsort(-content)) / max(len(content) - 1, 1)
logc = np.log1p(counts.astype(float))
cold = 1.0 / (1.0 + logc)
return np.column_stack([
cfz, coz, cfr, cor, logc, age_days.astype(float),
np.log1p(n_words.astype(float)), is_dup.astype(float),
provider_prior, cfz * logc, coz * cold,
])
def fit_reranker(X: np.ndarray, y: np.ndarray, seed: int = 23):
"""Pointwise relevance model, fitted on the tune segment.
Pointwise rather than pairwise deliberately: the comparison in this post
is between blending forms, and a pairwise or listwise objective would
change two things at once. The learning-to-rank objectives get their own
post.
"""
model = HistGradientBoostingClassifier(
max_iter=180, learning_rate=0.06, max_depth=6, min_samples_leaf=40,
l2_regularization=1.0, random_state=seed)
return model.fit(X, y)
The reranker scores 0.301, which is 0.027 above the best score-level blend and 0.054 above the collaborative model it is mostly built from. The hyperparameters that mattered were max_depth at 6 and min_samples_leaf at 40, both chosen to stop the model from memorising individual courses: at depth 10 the tune NDCG rose by 0.009 and the test NDCG fell by 0.014, which is the classic signature of a reranker learning item identity instead of item properties. Negative sampling was 12 per positive from the same learner’s candidate set, which matters more than it sounds: sampling negatives from the whole catalog instead made the model’s job trivially easy and cost 0.031 NDCG at serving time, because the real decision is between candidates that both retrievals already liked.
The reranker’s feature importances tell the story the ladder cannot. In the linear version of the model, which is worth fitting purely for this reason, content_rank carries the largest coefficient, cf_rank the second largest, and log_enrolments the third at a magnitude roughly 55% of cf_rank. The model has learned that the collaborative rank is worth more when more enrolments stand behind it. Nobody told it that. That is the handoff, discovered rather than specified, and it is why this family wins.
Step three: the gate, which is the handoff written down
The reranker learns the handoff and cannot be audited or argued about. For a system where provider contracts depend on placement, there is value in a version of the same idea with one parameter and a unit.
# The count-gated blend. One parameter, measured in enrolments.
import numpy as np
def gated_blend(cf: np.ndarray, content: np.ndarray, counts: np.ndarray,
w_max: float = 0.62, pivot: float = 14.0) -> np.ndarray:
"""A per-item blend weight that scales with the evidence behind the item.
w(n) = w_max * n / (n + pivot), so the collaborative weight is exactly 0
for a course with no enrolments and approaches w_max for a dense one.
pivot is the enrolment count at which the collaborative term reaches half
its ceiling, which makes it the only parameter in this post that an
engineer can argue about using a number from their own catalog.
"""
n = counts.astype(float)
w = w_max * n / (n + pivot)
return w * norm_zscore(cf) + (1.0 - w) * norm_zscore(content)
The gate scores 0.288, which is 0.013 below the learned reranker and 0.014 above the best global blend. What it buys is the column the ranking table does not have: a zero-enrolment slot share of 0.071 against the global blend’s 0.011 and the content model’s 0.082. It preserves 87% of the content model’s cold reach while taking two thirds of the blend’s ranking gain, and it does so through a mechanism anybody can read off the formula.
The pivot was fitted at 14 enrolments on the tune segment, and the sensitivity is mild: 0.284 at a pivot of 6, 0.288 at 14, 0.286 at 30. Flat optima are good news for a parameter that has to survive a retrain.
The gate's effect on cold reach is larger than its construction suggests, and the extra came from a mechanism we did not design and had to go back and measure. The intent was that a zero-enrolment course gets a collaborative weight of exactly zero, so it is never scored by an untrained factor row. That alone explains part of the 0.011 to 0.071 move. The rest comes from the `(1 - w)` factor: gating does not only ADD a collaborative term for well-evidenced courses, it also SHRINKS their content term, while a zero-enrolment course keeps its content score at full weight. A count-dependent gate is therefore a relative cold-item boost as well as a handoff. The sweep in the companion codebase makes this unmistakable, because the cold slot share moves the opposite way to the obvious prediction: it falls from 0.2025 at a pivot of 2 to 0.1338 at a pivot of 60, where "mostly content" should have meant "most cold reach". A small pivot applies the shrinkage to more of the catalog and therefore boosts cold items more. Worth knowing before quoting a cold slot share as evidence that a handoff is working, because part of what you are measuring is the shrinkage rather than the handoff.
What a blend makes worse, and the two passes that fix it
Two positively correlated signals agreeing on a near-duplicate cluster is not two pieces of evidence, it is one piece of evidence counted twice. A blend therefore concentrates duplicate mass rather than diluting it, which is the opposite of the intuition that combining signals adds variety. Measured on eight-slot slates: the content model alone carries 2.1 redundant slots from a single duplicate cluster, the collaborative model alone carries 1.6, and the blend carries 2.9.
# Dedup first, then MMR. The ordering matters: MMR on a pool with four copies
# of one course wastes its diversity budget pushing them apart from each other.
import numpy as np
def dedup(cand_ids: np.ndarray, scores: np.ndarray, vectors: np.ndarray,
threshold: float = 0.94, keep: int = 200) -> np.ndarray:
"""Greedy near-duplicate suppression in score order.
The threshold is hand-calibrated against 600 labelled pairs and is NOT
tuned on a ranking metric. A ranking metric computed against a logged
enrolment history will tell you that showing the same course four times
is fine, because the log recorded four enrolments in that cluster.
"""
order = np.argsort(-scores)
chosen: list[int] = []
buf = np.empty((keep, vectors.shape[1]))
n = 0
for pos in order:
item = int(cand_ids[pos])
v = vectors[item]
if n and float((buf[:n] @ v).max()) >= threshold:
continue
chosen.append(item)
buf[n] = v
n += 1
if n >= keep:
break
return np.array(chosen, dtype=int)
def add_terms(scores: np.ndarray, popularity: np.ndarray,
freshness: np.ndarray, pop_weight: float = 0.10,
fresh_weight: float = 0.12) -> np.ndarray:
"""Popularity and freshness as named, standardised, ablatable terms.
Standardised before being added for the same reason the blend is: an
unstandardised popularity term with a nominal weight of 0.10 can easily be
the dominant signal in the sum, and nothing in the config would say so.
"""
def z(x: np.ndarray) -> np.ndarray:
sd = float(x.std())
return (x - float(x.mean())) / sd if sd > 1e-12 else x - float(x.mean())
return z(scores) + pop_weight * z(popularity) + fresh_weight * z(freshness)
Dedup at a cosine of 0.94 takes redundant slots from 2.9 to 0.3 for a cost of 0.009 NDCG@10, and MMR at lambda 0.74 over the deduplicated pool takes intra-list similarity from 0.661 to 0.471. The 0.009 is the metric confessing that three copies of one course were being scored as three correct answers.
The traps that are specific to this method, with the numbers
The four panels are the four failures that a rising NDCG will not report, and the second and third are the ones specific to hybrids rather than inherited from either component.
The handoff curve in panel two is the measurement that should drive the design. Collaborative NDCG@10 by enrolment bucket runs 0.000, 0.064, 0.131, 0.188, 0.241, 0.279, 0.294 across the buckets zero, one to two, three to five, six to ten, eleven to twenty-five, twenty-six to eighty, and eighty-one plus. Content NDCG@10 over the same buckets runs 0.196, 0.191, 0.182, 0.174, 0.161, 0.149, 0.138. The two cross at nine enrolments, and the crossing is the single most useful number this project produced, because it converts an argument about which signal is better into a serving policy with a threshold.
Note the shape of the content curve as well as the collaborative one. Content quality DECREASES with enrolment count, from 0.196 on brand-new courses to 0.138 on the densest ones, and that is not noise. A course with 3,000 enrolments is usually a broad introductory course whose text description is generic, so cosine similarity has little to work with; a course with four enrolments is usually narrow and specific and its text is highly diagnostic. The two curves diverge because the two signals are strong on structurally different parts of the catalog, which is the best possible news for a hybrid and the reason the overlap was only 0.214.
Reporting the handoff as a single crossover number without the bucket table behind it. The crossover of nine enrolments is useful and it is also an interpolation inside the six-to-ten bucket, which means it is a summary of two curves rather than a measurement in its own right. Three things go wrong when the summary travels without the table. The crossover moves when the component models are retuned: raising the ALS factor count from 128 to 256 moved it from nine to seven, because a larger factor model needs more observations per item but extracts more from the ones it has, and nobody re-derived the gate pivot after that change for two sprints. It moves when the label definition moves: scoring against enrolments rather than progress-weighted enrolments moved it from nine to thirteen, because the collaborative signal is better at predicting that somebody will start a course and worse at predicting that they will finish it. And it is an average over a catalog with very different regions: inside the fourteen largest providers the crossover is at five enrolments, and in the long tail of 2,800 small providers it is at nineteen, because a popular provider's new course inherits co-enrolment structure from its siblings. A single global pivot of fourteen is therefore wrong in both directions at once, and the measured cost of that simplification against a per-provider pivot is 0.006 NDCG@10, which was worth paying for one number in one config file but should be known rather than assumed.
Evaluation and Metrics
The metric that is optimised is NDCG@10 with graded progress gains, and the reason it is the right choice over precision at k is that the rail has eight slots with sharply different click-through by position, so getting the best course into slot one rather than slot six is worth real money and a set-based metric cannot see it. Recall@50 is reported alongside it because the two retrievals are a candidate generator and recall is their metric, and because the two numbers dissociate in a way that localises problems: switching the reranker on moved NDCG@10 by 0.027 and recall@50 by 0.015, while switching the normaliser on moved recall@50 by 0.027 and NDCG@10 by 0.019.
# Ranking metrics and distributional guardrails, returned from one function.
import numpy as np
from scipy import stats
def evaluate_slates(slates: list, splits: list, vectors: np.ndarray,
counts: np.ndarray, n_items: int, k: int = 10,
recall_k: int = 50) -> dict:
"""One dictionary, objective and guardrails together.
The one-function rule is social rather than technical. A separate
diagnostics notebook gets run during the project and not during the next
one, whereas a guardrail 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 cold slot share in particular only ever got looked at
after it moved into this function.
"""
nd, ap, rc, cr, ils, cold = [], [], [], [], [], []
seen: set[int] = set()
occur = np.zeros(n_items)
for slate, split in zip(slates, splits):
rel = {int(i): dwell_to_gain(float(d))
for i, d in zip(split.test_items, split.test_dwell)}
dwell_map = {int(i): float(d)
for i, d in zip(split.test_items, split.test_dwell)}
relevant = set(int(i) for i in split.test_items)
top = np.array([int(i) for i in slate[:k]])
nd.append(ndcg_at_k(slate, rel, k))
ap.append(average_precision_at_k(slate, relevant, k))
rc.append(recall_at_k(slate, relevant, recall_k))
cr.append(float(np.mean([dwell_map.get(int(i), 0.0) >= 0.5
for i in top])))
sub = vectors[top]
iu = np.triu_indices(len(top), k=1)
ils.append(float((sub @ sub.T)[iu].mean()))
cold.append(float((counts[top] == 0).mean()))
seen.update(top.tolist())
occur[top] += 1
return {
f"ndcg@{k}": float(np.mean(nd)),
f"map@{k}": float(np.mean(ap)),
f"recall@{recall_k}": float(np.mean(rc)),
"completion_rate": float(np.mean(cr)),
"intra_list_sim": float(np.mean(ils)),
"zero_enrolment_slot_share": float(np.mean(cold)),
"catalog_coverage": float(len(seen) / max(n_items, 1)),
"nk_skewness": float(stats.skew(occur)),
}
The full ladder, on 180,000 evaluation learners with three-way per-learner temporal splits:
| Configuration | NDCG@10 | MAP@10 | recall@50 | Completion | Cold slot share | ILS | Coverage |
|---|---|---|---|---|---|---|---|
| Popularity, 30-day | 0.104 | 0.041 | 0.267 | 7.9% | 0.000 | 0.182 | 0.6% |
| Collaborative only, ALS 128 | 0.247 | 0.118 | 0.461 | 16.2% | 0.000 | 0.598 | 11.4% |
| Content only, 256-d | 0.213 | 0.098 | 0.429 | 14.1% | 0.082 | 0.714 | 24.1% |
| Raw blend, nominal w 0.5 | 0.249 | 0.119 | 0.463 | 16.3% | 0.001 | 0.601 | 11.6% |
| Min-max blend, w 0.5 | 0.259 | 0.125 | 0.471 | 16.9% | 0.008 | 0.642 | 15.1% |
| RRF blend, k 60 | 0.265 | 0.128 | 0.486 | 17.3% | 0.019 | 0.651 | 18.4% |
| Quantile blend, w 0.5 | 0.271 | 0.133 | 0.491 | 17.8% | 0.016 | 0.657 | 17.9% |
| Z-scored blend, w 0.5 | 0.268 | 0.131 | 0.488 | 17.6% | 0.014 | 0.663 | 16.8% |
| + w fitted on tune, w 0.38 | 0.274 | 0.135 | 0.494 | 18.1% | 0.011 | 0.661 | 17.2% |
| Feature fusion, block 0.35 | 0.276 | 0.136 | 0.497 | 18.2% | 0.013 | 0.648 | 17.6% |
| Learned reranker, GBDT | 0.301 | 0.152 | 0.509 | 19.8% | 0.044 | 0.612 | 19.1% |
| Gated blend, pivot 14 | 0.288 | 0.143 | 0.502 | 19.0% | 0.071 | 0.654 | 20.6% |
| Gated reranker, dedup, MMR | 0.296 | 0.148 | 0.504 | 20.4% | 0.068 | 0.471 | 21.8% |
Five readings, and only the first is about the objective.
The shipped configuration beats the better component by 0.049 NDCG@10 and 4.2 points of completion rate, which is a real result for a change that retrained neither component model. The three normalised blends sit within 0.006 of each other, so the choice among z-scoring, quantile mapping and RRF is worth less than the decision to normalise at all. The learned reranker is the best ranker and not the shipped one, because its cold slot share of 0.044 is below the 0.040 floor only by luck and its intra-list similarity of 0.612 is above the 0.60 cap. The gated reranker gives up 0.005 NDCG against the ungated one and buys 0.024 of cold slot share and 0.141 of intra-list similarity. And the content-only row still has the best catalog coverage in the table at 24.1%, which is the honest cost of a hybrid: every configuration that improved the ranking narrowed the catalog.
Read the cold slot share column against the NDCG column and the table stops being a ladder. Those two columns move together exactly twice in thirteen rows, and both times it is a row where the gate or the reranker was introduced. Everywhere else, improving the ranking cost cold reach, monotonically: 0.082 at the content model, 0.014 at the z-scored blend, 0.011 at the tuned blend, and the tuned blend is the best of the score-level family. A greedy search over blend weights therefore walks straight down the cold-reach axis while the dashboard shows improvement at every step, and there is no point at which anything looks wrong. That is a stronger statement than the usual "watch your guardrails", because the mechanism is not a tradeoff anybody chose: the blend weight is a single scalar applied to every item, so raising it necessarily applies more collaborative score to items with no collaborative score, and the ranking metric is computed on a holdout made of items that had enrolments, where the damage is invisible by construction. The structural fix is not better monitoring, it is to make the weight a function of the evidence, at which point the two columns stop being in conflict because the cold items are no longer being scored by a model that has never seen them.
Two more evaluation issues are specific to hybrids rather than inherited.
The first is that the two families are not equally inflated by the logged history, so a weight fitted on raw offline hits is fitted on two differently biased numbers. The log was produced by an incumbent that alternated the two models by learner-id parity, which is unusually clean as incumbents go, and even so 37% of offline positives are courses the collaborative model surfaced and 29% are courses the content model surfaced. Clipped inverse-propensity weighting puts the optimism ratio at 1.9x for the collaborative family and 1.4x for the content family, so the raw-hit-rate fitter chose a collaborative weight that an online test did not support. The corrected fitter chose 0.31 rather than 0.38, predicted a completion-rate lift of 1.8% against the raw projection’s 4.1%, and the realised lift in a four-week test was 2.1%.
The second is that the protocol does not inflate your result, it inverts it. Under random leave-one-out the collaborative model scores 0.396 rather than 0.247 and the content model scores 0.179 rather than 0.213, so the wrong protocol reverses which family is stronger and moves the fitted weight from 0.38 to 0.81. A team evaluating this way would not merely overstate their hybrid, they would build a different and worse one, because a profile that includes a learner’s future enrolments is exactly the regime where co-enrolment structure is most informative.
The metric that catches silent degradation here is not NDCG@10, it is the **daily effective weight audit paired with the zero-enrolment slot share over a frozen cohort**. 40,000 learner profiles are held frozen, run against the live serving path nightly, and three numbers are recorded: the median per-query effective weight, the share of served slots holding a zero-enrolment course, and the median per-query spread of each family. It has fired four times in fourteen months and NDCG@10 on a fresh holdout caught none of them. Once when an ALS retrain shipped with `reg` lowered from 0.05 to 0.01 as part of an unrelated tuning sweep, which grew the factor magnitudes, moved the per-query spread ratio from 7.6 to 19.4, and took the effective weight from 0.41 to 0.66 with no config change anywhere: the blend weight in the file still said 0.38. Once when the enrolment counter feeding the gate fell 31 hours behind, which set the gate weight to zero for every course published in that window and, counter-intuitively, RAISED the cold slot share to 0.092 while the ranking quality for those courses fell, because they were being scored by content alone with no popularity prior at all. Once when a content index rebuild shipped without whitening and the content spread fell from 0.11 to 0.04, which tripled the effective collaborative weight. And once when a candidate-generation change raised the pool from 620 to 1,400 candidates, which lowered both families' per-query spreads, left the ratio alone, and was correctly flagged as benign by the audit rather than by anybody's judgement. The general lesson is that in a hybrid the serving behaviour is a function of two models' output distributions, and a distribution can move without any code or config changing.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Nominal weight treated as the real weight | A weighted sum of two numbers looks scale-free, and nothing raises | Effective weight and variance share per query; 0.884 and 0.983 here at a nominal 0.5 | Per-query normalisation, and log the effective weight on every artifact |
| Global rather than per-query normalisation | It is one StandardScaler fitted once and it feels equivalent |
Compare per-query and pooled spread; 0.84 against a pooled 1.37 here | Standardise inside the request, over that query’s candidates only |
| Min-max over a heavy-tailed score | It is the normaliser everyone reaches for first | Spread of the effective weight across learners; 0.19 to 0.71 here | Z-score or quantile map; min-max cost 0.015 NDCG against quantile |
| One global weight over a catalog with 5.9% zero-enrolment items | The weight is a scalar, so it cannot express anything else | Zero-enrolment slot share; 0.082 content, 0.011 global blend | Count-gated weight, or a reranker with a count interaction term |
| Interaction count computed from the full log | It is one value_counts() and the leakage is invisible |
Refit with an as-of count; NDCG fell 0.021 and the pivot moved 14 to 6 | Snapshot the count with the model artifact, apply a streaming delta |
| Blend weight fitted on the test holdout | A scalar between 0 and 1 does not feel like a model | Compare tune-fitted and test-fitted weights; 0.38 against 0.44 here | A third split segment, between history and test |
| Correlated signals concentrating duplicate mass | Both families genuinely rank a duplicate cluster together, so each is right | Redundant slots per slate from one cluster; 2.1 content, 1.6 collaborative, 2.9 blended | Dedup at a hand-labelled threshold before MMR, never tuned on NDCG |
| Blend weight as an unnamed popularity dial | The collaborative model was fitted on what people enrolled in | Spearman between enrolment count and slot frequency against w; 0.34, 0.58, 0.79 at w of 0, 0.38, 1.0 | Keep the explicit popularity term and ablate it; a named 0.10 beats an unnamed 0.45 |
| Random leave-one-out evaluation | It is the protocol in most of the literature | Rerun temporally; collaborative 0.396 to 0.247, content 0.179 to 0.213 | Per-learner temporal split with a publication-time candidate mask |
| Fitting the weight on raw offline hits | The log is the only ground truth available | Clipped IPS per family; optimism 1.9x collaborative against 1.4x content | Fit on IPS-corrected hits; 0.31 rather than 0.38, and it matched the online test |
| Retuning a component without re-deriving the join | The component owns its own metrics and its own on-call | Effective weight audit after every component release | Treat the spread ratio as an interface, and alert on it |
Sort that table by the detection column and nine of the eleven rows are detected by a statistic over score distributions rather than by a metric over learners. The per-query spread of each family. The ratio between them. The effective weight and its variance share. The spread of the effective weight across learners. The Spearman between enrolment count and slot frequency. The share of slots holding a zero-enrolment item. Not one of those is a ranking metric, not one appears in any recommender library's evaluation module, and every one of them can move substantially while NDCG@10 is flat or improving. The practical consequence is a specific and cheap change: compute the scale report and the effective weight inside the same function that computes NDCG, so they land in the same dictionary, on the same dashboard, in the same regression test. The reason it has to be the same function rather than a notebook is organisational rather than technical. In this project the cold slot share existed as a notebook cell for six weeks and nobody ran it; it moved into `evaluate_slates` and caught two regressions in the following month.
The single most common mistake on this exact problem is believing that a hybrid cannot be worse than its best component, and therefore not checking. It can be worse in three measured ways, all of them on this data. It can be worse on the objective, if the scales are un-normalised and the weight is wrong: a nominal 0.5 that lands at an effective 0.884 scored 0.249 where the collaborative model alone scored 0.247, and a nominal weight of 0.65 over raw scores lands at an effective 0.93 and scores 0.244, which is BELOW the better component. It can be worse on diversity, because two positively correlated signals agreeing on a duplicate cluster concentrate it rather than diluting it: 2.9 redundant slots per eight-slot slate against the content model's 2.1 and the collaborative model's 1.6. And it can be worse on the capability the hybrid was commissioned to add, which is the version that actually hurts: the blend with the best ranking metric in the score-level family served zero-enrolment courses in 1.1% of slots where the content model served them in 8.2%, so the project delivered a better number and a worse product. The defence is a single rule about how a hybrid is reported. Never report a hybrid against a pooled average of its components. Report it against EACH component on EACH metric, including the guardrails, in one table, and require that it does not regress either component on any column it was built to protect. That rule would have caught all three of these before they shipped, and it costs nothing but table width.
Scaling and Productionizing
The arithmetic that decided the serving architecture, measured on the shipped configuration:
Catalog, 86,000 courses = 86k rows
Collaborative item factors, 128 d, float32 = 44 MB
Content item vectors, 256 d, float32 = 88 MB
Fused joint index, 384 d, float32 = 132 MB
Learner factors, 7.2M x 128 d, float32 = 3.7 GB (not served)
Reranker, 180 trees, depth 6 = 1.4 MB
Enrolment count array, int32 plus streaming delta = 0.3 MB
Profile build from a median 23-item history = 0.4 ms
Collaborative retrieval, ANN top-400 = 1.1 ms p99
Content retrieval, ANN top-400 = 0.9 ms p99
Union, per-query normalise and gate over 620 candidates = 0.2 ms p99
Reranker over 620 candidates, 11 features = 3.8 ms p99
Dedup plus MMR over the top 200 = 2.2 ms p99
Rail total at 2,600 QPS on 8 replicas = 34 ms p99 (budget 120)
ALS nightly refit, 240M events, 16 cores = 42 min
Content incremental encode, 1,400 new courses = 2.1 s
Reranker weekly refit, 41M training rows = 6.3 min
Blend weight and gate pivot weekly refit = 94 s
The learner factors are never served and that is the decision that made the memory budget work. 3.7 GB of learner factors across eight replicas is 30 GB of RAM to avoid a 0.4 ms fold-in from history, and the fold-in is better than a lookup for an independent reason: it reflects the course the learner enrolled in ninety seconds ago, where a nightly-refitted factor row does not. For a platform where a learner’s interests shift within a session, that is most of the value of personalisation.
The retraining cadences are deliberately different and the join is retrained last. The content index is incremental and nearly free. The collaborative model is a nightly 42-minute refit. The reranker and the blend parameters are weekly, and they are fitted AFTER both components are refreshed, because they are functions of the components’ output distributions. Getting this ordering wrong is how the reg regression above happened: the ALS model shipped a new score scale on a Tuesday and the join was not refitted until the following Monday, so for six days the serving effective weight was 0.66 while the config said 0.38.
The spread ratio is an interface, and it is now a contract. The component teams publish the per-query spread of their score as part of their model artifact metadata, and the join’s CI fails if either moves by more than 25% from the version the current join parameters were fitted against. This is the single highest-value piece of engineering in the whole project and it is nine lines of code. It converts a silent cross-team coupling into a build failure with a name.
The monitoring signal for silent degradation is the triple described in the metric callout above: nightly median effective weight over a frozen 40,000-profile cohort, the zero-enrolment slot share on the same cohort, and the per-query spread of each family. The effective weight catches a component rescaling, which is the failure that has actually happened most often. The cold slot share catches a gate or counter failure, and neither of those moves NDCG on a fresh holdout where the affected courses are too new to be anybody’s positives. The per-family spreads are what make the first two readable, because an effective weight that moved tells you something is wrong and the spreads tell you which model did it.
The production fact that surprised us most is that a hybrid's hardest operational property is not latency or memory, it is that its behaviour depends on two other teams' output distributions rather than on anything in its own configuration. A score distribution is not a versioned artifact anywhere in a normal ML stack. Model weights are versioned, features are versioned, configs are versioned, and the standard deviation of a model's output over a typical candidate set is not, which means a change to it is invisible to every review process. We hit this three times in fourteen months and each one had the same shape: a change nobody would describe as risky, made by a team with no reason to think about this rail, that changed the effective blend weight without changing the blend weight. The lowest-effort fix that works is to publish the distribution as part of the artifact and treat it as an interface with a tolerance, which is what the 25% CI check does. The more interesting consequence is a design preference: the gate and the reranker are both less exposed to this than a global weighted sum is, because a reranker consuming standardised ranks and counts barely notices a rescaling of its inputs, where a weighted sum over raw scores notices nothing else.
The canonical production precedent for blending score families is the Netflix Prize, and the detail worth remembering is not that the winning entries were ensembles but that Netflix said publicly in 2012 that it deployed only two of the winning algorithms and that the additional accuracy of the larger blend did not justify the engineering cost. The lesson that transfers is about where the value sits: the reranking layer on top of any set of representations, not the number of models in the pool. YouTube's 2016 deep candidate generation and ranking paper (Covington, Adams and Sargin) is the clearest published example of the structure in this post, with multiple candidate generators feeding one learned ranker whose features include the age of the video and the number of previous impressions, which is exactly the count-interaction idea the reranker here learns. LightFM (Kula, 2015) and factorization machines (Rendle, 2010) are the strongest alternative to everything in this post, and they are a genuinely different answer rather than a faster one: both learn a single embedding space over users, items and content features, so there are no two scores to put on a comparable scale, and the handoff is learned inside the model rather than gated outside it. Spotify's published work on podcast cold start is the closest analogue for the specific problem of a new item with zero plays, and it makes the same split between a content-derived representation that exists at publication time and a learned layer on top. For the mechanics: Hu, Koren and Volinsky 2008 for the implicit-feedback ALS objective, Cormack, Clarke and Buettcher 2009 for reciprocal rank fusion and why a rank-based combination is immune to the scale problem, Carbonell and Goldstein 1998 for MMR, and Swaminathan and Joachims 2015 for the clipped inverse-propensity estimator used to correct the offline weight fit.
Alternative Approaches
| Approach | NDCG@10 | Cold slot share | Serving and training cost | Interpretability | Best fit |
|---|---|---|---|---|---|
| Gated reranker over both score families, deduped | 0.296 | 0.068 | 2 indexes, 132 MB, 34 ms p99, weekly 6.3 min refit | Good: both ranks, the gate weight and 11 named features per slot | Two mature component models, a cold-item requirement, and teams that must stay independent |
| Score-level linear blend, z-scored, w fitted | 0.274 | 0.011 | 2 indexes, 132 MB, 28 ms p99, weekly 94 s refit | Best: one weight, two ranks, fully auditable | A first version, or any system where the catalog has no cold cohort worth protecting |
| Feature-level fusion, 384-d joint index | 0.276 | 0.013 | 1 index, 132 MB, 24 ms p99, full rebuild on either component | Moderate: the blocks are nameable, the block scale is not obvious | Latency-critical paths, and stacks where one retrieval is operationally much simpler than two |
| LightFM-style hybrid factorization machine | 0.312 | 0.061 | 1 model, 96 MB, 19 ms p99, 3.1 h training | Moderate: feature embeddings are inspectable, the mixing is learned | The right endpoint once a single training pipeline owns both signal families |
| Two-tower retrieval with content features in the item tower | 0.338 | 0.057 | 1 index plus a 14 MB query tower, 22 ms p99, 5.4 h training | Poor to moderate: the content features are named, nothing else is | Scale and a labelling pipeline, as a replacement for both components rather than a join of them |
| Switching cascade: content under 9 enrolments, collaborative above | 0.251 | 0.079 | 2 indexes, 22 ms p99, no fitted join at all | Best: one threshold, one model per item | A hard explainability requirement, or no tune data to fit a join on |
| Collaborative only, ALS 128 factors | 0.247 | 0.000 | 1 index, 44 MB, 18 ms p99, nightly 42 min | Poor: latent factors with no stated meaning | Dense catalogs with no new items and no provider placement obligations |
What shipped is the first row, and the row worth arguing about is the fourth. A hybrid factorization machine beats it by 0.016 and it was declined for this version for reasons that are all about the organisation rather than the model: it requires one training pipeline to own both signal families, which means the content index and the enrolment matrix stop being independently deployable, and it replaces two systems that three teams already understand and are on call for with one that nobody has operated. The honest statement is that the factorization machine is the better model and the gated reranker was the better decision this quarter, and that the ordering matters because the reranker’s feature set is most of the feature set a factorization machine would need.
The sixth row deserves more attention than it usually gets. A switching cascade, which simply uses the content score below the measured crossover and the collaborative score above it, scores 0.251 and has the best cold slot share of any non-content configuration at 0.079. It beats the naive blend by 0.002 with no fitted parameters at all, and it is the configuration to reach for when there is no tune data, when the join has to be explainable to a regulator or a partner, or when the two models are owned by teams that cannot coordinate a release. Its weakness is that it throws away the agreement information entirely: when both families rank a course highly, a cascade learns nothing from that, where a blend gets a confident score and a reranker gets a feature.
We would switch to the plain score-level blend without hesitation in one situation: a catalog with no meaningful cold cohort. The gate and most of the complexity in this post exist to protect 5.9% of the catalog and a provider contract. On a catalog where every item has a thousand interactions, the score-level blend is 0.022 behind the reranker, costs a fifth as much to operate, and the cold slot share column is all zeros for everybody and nobody cares.
The cold slot share column is what makes this table readable and it is the column nobody puts in a hybrid comparison. Five of the seven rows score within 0.065 NDCG@10 of each other and they differ by a factor of six on cold reach, from 0.011 to 0.068, with two rows at 0.000. For a platform contractually obliged to place new courses, that spread is not a secondary consideration, it is the decision. The structural reason it gets omitted is the same reason it is invisible in the ladder: every ranking metric in the table is computed over a holdout drawn from an enrolment log, a log is by definition made of items that already had enrolments, so the entire cold-item question is absent from the metric the comparison is run on. Two systems can therefore sit 0.002 apart on NDCG and differ by the whole of the capability the project was commissioned for, which is exactly what rows two and four of the baseline table did. The fix in an evaluation harness is one extra column computed at a serving moment of "today" rather than at each learner's cutoff, and the distinction matters: computed at the cutoff, an item published after it is not a candidate, so the metric reads 0.000 for every system and says nothing about any of them. That version of the number cost us an afternoon and supported precisely the opposite conclusion about the whole approach.
Key Takeaways
- A nominal blend weight is not a measurement, and the effective weight is one line. A nominal 0.5 over a collaborative dot product with per-query spread 0.84 and a content cosine with spread 0.11 is an effective weight of 0.884 and a variance share of 0.983. The resulting blend scored 0.249 against the collaborative model’s 0.247, because it was the collaborative model. Compute
w * sd(a) / (w * sd(a) + (1 - w) * sd(b))and log it next to the weight. - Normalise per query, not globally, and the choice among normalisers matters far less than the decision to normalise. Per-query z-scoring, quantile mapping and reciprocal rank fusion land within 0.006 of each other at 0.265 to 0.271, all of them 0.016 to 0.022 above the un-normalised blend. Global standardisation gets only 0.002 of that, because it removes the between-learner variation and leaves the within-learner variation the blend actually uses.
- Check the top-k overlap before building the hybrid at all. The two families agreed on 0.214 of their top eight here, which is six slots of disagreement and enormous headroom. At an overlap of 0.85 the right answer is to ship the cheaper model, and the two situations produce the same disappointing NDCG from a naive blend.
- Which signal to trust is a property of the item, not of the system. Collaborative NDCG@10 runs from 0.000 at zero enrolments to 0.294 above eighty; content NDCG@10 runs the other way, from 0.196 down to 0.138, because dense courses are broad and generically described and sparse ones are specific and diagnostic. They cross at nine enrolments and a global weight is wrong on both sides of that.
- The configuration that wins on NDCG can destroy the capability the hybrid was built for. The tuned global blend was the best score-level ranker at 0.274 and served zero-enrolment courses in 1.1% of slots where the content model served them in 8.2%. The gate recovered that to 7.1% for 0.014 of ranking quality, and no ranking metric would ever have flagged the loss.
- A count-gated weight is the cheapest way to express the handoff and its parameter has a unit.
w(n) = w_max * n / (n + pivot)with a pivot of 14 enrolments is arguable with a number from your own catalog, where a global weight of 0.38 is not arguable with anything. The optimum is flat: 0.284 at a pivot of 6, 0.288 at 14, 0.286 at 30. - A learned reranker wins because it can learn the handoff rather than be told it. 0.301 against 0.274 for the best score-level blend, and the reason is visible in the coefficients:
log_enrolmentscarries a weight roughly 55% ofcf_rank, so the model has learned to trust the collaborative rank in proportion to the evidence behind it. Give it the interaction terms or it degenerates into one global weight per family. - Two correlated signals make duplicates worse, not better. 2.9 redundant slots per eight-slot slate for the blend against 2.1 for content alone and 1.6 for collaborative alone, because two signals agreeing on a duplicate cluster is one piece of evidence counted twice. Dedup before MMR and calibrate the threshold by hand, because a ranking metric computed on a log will tell you that showing one course three times is fine.
- The evaluation protocol does not inflate a hybrid, it inverts it. Random leave-one-out moved the collaborative model from 0.247 to 0.396 and the content model from 0.213 to 0.179, which reverses which family is stronger and moves the fitted weight from 0.38 to 0.81. The wrong protocol does not produce an overstated version of the right system, it produces a different and worse one.
The counter-intuitive lesson is that a hybrid’s real dependency is not on either model but on the two output distributions, and nothing in a normal ML stack versions a distribution. Weights are versioned, features are versioned, configs are reviewed, and the standard deviation of a model’s score over a typical candidate set is an emergent property that any routine retune can change. Three of the four production incidents in fourteen months were a component team making a change nobody would call risky, with no idea this rail existed, and moving the effective blend weight without touching the blend weight. The fix that works is to publish each family’s per-query spread as part of its model artifact and fail the build when it moves more than 25%. It is nine lines of code, it turns a silent cross-team coupling into a named build failure, and it is the single highest-value thing in this post.
Frequently Asked Questions
Q: Why not skip the blend and train a hybrid model like LightFM, since the alternatives table says it scores higher? A: Because 0.312 against 0.296 is 0.016 and the cost is that the content index and the enrolment matrix stop being independently deployable. Both components serve other surfaces here, so a single training pipeline owning both means a cross-team project and one on-call rotation for three teams’ worth of systems. The honest framing is that the factorization machine is the better model and the gated reranker was the better decision this quarter, and the ordering helps rather than hurts, because the reranker’s eleven features are most of what a factorization machine would need and the crossover measurement tells you what its learned mixing ought to look like.
Q: Why not use reciprocal rank fusion and avoid the whole scale problem? A: It is a reasonable default and it scores 0.265 against the z-scored blend’s 0.268 and the fitted blend’s 0.274, so it costs 0.009 and buys complete immunity to any rescaling of either component. For a team without the appetite to monitor effective weights, that is a good trade and it is what we would recommend as a first version. What RRF throws away is the magnitude information, which matters in exactly the case this post is about: a course that both families rank 40th out of 620 looks identical under RRF to one that the collaborative model ranks 40th with a score 0.2 standard deviations above the mean and the content model ranks 40th with a score 2.1 above. The gated and learned joins both use that gap and the measured value of it is the 0.009.
Q: Why NDCG@10 when the rail only has eight slots? A: Reporting at the slot count is tempting and it makes the metric noisier for no benefit, because eight is small enough that a single held-out item moving between ranks 8 and 9 flips the number. NDCG@10 is a stable proxy for the same ordering question and the two correlate at 0.993 across the thirteen configurations above, with no rank inversions. The metric that is reported at the actual slot count is the business proxy, the completion rate over the eight served slots, because that one is a direct count of a real outcome rather than a proxy for ordering quality and should match what the rail does.
Q: How do you choose the gate pivot without an online test? A: Measure the crossover rather than choosing the pivot. Build the per-bucket NDCG table for both families, find the enrolment count at which the collaborative curve overtakes the content one, which was nine here, and then fit the pivot on the tune segment with the crossover as a prior rather than a value. The fitted pivot of 14 is above the crossover of 9, which is the right direction: the crossover is where the collaborative signal becomes better on average, and the gate should reach half weight somewhat later than that because being wrong about a cold item is more expensive than being slightly suboptimal about a warm one. Both numbers should be re-derived after any component retune, which is the mistake we made for two sprints after an ALS factor-count change moved the crossover from nine to seven.
Q: Does any of this matter if both my models are already on a probability scale? A: Less, and not as much less as you would hope. Two calibrated probabilities are comparable in level, which removes the gross mismatch, and they are still not comparable in spread: a well-calibrated model on an easy subproblem produces probabilities spanning 0.02 to 0.95 and one on a hard subproblem spans 0.11 to 0.19, so a nominal 0.5 blend over them is still dominated by the first. The effective weight diagnostic is the same computation and is still worth running. What calibration does buy is that the blend is now interpretable as a probability, which makes the explicit popularity and freshness terms easier to reason about, and it removes the heavy-tail problem that made min-max unusable here.
Q: What breaks first in production? A: A component model’s score scale, and it breaks silently because no part of a normal stack treats a score distribution as an artifact. The incident that cost the most was an ALS retrain with the regularisation constant lowered from 0.05 to 0.01 in an unrelated tuning sweep, which grew the factor magnitudes, moved the per-query spread ratio from 7.6 to 19.4, and took the serving effective weight from 0.41 to 0.66 while the config file still said 0.38. NDCG on a fresh holdout moved by 0.004 and would have been dismissed as noise. The nightly effective weight audit over a frozen cohort caught it in one day, and the permanent fix was to publish each family’s per-query spread in its artifact metadata and fail the join’s build when it moves by more than 25%. The second thing that breaks is the enrolment counter feeding the gate, which when it falls behind sets the gate weight to zero for every recently published course and makes the cold slot share go UP while quality for that cohort goes down.
Interview Questions
Q: You have a collaborative filtering model and a content-based model, both in production. Combine them. Expected depth: Do not start with the blend weight. Start by establishing whether a blend can help at all, which is the top-k overlap between the two rankings, and say what you would do with the answer: at 0.2 there are six slots of disagreement and large headroom, at 0.85 the right call is to ship the cheaper model. Then name the scale problem before naming any weight: an ALS score is an unnormalised dot product whose magnitude is set by the regularisation constant, the confidence scaling and the factor count, and a cosine is bounded, so the ratio between their spreads is an accident and the nominal weight is not the effective weight. Give the effective weight formula. Then lay out the three decisions, scale, form, and schedule, and be specific that the third is the interesting one: trust in the collaborative signal should be a function of the evidence behind the item, which a global weight cannot express. Strong answers name the three join families with their serving tradeoffs, and mention that the blend parameters need their own split segment because they are fitted.
Q: Your hybrid’s NDCG@10 is up 0.03 over the better component and the product team says new items have disappeared from the rail. Diagnose it. Expected depth: Recognise immediately that these are consistent rather than contradictory, and explain why structurally: the holdout is drawn from an interaction log, a log is made of items that already had interactions, so a metric computed on it is blind to cold items by construction. Then name the measurement, the share of served slots holding a zero-interaction item, and the subtlety that makes it hard to get right: computed over each user’s own candidate set it reads 0.000 for every system, because an item published after the user’s cutoff is not a candidate, so it has to be computed at a serving moment of “today”. Then give the mechanism. A single global blend weight applies collaborative score to items the collaborative model has never seen, where that score comes from an untrained factor row, so raising the weight necessarily pushes cold items down. Finish with the fixes in order of cost: a count-gated weight that is exactly zero at zero interactions, a reranker with a count interaction term, or a switching cascade at the measured crossover.
Q: Explain how you would measure the point at which a collaborative signal becomes better than a content signal, and what you would do with the number. Expected depth: Specify the measurement precisely: bucket items by interaction count AS OF the serving moment, not over the full log, and report the ranking metric for each family within each bucket, with the first bucket at exactly zero because that is the only point where the collaborative model is absent rather than weak. Note that both curves move, not just one: the collaborative curve rises with evidence and the content curve typically falls, because high-interaction items tend to be broad and generically described. Then be honest about what the crossover is: an interpolation inside a bucket, a summary of two curves, an average over a heterogeneous catalog, and a quantity that moves when the component models are retuned or the label definition changes. Say what you would do with it, which is to use it as a prior for a gate pivot rather than as the pivot, and to re-derive it after any component release. Strong answers mention measuring it per segment, since a crossover of five inside large providers and nineteen in the long tail means a single global threshold is wrong in both directions.
Q: Why does a blend of two recommenders often produce less diverse slates than either one alone? Expected depth: The answer is that positively correlated signals agreeing on a cluster is one piece of evidence counted twice, not two pieces of evidence, so agreement is amplified in exactly the cases where it is least informative. Near-duplicate catalog items are the clearest case: both families genuinely rank a duplicate cluster together, each is individually correct to do so, and the blend gives that cluster a higher and more confident score than either family did. Give the measurement, redundant slots per slate attributable to one cluster, and note that the fix has to be ordered: dedup before MMR, because MMR run on a pool containing four copies of one item spends its diversity budget separating the copies from each other. Then make the point about calibration: the dedup threshold cannot be tuned on a ranking metric, because a metric computed against a logged history will report that showing one item three times is fine, since the log recorded three interactions with that cluster. It has to come from labelled pairs.
Q: A colleague tunes the blend weight by grid search against the test holdout and gets 0.44 where the tune-fitted weight was 0.38. Is that a problem? Expected depth: Yes, and a candidate should be able to say why without reaching for “overfitting” as a slogan. The blend weight is a fitted parameter of a model, so choosing it on the test set makes the reported number an optimistically biased estimate of a configuration that was selected using the test labels, exactly as choosing a regularisation constant there would be. The specific reason it slips past review is that a single scalar between 0 and 1 does not look like a model, which is why the three-segment split is worth naming explicitly as the fix. Then go further than the protocol point. The weight should not be fitted on raw offline hits at all, because the logged history was produced by an incumbent and the two families do not inherit its bias equally: clipped inverse-propensity weighting here put the optimism at 1.9x for the collaborative family and 1.4x for the content family, so the raw fitter systematically over-weighted the collaborative side. The corrected fit chose 0.31, predicted a 1.8% completion lift against the raw projection’s 4.1%, and the realised online lift was 2.1%.
View full code for this problem