Algorithmadvanced
Balanced interleaving
Also called Joachims balanced interleaving.
Merges two rankings so that every prefix of the shown list holds top prefixes of both of nearly equal length, and compares the clicks inside those prefixes.
- Time
- O(n) worst
- Space
- O(n) extra
- Where
- n = the sum of the lengths of the two rankings
- Model
- Word RAM
- Properties
- randomizediterative
- Evidence
- Proof sketchCode in 1 languages
Balanced interleaving is the first interleaved evaluation method: it merges two rankings A and B of the same query into one shown list, so that every prefix of the shown list is the union of a top part of A and a top part of B whose lengths differ by at most 1. A fair coin decides which ranking gives the first document. The user's clicks then count for a ranking if they fall in the top k of that ranking, where k comes from the lowest click, and the ranking with more such clicks wins the query. The method is due to Joachims, and Radlinski, Kurup and Joachims later showed that it can prefer one ranking under clicks that carry no information.
In plain words
Two search engines each give a list of results for the same query. We want to show one list to the user and learn which engine is better from the clicks. Balanced interleaving takes results from the two lists in turns: first from one list, then from the other, and so on, and it skips a result that is already shown. A coin decides which list starts. So the top of the shown list always contains the top few results of both engines, in about equal numbers.
After the user clicks, look at the lowest click. Find how deep you must go in either engine's list to reach that result. Count the clicks inside that depth for each engine. The engine with more counted clicks wins this query.
The problem
The input is two rankings and for one query, each with no repeated document, and a fair coin. The output is a shown list with no repeated document. After the user clicks the set of documents of , the output is a preference , where 1 means that A is preferred.
Over many queries the wins of A and of B are counted, and a sign test on the queries with a preference decides if one ranking wins more often than chance.
The algorithm
BALANCED-INTERLEAVE(A, B, a_first) ▷ a_first: the result of one fair coin- 1
I ← empty list, ka ← 1, kb ← 1 - 2
while ka ≤ |A| and kb ≤ |B| do - 3
if ka < kb or (ka = kb and a_first) then - 4
if A[ka] ∉ I then append A[ka] to I - 5
ka ← ka + 1 - 6
else - 7
if B[kb] ∉ I then append B[kb] to I - 8
kb ← kb + 1 - 9
return I CREDIT(A, B, I, C) ▷ C: the clicked documents of I- 10
if C is empty then return 0 - 11
c ← the document of C at the lowest position in I - 12
k ← min(rank of c in A, rank of c in B) ▷ rank ∞ if absent - 13
ha ← |C ∩ {A[1], …, A[k]}|, hb ← |C ∩ {B[1], …, B[k]}| - 14
return 1 if ha > hb, -1 if ha < hb, else 0
The pointer is the next rank of A to look at, and the next rank of B. Line L3 lets the list with the smaller pointer move, and the coin decides when the pointers are equal. So the pointers never differ by more than 1. A document that is already in is passed over in line L4 or L7, but the pointer still moves. The loop stops as soon as one ranking is used up, so in practice both rankings are cut to the same length first, for example the number of results on a page.
Lines L11 to L13 are equations (1) to (3) of Radlinski, Kurup and Joachims. The rank is the smallest depth at which the lowest click is in the top of A or of B. The user is assumed to have read about results of each ranking, and the clicks inside these two tops are compared.
Example
Take the rankings of the bias example of Radlinski, Kurup and Joachims: and , with = true.
| step | ka | kb | line | document looked at | I |
|---|---|---|---|---|---|
| 1 | 1 | 1 | L4 | A[1] = a, new | a |
| 2 | 2 | 1 | L7 | B[1] = b, new | a, b |
| 3 | 2 | 2 | L4 | A[2] = b, already in I | a, b |
| 4 | 3 | 2 | L7 | B[2] = c, new | a, b, c |
| 5 | 3 | 3 | L4 | A[3] = c, already in I | a, b, c |
| 6 | 4 | 3 | L7 | B[3] = d, new | a, b, c, d |
| 7 | 4 | 4 | L4 | A[4] = d, already in I | a, b, c, d |
After step 7, and the loop stops. With = false the same steps give .
Now let the user click exactly one document, chosen uniformly at random from the 4 shown. For :
| click | rank in A | rank in B | k | ha | hb | outcome |
|---|---|---|---|---|---|---|
| a | 1 | 4 | 1 | 1 | 0 | A |
| b | 2 | 1 | 1 | 0 | 1 | B |
| c | 3 | 2 | 2 | 0 | 1 | B |
| d | 4 | 3 | 3 | 0 | 1 | B |
For the outcomes are B, A, B, B. So a click that does not depend on the documents at all prefers B with probability and A with probability . B is A with its first document moved to the end, and three of its four documents sit one rank higher than in A. This is the bias that Radlinski, Kurup and Joachims point out.
A second example, from the figure of the same paper: and . The two shown lists are and . If the user clicks b and e, the lowest click is e, which is at rank 2 of B and not in A, so . Then (only b is in the top 2 of A) and , and B wins with either shown list.
Correctness
The proof is in proofs/correctness.md. The key invariant holds after each step of the loop: the set of documents in equals , has no repeated document, and is 0 or 1 when is true, 0 or when it is false. A prefix of is the value of after some step, so every prefix of is the union of a top of A and a top of B with . This is the property that the sources state for the method. CREDIT computes equations (1) to (3) directly; the rank is finite because is in , and every document of comes from A or B.
The invariant does not make the method fair. A prefix holds equal numbers of ranks of A and B, but when the two rankings share documents, one ranking can have more of its documents in the prefix than the other at the depth that line L12 picks. The example above shows the result.
Proof: Balanced interleaving builds a list with balanced prefixes and computes the credit of equations (1) to (3)full
Let and be rankings, each with no repeated document. Write for , and the same for . Lines refer to the pseudocode on the page.
Invariant. Before each test of line L2, with and :
(J1) has no repeated document, and the set of documents of is .
(J2) if is true, and if it is false.
Initialization. Line L1 sets empty and . Both tops are empty, so (J1) holds, and , so (J2) holds.
Maintenance. Assume (J1) and (J2) and that the loop body runs, so and . Suppose is true; the other case is symmetric. By (J2), either or .
- If , then and is true, so line L3 takes the first branch. Line L4 appends if it is not in , and line L5 sets to . The new set of is the old set together with , which is . No document is appended twice, because of the test in line L4. The new difference is 1.
- If , then , so line L3 takes the second branch. In the same way, lines L7 and L8 add and set to . The new difference is 0.
So (J1) and (J2) hold again.
Termination. Each step increases by 1, and the body runs only while and . So the loop stops after at most steps.
Claim 1 (balanced prefixes). For every with , there are with and .
Proof. The list only grows, by one document at a time, and only in lines L4 and L7. So each prefix of the final is the value of at some test of line L2: the prefix of length 0 at the start, and the prefix of length at the test just after the step that appended . At that test (J1) and (J2) hold, with .
Claim 2 (credit). If is a nonempty set of documents of , CREDIT returns the sign of , where is the clicked document lowest in , , and .
Proof. By (J1) at the end of the loop, is in or in , so at least one of its ranks is finite. The smallest with or is the smaller of the rank of in and its rank in , which is the value of line L12. Lines L13 and L14 count the two sets and return the sign.
Claim 3 (the method is not fair under random clicks). There are rankings for which a user who clicks one shown document chosen uniformly at random, independently of the documents, makes CREDIT prefer B with probability more than 1/2.
Proof. Take and . By the invariant and a direct run of the loop, the coin gives or . In both lists, a click on a gives , , . A click on b gives and . A click on c gives , since c is , and , so B wins. A click on d gives , since d is , and , so B wins. So for each value of the coin, B wins with probability , and A with probability .
Cost. Each step of the loop runs once per increase of , so there are at most steps. With the documents of also kept in a hash set, each step costs expected time, and CREDIT reads each list once. Together this is time and extra space.
Complexity
- Time. Each step of the loop moves or by 1, so there are at most steps. With a hash set of the shown documents, the test in line L4 or L7 costs , so BALANCED-INTERLEAVE runs in time with . CREDIT finds the positions and ranks in one pass over each list, so it also costs .
- Space. and the hash set hold at most documents, so the extra space is .
- Coins. One fair coin per query, used only in line L3.
Properties
- Balanced prefixes. Every prefix of holds the top of A and the top of B with . If A and B are the same ranking, is that ranking.
- One shown list per coin value. For fixed A and B there are at most two shown lists, one for each value of the coin. The user sees a normal result list, and nothing marks which ranking gave which document.
- Biased under random clicks. A click model that ignores the documents can still prefer one ranking in expectation, as in the example. Hofmann, Whiteson and de Rijke show the same effect with and .
- Dominance does not always win. Call A dominant over B for a set of relevant documents if, at every depth, the top of A holds at least as many relevant documents as the top of B, and more at some depth. Let the user click each shown position with probability if its document is relevant and 0 if not. For all pairs of rankings of at most 3 documents, a dominant A then never loses in expectation. With 4 documents it can: for , and only a not relevant, the expected outcome is , so B is preferred. The shown lists are and , and a click on d counts for B, since d is at rank 3 of B and rank 4 of A. If the user also clicks a not relevant document with probability of the relevant case, the pair , with c not relevant gives .
Variants and improvements
- Team-draft interleaving. Give each shown document to the ranking that picked it, and credit clicks by team. Over the coin flips each ranking gets each position with probability 1/2, so clicks that ignore the documents give a tie in expectation. See team-draft interleaving.
- Probabilistic interleaving. Pick documents at random from softmax distributions over both rankings, and compare the clicks in expectation over the possible assignments. See probabilistic interleaving.
- Length cut. Cut both rankings to the page length before line L1, so that the loop does not stop early on a short ranking.
- Aggregation. Count a win per query, or give each user one vote from the majority of the user's queries; Radlinski, Kurup and Joachims report both.
When to use it
Use balanced interleaving when the two rankings differ a lot near the top, as in its first uses, and when a simple, deterministic credit rule is wanted. When the rankings are close, for example the same ranking with a small shift, the bias in the example can decide the outcome, and team-draft or probabilistic interleaving is the safer choice. All three methods need many queries; the outcome of one query is noisy.
Pitfalls
- No membership test. Lines L4 and L7 must append a document only if it is not already in . Without the test, and with = true give , and the user sees each result twice.
- Depth from the shown list. Line L12 must take the rank of the lowest click in A and in B, not its position in . In the example, a click on c in has position 3, and with both tops contain c, so the outcome is a tie. With the right line, and B wins.
- Or in place of and. Line L2 must stop when either ranking is used up. With "or", line L4 or L7 reads past the end of the shorter ranking. Cut both rankings to the same length instead.
- Assuming fairness. Random clicks do not give a tie in expectation. Before reading a small win as a real difference, check how close the two rankings are.
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/balanced-interleaving/. The authors are listed in prov/8GEA8G.jsonl.
from typing import Collection, Hashable, Sequence
def interleave(a: Sequence[Hashable], b: Sequence[Hashable], a_first: bool) -> list[Hashable]:
"""Return the balanced interleaving of rankings a and b.
Precondition: a and b have no repeated documents. a_first is the coin that
breaks the tie when both pointers are equal. Each loop step advances one
pointer, so there are at most len(a) + len(b) steps, each O(1) with a hash set:
O(len(a) + len(b)) time and space.
"""
out: list[Hashable] = []
shown: set[Hashable] = set()
ka, kb = 0, 0 # @line L1
while ka < len(a) and kb < len(b): # @line L2
if ka < kb or (ka == kb and a_first): # @line L3
if a[ka] not in shown: # @line L4
out.append(a[ka])
shown.add(a[ka])
ka += 1 # @line L5
else: # @line L6
if b[kb] not in shown: # @line L7
out.append(b[kb])
shown.add(b[kb])
kb += 1 # @line L8
return out # @line L9
def credit(
a: Sequence[Hashable], b: Sequence[Hashable], shown: Sequence[Hashable], clicked: Collection[Hashable]
) -> int:
"""Return 1 if the clicks prefer a, -1 if they prefer b, and 0 for no preference.
Precondition: shown is the interleaved list built from a and b, and clicked is a
set of documents of shown. The cost is O(len(a) + len(b) + len(shown)) time.
"""
if not clicked: # @line L10
return 0
pos = {d: i for i, d in enumerate(shown)}
low = max(clicked, key=lambda d: pos[d]) # @line L11
inf = len(a) + len(b) + 1
ra = a.index(low) + 1 if low in a else inf
rb = b.index(low) + 1 if low in b else inf
k = min(ra, rb) # @line L12
ha = sum(1 for d in a[:k] if d in clicked) # @line L13
hb = sum(1 for d in b[:k] if d in clicked)
return (ha > hb) - (ha < hb) # @line L14
test_balanced_interleaving.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/balanced-interleaving/. The authors are listed in prov/8GEA8G.jsonl.
import itertools
import random
from fractions import Fraction
from balanced_interleaving import credit, interleave
def oracle_interleave(a, b, a_first):
"""Closed form: step t touches a at odd t (a first) and b at even t, and the
loop runs min(2|a| - 1, 2|b|) steps. A document goes in at its first touch."""
first, second = (a, b) if a_first else (b, a)
steps = min(2 * len(first) - 1, 2 * len(second))
touch = {}
for t in range(1, steps + 1):
d = first[(t - 1) // 2] if t % 2 == 1 else second[t // 2 - 1]
touch.setdefault(d, t)
return sorted(touch, key=touch.get)
def oracle_credit(a, b, shown, clicked):
if not clicked:
return 0
low = max(clicked, key=shown.index)
k = next(j for j in range(1, max(len(a), len(b)) + 1) if (j <= len(a) and a[j - 1] == low) or (j <= len(b) and b[j - 1] == low))
ha = len(set(a[:k]) & set(clicked))
hb = len(set(b[:k]) & set(clicked))
return (ha > hb) - (ha < hb)
def click_sets(shown, prob):
"""All click sets of a model where position i is clicked with prob(i, doc), independently."""
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 {shown[i] for i in range(n) if pat[i]}, p
def expected_outcome(a, b, prob):
total = Fraction(0)
for a_first in (True, False):
shown = interleave(a, b, a_first)
for clicked, p in click_sets(shown, prob):
total += Fraction(1, 2) * p * credit(a, b, shown, clicked)
return total
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 test_paper_figure_example():
a = list("abcdgh")
b = list("beafgh")
assert interleave(a, b, True) == list("abecdfgh")
assert interleave(a, b, False) == list("baecfdgh")
for a_first in (True, False):
assert credit(a, b, interleave(a, b, a_first), {"b", "e"}) == -1
def test_trace_on_page():
a = list("abcd")
b = list("bcda")
assert interleave(a, b, True) == list("abcd")
assert interleave(a, b, False) == list("bacd")
def test_edge_cases():
assert interleave([], ["x"], True) == []
assert interleave(["x"], ["x"], False) == ["x"]
assert interleave(["x"], ["y", "z"], True) == ["x"]
assert interleave(["x"], ["y", "z"], False) == ["y", "x"]
assert credit(["x"], ["y"], ["x", "y"], set()) == 0
assert credit(["x", "y"], ["y", "x"], ["x", "y"], {"x", "y"}) == 0
def test_prefix_property_all_pairs_up_to_five():
"""Each prefix of the shown list is the union of a top ka of a and a top kb of b, |ka - kb| <= 1."""
for n in range(1, 6):
docs = list(range(n))
perms = list(itertools.permutations(docs))
for a in perms:
for b in perms:
for a_first in (True, False):
shown = interleave(a, b, a_first)
assert sorted(shown) == docs
for m in range(len(shown) + 1):
top = set(shown[:m])
assert any(
top == set(a[:ka]) | set(b[:kb])
for ka in range(n + 1)
for kb in range(max(0, ka - 1), min(n, ka + 1) + 1)
)
def test_bias_example_of_radlinski_kurup_joachims():
"""a = (a, b, c, d), b = (b, c, d, a), one click on a uniformly random shown document."""
a = list("abcd")
b = list("bcda")
wins = {1: Fraction(0), -1: Fraction(0), 0: Fraction(0)}
for a_first in (True, False):
shown = interleave(a, b, a_first)
for d in shown:
wins[credit(a, b, shown, {d})] += Fraction(1, 2) * Fraction(1, len(shown))
assert wins[-1] == Fraction(3, 4)
assert wins[1] == Fraction(1, 4)
def test_dominance_without_noise_three_documents():
"""With clicks only on relevant documents, a dominating ranking never loses for n <= 3."""
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):
assert expected_outcome(list(a), list(b), pbm(rel, 0)) >= 0
def test_dominating_ranking_can_lose():
"""The cases on the page where balanced interleaving prefers the dominated ranking."""
a, b = list("bcad"), list("cadb")
rel = {"a": 0, "b": 1, "c": 1, "d": 1}
assert dominates(a, b, rel)
assert expected_outcome(a, b, pbm(rel, 0)) == Fraction(-1, 16)
a, b = list("abc"), list("bca")
rel = {"a": 1, "b": 1, "c": 0}
assert dominates(a, b, rel)
assert expected_outcome(a, b, pbm(rel, 0)) == 0
assert expected_outcome(a, b, pbm(rel, Fraction(1, 5))) == Fraction(-1, 60)
def test_clear_winner():
a = list("abcd")
b = list("dcba")
rel = {"a": 1, "b": 1, "c": 0, "d": 0}
assert expected_outcome(a, b, pbm(rel, 0)) > 0
assert expected_outcome(b, a, pbm(rel, 0)) < 0
def test_random_against_oracle():
rng = random.Random(8)
for _ in range(800):
universe = list(range(rng.randint(1, 8)))
a = rng.sample(universe, rng.randint(0, len(universe)))
b = rng.sample(universe, rng.randint(0, len(universe)))
a_first = rng.random() < 0.5
shown = interleave(a, b, a_first)
assert shown == oracle_interleave(a, b, a_first)
if shown:
clicked = set(rng.sample(shown, rng.randint(0, len(shown))))
assert credit(a, b, shown, clicked) == oracle_credit(a, b, shown, clicked)
History
Joachims proposed the method in 2002 and 2003, in work on learning and evaluating rankings from clickthrough data, as a way to get unbiased paired comparisons from clicks. Radlinski, Kurup and Joachims (CIKM 2008) named it balanced interleaving, gave it as Algorithm 1 with the credit rule of equations (1) to (3), and showed its bias on close rankings. In a study on the arXiv.org search engine they made known changes to a ranking and found that none of eight absolute click metrics, such as the clicks per query, reliably showed the order of quality, while balanced and team-draft interleaving did. Hofmann, Whiteson and de Rijke (CIKM 2011) analysed the bias with a random click model, and Chapelle, Joachims, Radlinski and Yue (2012) compared interleaving methods on large commercial search engines and measured how well their outcomes agree with offline judgments.
References
- Evaluating retrieval performance using clickthrough data, the method that merges two rankings into one list with balanced prefixes and compares the clicks on the top of each ranking
- Filip Radlinski, Madhu Kurup and Thorsten Joachims, How does clickthrough data reflect retrieval quality?, CIKM 2008, pp. 43-52, Section 5.1, Algorithm 1 and equations (1) to (3) (balanced interleaving and its credit rule); Section 5.2 (the bias example with A = (a, b, c, d) and B = (b, c, d, a)); the user study on arXiv.org
- Katja Hofmann, Shimon Whiteson and Maarten de Rijke, A probabilistic method for inferring preferences from clicks, CIKM 2011, pp. 249-258, Section 3.1 and Figure 1 (the bias of balanced interleave under random clicks)
- Olivier Chapelle, Thorsten Joachims, Filip Radlinski and Yisong Yue, Large-scale validation and analysis of interleaved search evaluation, ACM Transactions on Information Systems 30(1), Article 6, 2012, the comparison of balanced and team-draft interleaving with each other and with offline judgments on commercial search engines
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 8GEA8G Edit this page History Report an error Markdown