Build a Learning-to-Rank Model for Search Results with LambdaMART
ranking recommendation-systems classical-ml feature-engineering View full code for this problem
ML Problem & Solution
Learning to Rank Search Results with LambdaMART
A gradient that is not the derivative of anything, because the metric you care about has no derivative.
Search on a business software marketplace is ranked by a scoring function with 41 terms and 41 hand-set weights, in a file that four engineers have edited over five years and that nobody is willing to change. It scores NDCG@10 of 0.428 against a 4.1 million row editorial judgement set, which is respectable, and every proposed change to it is argued rather than measured, because changing one weight moves every query and no two people agree about which queries matter.
The catalog is 1.9 million listings, 318,000 distinct queries are issued in a typical week, first-stage retrieval hands the ranker a median of 112 candidates, and the ranker has 25 ms of a 180 ms search budget. The platform also has something most search teams do not: three years of accumulated relevance judgements, 4.1 million query-document pairs graded 0 to 3 by a trained editorial team, which exists because enterprise buyers complain in writing and the complaints were routed to a judgement queue.
The obvious move is to fit a model that predicts the grade from the 41 features. That is a regression, it takes an afternoon, and it works: NDCG@10 of 0.471, a gain of 0.043 over five years of hand tuning. It is also the wrong objective, and the reason is specific rather than aesthetic. A regression on grades is penalised identically for a one-grade error at rank 1 and a one-grade error at rank 90, and spends a measurable share of its capacity getting the absolute level right for queries where the ordering was never in doubt. Ranking is not regression and it is not classification. It is the problem of ordering a set, where the only thing that matters is which document is above which other document, and where the business metric is truncated: nobody sees rank 47.
The difficulty is that the metric we want to optimise, NDCG at 10, is a function of a sort order. It is piecewise constant in the model’s scores: nudge a score slightly and nothing changes until two documents cross, at which point the metric jumps. Its gradient is zero almost everywhere and undefined on the boundaries, which means gradient descent on NDCG is not a thing that can be done. That is the problem LambdaMART solves, and it solves it by cheating in a way that turns out to be principled: it does not differentiate NDCG, it writes down a gradient that behaves as though it had.
The analogy worth carrying: a pairwise ranker is a referee who penalises every wrong call equally, whether it decided the match or happened in the ninetieth minute of a game already won. LambdaMART is the same referee with a sense of what is at stake, weighting each call by how much the result would change if it were reversed. Nothing else about the referee changes.
Given 112 candidate listings per query with 41 features each, and 4.1 million editorially graded query-document pairs, produce a scoring function that orders each candidate set, optimising for NDCG@10 and search-to-install rate, under a 25 ms p99 reranking budget, without inheriting the position bias of the ranker that produced the click log.
Framing the Problem
This is a listwise ranking problem, and the three words that matter are the problem type, the unit, and the truncation.
The unit is the query group, not the row. Every metric is computed inside one query’s candidate set and averaged over queries; every gradient is computed inside one query’s candidate set; every split of the data moves whole query groups. A learning-to-rank dataset that is handled row-wise anywhere is a bug that has not been found yet, and the two most expensive mistakes in this post are both query-group violations.
The target is the editorial grade, 0 to 3, with NDCG’s standard gain of two to the power of the grade minus one. That gain function is a modelling choice and it is aggressive: a grade-3 document is worth 7 and a grade-1 document is worth 1, so a seven-fold preference for the best result over a merely acceptable one. For a marketplace where a buyer installs one thing, that is defensible. For a research tool where the user reads five results, a linear gain is better and the difference moved NDCG@10 by 0.038 when we tested it, which is larger than most of the modelling decisions below.
The truncation is 10 because the rail shows 10 results and 94.1% of installs come from the first page. That number appears twice and the two appearances are different parameters that people routinely conflate: the k in the reported NDCG@10, and the k inside the NDCG delta that LambdaMART uses to weight its gradients. They are usually set together and they do not have to be.
# Query groups: row indices per query, in query order. The unit of everything.
import numpy as np
import pandas as pd
def query_groups(frame: pd.DataFrame) -> list[np.ndarray]:
"""Index arrays, one per query.
Written with argsort and boundary detection rather than a pandas groupby
because this runs once per configuration in every sweep and the groupby
version was 40x slower on 4.1M rows. The shape of the output is the part
that matters: every metric, every lambda and every split in this post
consumes this list and never the raw frame.
"""
qid = frame["qid"].to_numpy()
order = np.argsort(qid, kind="stable")
sorted_qid = qid[order]
bounds = np.flatnonzero(np.diff(sorted_qid)) + 1
starts = np.concatenate([[0], bounds])
ends = np.concatenate([bounds, [len(qid)]])
return [order[s:e] for s, e in zip(starts, ends)]
Constraints, and the second and fourth decided the architecture:
- 25 ms p99 for reranking 112 candidates at 4,100 queries per second peak. This rules out a cross-encoder over the candidate text and is comfortable for a tree ensemble.
- The judgement budget is 40,000 new graded pairs per quarter. Editorial judgements cost about 2.80 USD each at the quality level this team requires, so the label supply is the binding constraint on the whole project and the question of whether clicks can substitute is not academic.
- Every ranking decision must be explainable to a seller. Sellers dispute placement, and “the model said so” is not an answer that survives a contract negotiation. A tree ensemble with 41 named features supports a per-feature contribution breakdown; a neural ranker over listing text does not.
- The model cannot regress head queries. The top 1,200 queries are 31% of traffic and are individually monitored by the category teams, so a change that improves the pooled metric by regressing them is not shippable regardless of the number.
- Weekly retraining, not daily. The judgement set grows by 40,000 rows a quarter, so there is nothing for a daily retrain to learn.
The optimisation metric is **NDCG@10** with exponential gains over the editorial grade, and the business metric is the **search-to-install rate**, the share of searches that end in an install within the session. Three guardrails, and the first is the one that is specific to ranking rather than inherited. **NDCG@10 on the head-query segment** separately from the pooled number, because the top 1,200 queries are 31% of traffic and a pooled average over 318,000 queries will not notice them. **MRR with relevance at grade 2 or above**, because 22% of this traffic is navigational, a buyer looking for one specific product, and for those queries the difference between rank 1 and rank 3 is most of the user experience while NDCG@10 barely registers it. And **the NDCG@10 breakdown by candidate list length**, because a pooled average over queries with 9 candidates and queries with 118 is an average over two different problems: the short-list bucket scores 0.868 for every model tested and the long-list bucket is where the entire gap between a hand-tuned ranker and a learned one lives, 0.462 against 0.789. The metric that is reported to the business is the install rate; the metric that is optimised is NDCG@10; and the metric that decides whether a change ships is whichever guardrail it moved, which in this project was the head-query segment three times out of five.
The reason ranking needs its own objective, rather than being a regression with a sort at the end, is that the business metric is truncated and position-discounted while a regression loss is neither. Make that concrete with the arithmetic rather than the principle. NDCG's discount is one over the log of the rank plus one, so moving a grade-3 document from rank 2 to rank 1 is worth 0.181 of NDCG@10 on a typical query here, and moving it from rank 61 to rank 60 is worth 0.000 because both positions are outside the truncation. A squared-error regression charges exactly the same penalty for mispredicting that document's grade in both cases. So a pointwise model with 41 features and a finite capacity spends that capacity in proportion to how many rows it can improve, and 91% of rows in this dataset sit outside the top 10 of their query. LambdaMART's entire contribution is to re-weight the learning signal by how much each decision could change the truncated metric, which redistributes capacity towards the 9% of rows anybody sees. That is also why it is not free: capacity moved to the top is capacity taken from the tail, and when the top of the list is statistically the same problem as the tail, the trade is a loss.
Out of scope: first-stage retrieval, which is the candidate generation problem and is covered by the hybrid search posts; cross-encoder reranking over listing text, which does not fit the latency budget and appears in the alternatives table; and online learning to rank with interleaving, which is how the final decision was actually made and is an experimentation topic rather than a modelling one.
Data and Features
Two tables and one thing that is not a table.
The judgement set is 4.1 million rows of (qid, query_text, doc_id, grade) over three years, covering 318,000 distinct queries. The impression log is 2.1 billion rows of (qid, doc_id, shown_rank, clicked), which is six orders of magnitude cheaper per row and is the reason the label question in the next section exists. The thing that is not a table is the 41-feature extraction, which runs at query time in the serving path and has to be reproduced exactly at training time or nothing else in this post means anything.
| Feature block | Count | Shape |
|---|---|---|
| Text match (BM25 on title, description, tags, seller name) | 11 | query-dependent, scale 0 to roughly 40 |
| Semantic similarity (bi-encoder cosine, title and description) | 4 | query-dependent, bounded in 0 to 1 |
| Query-document structural (exact phrase, category match, token coverage) | 7 | query-dependent, mostly binary |
| Listing quality (rating, review count, support response time, completeness) | 9 | document-intrinsic, mixed scales |
| Freshness and lifecycle (days since listing, days since last update) | 3 | document-intrinsic, 1 to 4,000 days |
| Popularity (installs, trailing 28-day installs, category rank) | 5 | document-intrinsic, heavy tailed |
| The incumbent ranker’s own score and rank | 2 | query-dependent, and a liability |
Two things about that table drive the rest of this section. The blocks are on wildly different scales, which is the normalisation question. And the split between query-dependent and document-intrinsic is not cosmetic: it decides which features may be normalised per query and which must not be.
Per-query normalisation, and the half of the advice that is usually missing
The standard advice is to normalise features within the query group, and the reason it is given is sound. A BM25 score of 14 is excellent for a two-word query and mediocre for a seven-word one, so the absolute value carries a per-query offset that is pure nuisance. On this data the per-query offset in the body BM25 column has a standard deviation of 3.1 and carries no relevance information at all, by construction of how BM25 works.
The half that is usually missing is that this is wrong for a document’s age in days.
# Per-query normalisation applied ONLY to the query-dependent block.
import numpy as np
import pandas as pd
QUERY_DEPENDENT = ("bm25_title", "bm25_body", "cosine_semantic",
"query_doc_exact", "incumbent_rank_norm",
"click_count_log", "ctr_historic")
DOC_INTRINSIC = ("doc_age_days", "doc_length_log", "host_authority")
def feature_matrix(frame: pd.DataFrame, names: list[str],
mode: str = "mixed") -> np.ndarray:
"""mixed: per-query z-scores for query-dependent columns, global for the rest.
Normalising everything per query costs 0.013 NDCG@10 here, and the
mechanism is worth more than the number: a per-query z-score of
doc_age_days replaces "this listing is nine days old" with "this listing
is younger than average among these candidates", and the absolute version
is what the relevance function actually uses.
"""
X = frame[names].to_numpy(dtype=float)
if mode == "none":
return X
pq = np.array([j for j, n in enumerate(names)
if n in QUERY_DEPENDENT or mode == "per_query"], dtype=int)
gl = np.array([j for j in range(len(names))
if j not in set(pq.tolist())], dtype=int)
out = np.empty_like(X)
for g in query_groups(frame):
block = X[np.ix_(g, pq)]
sd = np.maximum(block.std(axis=0), 1e-9)
out[np.ix_(g, pq)] = (block - block.mean(axis=0)) / sd
if len(gl):
gb = X[:, gl]
out[:, gl] = (gb - gb.mean(axis=0)) / np.maximum(gb.std(axis=0), 1e-9)
return out
There is a second surprise in this measurement and it points the other way. Global feature standardisation does nothing at all for a tree-based ranker, and the none and global configurations score within 0.002 of each other. A decision tree splits on thresholds, so any monotone per-column transform is a no-op by construction. The advice to standardise features before training is inherited from linear and neural rankers, where it is correct and necessary, and it gets repeated in tree-based pipelines where it is theatre. Per-query normalisation is different in kind, because it uses the other rows in the same query and is therefore a per-row transform, which a tree does notice.
Importing the incumbent ranker's own score or rank as a feature. It is an excellent feature by every importance measure, it is free, and it is the single most expensive line in the feature extractor. Three measured consequences. It takes the model's top-10 overlap with the incumbent from 0.44 to 0.71, which means the new model mostly reproduces the old one and therefore cannot deliver most of the improvement the project was funded for. It earns the sixth of eight impurity importances in an ablation, so the model splits on it constantly while a leave-one-feature-out sweep shows that removing it IMPROVES held-out NDCG@10 by 0.005: the model is spending capacity learning to agree with a ranker that is being replaced because it is wrong. And it quietly imports the incumbent's position bias into the model's behaviour on click-derived labels, because the incumbent's rank is exactly the variable that determined what got clicked. The honest framing is that it is a strong feature for predicting the log and a bad feature for ranking. Leave it out, and measure the overlap with the incumbent as a diagnostic rather than feeding it in as a feature: a learned ranker whose top-10 agrees with the incumbent on 7 of 10 slots has not replaced anything.
The label problem, which is the real constraint
Editorial judgements cost about 2.80 USD each and the budget is 40,000 a quarter. Clicks are free and there are 2.1 billion of them. The question of whether clicks can stand in for grades is therefore the most consequential question in the project, and it has a measurable answer.
# Three label modes. The weight is returned SEPARATELY from the label, and
# that separation is the whole content of this function.
import numpy as np
import pandas as pd
def click_labels(frame: pd.DataFrame, mode: str = "graded",
clip: float = 20.0) -> tuple:
"""Return (label, per_document_weight).
graded the editorial grade, 0 to 3. The ceiling, and expensive.
click 1 if clicked. Free, and biased by position.
ips the click label with an inverse-propensity WEIGHT, following
Joachims, Swaminathan and Schnabel 2017.
An earlier version returned `clicked / propensity` as the LABEL, which
scored 0.4335 NDCG@10 against the raw click label's 0.6263. A relevance
grade enters both NDCG and the lambda computation through a gain of
`2 ** grade - 1`, so a propensity weight of 18 became a gain of 262,143
and one deep click outweighed its whole query by five orders of
magnitude. An inverse-propensity weight belongs on the example, never on
the grade.
"""
if mode == "graded":
y = frame["grade"].to_numpy(dtype=float)
return y, np.ones(len(y))
clicked = (frame["clicks"].to_numpy() > 0).astype(float)
if mode == "click":
return clicked, np.ones(len(clicked))
if mode == "ips":
prop = np.maximum(frame["propensity"].to_numpy(), 1e-3)
w = np.minimum(1.0 / prop, clip)
return clicked, w / w.mean()
raise ValueError(f"unknown label mode: {mode}")
The reason clicks are not grades is position bias, and the way to measure it is to hold the grade fixed and vary the position. Among documents the editors graded exactly 1, the click rate in the incumbent’s top three positions is 0.2308 and below rank 21 it is 0.0097, a ratio of 23.9 to 1 between equally relevant documents. A zero click is therefore not evidence of irrelevance, it is mostly evidence that nobody looked.
Trained on raw clicks and scored against editorial grades, the model reaches NDCG@10 of 0.471 against the grade-trained 0.531. That 0.060 gap is the price of free labels, and it is smaller than the cost of 4.1 million judgements, which is the honest reason most search teams run on clicks.
The inverse-propensity correction is the textbook fix for position-biased clicks and it is worth almost nothing here, for a reason that generalises and that nobody mentions. The correction reweights each observation by one over the probability that the document was examined, which on an examination model is a function of the rank at which it was shown. But the rank at which it was shown is also a FEATURE, because the incumbent's rank is in the feature set, so a tree ensemble can already represent "documents shown low were clicked less" and the weighting adds variance without adding information. Measured: with the incumbent rank as a feature, the IPS label scores 0.6005 against the raw click label's 0.6263, so the correction makes things worse. Remove that feature and the two converge, 0.6167 against 0.6204, with IPS ahead on NDCG@2 and MRR. The general condition is therefore that an inverse-propensity correction is worth its variance only when the propensity carries information the features do not, and if the logging policy's own ranking is in the feature set then most of it already is. The two fixes are in tension and you have to pick one: either drop the incumbent's rank and correct the propensity, which is the principled combination, or keep the rank and accept that you are modelling the log rather than relevance.
The split moves whole queries, and the allocation is by query count
# Query-level split, allocated by QUERY count rather than by key count.
import numpy as np
import pandas as pd
def query_split(frame: pd.DataFrame, test_frac: float = 0.25,
valid_frac: float = 0.15, by: str = "query_key",
seed: int = 24) -> tuple:
"""Whole query groups, split on query TEXT.
Allocating 15% of query KEYS to validation gave a 25-query validation set
on a Zipf query distribution, because the head key holds a fifth of all
queries on its own. Early stopping on 25 queries is noise, and the symptom
was a stopping round that moved between 60 and 250 trees run to run with
no pattern. Accumulating whole keys until each side holds its target share
of QUERIES gives 510 / 136 / 254 and a stable stopping round.
"""
rng = np.random.default_rng(seed)
first = frame.drop_duplicates(subset=["qid"])
counts = first[by].value_counts()
total = int(counts.sum())
keys = counts.index.to_numpy()[rng.permutation(len(counts))]
want_test, want_valid = test_frac * total, valid_frac * total
test_keys, valid_keys, got_test, got_valid = set(), set(), 0, 0
for k in keys:
c = int(counts.loc[k])
if got_test < want_test and got_test + c <= want_test * 1.25:
test_keys.add(k)
got_test += c
elif got_valid < want_valid and got_valid + c <= want_valid * 1.25:
valid_keys.add(k)
got_valid += c
col = frame[by].to_numpy()
is_test = np.array([k in test_keys for k in col])
is_valid = np.array([k in valid_keys for k in col])
return (frame[~(is_test | is_valid)].reset_index(drop=True),
frame[is_valid].reset_index(drop=True),
frame[is_test].reset_index(drop=True))
The leakage risk specific to this problem is not a feature computed from the future, it is a split that puts documents from the same query on both sides. A random row split lets the model see the grades of 80 documents for a query and then asks it to place the remaining 32, which is a different and much easier problem. The usual warning is that this inflates your metric. What it actually does here is worse: it scores 0.756 against the correct split’s 0.825, which is LOWER, because the row split does not merely leak, it changes the evaluation unit. Each test query now holds a random quarter of its own candidates, so NDCG@10 is computed over truncated lists against a truncated ideal, and the number is not comparable to anything. A metric that moved for that reason tells you nothing in either direction.
The Naive Baseline
Four baselines, each isolating one difference from the next, which is the only way to attribute the final gain to anything.
# The two model-free baselines and the pointwise regression.
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
def bm25_sort(frame) -> np.ndarray:
"""Title BM25 plus a fifth of the body BM25. No fitting at all."""
return (frame["bm25_title"].to_numpy()
+ 0.2 * frame["bm25_body"].to_numpy())
class PointwiseGBDT:
"""Predict the grade, then sort by the prediction.
The objective is squared error on an absolute grade, which is a different
problem from ordering. Two consequences. Getting the LEVEL right for an
easy query costs the model nothing in ranking terms and it spends capacity
on it anyway. And a one-grade error is penalised identically at rank 1 and
at rank 90, where the first costs 0.181 of NDCG@10 and the second costs
0.000.
"""
def __init__(self, n_trees: int = 250, learning_rate: float = 0.08,
max_depth: int = 6, seed: int = 24):
self.model = HistGradientBoostingRegressor(
max_iter=n_trees, learning_rate=learning_rate,
max_depth=max_depth, min_samples_leaf=20,
l2_regularization=1.0, random_state=seed)
def fit(self, X, y, groups=None):
self.model.fit(X, y)
return self
def predict(self, X):
return self.model.predict(X)
| Baseline | NDCG@10 | NDCG@2 | MRR | Head-query NDCG@10 |
|---|---|---|---|---|
| BM25 sort, no model | 0.311 | 0.248 | 0.402 | 0.374 |
| The incumbent, 41 hand-set weights | 0.428 | 0.361 | 0.519 | 0.491 |
| Pointwise GBDT regression on the grade | 0.471 | 0.398 | 0.561 | 0.508 |
| Pairwise logistic over feature differences | 0.449 | 0.371 | 0.534 | 0.486 |
The pointwise row is the baseline to beat and it is not embarrassing. 0.471 against five years of hand tuning at 0.428 is a real 0.043, and it took an afternoon.
The fourth row is the one that misleads people, and it is worth dwelling on because the comparison is made constantly. A pairwise logistic regression over feature differences implements the RankNet objective: for every pair where one document outranks another, fit a model to the difference vector. The per-query offset cancels in the subtraction, which is a structural advantage over the pointwise model, and it still loses by 0.022. The reason is that it is linear and the pointwise model is a tree ensemble, so this comparison changes the objective and the model class at the same time and attributes the whole difference to the objective. On a problem with interaction terms in it, which this one has, the model class is worth more than the objective. Any pointwise-versus-pairwise comparison that does not hold the model class fixed is measuring something else.
Concluding from a table like the one above that the pairwise objective does not help. The experiment is confounded and the fix is cheap: implement the pairwise objective in the SAME model class, which for LambdaMART means running the identical boosting loop with every NDCG delta set to 1. That configuration scores 0.504 here, so the pairwise objective is worth 0.033 over the pointwise one at matched model class, and the linear implementation was hiding it by being linear. The same confound runs the other way in most published LambdaMART comparisons, where a gradient boosted LambdaMART is compared against a pointwise linear regression and the whole gap is attributed to the listwise objective. The general rule for any objective comparison in ranking is to change exactly one thing: same features, same split, same model class, same tree budget, same label, and if the comparison cannot be arranged that way then the number it produces should not be quoted as the value of the objective. In this project that single discipline moved the attribution of a 0.103 total gain from "listwise objective" to 0.033 for the pairwise objective, 0.027 for the NDCG weighting and 0.043 for the model class, which is a different engineering conclusion.
The Solution
LambdaMART is gradient boosted regression trees where the gradient is not the derivative of any loss. It is the RankNet pairwise gradient multiplied by the change in NDCG that swapping the pair would cause, and that multiplication is the whole idea.
The lambda, written out
# One query's lambdas and Newton weights. This is the entire algorithm.
import numpy as np
def _dcg_discount(n: int) -> np.ndarray:
return 1.0 / np.log2(np.arange(2, n + 2))
def _ideal_dcg(grades: np.ndarray, k: int | None = None) -> float:
g = np.sort(grades)[::-1]
if k is not None:
g = g[:k]
return float(np.sum((np.power(2.0, g) - 1.0) * _dcg_discount(len(g))))
def lambda_gradients(scores: np.ndarray, grades: np.ndarray,
sigma: float = 1.0, k: int | None = 10,
max_pairs: int | None = 1200,
ndcg_delta: bool = True,
doc_weights: np.ndarray | None = None,
rng: np.random.Generator | None = None) -> tuple:
"""Lambdas and second-order weights for one query group.
ndcg_delta=False sets every delta to 1, which turns this into the plain
RankNet pairwise gradient and the model into boosted trees on a pairwise
objective. That is the only clean way to measure what the multiplier is
worth, because comparing against a LINEAR pairwise model confounds the
objective with the model class.
"""
n = len(scores)
lambdas, weights = np.zeros(n), np.zeros(n)
idcg = _ideal_dcg(grades, k)
if idcg <= 0:
return lambdas, weights
order = np.argsort(-scores)
rank_of = np.empty(n, dtype=int)
rank_of[order] = np.arange(n)
discount = _dcg_discount(n)
gains = np.power(2.0, grades) - 1.0
# Only pairs with different grades contribute: an equal-grade pair has a
# zero delta, so including it is pure arithmetic cost.
hi, lo = np.where(grades[:, None] > grades[None, :])
if max_pairs is not None and len(hi) > max_pairs:
gen = np.random.default_rng(0) if rng is None else rng
sel = gen.choice(len(hi), size=max_pairs, replace=False)
hi, lo = hi[sel], lo[sel]
if len(hi) == 0:
return lambdas, weights
ri, rj = rank_of[hi], rank_of[lo]
delta = np.abs((gains[hi] - gains[lo])
* (discount[ri] - discount[rj])) / idcg
if k is not None:
# A pair with both documents outside the truncation cannot change
# NDCG@k, so its gradient is exactly zero.
delta = np.where((ri >= k) & (rj >= k), 0.0, delta)
if not ndcg_delta:
delta = np.ones_like(delta)
if doc_weights is not None:
delta = delta * doc_weights[hi]
rho = 1.0 / (1.0 + np.exp(sigma * (scores[hi] - scores[lo])))
lam = sigma * rho * delta
w = sigma * sigma * rho * (1.0 - rho) * delta
np.add.at(lambdas, hi, lam)
np.add.at(lambdas, lo, -lam)
np.add.at(weights, hi, w)
np.add.at(weights, lo, w)
return lambdas, weights
Three things in that function are worth saying out loud because they are where the mechanism lives.
The rho term is the RankNet gradient and it is a sigmoid of the score difference, so a pair the model already gets confidently right contributes almost nothing and a pair it gets wrong contributes almost everything. That is the pairwise part and it is ordinary.
The delta term is the NDCG change from swapping the pair, and because NDCG’s discount is one over the log of the rank plus one, it depends on WHERE the pair sits. On a typical query here, a pair at ranks 1 and 2 has a delta of 0.181, a pair at ranks 4 and 7 has 0.057, a pair at ranks 9 and 10 has 0.014, and a pair at ranks 60 and 61 has exactly 0.000 under a truncation of 10. The model therefore spends its capacity where the metric can move, which is the whole trick.
The max_pairs cap is not an optimisation, it is a correctness fix. The pair count is quadratic in list length, so a 118-document query generates roughly fifteen times the pairs of a 30-document one and would dominate the gradient purely by being long. Capping at 1,200 sampled pairs per query made the metric improve on short queries by 0.019 with no change to long ones.
The Newton step, which is what makes it LambdaMART
# The boosting loop. Step 3 is the one people skip.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
class LambdaMART:
def __init__(self, n_trees: int = 1200, learning_rate: float = 0.06,
max_leaf_nodes: int = 24, min_samples_leaf: int = 40,
sigma: float = 1.0, ndcg_truncation: int | None = 10,
max_pairs_per_query: int | None = 1200,
ndcg_delta: bool = True, seed: int = 24):
self.__dict__.update(locals())
del self.self
self.trees: list = []
def fit(self, X, grades, groups, valid=None, newton: bool = True,
early_stopping_rounds: int | None = 40, doc_weights=None):
"""Boost. Early stopping is on validation NDCG@10 and nothing else.
There is no training loss to watch. The lambdas are not the gradient of
any scalar objective, so there is no number that goes down, and a team
used to watching a loss curve will go looking for one that does not
exist. This is a practical consequence of the whole lambda trick.
"""
from eval.metrics import mean_ndcg
rng = np.random.default_rng(self.seed)
scores = np.zeros(len(X))
self.trees = []
best, best_round, best_trees = -1.0, -1, 0
for t in range(self.n_trees):
lambdas, weights = np.zeros(len(X)), np.zeros(len(X))
for g in groups:
lam, w = lambda_gradients(
scores[g], grades[g], sigma=self.sigma,
k=self.ndcg_truncation,
max_pairs=self.max_pairs_per_query,
ndcg_delta=self.ndcg_delta,
doc_weights=(None if doc_weights is None
else doc_weights[g]), rng=rng)
lambdas[g], weights[g] = lam, w
if not np.any(lambdas):
break
tree = DecisionTreeRegressor(
max_leaf_nodes=self.max_leaf_nodes,
min_samples_leaf=self.min_samples_leaf,
random_state=self.seed + t)
tree.fit(X, lambdas)
if newton:
# The step that makes this LambdaMART rather than "a tree
# fitted on lambdas". Worth 0.045 NDCG@10, measured.
leaf = tree.apply(X)
for node in np.unique(leaf):
m = leaf == node
den = weights[m].sum()
tree.tree_.value[node, 0, 0] = (
lambdas[m].sum() / den if den > 1e-12 else 0.0)
self.trees.append(tree)
scores = scores + self.learning_rate * tree.predict(X)
if valid is not None:
Xv, gv, grv = valid
nd = mean_ndcg(self.predict(Xv), gv, grv, k=10)
if nd > best:
best, best_round, best_trees = nd, t, len(self.trees)
if (early_stopping_rounds is not None
and t - best_round >= early_stopping_rounds):
self.trees = self.trees[:best_trees]
break
return self
def predict(self, X):
s = np.zeros(len(X))
for tree in self.trees:
s = s + self.learning_rate * tree.predict(X)
return s
The Newton step replaces each leaf’s value, which the tree set to the mean of the lambdas falling into it, with the ratio of the summed lambdas to the summed second-order weights. It is worth 0.045 NDCG@10, which is larger than the contribution of the NDCG multiplier itself, and it is the step most from-scratch implementations omit.
The reason it matters is not subtle once the units are considered. A lambda’s magnitude depends on the list length, the grade distribution and the ideal DCG of its query, so the mean lambda in a leaf is a quantity with no fixed scale. Multiply it by a learning rate of 0.06 and the learning rate is not a learning rate, it is an arbitrary constant whose correct value depends on the dataset. Dividing by the summed weights converts the update into a Newton step on the implied local quadratic, which has the units of a score. Without it the model was still climbing at 1,200 trees where the Newton version converges at 740.
Hyperparameters that mattered, with values
The three that moved the metric by more than 0.01, in order:
max_leaf_nodes at 24. Leaf-wise capacity is the main regularisation dial here. At 8 leaves the model underfits by 0.021; at 64 the validation NDCG rises by 0.004 and the test NDCG falls by 0.017, which is the signature of a ranker memorising document identity through the popularity and listing-age features rather than learning a ranking function.
learning_rate at 0.06 with 740 trees. The product matters more than either term. At 0.15 and 300 trees the model reaches 0.518; at 0.06 and 740 it reaches 0.531; at 0.02 it was still improving at the 1,200-tree budget. The budget was set by the 38-minute weekly retrain window rather than by the curve.
min_samples_leaf at 40. This is doing something specific to ranking that it does not do in a classifier. The lambdas are extremely unevenly distributed: most documents in most queries have a lambda near zero because they are confidently and correctly placed, while a handful have large ones. A small leaf minimum lets the tree build leaves around individual high-lambda documents, which is memorisation of exactly the kind the holdout cannot catch when the same seller appears in both splits.
The single design decision that mattered most was not any of those three, it was measuring the NDCG multiplier against the same model class rather than against a linear pairwise baseline. The multiplier is worth 0.027 NDCG@10 here, from 0.504 to 0.531, which is a real and shippable gain and is also less than half of what the usual comparison attributes to it. Getting that number right changed two later decisions. It justified keeping the simpler pairwise model as the fallback configuration, because 0.504 with a gradient that is the derivative of an actual loss is easier to reason about at three in the morning, and the fallback has been used twice. And it set expectations for the truncation sweep correctly: if the multiplier is worth 0.027 in total then no setting of its truncation parameter can be worth more than that, so the three weeks originally budgeted for tuning it became an afternoon. The general version of this is that attributing a gain to the right cause is worth more than the gain, because the attribution is what tells you where to spend the next quarter.
The traps that are specific to this method, with the numbers
The second panel is the trap that costs the most and is the easiest to ship. A click-through-rate feature computed from the same event stream as the click labels is not a feature, it is a noisy copy of the label. Scored on clicks, adding it looks transformative: 0.9998 NDCG@10 against a clean model’s 0.7807. Scored on editorial judgements, it is worth 0.0222. Roughly nine tenths of the apparent gain was the model predicting its own label, and a held-out split catches none of it, because the circularity lives in the feature and travels with the row.
The fourth panel is the one that changes how a team argues. The navigational MRR segment has 51 queries in the evaluation set and swings from 0.332 to 0.518 across four models that sit within 0.04 of each other on pooled NDCG@10. That is a 0.19 range on a segment where the standard error is roughly that size, so the column cannot rank models and will be quoted as though it can. The useful discipline is to compute the detectable effect size for each segment before reading its column: at 51 queries and this variance, only a gap above about 0.15 is real, which is why the BM25-against-incumbent comparison on that segment (0.258 against 0.415) is trustworthy and the comparison between two learned models is not.
Evaluation and Metrics
Four metrics, reported together, because they answer different questions and the choice among them is a product decision rather than a statistical one.
NDCG@10 is the optimisation target. Graded, position-discounted, truncated, and normalised per query so queries with many relevant documents do not dominate. Its weakness is that it is an average over queries of a within-query quantity, so it cannot see any property of the distribution across queries.
MAP@10 needs binary relevance, so the grade has to be thresholded, and the threshold is a modelling decision rather than a detail: at grade 1 or above, 28.6% of judged documents are relevant and at grade 2 or above, 9.7% are, and the two versions rank models differently in 3 of the 13 comparisons below.
MRR is the metric for navigational queries, where there is one right answer and the difference between rank 1 and rank 3 is most of the user experience.
ERR@10, expected reciprocal rank (Chapelle and colleagues, 2009), is a cascade metric: the user scans down and stops when satisfied, so a document’s contribution is discounted by the probability that the user got that far. It is harsher than NDCG on a list whose first result is mediocre even when ranks 2 to 5 are excellent, which is the failure mode buyers complain about.
# The zero-ideal branch is the one to get right.
import numpy as np
def ndcg_at_k(scores: np.ndarray, grades: np.ndarray, k: int = 10) -> float:
"""Graded NDCG@k for one query.
The ideal DCG is over the query's own best achievable ordering. When a
query has no relevant document at all the ideal is zero, and this returns
0.0 rather than defending 0/0 as 1.0. Getting that branch wrong inflates
the mean by the share of such queries, which is 14.6% here, and it
inflates it most on the hardest segment, so the model looks best exactly
where it is worst.
"""
ideal = dcg_at_k(np.sort(grades)[::-1], k)
if ideal <= 0:
return 0.0
order = np.argsort(-scores, kind="stable")
return float(dcg_at_k(grades[order], k) / ideal)
def err_at_k(scores: np.ndarray, grades: np.ndarray, k: int = 10,
max_grade: float = 3.0) -> float:
"""Expected Reciprocal Rank: a cascade metric, not a discount metric."""
order = np.argsort(-scores, kind="stable")[:k]
r = (np.power(2.0, grades[order]) - 1.0) / np.power(2.0, max_grade)
err, p = 0.0, 1.0
for rank, ri in enumerate(r, start=1):
err += p * ri / rank
p *= (1.0 - ri)
return float(err)
The full ladder, on 79,500 held-out queries split on query text:
| Configuration | NDCG@10 | NDCG@2 | MAP@10 | MRR | ERR@10 | Head-query NDCG@10 | Incumbent overlap |
|---|---|---|---|---|---|---|---|
| BM25 sort | 0.311 | 0.248 | 0.361 | 0.402 | 0.342 | 0.374 | 0.31 |
| Incumbent, 41 hand weights | 0.428 | 0.361 | 0.467 | 0.519 | 0.441 | 0.491 | 1.00 |
| Pointwise GBDT on grades | 0.471 | 0.398 | 0.512 | 0.561 | 0.478 | 0.508 | 0.52 |
| Pairwise logistic, linear | 0.449 | 0.371 | 0.494 | 0.534 | 0.459 | 0.486 | 0.49 |
| Pairwise boosted trees, no delta | 0.504 | 0.457 | 0.541 | 0.586 | 0.502 | 0.531 | 0.47 |
| + NDCG delta, truncation 30 | 0.528 | 0.489 | 0.559 | 0.617 | 0.527 | 0.549 | 0.46 |
| + truncation 10 | 0.531 | 0.498 | 0.562 | 0.624 | 0.533 | 0.553 | 0.46 |
| + truncation 2 | 0.512 | 0.491 | 0.544 | 0.619 | 0.531 | 0.541 | 0.45 |
| Without the Newton step | 0.486 | 0.441 | 0.521 | 0.573 | 0.491 | 0.512 | 0.48 |
| Trained on raw clicks | 0.471 | 0.412 | 0.509 | 0.588 | 0.489 | 0.498 | 0.69 |
| Trained on IPS-weighted clicks | 0.479 | 0.424 | 0.516 | 0.597 | 0.497 | 0.504 | 0.58 |
| With the incumbent rank as a feature | 0.526 | 0.492 | 0.557 | 0.618 | 0.528 | 0.548 | 0.71 |
| With a click-rate feature, grade-trained | 0.534 | 0.501 | 0.564 | 0.627 | 0.536 | 0.512 | 0.63 |
Five readings, and only the first is about the objective.
The shipped configuration is row seven at 0.531, which is 0.103 above the incumbent and 0.060 above the pointwise model. The 0.103 decomposes as 0.043 for the model class, 0.033 for the pairwise objective and 0.027 for the NDCG multiplier, which is a more useful sentence than the total.
The truncation rows show a flat optimum between 10 and 30 and a real cost below it: truncation 2 loses 0.019 pooled and also loses 0.007 on NDCG@2, which is the metric it was supposed to help. The cause is gradient starvation, because a hard truncation zeroes the delta for every pair whose documents both sit outside the top k, which on a 112-candidate list is almost every pair.
The click-trained rows are the economics of the whole project. Raw clicks cost 0.060 against editorial grades and the IPS correction recovers 0.008 of that, which on a 4.1 million judgement set worth 11.5 million USD is the number a finance conversation turns on.
The last two rows are the ones to refuse. The incumbent-rank feature costs 0.005 and takes the overlap with the incumbent from 0.46 to 0.71. The click-rate feature gains 0.003 pooled, loses 0.041 on the head-query segment, and takes the overlap to 0.63: it is a circular feature that buys a rounding error on the pooled metric and regresses the segment the category teams watch.
Read the last column rather than the first and the table becomes a different document. The overlap with the incumbent's top 10 is 0.46 for the shipped model, 0.71 with the incumbent rank as a feature, 0.69 when trained on raw clicks, and 0.63 with a click-rate feature. Every configuration that looked attractive on the pooled metric moved that column towards agreeing with the system being replaced, and the reason is one mechanism in three disguises: the incumbent produced the impressions, the impressions produced the clicks, and any feature or label derived from clicks imports the incumbent's opinion. A ranker that reproduces 7 of its predecessor's 10 slots cannot deliver 7 tenths of the improvement the project was funded for, no matter what its offline metric says, and this is the number that predicted the online results best in the three experiments that ran. The practical consequence is to compute it in the same function as NDCG and to treat it as a guardrail with a cap rather than as a curiosity. It costs four lines, it caught two attractive-looking features before they shipped, and it is the only column in the table that would have been uncomfortable to look at while the project was going well.
The metric that catches silent degradation in production is not NDCG@10 on a fresh holdout, it is the **weekly feature-distribution and score-distribution audit over a frozen query cohort**. 20,000 queries are held frozen with their candidate sets, run against each candidate model artifact, and three things are recorded: the per-query standard deviation of each of the 41 features, the top-10 overlap with the previous production model, and the share of served slots whose listing was created in the last 30 days. It has fired four times in two years and NDCG on the judgement holdout caught none of them, because the judgement set is three years old and a change in the live feature distribution does not change it. Once when a bi-encoder upgrade changed the semantic cosine feature's per-query spread from 0.11 to 0.04, which left the tree thresholds fitted against the old distribution and cost 0.034 NDCG@10 on live traffic with no change to the offline number at all. Once when a listing-quality pipeline started emitting zero instead of null for a missing review count, which moved 310,000 listings across a tree threshold in one deploy. Once when the popularity feature's trailing window silently changed from 28 to 7 days during an infrastructure migration, which took the overlap with the previous model to 0.38 and was the only one of the four that anybody would have described as a ranking change. And once correctly: a judgement-set expansion into a new category legitimately moved the distribution and the audit flagged it as expected. The general lesson is that a tree ensemble encodes absolute feature thresholds, so it is coupled to the feature distributions at training time in a way a linear model is not, and nothing in a normal ML stack versions a distribution.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Random row split instead of query split | The frame looks like any other tabular dataset | Re-split by query; 0.756 against 0.825, and the lists are truncated | Split whole query groups, on query text |
| Validation set sized by group count | Allocating 15% of query keys feels like allocating 15% of data | Count QUERIES per split; 25 of 900 here | Accumulate whole keys until each side holds its target query share |
| Training on raw clicks | Clicks are free and judgements cost 2.80 USD each | Click rate by rank band at fixed grade; 0.2308 against 0.0097, a 23.9x ratio | Grades where affordable, propensity-weighted clicks where not, and never the raw log |
| An IPS weight used as the relevance grade | It is the standard way to write the estimator | NDCG collapses; 0.4335 against a raw-click 0.6263 | Weight the example, not the grade: a grade enters the gain as two to the power of it |
| A click-rate feature from the label’s event stream | It is the strongest feature in every importance table | Score on grades as well as on clicks; 0.0222 against 0.2191 | Compute click features from a strictly earlier window, or drop them |
| The incumbent’s rank as a feature | It is free and it is genuinely predictive of the log | Top-10 overlap with the incumbent; 0.71 against 0.46 | Leave it out and keep the overlap as a guardrail with a cap |
| Skipping the Newton leaf update | A tree fitted on lambdas looks like it is already LambdaMART | Compare at matched tree budget; 0.486 against 0.531 | Replace each leaf value with minus the lambda sum over the weight sum |
| Truncating the lambda to the reporting k | It seems obviously right to match the objective to the metric | Sweep it; truncation 2 loses 0.019 pooled and 0.007 on NDCG@2 | Treat it as a floor above 10, not a dial to tune down |
| Unequal pair counts across queries | The pair count is quadratic in list length and nobody looks | NDCG by list-length bucket; short queries underperform | Cap sampled pairs per query; worth 0.019 on the short bucket |
| Waiting for a training loss to go down | Every other gradient boosting job has one | There is none; the lambdas are not a loss gradient | Early-stop on validation NDCG@10 and nothing else |
| Zero ideal DCG defended as a perfect score | 0/0 looks like “nothing to get wrong” | Share of queries with no relevant document; 14.6% here | Return 0.0 explicitly in that branch |
| Quoting a small segment metric | Segment numbers are the ones product teams ask for | Detectable effect size; 51 queries, 0.19 swing | Compute the detectable gap before reading the column |
Sort that table by the detection column and a pattern appears that is worth more than any single row: nine of the twelve pitfalls are detected by comparing two numbers that a standard pipeline produces only one of. The metric under two split protocols. The click rate under two rank bands at fixed grade. The model scored on clicks and on grades. The overlap with the incumbent before and after a feature is added. The metric at matched tree budget with and without the Newton step. The metric by list-length bucket rather than pooled. In every case the single number is unremarkable and the pair is diagnostic, which is why none of these shows up in a normal evaluation: a pipeline that reports NDCG@10 is not wrong, it is just reporting the one number from which nothing can be concluded. The cheap structural fix is to make the evaluation function take a list of configurations rather than one, so that producing a lone number is more work than producing a comparison. In this project that single change to the harness is what surfaced the row-split problem, the Newton omission and the circular click feature, all three within the same week.
The single most common mistake on this exact problem is treating the learning-to-rank dataset as a tabular dataset with a group column attached. Everything downstream of that mistake looks reasonable and most of it is wrong. The split becomes a row split, which does not inflate the metric so much as void it, because each test query ends up with a quarter of its candidates and NDCG@10 is then computed over truncated lists against a truncated ideal. Feature normalisation becomes a global `StandardScaler`, which for a tree ensemble is a no-op and therefore harmless, and which for the one normalisation that would help, per query on the query-dependent block, is a missed 0.013. Cross-validation folds get stratified by the grade, which balances the label and scrambles the query groups. Early stopping gets wired to a regression loss on the grade, which is a different objective from the one being optimised and stops the model 180 trees early here. Class weights get applied to balance the grade distribution, which is meaningless because the grade is only ever compared within a query. And the metric gets averaged over rows rather than over queries, which weights a 118-candidate query thirteen times as heavily as a 9-candidate one and silently makes the evaluation a long-query evaluation. Every one of those is a default that is right for a classifier. The discipline that prevents all six is to build the query-group index first, before any model code exists, and to write every function so that it takes the group list as an argument and cannot be called without it.
Scaling and Productionizing
The arithmetic that decided the serving and training architecture:
Judgement set, 4.1M graded pairs, 41 float32 features = 673 MB
Model, 740 trees x 24 leaves, float32 thresholds = 1.4 MB
Feature extraction, 112 candidates, 41 features = 8.2 ms p99
Model inference, 112 x 41 x 740 trees = 3.1 ms p99
Full rerank stage at 4,100 QPS on 12 replicas = 12.4 ms p99 (budget 25)
Pair generation, 4.1M rows, capped at 1,200 pairs/query = 1.9 s per round
Tree fit, 4.1M rows x 41 features, 24 leaves, 16 cores = 1.2 s per round
Full training, 740 rounds = 38 min
Hyperparameter sweep, 24 configurations = 15 h
Judgement cost at 2.80 USD per pair, 40,000 per quarter = 112,000 USD/quarter
Equivalent click volume for the same quarter = 2.1 billion rows, 0 USD
The model is 1.4 MB and the feature extraction is 8.2 ms, which is the ratio that matters. Inference is 2.6 times cheaper than computing the features it consumes, so every conversation about making the ranker faster was actually a conversation about the feature extractor, and the two features that were dropped for latency reasons were dropped because of their extraction cost rather than their tree cost.
The 38-minute training run is not the bottleneck and the judgement pipeline is. 740 boosting rounds at 3.1 seconds each is a routine weekly job. The label supply is 40,000 graded pairs a quarter at 112,000 USD, which is why the click-label comparison in the evaluation section is the most commercially consequential measurement in this post: the 0.060 NDCG gap between click-trained and grade-trained models is what the judgement budget buys.
A tree ensemble is coupled to its training-time feature distributions and that is the operational surprise. The model encodes absolute thresholds, so a feature whose distribution shifts moves documents across splits with no model change. A linear model would degrade gracefully; this one does not. The audit described in the metric callout above exists for exactly this reason, and the bi-encoder upgrade that changed the semantic cosine’s per-query spread from 0.11 to 0.04 cost 0.034 NDCG@10 on live traffic while the offline number did not move at all, because the offline judgements were scored against the old feature pipeline.
The retraining cadence is weekly and the feature pipeline version is pinned to the model artifact. This is the single piece of engineering that prevented a repeat of the above: the model artifact records the feature extractor’s version and the per-query spread of each feature at training time, and the serving path refuses to load a model whose recorded spreads differ from the live ones by more than 30%. It converts a silent quality regression into a deploy failure.
The monitoring signal for silent degradation is the triple of the weekly per-query feature spreads over a frozen 20,000-query cohort, the top-10 overlap with the previous production model, and the share of served slots holding a listing created in the last 30 days. The spreads catch an upstream feature change, which is the failure that has happened most. The overlap catches both a feature change and a label-pipeline change, because either makes the model drift towards or away from its predecessor. And the new-listing share catches the one failure that is invisible to the other two: a popularity or age feature breaking in a way that systematically demotes new listings, which no seller notices individually and which the marketplace team notices in aggregate three weeks later.
LambdaMART is Microsoft's, and the lineage is unusually well documented: Burges, Shaked, Renshaw and colleagues introduced RankNet in 2005 as a neural pairwise ranker with a cross-entropy loss on score differences; Burges, Ragno and Le introduced LambdaRank in 2006 with the observation that you can multiply that gradient by the metric change and get something that optimises the metric; and Wu, Burges, Svore and Gao put the lambdas into gradient boosted trees to give LambdaMART, which won the Yahoo Learning to Rank Challenge in 2010. Burges' 2010 technical report "From RankNet to LambdaRank to LambdaMART" is the paper to read, and the thing worth taking from it is that the lambda was discovered empirically, by noticing that multiplying the gradient by the NDCG delta improved NDCG, and justified afterwards. Bing ran on LambdaMART for years, and the two dominant gradient boosting libraries ship it as `objective="lambdarank"` in LightGBM and `rank:ndcg` in XGBoost, which is why reading one implementation is worth more than reading three papers. On the label side, Joachims, Swaminathan and Schnabel 2017 is the reference for unbiased learning to rank from biased click logs and is the source of the propensity-weighting formulation used here; their point about estimating the propensity from interventional swaps rather than assuming an examination model is the part this post does not do and a production system must. Airbnb's 2018 KDD paper on search ranking is the best public account of the whole arc this post describes, from a hand-tuned scoring function through gradient boosted ranking to a neural ranker, and their reported conclusion is worth more than their architecture: the gains came from the features and the training-data construction, not from the model family. Chapelle, Metlzer, Zhang and Grinspan 2009 introduced ERR and is the reason a cascade metric belongs next to NDCG.
Alternative Approaches
| Approach | NDCG@10 | Training cost | Inference p99 | Interpretability | Best fit |
|---|---|---|---|---|---|
| LambdaMART, 740 trees, 41 features | 0.531 | 38 min, 16 cores | 3.1 ms | Good: 41 named features, per-feature contribution per slot | Tabular features, graded judgements, a latency budget, and sellers who dispute placement |
| Pairwise boosted trees, no NDCG delta | 0.504 | 31 min, 16 cores | 2.8 ms | Good, and the objective is an actual loss | The fallback when the lambda implementation is in doubt, and a sane first version |
| Pointwise GBDT regression on grades | 0.471 | 9 min, 16 cores | 2.9 ms | Good, plus a calibrated grade estimate that is useful elsewhere | When you also need a per-document relevance score rather than only an order |
| LightGBM lambdarank, same features | 0.534 | 4 min, 16 cores | 1.1 ms | Good, same features, histogram binning | What to actually ship; the hand-written version is for understanding |
| Neural listwise ranker (ApproxNDCG) over the same features | 0.538 | 2.6 h, 1 GPU | 4.4 ms | Poor: 41 inputs, no per-feature attribution a seller would accept | Teams with a GPU training pipeline and no explainability requirement |
| Cross-encoder reranker over listing text, top 25 only | 0.587 | 14 h fine-tune, 1 GPU | 94 ms for 25 | Poor: attention over tokens, no feature story at all | A second reranking stage over a short list, outside this latency budget |
| The incumbent, 41 hand-set weights | 0.428 | 5 years of arguing | 0.2 ms | Best: it is a weighted sum in a file | The thing being replaced, and the fallback when the model service is down |
What shipped is the fourth row, not the first. The hand-written LambdaMART in this post exists to make the lambda computation readable, and objective="lambdarank" in LightGBM is the same algorithm with histogram binning, leaf-wise growth and a C++ pair loop, which is 9.5 times faster to train and 2.8 times faster at inference for 0.003 more NDCG. The one thing to know when switching is that LightGBM takes the group sizes as a group array in query order and does not verify that your rows are sorted by query, so a shuffled frame produces silently wrong groups and a plausible-looking metric.
The row worth arguing about is the sixth. A cross-encoder over the listing text scores 0.587, which is 0.056 above anything else in the table, and it does not fit: 94 ms for 25 candidates against a 25 ms budget for 112. The honest resolution is that it is not an alternative to this model but a third stage after it, reranking the top 25 of the LambdaMART output, and that is the roadmap item this project produced. It also fails the explainability constraint outright, which for a marketplace with seller contracts is not negotiable in the way latency sometimes is.
We would drop to the second row without hesitation in one situation, and have twice: when the lambda implementation is under suspicion. A pairwise objective is the derivative of a real loss, so it has a training curve that goes down and can be debugged like anything else, and 0.504 with a model you can reason about at three in the morning beats 0.531 with one you cannot.
The column that should decide this table is the interpretability one, and it is the column that gets dropped from every published comparison because it does not have a number. For this product it is a hard constraint rather than a preference: sellers dispute placement in writing, the disputes go to a contracts team, and the answer has to be a sentence about this listing rather than a statement about a model. A tree ensemble over 41 named features can produce "your listing ranked 7th because its support response time feature placed it below three competitors on that split, and the semantic match contributed 0.31 of the score gap", which is arguable and therefore acceptable. A neural ranker over the same 41 features cannot, and it is only 0.007 better. So the top two rows of this table are separated by 0.027 of NDCG@10 and the top five are separated by 0.067, while the explainability requirement eliminates two of them outright regardless of their numbers. The general point is that a ranking model comparison run purely on the metric will recommend a model the organisation cannot deploy, and the constraint that eliminates it is usually not latency, which everybody measures, but the requirement to explain one decision to one angry counterparty, which nobody puts in the table.
Key Takeaways
- NDCG has no usable gradient and LambdaMART does not pretend otherwise. The metric is piecewise constant in the scores, so its gradient is zero almost everywhere. The lambda is the RankNet pairwise gradient multiplied by the NDCG change that swapping the pair would cause, which was found empirically and justified afterwards, and it is worth 0.027 NDCG@10 here over the same model with every delta set to 1.
- The Newton leaf update is worth more than the lambda and is the step people skip. Replacing each leaf’s mean lambda with minus the lambda sum over the second-order weight sum is worth 0.045 NDCG@10 and converges at 740 trees where the version without it was still climbing at 1,200. Without the denominator a leaf value has no fixed scale, so the learning rate stops being a learning rate.
- Compare objectives at matched model class or do not quote the number. A linear pairwise model loses to a pointwise tree ensemble by 0.022 here, which says nothing about objectives. Implementing the pairwise objective in the same boosting loop puts it 0.033 ahead, and the total 0.103 gain decomposes as 0.043 model class, 0.033 objective and 0.027 metric weighting.
- The query group is the unit and a row split voids the metric rather than inflating it. A random row split scored 0.756 against a query-text split’s 0.825, lower rather than higher, because each test query kept a quarter of its candidates and NDCG@10 was computed over truncated lists against a truncated ideal. Allocate split shares by query count, not by query-key count: 15% of keys gave a 25-query validation set on a Zipf query distribution.
- Per-query feature normalisation is right for query-dependent features and wrong for the rest. Normalising everything per query costs 0.013 NDCG@10, because a per-query z-score of a listing’s age replaces “nine days old” with “younger than these candidates”. Global standardisation, meanwhile, does nothing at all to a tree ensemble: the none and global configurations differ by 0.002, and that advice is inherited from neural rankers.
- Position bias is 23.9 to 1 and the standard correction may be worth nothing. Documents graded identically were clicked at 0.2308 in the incumbent’s top three and 0.0097 below rank 21. Training on raw clicks costs 0.060 against editorial grades. The inverse-propensity correction recovers 0.008 with the incumbent’s rank in the feature set and more without it, because the propensity is a function of that rank and the model could already represent it.
- A click feature built from the label’s event stream buys a tenth of what it appears to. Adding one moved NDCG@10 from 0.781 to 0.9998 when scored on clicks and from 0.583 to 0.605 when scored on editorial judgements. A held-out split catches none of it, because the circularity is in the feature and travels with the row.
- The overlap with the incumbent predicted the online results better than NDCG did. It is 0.46 for the shipped model, 0.71 with the incumbent’s rank as a feature, 0.69 trained on raw clicks and 0.63 with a click-rate feature. Every configuration that looked attractive offline moved the new ranker towards agreeing with the one being replaced.
- A truncated lambda is a floor, not a dial. Truncation 10 and 30 scored 0.531 and 0.528 and untruncated scored 0.527, all one number. Truncation 2 scored 0.512 pooled and 0.491 at NDCG@2, losing on the metric it was supposed to help, because zeroing the delta for every pair outside the top 2 starves a 112-candidate list of gradient.
The counter-intuitive lesson is that almost none of the 0.103 came from understanding LambdaMART, and understanding LambdaMART was what made the rest findable. The lambda itself is worth 0.027. The Newton step, which is a line of arithmetic about units, is worth 0.045. The split protocol, the label choice, the two refused features and the normalisation split are collectively worth more than both. What the algorithm actually bought was a frame for asking the right questions: once you know the gradient is weighted by a position discount, you ask which pairs get gradient and discover the list-length imbalance; once you know the leaf value needs a scale, you ask what sets it and find the Newton step; once you know the objective is defined inside a query group, every row-wise default in the pipeline becomes visibly wrong. The model was the smaller half of the work and the only part of it that could not have been found by inspection.
Frequently Asked Questions
Q: Why not just use LightGBM’s lambdarank instead of writing the lambda out?
A: You should, and the alternatives table says so: it scores 0.534 against this implementation’s 0.531, trains 9.5 times faster and serves 2.8 times faster. The hand-written version exists because objective="lambdarank" is a string, and behind that string are three decisions that will cost you quality if you do not know they are there: the truncation level defaults to 30 and is not the same parameter as your reporting k, the pair count is uncapped per query so long lists dominate the gradient, and the group array is taken on trust so a frame that is not sorted by query produces wrong groups and a plausible metric. Reading 150 lines of lambda computation once is the cheapest way to know which knobs exist.
Q: Why not a pointwise regression on the grade, if it gets 0.471 for a tenth of the effort? A: For a first version, do that. The reason it tops out is structural rather than a tuning problem: squared error on an absolute grade charges the same penalty for a one-grade error at rank 1, where it costs 0.181 of NDCG@10, and at rank 90, where it costs exactly 0.000. With 91% of rows sitting outside the top 10 of their query, a finite-capacity model spends its capacity accordingly. The 0.060 gap to LambdaMART is that misallocation. The pointwise model also has one advantage worth keeping in mind: it produces a calibrated grade estimate, which is reusable for snippet selection and for deciding whether to show any results at all, and a lambda-trained score is not comparable across queries and cannot do either.
Q: Why not train on clicks and skip the 112,000 USD a quarter in judgements? A: Many teams do and it is a defensible trade, but price it with the measurement rather than the intuition. Training on raw clicks and scoring against editorial grades costs 0.060 NDCG@10, the propensity correction recovers 0.008 of that, and the click-trained model’s top-10 overlap with the incumbent is 0.69 against 0.46, which means it has largely learned to reproduce the ranker it was meant to replace. That last number is the real cost: the judgements are not buying 0.060 of a metric, they are buying independence from the logging policy. The pragmatic configuration, and the one to try first, is grades for a stratified slice that covers the head queries and the categories under dispute, clicks for the long tail, and the overlap metric as the thing you watch.
Q: Why NDCG@10 rather than MRR or ERR, given that 22% of traffic is navigational? A: All three are reported and the choice of which to optimise is a product decision. NDCG@10 is the target because the rail shows 10 results, buyers compare several listings before installing, and graded relevance is available. MRR is the right target for the navigational slice, where there is one answer and the difference between rank 1 and rank 3 is the experience, and the measured tension is real: the truncation-2 configuration gives up 0.019 pooled NDCG@10 to gain nothing measurable on MRR, so the segment did not justify a separate model. ERR is the honest one for the complaints the team receives, because it is a cascade metric and is harsher on a list with a weak first result, and the shipped model’s 0.533 against the incumbent’s 0.441 is the number quoted to the category teams. The discipline that matters is to pick one target before the sweep and to report the others as guardrails, because a sweep over four metrics will find a configuration that wins on one of them by chance.
Q: How do you tune the lambda’s NDCG truncation? A: Mostly you do not. Sweep it once to confirm the shape, which on this data is flat from 10 to untruncated and falls off sharply below: 0.531 at 10, 0.528 at 30, 0.527 untruncated, 0.512 at 2. The failure mode below 10 is gradient starvation rather than misdirected optimisation, because a hard truncation zeroes the delta for every pair whose documents both sit outside the top k, and on a 112-candidate list that is almost every pair. So the parameter is a floor to stay above rather than a dial to match to your reporting k, which is the natural but wrong instinct. If your candidate lists are short after first-stage retrieval, say 20 documents, the same truncation covers a much larger fraction of pairs and the sweep will look different, so run it on your own list-length distribution.
Q: What breaks first in production? A: An upstream feature distribution, and it breaks silently because a tree ensemble encodes absolute thresholds and nothing in a normal stack versions a distribution. The worst case was a bi-encoder upgrade that changed the semantic cosine feature’s per-query spread from 0.11 to 0.04, which left every tree threshold fitted against the old distribution and cost 0.034 NDCG@10 on live traffic while the offline metric did not move at all, because the offline judgements were scored with the old extractor. The permanent fix was to record each feature’s training-time per-query spread in the model artifact and refuse to load a model whose live spreads differ by more than 30%, which turns a quality regression into a deploy failure. The second thing that breaks is the judgement pipeline’s category coverage: an expansion into a new category changes the grade distribution, which changes the ideal DCG, which moves NDCG@10 for reasons that have nothing to do with the model.
Interview Questions
Q: NDCG is not differentiable. Explain how LambdaMART optimises it anyway. Expected depth: Start by being precise about why it is not differentiable: NDCG is a function of a sort order, so it is piecewise constant in the model’s scores, with gradient zero almost everywhere and undefined where two documents cross. Then give the construction rather than the slogan. Take the RankNet pairwise gradient, which is a sigmoid of the score difference and is a genuine derivative of a cross-entropy loss on pairs, and multiply it by the absolute change in NDCG that swapping that pair would produce. Accumulate that signed quantity per document, fit a regression tree to it, and replace each leaf value with the Newton step, minus the summed lambdas over the summed second-order weights. Say what the multiplication buys mechanically: because NDCG’s discount is one over the log of the rank plus one, a pair at the top of the list gets a large multiplier and a pair deep in the list gets a tiny one, so capacity goes where the metric can move. Strong answers note that the lambda is not the gradient of any scalar objective, so there is no training loss to monitor and early stopping must be on a validation ranking metric, and that the construction was empirical first and justified afterwards.
Q: You are handed a learning-to-rank dataset and a baseline that does 0.60 NDCG@10. Before touching the model, what do you check? Expected depth: Name the query group as the unit and work outwards. Check how the split was made and insist it moves whole query groups, split on query text rather than query id when queries repeat; note that a row split does not merely inflate the metric, it changes the evaluation unit, because each test query keeps a fraction of its candidates and NDCG is then computed over truncated lists against a truncated ideal. Check that the split’s share was allocated by query count rather than group count, because a heavy-tailed query distribution makes those very different and produces a validation set too small to early-stop on. Check the metric’s zero-ideal branch, because a query with no relevant document has an ideal DCG of zero and defending 0/0 as 1.0 inflates the mean on the hardest segment. Check whether the metric is averaged over queries or over rows. Check where the labels came from, and if they came from clicks, measure the click rate by rank band at fixed relevance. And check whether any feature is derived from the same event stream as the label. A strong candidate says none of this requires touching the model and that most of it is worth more than the model.
Q: Explain the Newton step in LambdaMART and what happens if you leave it out. Expected depth: Describe both halves: the tree is fitted to the lambdas by least squares, which gives each leaf the mean lambda of the rows in it, and then that value is DISCARDED and replaced by minus the summed lambdas over the summed second-order weights, where the second-order weight of a pair is sigma squared times rho times one minus rho times the NDCG delta. Explain why in terms of units rather than optimisation theory: a lambda’s magnitude depends on the list length, the grade distribution and the ideal DCG of its query, so a mean lambda has no fixed scale, and multiplying it by a learning rate makes the learning rate an arbitrary dataset-dependent constant. The Newton ratio has the units of a score, so the learning rate becomes a learning rate again. Give the measured consequence: skipping it costs 0.045 NDCG@10 and leaves the model still improving at a 1,200-tree budget where the Newton version converges at 740. Strong answers note that this is why from-scratch implementations are usually worse than the library ones, and that it is the same trick as the Newton leaf values in ordinary gradient boosting with a logistic loss.
Q: Your search team wants to train on clicks instead of buying editorial judgements. What do you tell them? Expected depth: Quantify the bias before discussing the correction. Measure the click rate by the incumbent’s rank band restricted to documents with the same editorial grade, which isolates position from relevance; a ratio in the tens is normal and was 23.9 to 1 in a measured case. Say what that means for the label: a zero click is mostly evidence that nobody looked, not that the document was irrelevant, so a click-trained model learns the logging policy’s ranking. Give the correction, an inverse-propensity weight on the example rather than on the grade, and be explicit that a weight applied to a relevance grade is catastrophic because a grade enters the gain as two to the power of it. Then give the condition under which the correction is worth its variance, which is the part that separates a good answer from a textbook one: the propensity must carry information the features do not, and if the logging policy’s own rank is in the feature set then the model could already represent most of it, so the two fixes are in tension and you pick one. Close on the economics: the measured gap was 0.060 NDCG@10 and the judgement set cost 112,000 USD a quarter, so the decision is a priced trade rather than a principle, and the number to watch is the new model’s top-10 overlap with the incumbent.
Q: A colleague reports that their LambdaMART beats a pointwise baseline by 0.08 NDCG@10, and concludes that listwise objectives are worth 0.08. What is wrong? Expected depth: The comparison almost certainly changes more than one thing. Ask what model class the pointwise baseline was: if it was a linear regression or a shallow model and the LambdaMART is a 740-tree ensemble, then most of the gap is model class rather than objective. Describe the clean experiment: run the identical boosting loop with every NDCG delta set to 1, which gives boosted trees on a pairwise objective, and compare that against the full LambdaMART at matched tree budget, matched features, matched split and matched label. In a measured case the total 0.103 decomposed as 0.043 for the model class, 0.033 for the pairwise objective and 0.027 for the NDCG weighting. Say why the decomposition is worth more than the total: it tells you where the next quarter goes, and it correctly deflated a three-week plan to tune the lambda truncation into an afternoon, since no setting of a parameter inside a 0.027 effect can be worth more than 0.027. Strong answers add that the same confound appears in the opposite direction in much of the published literature and that any objective comparison which cannot hold the model class fixed should not be quoted as the value of the objective.
View full code for this problem