Algorithm Search⌘K

Algorithmadvanced

ListNet

Also called listwise top-one probability loss.

Trains a scorer by minimizing the cross-entropy between top-one probability distributions induced by predicted and true scores.

Time
O(T N d) totalO(N d) per_step
Space
O(N + d) extra
Where
N = the number of documents; T = the number of steps; d = the number of features
Properties
deterministicnot exactofflineiterative
Origin
Zhe Cao, Tao Qin, Tie Yan Liu, Ming Feng Tsai, Hang Li, 2007

ListNet trains a scoring function for learning to rank with a loss on the whole list of a query. It turns the scores into a probability distribution over the documents with a softmax, does the same with the labels, and minimizes the cross-entropy between the two. The cross-entropy-loss page treats a fixed target class; here the target is itself a distribution made from graded labels, and the classes are the documents of one query, so the number of classes changes from query to query. Unlike RankNet and the Ranking SVM, no pairs are formed. This page gives the loss, the reason the softmax is the probability of being ranked first, the gradient Ps−PyP_s - P_y, a safe step for the linear model, and its known limits.

In plain words

For one search request, we turn the scores of the results into shares that add up to 1. A result with a much higher score gets a much larger share. We also turn the true labels into shares in the same way. The method changes the scoring rule so that the two sets of shares agree. The share of a result can be read as the chance that it comes out first if we draw the results one by one at random, with better results more likely. The method looks at the whole list at once, and its cost grows with the number of results, not with the number of pairs.

The problem

The input is a set of queries; query qq has documents x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb R^d and labels y1,…,yny_1, \ldots, y_n. The code uses the linear scorer sj=w⋅xjs_j = w \cdot x_j; Cao et al. (2007) train a neural network scorer, which changes only how ∂sj/∂w\partial s_j / \partial w is computed. With φ=exp⁡\varphi = \exp, the top-one probabilities of the scores and of the labels are

Ps(j)=esj∑l=1nesl,Py(j)=eyj∑l=1neyl,P_s(j) = \frac{e^{s_j}}{\sum_{l=1}^{n} e^{s_l}}, \qquad P_y(j) = \frac{e^{y_j}}{\sum_{l=1}^{n} e^{y_l}},

and the loss is

L(w)=∑queries−∑j=1nPy(j)log⁡Ps(j).L(w) = \sum_{\text{queries}} -\sum_{j=1}^{n} P_y(j) \log P_s(j).

Ps(j)P_s(j) is the probability that jj comes first under the Plackett-Luce model, which draws document jj first with probability proportional to esje^{s_j}, then the next one among those left in the same way. So the loss compares the first-place marginals of two distributions over the n!n! permutations, at the cost of nn numbers instead of n!n!.

The algorithm

  1. LISTNET(queries, T)
  2. 1w ← 0; η ← 1 / M, where M = Σ_queries max_j ‖x_j‖²
  3. 2repeat T times:
  4. 3for each query: s_j ← w · x_j
  5. 4P_s ← softmax(s), P_y ← softmax(y)
  6. 5g ← Σ_queries Σ_j (P_s(j) - P_y(j)) x_j
  7. 6w ← w - η g
  8. 7return w

Line L4 is the whole loss computation. The gradient in the scores is Ps−PyP_s - P_y, so line L5 is one pass over the documents. Cao et al. (2007) train with a fixed learning rate; the step 1/M1/M of line L1 is the one for which the proof shows that the loss never increases.

Example

One query has three documents with labels y=(2,0,1)y = (2, 0, 1) and current scores s=(1,0,0.5)s = (1, 0, 0.5).

document yjy_j sjs_j Py(j)P_y(j) Ps(j)P_s(j) Ps(j)−Py(j)P_s(j) - P_y(j)
0 2 1.0 0.6652 0.5065 -0.1588
1 0 0.0 0.0900 0.1863 0.0963
2 1 0.5 0.2447 0.3072 0.0625

The loss is 0.89270.8927. The scores already rank the documents in the label order, so NDCG is 1, but the loss is not at its minimum: document 0 should have a larger share, and the gradient asks for a higher s0s_0 and lower s1s_1 and s2s_2. The minimum of the loss for this query is the entropy of PyP_y, 0.83240.8324, reached exactly when s−ys - y is a constant vector. At s=0s = 0 the loss is ln⁡3=1.0986\ln 3 = 1.0986 and the score gradient is (−0.3319,0.2433,0.0886)(-0.3319, 0.2433, 0.0886).

Correctness

The proof in proofs/correctness.md shows:

  • Top-one probability. Under the Plackett-Luce model with weights esje^{s_j}, the probability that jj is ranked first is Ps(j)P_s(j). The tests check it by a sum over the 24 permutations of 4 documents.
  • Gradient. ∂L/∂sj=Ps(j)−Py(j)\partial L / \partial s_j = P_s(j) - P_y(j) and ∇wL=∑j(Ps(j)−Py(j))xj\nabla_w L = \sum_j (P_s(j) - P_y(j)) x_j. The tests check both by central finite differences.
  • Convex and smooth. For the linear model, LL is convex and its Hessian is at most MIM I, because the Hessian of one query is a covariance of u⋅xju \cdot x_j under PsP_s.
  • Descent. With the step 1/M1/M, L(wt+1)≤L(wt)−12M∥∇L(wt)∥2L(w_{t+1}) \le L(w_t) - \frac{1}{2M}\lVert \nabla L(w_t) \rVert^2.
  • Minimum. For each query, L≥H(Py)L \ge H(P_y), with equality exactly when s−ys - y is constant.

On the planted set of the tests (6 queries of 5 documents), 200 steps lower the loss from 9.657 to 8.410, against the bound ∑H(Py)=7.997\sum H(P_y) = 7.997, and the mean NDCG on the training queries rises from 0.713 at w=0w = 0 to 1.0. The NDCG figures are measured, not proved: a lower loss does not imply a higher NDCG.

Proof: The ListNet top-one loss is convex with gradient P_s minus P_y, and the step 1/M never increases itfull

One query has documents x1,…,xnx_1, \ldots, x_n with labels y1,…,yny_1, \ldots, y_n and scores sj=w⋅xjs_j = w \cdot x_j. With φ=exp⁡\varphi = \exp, the top-one probabilities are

Ps(j)=esj∑lesl,Py(j)=eyj∑leyl,P_s(j) = \frac{e^{s_j}}{\sum_l e^{s_l}}, \qquad P_y(j) = \frac{e^{y_j}}{\sum_l e^{y_l}},

and the loss of the query is the cross-entropy L(s)=−∑jPy(j)log⁡Ps(j)L(s) = -\sum_j P_y(j) \log P_s(j). The training loss is the sum over the queries.

Lemma 1 (top-one probability). Under the Plackett-Luce model with weights esje^{s_j}, the probability that document jj is ranked first is Ps(j)P_s(j).

Proof. The model picks the first document with probability esπ(1)/∑lesle^{s_{\pi(1)}} / \sum_l e^{s_l} and then each next document in the same way among those left. Group the permutations by their first element. For first element jj, the remaining factors are the probabilities of a Plackett-Luce ranking of the other n−1n - 1 documents, and these sum to 1 over all such rankings, by induction on nn. So the sum over the permutations that start with jj is esj/∑lesle^{s_j} / \sum_l e^{s_l}. □\square

This is the theorem of Cao et al. (2007) that lets ListNet replace the n!n! permutation probabilities by nn top-one probabilities.

Lemma 2 (gradient). ∂L/∂sj=Ps(j)−Py(j)\partial L / \partial s_j = P_s(j) - P_y(j), and ∇wL=∑j(Ps(j)−Py(j))xj\nabla_w L = \sum_j (P_s(j) - P_y(j)) x_j.

Proof. Since ∑jPy(j)=1\sum_j P_y(j) = 1, L(s)=log⁡∑lesl−∑jPy(j)sjL(s) = \log \sum_l e^{s_l} - \sum_j P_y(j) s_j. The derivative of the first term in sjs_j is Ps(j)P_s(j), and of the second term Py(j)P_y(j). The chain rule with ∂sj/∂w=xj\partial s_j / \partial w = x_j gives the rest. □\square

Line L4 of the code computes Ps−PyP_s - P_y, and lines L3 and L5 form the sum. The gradient of one query costs O(nd)O(n d) for nn documents with dd features, in place of the O(n2d)O(n^2 d) of a pairwise loss.

Lemma 3 (convex and smooth). The loss is convex in ww, and its Hessian satisfies 0⪯∇2L⪯MI0 \preceq \nabla^2 L \preceq M I with M=∑queriesmax⁡j∥xj∥2M = \sum_{\text{queries}} \max_j \lVert x_j \rVert^2.

Proof. For one query, ∇w2L=X⊤(diag⁡(p)−pp⊤)X\nabla^2_w L = X^\top (\operatorname{diag}(p) - p p^\top) X with p=Psp = P_s and XX the matrix with rows xjx_j. For a vector uu, let aj=u⋅xja_j = u \cdot x_j. Then u⊤∇w2L u=∑jpjaj2−(∑jpjaj)2u^\top \nabla^2_w L\, u = \sum_j p_j a_j^2 - (\sum_j p_j a_j)^2, the variance of aa under pp. It is at least 0, and at most ∑jpjaj2≤max⁡jaj2≤max⁡j∥xj∥2∥u∥2\sum_j p_j a_j^2 \le \max_j a_j^2 \le \max_j \lVert x_j \rVert^2 \lVert u \rVert^2. Sum over the queries. □\square

Theorem (monotone descent). With wt+1=wt−1M∇L(wt)w_{t+1} = w_t - \frac{1}{M} \nabla L(w_t), as in lines L1 and L6,

L(wt+1)≤L(wt)−12M∥∇L(wt)∥2.L(w_{t+1}) \le L(w_t) - \frac{1}{2M} \lVert \nabla L(w_t) \rVert^2.

Proof. Lemma 3 and Taylor's theorem give L(v)≤L(w)+∇L(w)⋅(v−w)+M2∥v−w∥2L(v) \le L(w) + \nabla L(w) \cdot (v - w) + \frac{M}{2} \lVert v - w \rVert^2. Put v=w−∇L(w)/Mv = w - \nabla L(w)/M. □\square

Lemma 4 (the minimum and two invariances). For each query, L(s)≥H(Py)=−∑jPy(j)log⁡Py(j)L(s) \ge H(P_y) = -\sum_j P_y(j) \log P_y(j), with equality exactly when Ps=PyP_s = P_y, that is when s−ys - y is a constant vector. Adding the same constant to all scores of a query leaves LL unchanged.

Proof. L(s)−H(Py)L(s) - H(P_y) is the Kullback-Leibler divergence of PsP_s from PyP_y, which is nonnegative and zero exactly when the two distributions are equal. The softmax does not change when a constant is added to every entry. □\square

So the loss is not zero at its minimum, and its minimum depends on the label values, not only on their order: the labels 2,0,12, 0, 1 and 4,0,24, 0, 2 give different targets. With a linear model the minimum over ww is usually larger than ∑H(Py)\sum H(P_y), since no ww needs to reproduce yy up to a shift.

What is not proved. A smaller loss does not imply a larger NDCG, and nothing here bounds the error on new queries. The tests measure NDCG before and after training on one planted set.

The tests in impl/python/test_listnet.py check Lemma 2 by central finite differences in ss and in ww, Lemma 1 by a brute force over the 24 permutations of 4 documents, convexity on random segments, the shift invariance, the theorem along 200 steps, Lemma 4, and the worked example of the page.

Complexity

Each step computes NN scores in O(Nd)O(N d), one softmax per query in O(nq)O(n_q), and the gradient in O(Nd)O(N d). So a step costs O(Nd)O(N d), and TT steps O(TNd)O(T N d). A pairwise loss on the same data costs O(P+Nd)O(P + N d) per step with the lambda factorization and O(Pd)O(P d) without it, with PP up to ∑nq2/2\sum n_q^2 / 2. The extra space is O(N+d)O(N + d). The full permutation distribution would cost n!n! terms per query, which the top-one form avoids.

Properties

  • Shift invariant per query. Adding a constant to all scores of a query does not change PsP_s.
  • Depends on label values, not only their order. The labels (2,0,1)(2, 0, 1) and (4,0,2)(4, 0, 2) give different PyP_y and different minimizers. A rescaling of the label grades is a modeling choice.
  • Nonzero minimum. The loss at its minimum is ∑H(Py)\sum H(P_y), so its value alone does not show how close the model is to the best possible.
  • Not position aware. The loss does not use a discount by rank; errors at the top and errors at the bottom count through the shares only.
  • Bounded gradient. Each entry of Ps−PyP_s - P_y is in (−1,1)(-1, 1).

Variants and improvements

  • Top-kk probabilities. Cao et al. (2007) define the probability of the first kk positions in general and use k=1k = 1 for cost reasons.
  • ListMLE. Maximizes the Plackett-Luce likelihood of the label order itself, which fixes one permutation instead of matching marginals.
  • Softmax cross-entropy with one positive. If PyP_y puts all mass on one relevant document, the loss is the softmax loss used to train retrieval models such as dense passage retrieval, with the other documents as negatives.
  • Other transforms. A different increasing φ\varphi in place of exp⁡\exp, or a temperature on yy, changes how much the top label dominates PyP_y.

When to use it

Use ListNet when the scorer is trained by gradients and the data have graded labels for every document of a query, and when the cost per step must be linear in the number of documents. Its loss is smooth, convex for a linear model, and simple to implement. If the target metric is NDCG@kk with a small kk, LambdaRank or LambdaMART weight the top positions more directly; which works better on a given data set is a matter of measurement.

Pitfalls

  • Overflow. Line L4 must subtract the largest entry before exponentiating, or large scores or labels overflow. Use a log-softmax for the loss.
  • Softmax across queries. Line L4 must normalize within one query. A softmax over all documents of all queries compares documents that never compete.
  • Large label scales. Labels on a scale of 0 to 100 make PyP_y almost one-hot. Rescale the labels before line L4, or the loss ignores all but the top document.
  • Reading the loss as quality. The loss stays above ∑H(Py)\sum H(P_y) even for a perfect ranking, as in the example, where NDCG is 1 but the loss is 0.8927. Monitor NDCG on held-out queries.
  • Step size. A fixed step much larger than 1/M1/M in line L6 can make the loss oscillate. MM grows with the number of queries in the batch.

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.

listnet.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/listnet/. The authors are listed in prov/TRPVZ8.jsonl.

"""ListNet with the top-one probability and a linear scoring function.

For one query with scores s and labels y, the top-one probabilities with
phi = exp are the softmax values

    P_s(j) = exp(s_j) / sum_k exp(s_k),   P_y(j) = exp(y_j) / sum_k exp(y_k).

The loss of the query is the cross-entropy L = -sum_j P_y(j) log P_s(j),
and its gradient in s is P_s - P_y. With s_j = w . x_j the gradient in w
is sum_j (P_s(j) - P_y(j)) x_j. Training is full-batch gradient descent
with the step 1 / M, where M = sum over queries of max_j ||x_j||^2 bounds
the curvature, so the loss never increases (see proofs/correctness.md).
NDCG uses the gain 2^g - 1 and the discount 1 / log2(rank + 1).
"""

import math


def dot(a, b):
    return sum(p * q for p, q in zip(a, b))


def softmax(v):
    m = max(v)
    e = [math.exp(x - m) for x in v]
    z = sum(e)
    return [x / z for x in e]


def log_softmax(v):
    m = max(v)
    lz = m + math.log(sum(math.exp(x - m) for x in v))
    return [x - lz for x in v]


def scores(w, xs):
    return [dot(w, x) for x in xs]


def query_loss(s, y):
    py = softmax([float(g) for g in y])
    return -sum(p * l for p, l in zip(py, log_softmax(s)))


def query_score_gradient(s, y):
    """dL/ds = P_s - P_y."""
    return [a - b for a, b in zip(softmax(s), softmax([float(g) for g in y]))]   # @line L4


def loss(w, queries):
    return sum(query_loss(scores(w, xs), y) for xs, y in queries)


def gradient(w, queries):
    g = [0.0] * len(w)
    for xs, y in queries:
        for d, x in zip(query_score_gradient(scores(w, xs), y), xs):     # @line L3
            for c in range(len(w)):
                g[c] += d * x[c]                                         # @line L5
    return g


def curvature_bound(queries):
    """M = sum over queries of max_j ||x_j||^2; the Hessian of the loss is at most M I."""
    return sum(max(dot(x, x) for x in xs) for xs, _ in queries)


def train(queries, d, steps=100):
    """Gradient descent from w = 0 with the step 1 / M. Returns w and the loss history."""
    w = [0.0] * d                                                        # @line L1
    eta = 1.0 / curvature_bound(queries)
    history = [loss(w, queries)]
    for _ in range(steps):                                               # @line L2
        g = gradient(w, queries)
        w = [a - eta * b for a, b in zip(w, g)]                          # @line L6
        history.append(loss(w, queries))
    return w, history                                                    # @line L7


def plackett_luce(s, perm):
    """Probability of the full permutation perm under the Plackett-Luce model with phi = exp."""
    p = 1.0
    rest = list(perm)
    for j in perm:
        p *= math.exp(s[j]) / sum(math.exp(s[k]) for k in rest)
        rest.remove(j)
    return p


def ranking(s):
    return sorted(range(len(s)), key=lambda i: (-s[i], i))


def ndcg(s, y, k=None):
    k = len(y) if k is None else k
    ideal = sum((2 ** g - 1) / math.log2(r + 2) for r, g in enumerate(sorted(y, reverse=True)[: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 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_listnet.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/listnet/. The authors are listed in prov/TRPVZ8.jsonl.

import itertools
import math
import random

from listnet import (
    curvature_bound,
    gradient,
    loss,
    mean_ndcg,
    plackett_luce,
    query_loss,
    query_score_gradient,
    softmax,
    train,
)


def planted(seed, n_queries=6, n_docs=5, 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 test_page_example():
    # Labels 2, 0, 1 and scores 1.0, 0.0, 0.5.
    s = [1.0, 0.0, 0.5]
    y = [2, 0, 1]
    assert [round(v, 4) for v in softmax(s)] == [0.5065, 0.1863, 0.3072]
    assert [round(v, 4) for v in softmax([2.0, 0.0, 1.0])] == [0.6652, 0.0900, 0.2447]
    assert round(query_loss(s, y), 4) == 0.8927
    assert [round(v, 4) for v in query_score_gradient(s, y)] == [-0.1588, 0.0963, 0.0625]
    # At s = 0 the loss is log 3.
    assert abs(query_loss([0.0, 0.0, 0.0], y) - math.log(3)) < 1e-12


def test_score_gradient_by_finite_differences():
    rng = random.Random(1)
    h = 1e-6
    for _ in range(100):
        n = rng.randint(1, 6)
        y = [rng.randint(0, 3) for _ in range(n)]
        s = [rng.uniform(-3, 3) for _ in range(n)]
        g = query_score_gradient(s, y)
        for i in range(n):
            a = list(s)
            b = list(s)
            a[i] += h
            b[i] -= h
            assert abs((query_loss(a, y) - query_loss(b, y)) / (2 * h) - g[i]) < 1e-6


def test_weight_gradient_by_finite_differences():
    rng = random.Random(2)
    queries = planted(seed=3)
    h = 1e-6
    for _ in range(5):
        w = [rng.uniform(-2, 2) for _ in range(3)]
        g = gradient(w, queries)
        for c in range(3):
            a = list(w)
            b = list(w)
            a[c] += h
            b[c] -= h
            assert abs((loss(a, queries) - loss(b, queries)) / (2 * h) - g[c]) < 1e-6


def test_top_one_probability_is_sum_of_plackett_luce():
    rng = random.Random(4)
    s = [rng.uniform(-1, 1) for _ in range(4)]
    p = softmax(s)
    total = 0.0
    for j in range(4):
        pj = sum(plackett_luce(s, perm) for perm in itertools.permutations(range(4)) if perm[0] == j)
        assert abs(pj - p[j]) < 1e-12
        total += pj
    assert abs(total - 1.0) < 1e-12


def test_loss_is_convex_in_w_on_segments():
    rng = random.Random(5)
    queries = planted(seed=6)
    for _ in range(30):
        u = [rng.uniform(-3, 3) for _ in range(3)]
        v = [rng.uniform(-3, 3) for _ in range(3)]
        t = rng.random()
        mid = [t * a + (1 - t) * b for a, b in zip(u, v)]
        assert loss(mid, queries) <= t * loss(u, queries) + (1 - t) * loss(v, queries) + 1e-12


def test_shift_invariance():
    s = [0.3, -1.2, 2.0]
    y = [1, 0, 2]
    assert abs(query_loss(s, y) - query_loss([v + 5.0 for v in s], y)) < 1e-12


def test_step_one_over_m_never_increases_loss():
    queries = planted(seed=7)
    assert curvature_bound(queries) > 0
    w, history = train(queries, 3, steps=200)
    assert all(b <= a + 1e-12 for a, b in zip(history, history[1:]))
    assert history[-1] < history[0]
    # Measured on this planted set, not a theorem.
    assert mean_ndcg(w, queries) > mean_ndcg([0.0, 0.0, 0.0], queries)


def test_minimum_is_not_zero():
    # The loss is at least the entropy of P_y, and equals it only if P_s = P_y.
    y = [2, 0, 1]
    py = softmax([2.0, 0.0, 1.0])
    entropy = -sum(p * math.log(p) for p in py)
    assert abs(query_loss([2.0, 0.0, 1.0], y) - entropy) < 1e-12
    assert query_loss([5.0, 0.0, 1.0], y) > entropy

History

Cao, Qin, Liu, Tsai and Li (2007) argued that pairwise methods such as the Ranking SVM, RankBoost and RankNet optimize a loss on pairs, while ranking quality is a property of whole lists. They defined permutation probabilities by the Plackett-Luce model, showed that the top-one marginals are a softmax of the scores, and trained a neural network scorer with the resulting cross-entropy. ListNet started the listwise family of losses, which includes ListMLE and many later softmax losses.

References

  1. Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai and Hang Li, Learning to rank, from pairwise approach to listwise approach, Proceedings of the 24th International Conference on Machine Learning (ICML 2007), pp. 129-136 (the permutation probability, the top-one probability, the cross-entropy loss and its gradient, and training of a neural network scorer by gradient descent)

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_step
  • 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