Algorithmresearch
Probabilistic interleaving
Also called Hofmann probabilistic interleave.
Draws each shown document from a softmax over a ranking picked by a fair coin, then credits clicks by the exact posterior of which ranking drew each document.
- Time
- O(n^2) worst
- Space
- O(n) extra
- Where
- c = the number of clicks; n = the number of documents in each ranking
- Model
- Word RAM
- Properties
- randomizediterative
- Evidence
- Proof sketchCode in 1 languages
Probabilistic interleaving is an interleaved evaluation method that builds the shown list at random from both rankings. For each position a fair coin picks one of the two rankings, and a document that is not yet shown is drawn from a softmax over that ranking, which gives the top documents most of the weight but every document some weight. Hofmann, Whiteson and de Rijke introduced it in 2011 to fix two faults of the older methods: balanced interleaving is biased when the rankings are close, and team-draft interleaving can miss a real difference. Because every document can reach every position, the clicks can be credited not only by the coin results that were drawn but by their exact posterior given the shown list, which removes noise and keeps the outcome unbiased.
In plain words
Two search engines each give their result list. To fill each slot of the page, flip a coin to pick an engine, then let that engine pick a result that is not yet on the page. The engine does not always take its best result: it takes its first one most of the time, its second one less often, and so on.
After the user clicks, give each click to the engine that most likely filled that slot. For each slot you can work out how likely each engine was to put that result there, given the page as a whole. The engine with more expected clicks wins. A wrong guess about who filled a slot cannot make a winner from a loser on average, and the guess is less noisy than the coin that was really flipped.
The problem
The input is two rankings and of the same documents for one query, a parameter , and a source of random numbers. Let and be the ranks of document in and , from 1. The method shows a list , an ordering of the documents, and keeps an assignment that says which ranking drew each position. After the user clicks the set of positions of , the output is a preference in , where a positive value means that is preferred. Over many queries, a sign test on the signs of the preferences, or a mean, decides if one ranking wins more often than chance.
The algorithm
PROBABILISTIC-INTERLEAVE(A, B, τ)- 1
w_x(d) ← 1 / r_x(d)^τ for x ∈ {1, 2} and every document d - 2
R ← the documents of A, L ← empty list, a ← empty list - 3
while R ≠ ∅ do - 4
x ← 1 or 2, each with probability 1/2 - 5
draw d from R with probability w_x(d) / Σ_{e ∈ R} w_x(e), remove d from R - 6
append d to L, append x to a - 7
return L, a OUTCOME(a, C) ▷ C: the clicked positions of L- 8
c1 ← |{r ∈ C : a_r = 1}|, c2 ← |{r ∈ C : a_r = 2}| - 9
return 1 if c1 > c2, -1 if c1 < c2, else 0 MARGINAL(A, B, L, C, τ)- 10
for r ← 1 to n: f_x ← w_x(L_r) / Σ_{s ≥ r} w_x(L_s) for x ∈ {1, 2}, q_r ← f_1 / (f_1 + f_2) - 11
P ← the table {0: 1} - 12
for each r ∈ C: P'[k + 1] ← P'[k + 1] + q_r P[k] and P'[k - 1] ← P'[k - 1] + (1 - q_r) P[k] for each k, then P ← P' - 13
return Σ_{k > 0} P[k] - Σ_{k < 0} P[k]
Lines L1 to L7 are the sampler of Hofmann, Whiteson and de Rijke, who use . Line L5 is a roulette wheel draw over the documents that are left, so the softmax is taken again over a smaller set at each position. OUTCOME is the plain credit by the assignment that was drawn. MARGINAL is the credit that the paper prefers: the expected value of OUTCOME over all assignments , weighted by their probability given the shown list .
The paper writes this marginal as a sum over assignments. The sum does not need terms. Given , the probability of a pair is a product of one factor per position, where the denominator of is the weight of the documents at positions to and depends only on . So given , the components of are independent, and position came from with probability (line L10). The outcome depends only on the sign of the sum of over the clicked positions, and lines L11 to L13 compute the distribution of that sum with a dynamic program.
Example
This is the example of Figure 5 of Hofmann, Whiteson and de Rijke, with . Let and . The softmax of over all four documents is . Suppose the sampler shows , which has probability , and the user clicks positions 2 and 3. Line L10 gives:
| position | document | weight of left | weight of left | |||||
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 1.1777 | 0.8491 | 0.0156 | 1.1777 | 0.0133 | 0.9846 | |
| 2 | 0.125 | 0.1777 | 0.7036 | 1 | 1.1620 | 0.8606 | 0.4498 | |
| 3 | 0.0370 | 0.0527 | 0.7033 | 0.125 | 0.1620 | 0.7714 | 0.4769 | |
| 4 | 0.0156 | 0.0156 | 1 | 0.0370 | 0.0370 | 1 | 0.5 |
Only positions 2 and 3 are clicked. gets both clicks with probability , gets both with probability , and the clicks split one and one with probability , a tie. MARGINAL returns , a small preference for , which ranks the two clicked documents higher. In the figure of the paper the two win probabilities are half of these values; the sign and the ratio are the same.
The sampled assignment would give , or for this page, depending on two coins and two draws that the user cannot see. MARGINAL replaces that random value by its mean given what the user saw.
Correctness
The proof is in proofs/correctness.md. Lines L1 to L7 return an ordering and an assignment with . Summing over gives , so the posterior of given is a product of independent Bernoulli terms with parameters . The table of lines L11 and L12 is the exact distribution of the difference of credited clicks over the clicked positions seen so far, so MARGINAL returns . When the clicks depend on the shown page but not on , which the user cannot see, the tower rule of conditional expectation gives : the marginalized outcome is unbiased for the expected outcome of the method, and its variance is no larger. The tests check this equality exactly, with fractions, over all pairs of rankings of at most 3 documents and all relevance labels.
Proof: Probabilistic interleaving has a posterior that factorizes by position, and its marginalized outcome is unbiasedfull
Let and be orderings of the same set of documents, and let . Lines refer to the pseudocode on the page. For a ranking (1 for , 2 for ) and a document at rank , from 1, let , and for a set let . All weights are positive.
Claim 1 (the sampler). INTERLEAVE returns an ordering of and an assignment with
Proof. Before the test of line L3 for position , the list of remaining documents holds , because line L5 removes each drawn document and line L6 appends it to . So the loop runs times and is an ordering of . At position , line L4 gives with probability , independent of all earlier draws. The roulette draw takes uniform in and returns the first remaining document whose prefix sum of weights exceeds , so it returns with probability . The product of these conditional probabilities is the formula.
Note that depends only on , not on . Write , so .
Claim 2 (the posterior factorizes). Given , the components of are independent, and .
Proof. Summing the product over all gives , because the sum over of a product of one factor per position is the product of the sums. Every factor is positive, so for every ordering , and
which is a product of one Bernoulli term per position with parameter .
Function POSTERIOR computes as the suffix sum , which is the same set, and then in line L10.
Claim 3 (the dynamic program). For a set of clicked positions, MARGINAL returns , where is the outcome of lines L8 and L9.
Proof. The outcome is the sign of , with if and otherwise, so it depends only on the components with . By Claim 2 these are independent with . After the loop of line L12 has processed the first clicked positions, the table holds the exact distribution of the sum of their : this is true for (the sum is 0 with probability 1), and each step convolves the table with the two values of the next independent . After all of , line L13 returns .
Claim 4 (unbiased). Let the clicks be drawn from any distribution that depends on the shown list but not on . Then .
Proof. As and are independent given , , so by Claim 3. Taking the expectation of both sides over gives the claim.
The hypothesis holds for every click model in which the user sees only the page: the assignment is not shown. So the marginalized outcome has the same expected value as the outcome of the sampled assignment, and it has no larger variance, because it is a conditional expectation of it.
Claim 5 (no preference under random clicks). If is drawn from a distribution on positions that is independent of , then and .
Proof. By line L4 each is a fair coin drawn independently of everything before it, so the marginal distribution of is uniform on . Let swap 1 and 2 in every component. This map is a bijection that keeps the uniform distribution, and for every , since it swaps the two counts. So for each fixed , , and averaging over the independent gives . The second equality follows by Claim 4.
Cost. INTERLEAVE makes draws, and each scans the remaining documents, so it takes time; a balanced tree of weights would make each draw . POSTERIOR makes two passes over , time. In MARGINAL, after clicks the table has at most keys, so the loop costs for , and sorting costs . With POSTERIOR the total is , against terms for the plain sum over assignments.
Complexity
- Time. The sampler makes draws, and each scans the documents that are left, so it takes time. A balanced tree of partial sums would make each draw . Line L10 takes time with suffix sums. After clicks the table has at most keys, so lines L11 to L13 take time for clicks, and MARGINAL takes in total.
- Space. The weights, , and the suffix sums take space, and the table takes .
- Random numbers. Two per position: one coin and one draw.
Properties
- Every page is possible. All weights are positive, so every ordering of the documents is shown with positive probability. This is what makes the posterior defined for every page, and it is also the cost of the method: users sometimes see a poor ordering.
- Fair under random clicks. Each coin of line L4 is fair and independent of the earlier draws, so the assignment is uniform over . Swapping 1 and 2 at every position negates the outcome, so clicks that depend only on positions give an expected outcome of 0, with OUTCOME and with MARGINAL. The tests check this exactly for all pairs of rankings of at most 3 documents and one pair of 4.
- Unbiased marginal. The marginalized outcome has the same expected value as the sampled one for every click model that does not see the assignment.
- A dominating ranking wins here. Call dominant over if, at every depth, the top of holds at least as many relevant documents as the top of , and more at some depth. Let the user click position with probability for a relevant document, and or 0 for a document that is not relevant. For all pairs of rankings of at most 4 documents, the expected outcome is then strictly positive when dominates . With , and only relevant, where team draft gives a tie, it is . With , and only not relevant, where balanced interleaving prefers , it is . The sources give no proof of this for longer lists or other click models.
Variants and improvements
- Credit by the sampled assignment. Return OUTCOME instead of MARGINAL. It has the same expected value and needs no posterior, but it is noisier, so more queries are needed for the same confidence.
- The softmax parameter. A large puts almost all the weight on the top document of each ranking, and the shown list comes close to a team-draft list, with its blind spots and with posteriors near 0 or 1. A small shows more varied pages and gives more information per click, but the pages are worse for the user.
- Reuse of logged clicks. Since every page has a known, positive probability under any pair of rankings, clicks logged while comparing one pair can be reweighted by the ratio of the probabilities of the shown page, as in importance sampling, to estimate a comparison of another pair. Hofmann, Whiteson and de Rijke continued this line in later work on interleaving with historical data.
- More than two rankings. The same sampler works with one softmax per ranker and a fair die in line L4, which gives a probabilistic form of multileaved comparison.
When to use it
Use probabilistic interleaving when the rankers to compare are close, so that team draft often gives ties, or when you want to reuse logged clicks for comparisons that were not run live. It needs the full rankings of both rankers at serving time and shows more varied pages than team draft, so it costs some user experience. For a plain A/B choice between two rankers that differ clearly, team draft is simpler and shows better pages.
Pitfalls
- Drawing from the full ranking. Line L5 must take the softmax over the documents that are left. If it draws from the full softmax and redraws on a repeat, the draw has the same distribution, but if it takes the next document of the ranking after a repeat, the probability of the page is no longer the product of line L10 and the posterior is wrong.
- The wrong denominator in line L10. The denominator of is the weight of the documents at positions to of . Using the weight of all documents, as for position 1, gives posteriors that do not match the sampler, and the marginal is then biased.
- A different at serving and at credit time. Lines L1 and L10 must use the same and the same rankings. If the ranker changes between serving and credit, the posterior belongs to another sampler.
- Using clicks that see the assignment. The unbiased property needs clicks that depend only on the page. If the page shows which ranker filled a slot, for example by a different style of snippet, the clicks are no longer independent of given .
- Summing over all assignments. Code that enumerates to compute the marginal is correct but takes steps. Use the factorized posterior and the dynamic program of lines L10 to L13.
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/probabilistic-interleaving/. The authors are listed in prov/5WYWSE.jsonl.
import random
from typing import Collection, Hashable, Sequence
def softmax_weights(ranking: Sequence[Hashable], tau: float) -> dict[Hashable, float]:
"""Return the weight 1 / r**tau of each document at rank r (from 1)."""
return {d: 1.0 / (r + 1) ** tau for r, d in enumerate(ranking)}
def interleave(
a: Sequence[Hashable], b: Sequence[Hashable], rng: random.Random, tau: float = 3.0
) -> tuple[list[Hashable], list[int]]:
"""Return the shown list and the assignment (1 for a, 2 for b) of each position.
Precondition: a and b are orderings of the same set of n documents. At each
position a fair coin picks a softmax, and a document is drawn from it among the
documents not yet shown. Each draw scans the remaining documents, so the time is
O(n^2) and the extra space is O(n).
"""
w = {1: softmax_weights(a, tau), 2: softmax_weights(b, tau)} # @line L1
shown: list[Hashable] = []
assign: list[int] = []
left = list(a) # @line L2
while left: # @line L3
x = 1 if rng.random() < 0.5 else 2 # @line L4
total = sum(w[x][d] for d in left)
u = rng.random() * total
k = 0
acc = w[x][left[0]]
while acc <= u and k + 1 < len(left):
k += 1
acc += w[x][left[k]]
d = left.pop(k) # @line L5
shown.append(d) # @line L6
assign.append(x)
return shown, assign # @line L7
def outcome(assign: Sequence[int], clicked: Collection[int]) -> int:
"""Return 1 if the clicked positions (from 0) credit a more often, -1 if b, else 0."""
c1 = sum(1 for r in clicked if assign[r] == 1) # @line L8
c2 = sum(1 for r in clicked if assign[r] == 2)
return (c1 > c2) - (c1 < c2) # @line L9
def posterior(a: Sequence[Hashable], b: Sequence[Hashable], shown: Sequence[Hashable], tau: float = 3.0) -> list[float]:
"""Return q[r] = P(position r was drawn from a's softmax | shown list).
Precondition: shown is an ordering of the documents of a and b. Given the shown
list, the assignments of the positions are independent, so two passes with
suffix sums suffice: O(n) time.
"""
w1 = softmax_weights(a, tau)
w2 = softmax_weights(b, tau)
n = len(shown)
z1 = [0.0] * (n + 1)
z2 = [0.0] * (n + 1)
for r in range(n - 1, -1, -1): # suffix sums: the weight left before position r
z1[r] = z1[r + 1] + w1[shown[r]]
z2[r] = z2[r + 1] + w2[shown[r]]
q: list[float] = []
for r, d in enumerate(shown): # @line L10
f1 = w1[d] / z1[r]
f2 = w2[d] / z2[r]
q.append(f1 / (f1 + f2))
return q
def marginal_outcome(
a: Sequence[Hashable], b: Sequence[Hashable], shown: Sequence[Hashable], clicked: Collection[int], tau: float = 3.0
) -> float:
"""Return the sum over assignments x of P(x | shown) * outcome(x, clicked).
Precondition: as for posterior; clicked holds positions from 0. A dynamic
program over the clicked positions tracks the distribution of c1 - c2, so the
time is O(n + c^2) for c clicks, against 2^n terms for the plain sum.
"""
q = posterior(a, b, shown, tau) # @line L11
dist = {0: 1.0}
for r in sorted(clicked): # @line L12
nxt: dict[int, float] = {}
for diff, p in dist.items():
nxt[diff + 1] = nxt.get(diff + 1, 0.0) + p * q[r]
nxt[diff - 1] = nxt.get(diff - 1, 0.0) + p * (1.0 - q[r])
dist = nxt
return sum(p for diff, p in dist.items() if diff > 0) - sum(p for diff, p in dist.items() if diff < 0) # @line L13
test_probabilistic_interleaving.py 200 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/probabilistic-interleaving/. The authors are listed in prov/5WYWSE.jsonl.
import itertools
import math
import random
from fractions import Fraction
from probabilistic_interleaving import interleave, marginal_outcome, outcome, posterior, softmax_weights
TAU = 3
def exact_weights(ranking):
return {d: Fraction(1, (r + 1) ** TAU) for r, d in enumerate(ranking)}
def prob_list_given_assign(a, b, shown, assign):
w = {1: exact_weights(a), 2: exact_weights(b)}
p = Fraction(1)
left = set(shown)
for d, x in zip(shown, assign):
p *= w[x][d] / sum(w[x][e] for e in left)
left.remove(d)
return p
def exact_dist(a, b):
"""All (shown, assign) pairs with their exact probability."""
out = {}
n = len(a)
for shown in itertools.permutations(a):
for assign in itertools.product((1, 2), repeat=n):
p = prob_list_given_assign(a, b, shown, assign) / 2**n
if p:
out[(shown, assign)] = p
return out
def brute_marginal(a, b, shown, clicked):
n = len(shown)
joint = {x: prob_list_given_assign(a, b, shown, x) for x in itertools.product((1, 2), repeat=n)}
z = sum(joint.values())
return sum(p / z * outcome(x, clicked) for x, p in joint.items())
def click_sets(shown, prob):
n = len(shown)
for pat in itertools.product((0, 1), repeat=n):
p = Fraction(1)
for i, bit in enumerate(pat):
q = prob(i, shown[i])
p *= q if bit else 1 - q
if p:
yield {i for i in range(n) if pat[i]}, p
def pbm(rel, eps):
return lambda i, d: Fraction(1, i + 1) * (1 if rel[d] else eps)
def dominates(a, b, rel):
ca = cb = 0
strict = False
for x, y in zip(a, b):
ca += rel[x]
cb += rel[y]
if ca < cb:
return False
strict = strict or ca > cb
return strict
def expected_outcome(a, b, prob):
total = Fraction(0)
for (shown, assign), p in exact_dist(a, b).items():
for clicked, pc in click_sets(shown, prob):
total += p * pc * outcome(assign, clicked)
return total
def test_figure_example_of_hofmann_whiteson_de_rijke():
l1 = ["d1", "d2", "d3", "d4"]
l2 = ["d2", "d3", "d4", "d1"]
w = softmax_weights(l1, TAU)
z = sum(w.values())
assert [round(w[d] / z, 3) for d in l1] == [0.849, 0.106, 0.031, 0.013]
shown = ["d1", "d2", "d3", "d4"]
q = posterior(l1, l2, shown, TAU)
assert math.isclose(q[3], 0.5)
win1 = q[1] * q[2]
win2 = (1 - q[1]) * (1 - q[2])
assert round(win1, 4) == 0.2145 and round(win2, 4) == 0.2878
m = marginal_outcome(l1, l2, shown, {1, 2}, TAU)
assert math.isclose(m, win1 - win2)
assert math.isclose(m, float(brute_marginal(l1, l2, shown, {1, 2})))
assert round(m, 4) == -0.0733
def test_edge_cases():
rng = random.Random(1)
shown, assign = interleave(["x"], ["x"], rng)
assert shown == ["x"] and assign in ([1], [2])
assert posterior(["x"], ["x"], ["x"]) == [0.5]
assert marginal_outcome(["x"], ["x"], ["x"], {0}) == 0.0
assert marginal_outcome(["x", "y"], ["y", "x"], ["x", "y"], set()) == 0.0
a = ["p", "q", "r", "s"]
assert all(math.isclose(v, 0.5) for v in posterior(a, a, ["s", "q", "p", "r"]))
assert outcome([1, 2, 2], {0}) == 1 and outcome([1, 2, 2], {0, 1, 2}) == -1
def test_marginal_matches_brute_force():
rng = random.Random(2)
for _ in range(600):
n = rng.randint(1, 6)
docs = list(range(n))
a = rng.sample(docs, n)
b = rng.sample(docs, n)
shown = rng.sample(docs, n)
clicked = set(rng.sample(range(n), rng.randint(0, n)))
assert math.isclose(marginal_outcome(a, b, shown, clicked, TAU), float(brute_marginal(a, b, shown, clicked)), abs_tol=1e-12)
def unbiased_case(a, b, prob):
dist = exact_dist(a, b)
direct = Fraction(0)
by_list = {}
for (shown, assign), p in dist.items():
by_list[shown] = by_list.get(shown, 0) + p
for clicked, pc in click_sets(shown, prob):
direct += p * pc * outcome(assign, clicked)
marginal = 0.0
for shown, p in by_list.items():
for clicked, pc in click_sets(shown, prob):
marginal += float(p * pc) * marginal_outcome(a, b, list(shown), clicked, TAU)
assert math.isclose(float(direct), marginal, abs_tol=1e-12)
def test_marginal_estimate_is_unbiased_by_enumeration():
for n in range(1, 4):
docs = list(range(n))
for rels in itertools.product((0, 1), repeat=n):
rel = dict(zip(docs, rels))
for a in itertools.permutations(docs):
for b in itertools.permutations(docs):
unbiased_case(list(a), list(b), pbm(rel, Fraction(1, 5)))
rng = random.Random(3)
for _ in range(3):
a = rng.sample(range(4), 4)
b = rng.sample(range(4), 4)
rel = {d: rng.randint(0, 1) for d in range(4)}
unbiased_case(a, b, pbm(rel, Fraction(1, 5)))
def test_random_clicks_give_a_tie_in_expectation():
cases = [(list(a), list(b)) for n in range(1, 4) for a in itertools.permutations(range(n)) for b in itertools.permutations(range(n))]
cases.append(([0, 1, 2, 3], [1, 2, 3, 0]))
for a, b in cases:
dist = exact_dist(a, b)
for pat in itertools.product((0, 1), repeat=len(a)):
clicked = {i for i in range(len(a)) if pat[i]}
assert sum(p * outcome(assign, clicked) for (shown, assign), p in dist.items()) == 0
def test_dominating_ranking_wins():
for n in range(1, 4):
docs = list(range(n))
for rels in itertools.product((0, 1), repeat=n):
rel = dict(zip(docs, rels))
for a in itertools.permutations(docs):
for b in itertools.permutations(docs):
if dominates(a, b, rel):
for eps in (0, Fraction(1, 5)):
assert expected_outcome(list(a), list(b), pbm(rel, eps)) > 0
def test_cases_where_other_methods_fail():
# Team draft gives a tie here.
l1, l2 = ["d1", "d2", "d3"], ["d2", "d3", "d1"]
rel = {"d1": 0, "d2": 0, "d3": 1}
assert expected_outcome(l2, l1, pbm(rel, 0)) > 0
# Balanced interleaving prefers b here.
a, b = list("bcad"), list("cadb")
rel = {"a": 0, "b": 1, "c": 1, "d": 1}
assert expected_outcome(a, b, pbm(rel, 0)) > 0
def test_sampler_follows_the_distribution():
a, b = ["x", "y", "z"], ["z", "x", "y"]
dist = exact_dist(a, b)
rng = random.Random(4)
trials = 40000
counts = {}
for _ in range(trials):
shown, assign = interleave(a, b, rng, TAU)
key = (tuple(shown), tuple(assign))
counts[key] = counts.get(key, 0) + 1
assert set(counts) <= set(dist)
for key, p in dist.items():
assert abs(counts.get(key, 0) / trials - float(p)) < 0.01
History
Hofmann, Whiteson and de Rijke presented probabilistic interleaving at CIKM 2011. They showed that balanced interleaving can prefer a ranker under random clicks, and that team draft can fail to see a ranker that places the only relevant document higher. Their method draws the page from softmax functions of the ranks, and they argued that it is fair under random clicks and that it detects such differences. They also introduced the marginalized comparison, which credits clicks by the posterior over assignments, and compared it with the older methods in experiments with simulated clicks. As for every interleaving method, the agreement of its outcomes with offline metrics is a measured property, not a proved one. Later work by the same authors used the known page probabilities to reuse logged clicks for new comparisons.
References
- Katja Hofmann, Shimon Whiteson and Maarten de Rijke, A probabilistic method for inferring preferences from clicks, CIKM 2011, pp. 249-258, the probabilistic interleave method with the softmax of rank to the power minus tau, tau = 3, the marginalized comparison and its example in Figure 5; Sections 3.1 and 3.2 for the faults of balanced and team-draft interleaving
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 5WYWSE Edit this page History Report an error Markdown