Algorithmadvanced
LambdaRank
Also called lambda gradients for ranking.
Scales each pairwise RankNet gradient by the change in nDCG that swapping the pair would cause, to optimize the metric directly.
- Solves
- Learning to rank
- Time
- O(T (N log N + P + N d)) totalO(N log N + P + N d) per_step
- Space
- O(N + d) extra
- Where
- N = the number of documents; P = the number of preferred pairs; T = the number of steps; d = the number of features
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chris Burges, Robert Ragno, Quoc Viet Le, 2006
LambdaRank trains a scoring function for learning to rank by gradient steps whose direction is defined directly, not derived from a cost. It starts from the per-pair gradients of RankNet and multiplies each one by , the absolute change of NDCG if documents and swapped their ranks. Pairs near the top of the list, where NDCG is sensitive, get large pushes, and pairs deep in the list get small ones or none. The learning-to-rank page shows one such step on three documents; this page gives the algorithm with a cutoff , the closed form of , the exact sense in which the lambdas are a gradient, and why they are not the gradient of NDCG. Fitting trees to the same lambdas gives LambdaMART.
In plain words
RankNet treats every wrongly ordered pair of results the same. But users look mostly at the top of a result list, so a mistake at the top costs much more than a mistake near the bottom. LambdaRank keeps the pushes of RankNet and makes each one bigger or smaller. For each pair, it asks how much the quality score of the whole list would change if the two results traded places. A pair whose swap would change the list quality a lot gets a strong push. A pair whose swap changes little gets a weak push. The method never needs the quality score to be smooth, because it only uses these pushes.
The problem
The input is a set of queries; query has documents with features and graded labels . The scorer is ; the code uses . The ranking sorts by score, highest first, ties to the smaller index, and is the rank of document . NDCG@ uses the gain and the discount for and 0 beyond. The goal is a high mean NDCG@ over the queries. NDCG depends on the scores only through the ranking, so it is piecewise constant in and its gradient is zero wherever it exists. Gradient methods cannot use it directly.
For a pair with , the swap change has the closed form
The algorithm
With , the RankNet gradient of a pair in is . LambdaRank uses
and moves against .
LAMBDARANK(queries, σ, k, η, T)- 1
w ← 0 - 2
repeat T times: - 3
for each query: s_i ← w · x_i, sort to get the ranks r_i and IDCG@k - 4
for each pair with y_i > y_j: λ_ij ← -σ |ΔZ_ij| / (1 + e^{σ (s_i - s_j)}) - 5
λ_i ← Σ_j λ_ij - Σ_j λ_ji - 6
w ← w - η Σ_queries Σ_i λ_i x_i - 7
return w
Line L3 is the only place where the ranking enters. Line L4 is the RankNet gradient times the swap change. Lines L5 and L6 are the factorization of RankNet: one sum per document, then one gradient per document.
Example
One query has four documents with scores and labels , with and no cutoff. The ranking is (document 3 first), so the best document is last. NDCG is , with IDCG .
| pair | RankNet | |||
|---|---|---|---|---|
| (0, 1) | -1.0 | -0.7311 | 0.1103 | -0.0806 |
| (0, 2) | -0.5 | -0.6225 | 0.0573 | -0.0357 |
| (0, 3) | -1.5 | -0.8176 | 0.4704 | -0.3846 |
| (1, 2) | 0.5 | -0.3775 | 0.0361 | -0.0136 |
| (1, 3) | -0.5 | -0.6225 | 0.1016 | -0.0633 |
The pair (0, 3) holds the best document at rank 4 and a document of label 0 at rank 1, so its swap change is by far the largest. The lambdas are . Plain RankNet gives on the same scores; it pushes document 1 up, while LambdaRank pushes it slightly down, because its pairs matter little for NDCG compared with the push that document 0 needs. With the cutoff the lambdas are : they are larger, because IDCG@2 is smaller, and they act mainly on the two documents that are or should be in the top 2.
Correctness
LambdaRank has no cost that it provably decreases, and the proof in proofs/correctness.md states what does hold.
- The swap change. The closed form above equals the change of NDCG@ computed by swapping the two documents and recomputing. Pairs with both ranks beyond get .
- A gradient on each region. On each open region of score vectors with one fixed ranking, the weights are constant, and the lambdas are the exact gradient of the weighted RankNet cost , a convex function of . This is the observation of Burges (2010), Section 4.3. Across region boundaries the weights jump.
- Not the gradient of NDCG. NDCG is constant on each region, so the lambdas are not its gradient. That steps along the lambdas raise NDCG is an experimental finding, which Burges (2010), Section 4.1, calls empirical.
The tests check each against a finite-difference RankNet gradient times the NDCG change of the swap computed by sorting, on 200 random queries. The rise of NDCG during training on a planted set is measured, not proved.
Proof: The closed form of the swap change of NDCG, and the lambdas as a local gradientfull
One query has documents with labels and scores . The ranking sorts by score, highest first, with ties to the smaller index; is the rank of document . The gain is , and for a cutoff the discount is if and otherwise. Then , is the DCG@ of the order by label, and when . This is the NDCG with the gain .
For a pair with , is the absolute change of NDCG@ when documents and swap ranks and every other document keeps its rank.
Lemma 1 (closed form).
Proof. The swap leaves the ideal DCG and the terms of all other documents unchanged. Before the swap the two terms are , after it . The difference is . Divide by .
Two consequences follow. If both ranks are beyond , and the lambda of the pair is 0, so pairs deep in the list do not move. If , the pair is not formed at all, since only pairs with enter.
Definition (the lambdas). With , the RankNet gradient of the pair cost in is (see the RankNet proof). LambdaRank sets
This is Equation (6) of Burges (2010), Section 4.1, written with the sign of a cost to minimize. Lines L3 to L5 of the code compute the ranks, then by Lemma 1, then . Each enters and with opposite signs, so the lambdas of a query sum to zero.
Lemma 2 (the lambdas are a gradient where the ranking is fixed). Let be the open set of score vectors with no ties and the same ranking as a given . On the weights are constant, and the vector is the gradient of
Proof. On every rank is constant, so by Lemma 1 every weight is constant. is then a weighted RankNet cost with fixed weights, and the computation of Lemma 1 of the RankNet proof, term by term, gives .
So on each region of fixed ranking, a LambdaRank step is a gradient step on a convex function of the scores, which is the observation of Burges (2010), Section 4.3. At the boundary of the regions, where two scores tie, the weights jump, and no single function has the lambdas as its gradient everywhere.
What the lambdas are not. NDCG@ is constant on each region , so its gradient in is zero wherever it exists. The lambdas are therefore not the gradient of NDCG. The claim that steps along the lambdas raise NDCG is supported by experiments, which Burges (2010) calls empirical. Wang et al. (2018) later placed LambdaRank in a framework of well-defined losses and described it as the minimization of a coarse upper bound on an NDCG-based cost; that analysis is not repeated here.
The tests in impl/python/test_lambdarank.py check, on 200 random queries with several and , that each equals a finite-difference RankNet gradient times the NDCG change of the swap computed by sorting the swapped list. They also check Lemma 1 against the direct swap, Lemma 2 against finite differences of , the zero lambdas below the cutoff, the zero sum, and the worked example of the page. The rise of NDCG during training is measured on one planted set and is not a theorem.
Complexity
One step sorts each query, , and computes IDCG. Each pair then costs by the closed form, so the lambdas cost for pairs, and line L6 costs for documents. The total per step is . Recomputing NDCG for each swap would cost per pair, in total, which the closed form avoids. With a cutoff , only pairs with at least one rank at most have nonzero lambdas, which leaves pairs per query. The extra space is .
Properties
- Zero sum. The lambdas of a query sum to zero, as in RankNet.
- Local to the top. With a cutoff , documents whose pairs all lie below rank get no push.
- Scale. Each , so every .
- Any metric with a swap change. The same recipe works with the swap change of ERR, MRR or MAP in place of NDCG.
- No cost function in general. The lambdas are a gradient only inside each region of fixed ranking. Line searches and convergence tests that need a cost value use of the current region, which changes when the ranking changes.
Variants and improvements
- LambdaMART fits gradient-boosted regression trees to the lambdas, with a Newton step in each leaf, and is the most used form.
- LambdaLoss. Wang et al. (2018) give a family of well-defined losses that contains LambdaRank as one case, and propose new losses inside the family.
- Other metrics. Replace by the swap change of the metric that matters, for example ERR when a user is likely to stop at the first very good result.
- Neural scorers. The original setting: line L6 becomes back-propagation of through the network.
When to use it
Use LambdaRank when the target metric weights the top of the list, such as NDCG@10, and the scorer is trained by gradients, for example a neural network. With hand-made features and tree models, use LambdaMART. If the metric weights all pairs equally, as AUC does, RankNet or the Ranking SVM is simpler and the weights add nothing. The advantage of LambdaRank over RankNet on NDCG is a measured result.
Pitfalls
- The ranks come from the current scores. Line L3 must sort by the current , not by the labels or by stale scores. With the ideal ranks, every pair of the closed form is computed at the wrong positions.
- Ties in the scores. At the start, all scores are 0. Line L3 needs a fixed tie rule, such as the smaller index first, or the ranks and the lambdas change from run to run.
- Queries with no relevant document. IDCG@ is 0 when every label in the top of the ideal order is 0. Line L4 must skip such queries rather than divide by zero.
- Treating the lambdas as a cost. Monitoring or a RankNet cost does not track NDCG. Monitor NDCG@ on validation queries.
- The sign. Line L4 gives the gradient of a cost to minimize, so line L6 subtracts it. Adding it moves every pair the wrong way. Texts that write the lambdas as the direction to move up use the opposite sign, so check the convention before mixing code.
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/lambdarank/. The authors are listed in prov/6YEMD5.jsonl.
"""LambdaRank lambdas for a linear scoring function s = w . x.
For a pair (i, j) of one query with y[i] > y[j], RankNet has the gradient
dC_ij/ds_i = -sigma / (1 + exp(sigma (s_i - s_j))).
LambdaRank multiplies it by |delta NDCG_ij|, the change of NDCG@k when the
documents i and j swap their positions in the current ranking, and sums
the results per document:
lambda_i = sum over j with y_i > y_j of lambda_ij
- sum over j with y_j > y_i of lambda_ji.
The lambdas are defined directly. They are not the gradient of NDCG, which
is flat almost everywhere. The update is w <- w - eta sum_i lambda_i x_i.
NDCG uses the gain 2^g - 1 and the discount 1 / log2(rank + 1), and the
ranking sorts by score descending, then by index ascending.
"""
import math
def dot(a, b):
return sum(p * q for p, q in zip(a, b))
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 scores(w, xs):
return [dot(w, x) for x in xs]
def ranking(s):
"""Indices by score descending, then index ascending."""
return sorted(range(len(s)), key=lambda i: (-s[i], i))
def gain(g):
return 2 ** g - 1
def discount(r):
"""The discount of rank r (r starts at 1)."""
return 1.0 / math.log2(r + 1)
def ideal_dcg(y, k):
return sum(gain(g) * discount(r + 1) for r, g in enumerate(sorted(y, reverse=True)[:k]))
def ndcg_of_order(order, y, k=None):
"""NDCG@k of a given order of the documents; None if no positive label."""
k = len(y) if k is None else k
ideal = ideal_dcg(y, k)
if ideal == 0:
return None
return sum(gain(y[d]) * discount(r + 1) for r, d in enumerate(order[:k])) / ideal
def ndcg(s, y, k=None):
return ndcg_of_order(ranking(s), y, k)
def delta_ndcg(s, y, k=None):
"""|delta NDCG_ij| for every pair, by the closed form.
With r_i the rank of i in the current ranking, the swap changes DCG@k
by (gain(y_i) - gain(y_j)) (D(r_j) - D(r_i)), where D(r) is the
discount of rank r if r <= k and 0 otherwise.
"""
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)): # @line L3
rank[d] = r + 1
disc = [discount(rank[i]) 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((gain(y[i]) - gain(y[j])) * (disc[j] - disc[i])) / ideal
return out
def ranknet_pair_gradient(s, i, j, sigma=1.0):
"""dC_ij/ds_i of the RankNet cost log(1 + exp(-sigma (s_i - s_j)))."""
return -sigma * sigmoid(-sigma * (s[i] - s[j]))
def pair_lambdas(s, y, sigma=1.0, k=None):
"""lambda_ij for every pair with y_i > y_j."""
dz = delta_ndcg(s, y, k)
return {(i, j): ranknet_pair_gradient(s, i, j, sigma) * v for (i, j), v in dz.items()} # @line L4
def lambdas(s, y, sigma=1.0, k=None):
"""The per-document lambdas (Burges 2010, Section 4.1)."""
lam = [0.0] * len(s)
for (i, j), v in pair_lambdas(s, y, sigma, k).items():
lam[i] += v # @line L5
lam[j] -= v
return lam
def frozen_cost(s, y, weights, sigma=1.0):
"""sum of |delta Z_ij| log(1 + exp(-sigma (s_i - s_j))) with fixed weights.
For scores near s with the same ranking, the gradient of this function
in s is the lambda vector (Burges 2010, Section 4.3).
"""
return sum(v * softplus(-sigma * (s[i] - s[j])) for (i, j), v in weights.items())
def direction(w, queries, sigma=1.0, k=None):
"""sum over queries and documents of lambda_i x_i."""
g = [0.0] * len(w)
for xs, y in queries:
lam = lambdas(scores(w, xs), y, sigma, k)
for li, x in zip(lam, xs):
for c in range(len(w)):
g[c] += li * x[c]
return g
def train(queries, d, eta=0.1, sigma=1.0, k=None, steps=100):
"""Full-batch steps w <- w - eta * direction, from w = 0.
Returns w and the mean NDCG@k after each step. Nothing guarantees that
the mean NDCG grows; it is measured.
"""
w = [0.0] * d # @line L1
history = [mean_ndcg(w, queries, k)]
for _ in range(steps): # @line L2
g = direction(w, queries, sigma, k)
w = [a - eta * b for a, b in zip(w, g)] # @line L6
history.append(mean_ndcg(w, queries, k))
return w, history # @line L7
def mean_ndcg(w, queries, k=None):
vals = [ndcg(scores(w, xs), y, k) for xs, y in queries]
vals = [v for v in vals if v is not None]
return sum(vals) / len(vals) if vals else None
test_lambdarank.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambdarank/. The authors are listed in prov/6YEMD5.jsonl.
import math
import random
from lambdarank import (
delta_ndcg,
frozen_cost,
lambdas,
ndcg,
ndcg_of_order,
pair_lambdas,
ranking,
softplus,
train,
)
def planted(seed, n_queries=8, n_docs=6, d=3):
rng = random.Random(seed)
w_true = [rng.uniform(-1, 1) for _ in range(d)]
queries = []
for _ in range(n_queries):
xs = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(n_docs)]
t = [sum(a * b for a, b in zip(w_true, x)) + rng.gauss(0, 0.1) for x in xs]
order = sorted(t)
y = [0 if v < order[2] else (1 if v < order[4] else 2) for v in t]
queries.append((xs, y))
return queries
def swapped_ndcg_change(s, y, i, j, k=None):
"""|NDCG after swapping the positions of i and j - NDCG now|, computed directly."""
order = ranking(s)
a, b = order.index(i), order.index(j)
new = list(order)
new[a], new[b] = new[b], new[a]
return abs(ndcg_of_order(new, y, k) - ndcg_of_order(order, y, k))
def ranknet_pair_gradient_numeric(s, i, j, sigma, h=1e-6):
def c(v):
return softplus(-sigma * (v[i] - v[j]))
a = list(s)
b = list(s)
a[i] += h
b[i] -= h
return (c(a) - c(b)) / (2 * h)
def test_page_example():
# Four documents with labels 2, 1, 0, 0 and scores 0.5, 1.5, 1.0, 2.0.
s = [0.5, 1.5, 1.0, 2.0]
y = [2, 1, 0, 0]
assert ranking(s) == [3, 1, 2, 0]
assert abs(ndcg(s, y) - 0.5296) < 1e-4
lam = lambdas(s, y)
assert [round(v, 4) for v in lam] == [-0.5009, 0.0038, 0.0493, 0.4479]
lam2 = lambdas(s, y, k=2)
assert [round(v, 4) for v in lam2] == [-0.9296, 0.1252, 0.0656, 0.7388]
def test_lambda_is_ranknet_gradient_times_swap_change():
rng = random.Random(1)
for trial in range(200):
n = rng.randint(2, 7)
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, 1, 2, 3, 5])
if ndcg(s, y, k) is None:
continue
lam = pair_lambdas(s, y, sigma, k)
for (i, j), v in lam.items():
direct = ranknet_pair_gradient_numeric(s, i, j, sigma) * swapped_ndcg_change(s, y, i, j, k)
assert abs(v - direct) < 1e-6
def test_closed_form_delta_equals_direct_swap():
rng = random.Random(2)
for _ in range(200):
n = rng.randint(2, 7)
y = [rng.randint(0, 3) for _ in range(n)]
s = [rng.uniform(-2, 2) for _ in range(n)]
k = rng.choice([None, 1, 2, 4])
if ndcg(s, y, k) is None:
continue
for (i, j), v in delta_ndcg(s, y, k).items():
assert abs(v - swapped_ndcg_change(s, y, i, j, k)) < 1e-12
def test_lambdas_are_gradient_of_frozen_cost():
rng = random.Random(3)
h = 1e-6
for _ in range(50):
n = rng.randint(2, 6)
y = [rng.randint(0, 2) for _ in range(n)]
s = [rng.uniform(-2, 2) for _ in range(n)]
if ndcg(s, y) is None:
continue
weights = delta_ndcg(s, y)
lam = lambdas(s, y)
for c in range(n):
a = list(s)
b = list(s)
a[c] += h
b[c] -= h
num = (frozen_cost(a, y, weights) - frozen_cost(b, y, weights)) / (2 * h)
assert abs(num - lam[c]) < 1e-6
def test_pairs_below_cutoff_get_zero():
s = [4.0, 3.0, 2.0, 1.0]
y = [0, 0, 1, 2]
lam = pair_lambdas(s, y, k=2)
assert lam[(3, 2)] == 0.0
assert lam[(3, 0)] != 0.0
def test_lambdas_sum_to_zero():
rng = random.Random(4)
for _ in range(50):
y = [rng.randint(0, 3) for _ in range(5)]
s = [rng.uniform(-1, 1) for _ in range(5)]
assert abs(sum(lambdas(s, y))) < 1e-12
def test_training_on_planted_set():
# Measured on this planted set, not a theorem.
queries = planted(seed=5)
w, history = train(queries, 3, eta=0.5, steps=60)
assert history[-1] > history[0]
assert max(history) > 0.9
def test_no_relevant_document():
assert ndcg([1.0, 2.0], [0, 0]) is None
assert lambdas([1.0, 2.0], [0, 0]) == [0.0, 0.0]
assert math.isclose(ndcg([2.0, 1.0], [1, 0]), 1.0)
History
Burges, Ragno and Le (2006) observed that one does not need a smooth cost to train a ranker by gradient descent: it is enough to specify the gradient of each document's score, and they chose the RankNet gradient times the NDCG change of a swap. Burges (2010) reviewed the method together with RankNet and LambdaMART, stated when the lambdas are the gradient of a cost, and called the optimization of NDCG empirical. Wang et al. (2018) later embedded LambdaRank in a framework of well-defined losses.
References
- Christopher J. C. Burges, Robert Ragno and Quoc Viet Le, Learning to rank with nonsmooth cost functions, Advances in Neural Information Processing Systems 19 (NIPS 2006), MIT Press, 2007, pp. 193-200 (defining the gradients of a nonsmooth ranking cost directly, with NDCG as the main case)
- Christopher J. C. Burges, From RankNet to LambdaRank to LambdaMART: an overview, Microsoft Research Technical Report MSR-TR-2010-82, 2010, Section 4.1 and Equation (6) (the lambdas scaled by the NDCG change of a swap, called empirically optimizing NDCG) and Section 4.3 (when the lambdas are a gradient)
- Xuanhui Wang, Cheng Li, Nadav Golbandi, Michael Bendersky and Marc Najork, The LambdaLoss framework for ranking metric optimization, Proceedings of the 27th ACM CIKM, 2018, pp. 1313-1322 (a loss framework in which LambdaRank is a special case)
Where this leads
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 6YEMD5 Edit this page History Report an error Markdown