Algorithm Search⌘K

Algorithmadvanced

LambdaMART

Also called lambda-gradient boosted trees.

Fits gradient-boosted regression trees to LambdaRank gradients, a strong standard ranker on feature-based benchmarks.

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
Properties
deterministicnot exactofflineiterative
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 x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb R^d and graded labels yiy_i. The model is F(x)=η∑m=1Mfm(x)F(x) = \eta \sum_{m=1}^{M} f_m(x), a sum of regression trees fmf_m of depth at most DD, with shrinkage η∈(0,1]\eta \in (0, 1]. The goal is a high mean NDCG@kk. At the current scores s=F(x)s = F(x) of a query, let ∣ΔZij∣|\Delta Z_{ij}| be the NDCG@kk change of swapping ii and jj and ρij=1/(1+eσ(si−sj))\rho_{ij} = 1/(1 + e^{\sigma(s_i - s_j)}). Freeze the weights ∣ΔZij∣|\Delta Z_{ij}| and define the cost

C(s)=∑(i,j):yi>yj∣ΔZij∣log⁡(1+e−σ(si−sj)).C(s) = \sum_{(i,j) : y_i > y_j} |\Delta Z_{ij}| \log\left(1 + e^{-\sigma (s_i - s_j)}\right).

The round targets and weights are the negative first and the second derivatives of CC:

gi=−∂C∂si=−λi,hi=∂2C∂si2=∑pairs p∋iσ2∣ΔZp∣ ρp(1−ρp).g_i = -\frac{\partial C}{\partial s_i} = -\lambda_i, \qquad h_i = \frac{\partial^2 C}{\partial s_i^2} = \sum_{\text{pairs } p \ni i} \sigma^2 |\Delta Z_p|\, \rho_p (1 - \rho_p).

The algorithm

  1. LAMBDAMART(queries, M, D, η, σ, k)
  2. 1F(x_i) ← 0 for every document
  3. 2for m ← 1 to M:
  4. 3for each query: sort by F, get |ΔZ_ij| and ρ_ij for each pair with y_i > y_j
  5. 4g_i ← Σ σ |ΔZ| ρ over pairs where i is better, minus over pairs where i is worse; h_i ← Σ σ² |ΔZ| ρ (1 - ρ)
  6. 5fit a regression tree of depth D to the targets g by least squares, over all documents
  7. 6for each leaf R: γ_R ← Σ_{i ∈ R} g_i / Σ_{i ∈ R} h_i (0 if the sum of h is 0)
  8. 7F(x) ← F(x) + η γ_{leaf(x)}
  9. 8return 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 gg, 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, yi=λiy_i = \lambda_i, wi=∂yi/∂Fw_i = \partial y_i / \partial F and γ=∑yi/∑wi\gamma = \sum y_i / \sum w_i, with the sign of a utility.

Example

One query has four documents with the current scores s=(0.5,1.5,1.0,2.0)s = (0.5, 1.5, 1.0, 2.0), labels (2,1,0,0)(2, 1, 0, 0), σ=1\sigma = 1, no cutoff, and one binary feature that is 1 for documents 0 and 1 and 0 for documents 2 and 3. The ranking is 3,1,2,03, 1, 2, 0 and NDCG is 0.52960.5296. The pairs and their ρ\rho and ∣ΔZ∣|\Delta Z| are those of the LambdaRank example.

document label ss gig_i hih_i leaf γ\gamma new ss
0 2 0.5 0.5009 0.1053 {0,1}\{0, 1\} 3.1196 0.8120
1 1 1.5 -0.0038 0.0540 {0,1}\{0, 1\} 3.1196 1.8120
2 0 1.0 -0.0493 0.0219 {2,3}\{2, 3\} -4.2863 0.5714
3 0 2.0 -0.4479 0.0940 {2,3}\{2, 3\} -4.2863 1.5714

The only split is on the feature, so the depth-1 tree has the leaves {0,1}\{0, 1\} and {2,3}\{2, 3\}. Leaf {0,1}\{0, 1\} has ∑g=0.4971\sum g = 0.4971 and ∑h=0.1594\sum h = 0.1594, so γ=3.1196\gamma = 3.1196; leaf {2,3}\{2, 3\} has ∑g=−0.4971\sum g = -0.4971 and ∑h=0.1160\sum h = 0.1160, so γ=−4.2863\gamma = -4.2863. With η=0.1\eta = 0.1 the new scores rank the documents 1,3,0,21, 3, 0, 2, and NDCG rises to 0.68850.6885. 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 4.28634.2863, not 3.11963.1196 (see the proof file).

Correctness

The proof in proofs/correctness.md shows:

  • Targets and weights. gi=−∂C/∂sig_i = -\partial C / \partial s_i and hi=∂2C/∂si2h_i = \partial^2 C / \partial s_i^2 for the frozen cost CC. The tests check both by central finite differences on 100 random queries.
  • Leaf values. γR\gamma_R of line L6 minimizes the second-order model of CC 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 ∑h\sum h 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 s=0s = 0, multiplying σ\sigma by cc divides every leaf value by cc, the 1/σ1/\sigma scaling that Burges (2010) mentions.

No round provably lowers CC 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 x0>0x_0 > 0 and x1>0x_1 > 0, 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 σ>0\sigma > 0 and a cutoff kk. For one query with labels yy and current scores s=F(x)s = F(x), let ∣ΔZij∣|\Delta Z_{ij}| be the absolute change of NDCG@kk when documents ii and jj swap ranks, for each pair with yi>yjy_i > y_j. The LambdaRank proof gives its closed form. Freeze these weights at the current ranking and define

C(s)=∑(i,j):yi>yj∣ΔZij∣log⁡(1+e−σ(si−sj)),ρij=11+eσ(si−sj).C(s) = \sum_{(i, j) : y_i > y_j} |\Delta Z_{ij}| \log\left(1 + e^{-\sigma (s_i - s_j)}\right), \qquad \rho_{ij} = \frac{1}{1 + e^{\sigma (s_i - s_j)}}.

The cost of a round is the sum of CC over the queries. The code computes, for each document,

gi=∑j:yi>yjσ∣ΔZij∣ρij−∑j:yj>yiσ∣ΔZji∣ρji,hi=∑pairs p∋iσ2∣ΔZp∣ρp(1−ρp).g_i = \sum_{j : y_i > y_j} \sigma |\Delta Z_{ij}| \rho_{ij} - \sum_{j : y_j > y_i} \sigma |\Delta Z_{ji}| \rho_{ji}, \qquad h_i = \sum_{\text{pairs } p \ni i} \sigma^2 |\Delta Z_p| \rho_p (1 - \rho_p).

Lemma 1 (targets and weights). gi=−∂C/∂sig_i = -\partial C / \partial s_i and hi=∂2C/∂si2h_i = \partial^2 C / \partial s_i^2. So gi=−λig_i = -\lambda_i for the LambdaRank lambdas λi\lambda_i.

Proof. Let c(o)=log⁡(1+e−σo)c(o) = \log(1 + e^{-\sigma o}) with o=si−sjo = s_i - s_j. Then c′(o)=−σρc'(o) = -\sigma \rho and c′′(o)=σ2ρ(1−ρ)c''(o) = \sigma^2 \rho (1 - \rho), because dρ/do=−σρ(1−ρ)d\rho / do = -\sigma \rho (1 - \rho). The pair term v c(si−sj)v\, c(s_i - s_j), with v=∣ΔZij∣v = |\Delta Z_{ij}|, has the derivative −σvρ-\sigma v \rho in sis_i and +σvρ+\sigma v \rho in sjs_j, and the second derivative σ2vρ(1−ρ)\sigma^2 v \rho (1 - \rho) in each of sis_i and sjs_j. Lines L3 and L4 add exactly these amounts, with the sign of gg reversed. □\square

Burges (2010), Section 7, writes yi=λiy_i = \lambda_i and wi=∂yi/∂Fw_i = \partial y_i / \partial F for a utility to be maximized. The code uses a cost to be minimized, so its target is gi=−λig_i = -\lambda_i and its weight hih_i is positive. The two conventions give the same step.

Lemma 2 (leaf value). Let a tree send the set RR of documents to one leaf. Line L6 sets

γR=∑i∈Rgi∑i∈Rhi,\gamma_R = \frac{\sum_{i \in R} g_i}{\sum_{i \in R} h_i},

and γR=0\gamma_R = 0 when the denominator is 0. This is the value γ\gamma that minimizes the quadratic model

qR(γ)=C(s)−γ∑i∈Rgi+γ22∑i∈Rhi,q_R(\gamma) = C(s) - \gamma \sum_{i \in R} g_i + \frac{\gamma^2}{2} \sum_{i \in R} h_i,

which is the second-order Taylor model of CC along the move si←si+γs_i \leftarrow s_i + \gamma for i∈Ri \in R with the mixed second derivatives dropped.

Proof. qRq_R is a parabola with positive leading coefficient when ∑Rhi>0\sum_R h_i > 0, and its derivative −∑Rgi+γ∑Rhi-\sum_R g_i + \gamma \sum_R h_i vanishes at γR\gamma_R. The first-order term is exact by Lemma 1. The exact second derivative of γ↦C(s+γ1R)\gamma \mapsto C(s + \gamma \mathbf 1_R) at 0 is ∑i,l∈R∂2C/∂si∂sl\sum_{i, l \in R} \partial^2 C / \partial s_i \partial s_l, and qRq_R keeps only the terms with i=li = l. □\square

When both documents of a pair are in RR, moving them together does not change si−sjs_i - s_j, so the exact one-dimensional Newton step would not count the pair at all, while ∑Rhi\sum_R h_i 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 {0,1}\{0, 1\} gets γ=3.1196\gamma = 3.1196, while the exact step would be 4.28634.2863; the leaf {2,3}\{2, 3\} has no pair inside it and both values are −4.2863-4.2863. A denominator of 0 means that no document of the leaf is in a pair with a nonzero weight, so gi=0g_i = 0 on the leaf and γ=0\gamma = 0 is the only sensible value.

Lemma 3 (the split). For one node with the document set II, line L5 returns the split (f,θ)(f, \theta) that minimizes, over all features ff and all thresholds θ\theta that split II into two nonempty parts, the sum of squared errors of the targets gg around the mean of each part.

Proof. A threshold θ\theta splits II into {xf≤θ}\{x_f \le \theta\} and {xf>θ}\{x_f > \theta\}, and this partition depends only on which consecutive pair of distinct values of xfx_f in II 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. □\square

Lemma 4 (scale). If σ\sigma is multiplied by c>0c > 0, every gig_i is multiplied by cc times a factor that depends on cc only through ρ\rho, and every hih_i by c2c^2 times such a factor. At s=0s = 0, where ρ=1/2\rho = 1/2 for every pair, γR\gamma_R is exactly divided by cc.

Proof. Read the factors off the definitions of gig_i and hih_i. □\square

This is the 1/σ1/\sigma scaling that Burges (2010) mentions for the leaf values.

What is not proved. Each round reduces the frozen cost CC only approximately: the tree is fitted by least squares, the step is a diagonal Newton step, the shrinkage η\eta scales it, and the weights ∣ΔZ∣|\Delta Z| 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 O(Nlog⁡N+P)O(N \log N + P) for NN documents and PP pairs. A depth-DD tree on NN points and dd features costs O(D d Nlog⁡N)O(D\, d\, N \log N) with sorting at each level, or O(D d N)O(D\, d\, N) with presorted features or histograms of binned feature values, as production libraries use. Line L7 costs O(ND)O(N D). The model has MM trees of at most 2D2^D leaves, and predicting one document costs O(MD)O(M D). 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-DD tree models interactions of up to DD 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 (hh 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 gg and hh per bin makes split search linear in NN, as in LightGBM and XGBoost.
  • Second-order split gain. Choose the split by the Newton gain (∑g)2/∑h(\sum g)^2 / \sum h of each child, with a regularizer, rather than by least squares on gg. This is common in later libraries and differs from Burges (2010), Section 7.
  • Other metrics. Replace ∣ΔZ∣|\Delta Z| 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@kk 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 FF. 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 ∑h=0\sum h = 0. 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 η=1\eta = 1 in line L7, the Newton step of a nearly flat leaf can be huge, as in the example, and overshoot. Use η\eta around 0.1 and more rounds.
  • The sign convention. Line L4 uses g=−λg = -\lambda for a cost. Mixing it with the utility convention y=λy = \lambda 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.

lambdamart.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_round
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example