Algorithmadvanced
LambdaMART
Also called lambda-gradient boosted trees.
Fits gradient-boosted regression trees to LambdaRank gradients, a strong standard ranker on feature-based benchmarks.
- Solves
- Learning to rank
- Time
- O(M (N log N + P + D d N log N)) totalO(N log N + P + D d N log N) per_round
- Space
- O(N + M 2^D) extra
- Where
- D = the tree depth; M = the number of rounds; N = the number of documents; P = the number of preferred pairs; d = the number of features
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Qiang Wu, Chris Burges, Krysta Svore, Jianfeng Gao, 2010
LambdaMART is a gradient boosting machine for learning to rank: each round fits a small regression tree to the LambdaRank lambdas of the current scores and sets each leaf by one Newton step. The gradient-boosting page explains boosting for a fixed differentiable loss; here there is no fixed loss, because the lambdas change with the ranking, and the Newton weights come from the second derivatives of a frozen pairwise cost. The learning-to-rank page lists LambdaMART among the methods and mentions the 2010 Yahoo! challenge; this page gives the targets, the weights, the leaf formula of Burges (2010) and what it is a Newton step of, and a worked round.
In plain words
We build the scoring rule as a sum of many small decision trees, one tree at a time. Before each new tree, we score every result with the trees so far and sort each list. For every result, we work out how strongly it should move up or down to improve the list, using the same pushes as LambdaRank. The new tree groups results with similar features and similar pushes. Each group gets one number, which says how far to move every result in the group. That number takes into account both the push and how sure we are about it. We add a small part of the new tree to the scores and repeat.
The problem
The input is a set of queries, each with documents and graded labels . The model is , a sum of regression trees of depth at most , with shrinkage . The goal is a high mean NDCG@. At the current scores of a query, let be the NDCG@ change of swapping and and . Freeze the weights and define the cost
The round targets and weights are the negative first and the second derivatives of :
The algorithm
LAMBDAMART(queries, M, D, η, σ, k)- 1
F(x_i) ← 0 for every document - 2
for m ← 1 to M: - 3
for each query: sort by F, get |ΔZ_ij| and ρ_ij for each pair with y_i > y_j - 4
g_i ← Σ σ |ΔZ| ρ over pairs where i is better, minus over pairs where i is worse; h_i ← Σ σ² |ΔZ| ρ (1 - ρ) - 5
fit a regression tree of depth D to the targets g by least squares, over all documents - 6
for each leaf R: γ_R ← Σ_{i ∈ R} g_i / Σ_{i ∈ R} h_i (0 if the sum of h is 0) - 7
F(x) ← F(x) + η γ_{leaf(x)} - 8
return the trees and their leaf values
Line L4 is the LambdaRank computation with the sign of a cost. Line L5 chooses the shape of the tree by least squares on , as in MART. Line L6 then replaces the least-squares means of the leaves by Newton steps, which is the difference between MART for ranking and plain gradient boosting on the lambdas. In the notation of Burges (2010), Section 7, , and , with the sign of a utility.
Example
One query has four documents with the current scores , labels , , no cutoff, and one binary feature that is 1 for documents 0 and 1 and 0 for documents 2 and 3. The ranking is and NDCG is . The pairs and their and are those of the LambdaRank example.
| document | label | leaf | new | ||||
|---|---|---|---|---|---|---|---|
| 0 | 2 | 0.5 | 0.5009 | 0.1053 | 3.1196 | 0.8120 | |
| 1 | 1 | 1.5 | -0.0038 | 0.0540 | 3.1196 | 1.8120 | |
| 2 | 0 | 1.0 | -0.0493 | 0.0219 | -4.2863 | 0.5714 | |
| 3 | 0 | 2.0 | -0.4479 | 0.0940 | -4.2863 | 1.5714 |
The only split is on the feature, so the depth-1 tree has the leaves and . Leaf has and , so ; leaf has and , so . With the new scores rank the documents , and NDCG rises to . The pair (0, 1) lies inside one leaf, so moving the leaf does not change its score difference; the exact one-dimensional Newton step for that leaf would be , not (see the proof file).
Correctness
The proof in proofs/correctness.md shows:
- Targets and weights. and for the frozen cost . The tests check both by central finite differences on 100 random queries.
- Leaf values. of line L6 minimizes the second-order model of along the move of all documents of the leaf, with the mixed second derivatives dropped. It is a diagonal Newton step, not the exact Newton step: pairs inside one leaf are counted in but do not change. The tests check each leaf of a fitted depth-2 tree against the ratio of finite-difference derivatives.
- The split. Line L5 finds the least-squares split over all features and thresholds; the tests compare it with a brute force.
- Scale. At , multiplying by divides every leaf value by , the scaling that Burges (2010) mentions.
No round provably lowers or raises NDCG, since the tree shape comes from least squares, the step is diagonal and shrunk, and the weights change with the ranking. On the planted set of the tests, where the label depends on whether both and , 30 rounds of depth-2 trees raise the mean NDCG from 0.6916 to 1.0. That is a measurement on one data set.
Proof: The LambdaMART targets, weights and leaf values are the derivatives and the diagonal Newton step of the frozen lambda costfull
Fix and a cutoff . For one query with labels and current scores , let be the absolute change of NDCG@ when documents and swap ranks, for each pair with . The LambdaRank proof gives its closed form. Freeze these weights at the current ranking and define
The cost of a round is the sum of over the queries. The code computes, for each document,
Lemma 1 (targets and weights). and . So for the LambdaRank lambdas .
Proof. Let with . Then and , because . The pair term , with , has the derivative in and in , and the second derivative in each of and . Lines L3 and L4 add exactly these amounts, with the sign of reversed.
Burges (2010), Section 7, writes and for a utility to be maximized. The code uses a cost to be minimized, so its target is and its weight is positive. The two conventions give the same step.
Lemma 2 (leaf value). Let a tree send the set of documents to one leaf. Line L6 sets
and when the denominator is 0. This is the value that minimizes the quadratic model
which is the second-order Taylor model of along the move for with the mixed second derivatives dropped.
Proof. is a parabola with positive leading coefficient when , and its derivative vanishes at . The first-order term is exact by Lemma 1. The exact second derivative of at 0 is , and keeps only the terms with .
When both documents of a pair are in , moving them together does not change , so the exact one-dimensional Newton step would not count the pair at all, while counts it twice. The leaf value of Burges's formula is therefore a diagonal Newton step, as in MART, and not the exact Newton step on the leaf. In the worked example of the page, the leaf gets , while the exact step would be ; the leaf has no pair inside it and both values are . A denominator of 0 means that no document of the leaf is in a pair with a nonzero weight, so on the leaf and is the only sensible value.
Lemma 3 (the split). For one node with the document set , line L5 returns the split that minimizes, over all features and all thresholds that split into two nonempty parts, the sum of squared errors of the targets around the mean of each part.
Proof. A threshold splits into and , and this partition depends only on which consecutive pair of distinct values of in the threshold falls between. The code tries one threshold, the midpoint, for each such pair, so it tries every distinct nonempty partition by a threshold, and keeps the one of least error. The depth-2 tree applies the same rule to each child.
Lemma 4 (scale). If is multiplied by , every is multiplied by times a factor that depends on only through , and every by times such a factor. At , where for every pair, is exactly divided by .
Proof. Read the factors off the definitions of and .
This is the scaling that Burges (2010) mentions for the leaf values.
What is not proved. Each round reduces the frozen cost only approximately: the tree is fitted by least squares, the step is a diagonal Newton step, the shrinkage scales it, and the weights change once the ranking changes. Nothing here shows that NDCG rises, and nothing bounds the error on new queries. The rise of NDCG in the tests is measured on one planted set.
The tests in impl/python/test_lambdamart.py check Lemma 1 against central finite differences of the frozen cost on 100 random queries, the leaf values of a fitted depth-2 tree against the ratio of the finite-difference derivatives summed over each leaf, Lemma 3 against a brute force over all thresholds, a query with one label value, and the worked example of the page.
Complexity
Each round sorts each query and computes the lambdas in for documents and pairs. A depth- tree on points and features costs with sorting at each level, or with presorted features or histograms of binned feature values, as production libraries use. Line L7 costs . The model has trees of at most leaves, and predicting one document costs . The code is a simple reference and tries every midpoint with a fresh sum, which is quadratic in the node size.
Properties
- Invariant to monotone feature transforms. Trees split on thresholds, so rescaling or taking the logarithm of a feature changes nothing. Linear scorers do not have this property.
- Interactions. A depth- tree models interactions of up to features. The planted rule of the tests needs depth 2.
- Uses the second derivative. The leaf step is larger where the frozen cost is flat ( small) and smaller where it is curved, unlike plain gradient boosting with a fixed step.
- Query-local targets. The targets and weights of each query depend only on that query, but the trees are shared by all queries.
- Deterministic. With a fixed tie rule for scores and splits, the output depends only on the data and the parameters.
Variants and improvements
- Histogram split finding. Binning features and summing and per bin makes split search linear in , as in LightGBM and XGBoost.
- Second-order split gain. Choose the split by the Newton gain of each child, with a regularizer, rather than by least squares on . This is common in later libraries and differs from Burges (2010), Section 7.
- Other metrics. Replace by the swap change of ERR or MAP, as in LambdaRank.
- Unbiased versions. Weight the pairs by inverse examination propensities when the labels are clicks; see unbiased learning to rank.
- Ensembles. Average several LambdaMART models trained with different seeds or subsamples; the winning 2010 Yahoo! entry was such an ensemble.
When to use it
Use LambdaMART when each query-document pair is described by a few hundred hand-made features such as BM25 scores, click counts and page quality signals, and the metric is NDCG@ or similar. It is the usual baseline on feature-based ranking benchmarks, and its strong results there are measured, not proved. When the inputs are raw text, a neural scorer such as a cross-encoder usually does better, at a much higher cost per document.
Pitfalls
- Recompute the ranks every round. Line L3 must sort by the current . Reusing the ranks of round 1 fits every later tree to stale weights.
- Zero weights. A leaf whose documents are in no pair with nonzero weight has . Line L6 must return 0 there, not divide by zero.
- Exact Newton by mistake. Computing the leaf value from the full Hessian of the leaf gives a different step from line L6. Both are defensible, but only line L6 is the formula of Burges (2010), and they differ whenever a pair lies inside a leaf.
- No shrinkage. With in line L7, the Newton step of a nearly flat leaf can be huge, as in the example, and overshoot. Use around 0.1 and more rounds.
- The sign convention. Line L4 uses for a cost. Mixing it with the utility convention without also flipping the weights moves every leaf the wrong way.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambdamart/. The authors are listed in prov/HY1P4E.jsonl.
"""LambdaMART: boosted regression trees fitted to LambdaRank lambdas.
The model is F(x) = sum over trees of eta * tree(x). In each round, for
every document i of every query, with the current scores s = F(x):
rho_ij = 1 / (1 + exp(sigma (s_i - s_j))) for y_i > y_j
g_i = sum_j sigma |dZ_ij| rho_ij - sum_j sigma |dZ_ji| rho_ji
h_i = sum over the pairs of i of sigma^2 |dZ| rho (1 - rho)
g_i is minus the derivative, and h_i the second derivative, of the cost
C = sum |dZ_ij| log(1 + exp(-sigma (s_i - s_j))) in s_i, with the weights
|dZ_ij| = |delta NDCG_ij| held fixed at the current ranking. A tree of
depth 1 or 2 is fitted to the targets g_i by least squares, and each leaf
R gets the Newton value sum of g_i / sum of h_i over the documents in R
(Burges 2010, Section 7). NDCG uses the gain 2^g - 1, the discount
1 / log2(rank + 1), and ties by index ascending.
"""
import math
def sigmoid(z):
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
e = math.exp(z)
return e / (1.0 + e)
def softplus(z):
if z > 0:
return z + math.log1p(math.exp(-z))
return math.log1p(math.exp(z))
def ranking(s):
return sorted(range(len(s)), key=lambda i: (-s[i], i))
def ideal_dcg(y, k):
return sum((2 ** g - 1) / math.log2(r + 2) for r, g in enumerate(sorted(y, reverse=True)[:k]))
def ndcg(s, y, k=None):
k = len(y) if k is None else k
ideal = ideal_dcg(y, k)
if ideal == 0:
return None
return sum((2 ** y[d] - 1) / math.log2(r + 2) for r, d in enumerate(ranking(s)[:k])) / ideal
def delta_ndcg(s, y, k=None):
"""|delta NDCG_ij| for the pairs with y_i > y_j, at the current ranking."""
n = len(y)
k = n if k is None else k
ideal = ideal_dcg(y, k)
rank = [0] * n
for r, d in enumerate(ranking(s)):
rank[d] = r + 1
disc = [1.0 / math.log2(rank[i] + 1) if rank[i] <= k else 0.0 for i in range(n)]
out = {}
for i in range(n):
for j in range(n):
if y[i] > y[j]:
out[(i, j)] = 0.0 if ideal == 0 else abs((2 ** y[i] - 2 ** y[j]) * (disc[j] - disc[i])) / ideal
return out
def frozen_cost(s, y, weights, sigma=1.0):
return sum(v * softplus(-sigma * (s[i] - s[j])) for (i, j), v in weights.items())
def targets_and_weights(s, y, sigma=1.0, k=None):
"""The targets g_i (minus the lambdas) and the Newton weights h_i of one query."""
n = len(s)
g = [0.0] * n
h = [0.0] * n
for (i, j), dz in delta_ndcg(s, y, k).items():
rho = sigmoid(-sigma * (s[i] - s[j])) # @line L3
g[i] += sigma * dz * rho # @line L4
g[j] -= sigma * dz * rho
hw = sigma * sigma * dz * rho * (1.0 - rho)
h[i] += hw
h[j] += hw
return g, h
class Tree:
"""A regression tree. A node is ('leaf', value) or ('split', f, t, left, right)."""
def __init__(self, root):
self.root = root
def leaf_of(self, x):
node, path = self.root, ""
while node[0] == "split":
if x[node[1]] <= node[2]:
node, path = node[3], path + "L"
else:
node, path = node[4], path + "R"
return path
def predict(self, x):
node = self.root
while node[0] == "split":
node = node[3] if x[node[1]] <= node[2] else node[4]
return node[1]
def sse(vals):
if not vals:
return 0.0
m = sum(vals) / len(vals)
return sum((v - m) ** 2 for v in vals)
def best_split(xs, g, idx):
"""The (feature, threshold) of least squared error on the targets, or None.
Thresholds are midpoints between consecutive distinct values. Ties of
the error keep the first (smallest feature, then smallest threshold).
"""
best = None
for f in range(len(xs[0])):
vals = sorted(set(xs[i][f] for i in idx))
for a, b in zip(vals, vals[1:]):
t = (a + b) / 2.0
left = [g[i] for i in idx if xs[i][f] <= t]
right = [g[i] for i in idx if xs[i][f] > t]
err = sse(left) + sse(right)
if best is None or err < best[0] - 1e-15:
best = (err, f, t)
return None if best is None else (best[1], best[2])
def leaf_value(idx, g, h):
"""The Newton step sum g / sum h; 0 if the leaf holds no pair."""
hs = sum(h[i] for i in idx)
return sum(g[i] for i in idx) / hs if hs > 0 else 0.0 # @line L6
def build(xs, g, h, idx, depth):
split = best_split(xs, g, idx) if depth > 0 and len(idx) > 1 else None
if split is None:
return ("leaf", leaf_value(idx, g, h))
f, t = split
left = [i for i in idx if xs[i][f] <= t]
right = [i for i in idx if xs[i][f] > t]
return ("split", f, t, build(xs, g, h, left, depth - 1), build(xs, g, h, right, depth - 1))
def flatten(queries):
xs, owner = [], []
for q, (qx, _) in enumerate(queries):
for x in qx:
xs.append(x)
owner.append(q)
return xs, owner
def round_targets(queries, scores, sigma=1.0, k=None):
"""Targets and weights for all documents, in the order of flatten()."""
g, h = [], []
for (qx, y), s in zip(queries, scores):
gq, hq = targets_and_weights(s, y, sigma, k)
g += gq
h += hq
return g, h
def fit(queries, rounds=20, depth=2, eta=0.1, sigma=1.0, k=None):
"""Train LambdaMART from F = 0. Returns the trees and the mean NDCG@k per round."""
xs, _ = flatten(queries)
scores = [[0.0] * len(qx) for qx, _ in queries] # @line L1
trees = []
history = [mean_ndcg(queries, scores, k)]
for _ in range(rounds): # @line L2
g, h = round_targets(queries, scores, sigma, k)
tree = Tree(build(xs, g, h, list(range(len(xs))), depth)) # @line L5
trees.append(tree)
scores = [[s + eta * tree.predict(x) for s, x in zip(sq, qx)] for sq, (qx, _) in zip(scores, queries)] # @line L7
history.append(mean_ndcg(queries, scores, k))
return trees, history # @line L8
def predict(trees, x, eta=0.1):
return sum(eta * t.predict(x) for t in trees)
def mean_ndcg(queries, scores, k=None):
vals = [ndcg(s, y, k) for s, (_, y) in zip(scores, queries)]
vals = [v for v in vals if v is not None]
return sum(vals) / len(vals) if vals else None
test_lambdamart.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambdamart/. The authors are listed in prov/HY1P4E.jsonl.
import itertools
import random
from lambdamart import (
Tree,
build,
delta_ndcg,
fit,
flatten,
frozen_cost,
leaf_value,
ndcg,
round_targets,
sse,
targets_and_weights,
)
def planted(seed, n_queries=8, n_docs=6, d=3):
"""Labels from a hidden rule that a linear scorer cannot fit: x0 * x1 > 0."""
rng = random.Random(seed)
queries = []
for _ in range(n_queries):
xs = [[round(rng.uniform(-1, 1), 3) for _ in range(d)] for _ in range(n_docs)]
y = [2 if x[0] > 0 and x[1] > 0 else (1 if x[0] > 0 else 0) for x in xs]
queries.append((xs, y))
return queries
def derivatives_by_finite_differences(s, y, sigma, k, h=1e-4):
"""-dC/ds_i and d2C/ds_i2 of the frozen cost, by central differences."""
weights = delta_ndcg(s, y, k)
c0 = frozen_cost(s, y, weights, sigma)
g, hh = [], []
for i in range(len(s)):
a = list(s)
b = list(s)
a[i] += h
b[i] -= h
ca = frozen_cost(a, y, weights, sigma)
cb = frozen_cost(b, y, weights, sigma)
g.append(-(ca - cb) / (2 * h))
hh.append((ca - 2 * c0 + cb) / (h * h))
return g, hh
def test_page_example():
# One query: labels 2, 1, 0, 0 and scores 0.5, 1.5, 1.0, 2.0, sigma = 1.
s = [0.5, 1.5, 1.0, 2.0]
y = [2, 1, 0, 0]
g, h = targets_and_weights(s, y)
assert [round(v, 4) for v in g] == [0.5009, -0.0038, -0.0493, -0.4479]
assert [round(v, 4) for v in h] == [0.1053, 0.0540, 0.0219, 0.0940]
assert round(leaf_value([0, 1], g, h), 4) == 3.1196
assert round(leaf_value([2, 3], g, h), 4) == -4.2863
def test_targets_and_weights_by_finite_differences():
rng = random.Random(1)
for _ in range(100):
n = rng.randint(2, 6)
y = [rng.randint(0, 3) for _ in range(n)]
s = [rng.uniform(-2, 2) for _ in range(n)]
sigma = rng.choice([0.5, 1.0, 2.0])
k = rng.choice([None, 2, 3])
if ndcg(s, y, k) is None:
continue
g, h = targets_and_weights(s, y, sigma, k)
gn, hn = derivatives_by_finite_differences(s, y, sigma, k)
assert all(abs(a - b) < 1e-6 for a, b in zip(g, gn))
assert all(abs(a - b) < 1e-4 for a, b in zip(h, hn))
def test_leaf_values_against_direct_computation():
queries = planted(seed=2)
rng = random.Random(3)
scores = [[rng.uniform(-1, 1) for _ in qx] for qx, _ in queries]
xs, _ = flatten(queries)
g, h = round_targets(queries, scores)
tree = Tree(build(xs, g, h, list(range(len(xs))), depth=2))
# Direct computation: finite-difference derivatives, grouped by leaf.
gd, hd = [], []
for (qx, y), s in zip(queries, scores):
a, b = derivatives_by_finite_differences(s, y, 1.0, None)
gd += a
hd += b
groups = {}
for i, x in enumerate(xs):
groups.setdefault(tree.leaf_of(x), []).append(i)
for path, idx in groups.items():
direct = sum(gd[i] for i in idx) / sum(hd[i] for i in idx)
assert abs(tree.predict(xs[idx[0]]) - direct) < 1e-4
def test_split_is_least_squares():
rng = random.Random(4)
xs = [[round(rng.uniform(0, 1), 2), round(rng.uniform(0, 1), 2)] for _ in range(9)]
g = [rng.uniform(-1, 1) for _ in xs]
h = [1.0] * len(xs)
root = build(xs, g, h, list(range(len(xs))), depth=1)
_, f, t, _, _ = root
got = sse([g[i] for i in range(9) if xs[i][f] <= t]) + sse([g[i] for i in range(9) if xs[i][f] > t])
best = min(
sse([g[i] for i in range(9) if xs[i][ff] <= tt]) + sse([g[i] for i in range(9) if xs[i][ff] > tt])
for ff, tt in itertools.product(range(2), sorted(set(v for x in xs for v in x)))
)
assert got <= best + 1e-12
def test_query_with_one_label_gets_no_push():
g, h = targets_and_weights([0.1, 0.2, 0.3], [1, 1, 1])
assert g == [0.0, 0.0, 0.0] and h == [0.0, 0.0, 0.0]
assert leaf_value([0, 1, 2], g, h) == 0.0
def test_training_on_planted_set():
# Measured on this planted set, not a theorem: depth 2 trees learn the
# interaction x0 * x1 > 0 that a linear scorer cannot express.
queries = planted(seed=5)
trees, history = fit(queries, rounds=30, depth=2, eta=0.3)
assert history[-1] > history[0]
assert history[-1] > 0.95
History
Friedman's MART is the gradient boosting machine with regression trees and a Newton step per leaf. Burges and colleagues had defined the LambdaRank gradients for neural networks, and Wu, Burges, Svore and Gao (2010) fitted MART to those gradients, which gave LambdaMART. In his 2010 overview, Burges described the algorithm in full and noted that an ensemble of LambdaMART rankers won Track 1 of the 2010 Yahoo! Learning to Rank Challenge. Boosted tree libraries later added LambdaMART objectives, and it became the common reference model for feature-based ranking.
References
- Qiang Wu, Christopher J. C. Burges, Krysta M. Svore and Jianfeng Gao, Adapting boosting for information retrieval measures, Information Retrieval 13(3), 2010, pp. 254-270 (LambdaMART as boosted trees fitted to the lambdas, and its comparison with LambdaRank)
- Christopher J. C. Burges, From RankNet to LambdaRank to LambdaMART: an overview, Microsoft Research Technical Report MSR-TR-2010-82, 2010, Sections 5 and 6 (MART and its Newton step in each leaf) and Section 7 (the LambdaMART algorithm, with targets y_i = lambda_i, weights w_i = dy_i/dF and leaf values sum y over sum w)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HY1P4E Edit this page History Report an error Markdown