Algorithm Search⌘K

Algorithmresearch

Block-max WAND

Also called BMW.

Refines WAND with score upper bounds stored per block of postings, so whole blocks are skipped when their local bounds cannot reach the threshold.

Time
O(T m log m) worst
Space
O(m + k) extraO(T / b) index
Where
T = the total length of the m posting lists; b = the block size; k = the number of results; m = the number of query terms
Properties
deterministiconlineiterative
Origin
Shuai Ding, Torsten Suel, 2011

Block-max WAND is a dynamic pruning method for ranked retrieval that adds a second, local bound to WAND. Each posting list is cut into blocks of bb consecutive postings, and the index stores the last docid and the largest weight of each block, the block max. WAND finds a pivot with the bounds of the whole lists. Block-max WAND then checks the pivot again with the block maxes of the blocks that can hold it. These are usually much smaller than the list bounds, so the check fails often, and then no document from the pivot to the end of the nearest block boundary can enter the top kk. The cursors jump past that range without a score. With exact arithmetic the method is safe: it returns exactly the top kk of exhaustive scoring.

In plain words

Plain WAND knows only the best contribution of each word over the whole collection. One great document makes that number large for the word, and then WAND cannot skip much. Block-max WAND also keeps the best contribution in each small group of documents in the word's list. When WAND says that a document might make the top results, the method looks at the groups that hold this document. If even the best contributions of those groups cannot beat the current results, it skips to the end of the nearest group without scoring anything in between. Only documents that pass both tests get a full score.

The problem

The input is a query of mm distinct terms, the posting list of each term in increasing docid order with weights w≥0w \ge 0, and k≥1k \ge 1. The score of a document is the sum of the weights of the query terms that it contains, and a document matches if it contains at least one. The output is the kk matching documents of highest score, by score descending and then docid ascending. Each list ii has the bound UiU_i, its largest weight, and is cut into blocks of bb postings. Block jj of list ii stores lastij\mathit{last}_{ij}, its last docid, and bmaxij\mathit{bmax}_{ij}, its largest weight.

The algorithm

Each cursor has a posting position and a block pointer. A shallow move shallow(d)\mathit{shallow}(d) moves the block pointer to the first block with last docid at least dd, and reads only the block metadata, not the postings. Past the last block the block max is 0 and the last docid is ∞\infty. The heap is the one of DAAT, with θ=−∞\theta = -\infty while it has fewer than kk entries.

  1. BLOCK-MAX-WAND(q, k)
  2. 1for i ← 1 to m do c_i ← a cursor on list i, with U_i and the block metadata of list i
  3. 2H ← an empty heap of size k; θ is -∞ while |H| < k, else the least score in H
  4. 3loop
  5. 4sort the cursors by docid, so that c_1.docid ≤ … ≤ c_m.docid
  6. 5p ← the least index with c_p.docid < ∞ and U_1 + … + U_p > θ
  7. 6if there is no such p then return the entries of H, by score descending and then docid ascending
  8. 7d ← c_p.docid ▷ the pivot
  9. 8while p < m and c_(p+1).docid = d do p ← p + 1
  10. 9for i ← 1 to p do c_i.shallow(d); B ← the sum of the block maxes of c_1, …, c_p
  11. 10if B > θ then
  12. 11if c_1.docid = d then s ← the sum of the weights of the cursors at d; move each of them by next
  13. 12offer (s, d) to H
  14. 13else j ← the largest index ≤ p with c_j.docid < d; c_j.next_geq(d)
  15. 14else ▷ no document in [d, n) can enter the top k
  16. 15n ← 1 + the least last docid of the blocks of c_1, …, c_p; if p < m then n ← min(n, c_(p+1).docid)
  17. 16for i ← 1 to p do c_i.next_geq(n)

Line L8 extends the prefix over all the cursors at the pivot. This makes the check in line L9 use every list that can hold dd, and it makes n>dn > d in line L15, so the loop always moves on. Line L16 moves all the cursors of the prefix. Many implementations move only one of them, for example the one with the largest bound, and both choices are safe.

Example

Take the toy collection with BM25 weights (k1=1.2k_1 = 1.2, b=0.75b = 0.75 in the BM25 formula, the Lucene IDF with the natural log), q1 "sorted array search", k=2k = 2, and blocks of 2 postings. The lists and blocks are:

term postings blocks (last docid, block max) UU
sorted d1 0.7192, d2 0.9497, d4 0.6896, d8 0.6896 (d2, 0.9497), (d8, 0.6896) 0.9497
array d1 0.98, d2 0.9396, d8 0.9396 (d2, 0.98), (d8, 0.9396) 0.98
search d1 1.3291, d7 1.2743 (d7, 1.3291) 1.3291
step cursors by docid θ\theta pivot, prefix BB action
1 sorted 1, array 1, search 1 −∞-\infty d1, all three 3.2588 score d1 = 3.0283
2 sorted 2, array 2, search 7 −∞-\infty d2, sorted and array 1.9297 score d2 = 1.8893
3 sorted 4, search 7, array 8 1.8893 d7, sorted and search 2.0187 move sorted to d7 or later: d8
4 search 7, sorted 8, array 8 1.8893 d8, all three 1.6292 skip: all move to d9 or later
5 all at ∞\infty 1.8893 none stop

In step 3 the block of sorted that can hold d7 is its second block, with block max 0.6896, and 0.6896+1.3291=2.0187>1.88930.6896 + 1.3291 = 2.0187 > 1.8893, so the pivot passes. In step 4 search has no block with last docid at least d8, so its block max is 0, and 0+0.6896+0.9396=1.62920 + 0.6896 + 0.9396 = 1.6292 is not greater than θ\theta. All three cursors jump to d9, which ends all lists. Block-max WAND scored 2 documents; WAND scores 3 on the same query, since it scores d8. Both return d1 3.0283 and d2 1.8893.

A case where the block maxes matter more: list a is d1 9, d2 1, d3 1, d4 1, d5 1 and list b is d1 1, d3 2, d4 2, d5 2, with k=1k = 1 and b=2b = 2. After d1, θ=10\theta = 10, and the list bounds 9+2=119 + 2 = 11 pass every pivot. WAND scores d1, d3, d4 and d5. Block-max WAND sees block sums of 3 at d3, d4 and d5 and skips them all; it scores only d1.

Correctness

The proof uses the three conditions of WAND. (1) Each list bound and each block max is at least every weight that it bounds, and the sums are computed exactly. (2) The heap replaces its least entry only on a strictly greater score, and the documents are scored in increasing docid order, so a tie keeps the smaller docid. (3) Each skipped document has a score of at most θ\theta. Steps that pass line L10 are WAND steps, and a document skipped there is covered by the WAND argument. For a block skip in line L16, take a document xx with d≤x<nd \le x < n. Lists after the prefix have their cursors at nn or later, and no cursor has passed xx, so xx can only be in lists of the prefix. In each of them, xx is at most the last docid of the current block and at least dd, so it lies in the current block, and its weight is at most that block max. So s(x)≤B≤θs(x) \le B \le \theta. After a skip all the cursors are at nn or later, so the pivots never go back, and every scored document gets its exact score. The full proof is in the proof file.

Proof: Block-max WAND returns the exact top k under the tie rulefull

The rank order ≺\prec is score descending, then docid ascending, and topk(S)\mathrm{top}_k(S) is the first min⁡(k,∣S∣)\min(k, |S|) pairs of a set SS in this order. Let MM be the set of matching documents and s(x)s(x) the score of xx. A step is one pass through lines L4 to L16. In a step, dd is the pivot, p0p_0 is the index found in line L5 and p≥p0p \ge p_0 the index after line L8. A step is a pass step if the test of line L10 is true and a skip step if it is false; a skip step has the range [d,n)[d, n) of line L15. List ii still holds xx if list ii contains xx and ci.docid≤xc_i.\mathit{docid} \le x.

The three conditions.

(C1) Each weight is at least 0. For every list ii, UiU_i is at least every weight of list ii, and each block max is at least every weight of its block. Sums are computed exactly, or in an arithmetic in which a sum of numbers each at most its partner is at most the sum of the partners.

(C2) The heap replaces its least entry only on a strictly greater score, and documents are offered in increasing docid order.

(C3) Each document that is skipped has a score of at most the current threshold θ\theta.

(C1) is an assumption; (C2) and (C3) are proved below.

Lemma 1 (after a step). At the start of a step, every cursor with docid less than dd is among c1,…,cp0−1c_1, \ldots, c_{p_0 - 1}, and the bounds of these cursors sum to at most θ\theta. After a step that scores dd, no cursor is at dd or below. After a skip step, every cursor is at nn or later, and n>dn > d.

Proof. The first claim is the choice of p0p_0 in line L5, as in Lemma 1 of the WAND proof. Line L11 moves every cursor at dd past dd, and no cursor is below dd since c1.docid=dc_1.\mathit{docid} = d. In a skip step, each cursor of the prefix has, after line L9, a block with last docid at least dd, or no block left, in which case its last docid is ∞\infty; and if p<mp < m, then cp+1.docid>dc_{p+1}.\mathit{docid} > d by line L8. So n>dn > d. Line L16 moves c1,…,cpc_1, \ldots, c_p to nn or later, and cp+1,…,cmc_{p+1}, \ldots, c_m are at cp+1.docid≥nc_{p+1}.\mathit{docid} \ge n or later. □\square

Lemma 2 (the pivots do not decrease). The pivot of each step is at least the pivot dd of every earlier step. It is greater than dd if that earlier step scored dd, and at least nn if that earlier step was a skip step.

Proof. Every step moves cursors only forward, and θ\theta never decreases. After a step of line L13, the cursors with docid less than dd are a subset of the old c1,…,cp0−1c_1, \ldots, c_{p_0-1}: they form a prefix of the next sorted order, and their bounds sum to at most the old θ\theta, so to at most the new one, so line L5 does not pick them. After a scoring step or a skip step, Lemma 1 puts all cursors above dd, or at nn or later. Induction on the steps gives the claim. □\square

Lemma 3 (moves that pass a document). Let list ii contain xx, and let a step move cic_i from a docid at most xx to one greater than xx. Then either the step scores x=dx = d, or x<dx < d, or the step is a skip step with d≤x<nd \le x < n.

Proof. Line L11 moves a cursor at dd to the next posting of its list, which passes a posting of xx only if x=dx = d. Line L13 moves to the first docid at least dd, which passes xx only if x<dx < d. Line L16 moves to the first docid at least nn, which passes xx only if x<nx < n, so either x<dx < d or d≤x<nd \le x < n. □\square

Lemma 4 (exact scores). Each document scored in line L11 gets its exact score, and the scored documents are in strictly increasing docid order.

Proof. The order follows from Lemma 2. Let dd be scored, and let list ii contain dd. Suppose that ci.docid>dc_i.\mathit{docid} > d at this time. Then an earlier step with pivot d′d' moved cic_i past dd. By Lemma 3, either it scored d′=dd' = d, or d<d′d < d', or it was a skip step with d′≤d<n′d' \le d < n'. By Lemma 2 each case makes every later pivot greater than dd, which is false for the current step. So ci.docid≤dc_i.\mathit{docid} \le d, and since d=c1.docidd = c_1.\mathit{docid} is the least cursor docid, ci.docid=dc_i.\mathit{docid} = d. Line L11 adds the weight of every list that contains dd, and no other weight. □\square

Lemma 5 (skipped documents). If a matching document yy is never scored, then at some point the heap holds kk documents, each with a score at least s(y)s(y) and a docid less than yy.

Proof. If some step moves a cursor of a list that contains yy past yy, take the first such step, with pivot dd. Before it, every list that contains yy still holds yy. By Lemma 3, and since yy is not scored, there are two cases.

Case A: y<dy < d. The lists that still hold yy have cursors at most y<dy < d, so by Lemma 1 they are among c1,…,cp0−1c_1, \ldots, c_{p_0-1}, and s(y)s(y) is at most the sum of their bounds, which is at most θ\theta. If θ=−∞\theta = -\infty, then p0=1p_0 = 1 and no cursor is below dd, which is false for the cursor that moves past yy; so θ>−∞\theta > -\infty.

Case B: a skip step with d≤y<nd \le y < n. Since BB is a finite number, a skip step needs θ>−∞\theta > -\infty. Each list that contains yy has its cursor at most y<ny < n, while cp+1,…,cmc_{p+1}, \ldots, c_m are at nn or later, so the list is one of c1,…,cpc_1, \ldots, c_p. After line L9 its block is the first block with last docid at least dd, and by line L15 that last docid is at least n−1≥yn - 1 \ge y. The block before it ends below d≤yd \le y. So the posting of yy lies in this block, and its weight is at most the block max by (C1). With weights at least 0, s(y)≤B≤θs(y) \le B \le \theta.

If no step moves such a cursor past yy, the run ends in line L6 with every list that contains yy still holding it. No index qualifies in line L5, so the bounds of all cursors before ∞\infty sum to at most θ\theta, and s(y)≤θs(y) \le \theta. If ∣H∣<k|H| < k, then θ=−∞\theta = -\infty and line L5 would pick c1c_1; so θ>−∞\theta > -\infty.

In every case the heap is full, and each entry has a score at least θ≥s(y)\theta \ge s(y). Each entry zz was scored in an earlier step, after which no cursor was at zz or below by Lemma 1. In each case some cursor is at most yy at the time, so z<yz < y. □\square

Theorem. Under (C1), BLOCK-MAX-WAND(q,k)(q, k) returns topk({(x,s(x)):x∈M})\mathrm{top}_k(\{(x, s(x)) : x \in M\}) in the order ≺\prec.

Proof. Let SS be the set of scored documents with their scores. By Lemma 4 they are offered in increasing docid order with exact scores, so by Lemma 1 of the DAAT proof, the heap rule, the final heap is topk(S)\mathrm{top}_k(S). Each y∈M∖Sy \in M \setminus S ranks after kk members of SS by Lemma 5, so topk(M)=topk(S)\mathrm{top}_k(M) = \mathrm{top}_k(S). ■\blacksquare

Termination. A pass step moves at least one cursor past at least one posting, as in WAND. A skip step moves cpc_p, which is at dd, to n>dn > d or later. So there are at most TT steps.

Remark (ties and strictness). Lemma 5 uses s(y)≤θs(y) \le \theta, not s(y)<θs(y) < \theta. A skipped document with s(y)=θs(y) = \theta is correctly left out, because all heap entries have smaller docids. This needs the docid order of (C2) and the strict test B>θB > \theta in line L10.

Remark (moving one cursor). Many implementations move only one cursor of the prefix to nn in line L16. The same block bound shows that every document in [d,n)[d, n) has a score of at most θ\theta; the order argument of Lemma 2 changes, since other cursors of the prefix stay below nn. This version is not proved here.

Complexity

The model is the word RAM with the index in memory. Let TT be the total length of the mm query lists and bb the block size.

  • Worst case. Each step moves at least one cursor past at least one posting, so there are at most TT steps, each with a sort of mm cursors and at most mm shallow moves. This is O(Tmlog⁡m)O(T m \log m), not better than WAND or DAAT.
  • Documents scored. At most as many as WAND on the same input, in practice, but this is not a theorem for each query: the two methods visit different pivots and can raise θ\theta in a different order.
  • Index space. Two numbers for each block, O(T/b)O(T / b) for the query lists. Small blocks give tight bounds and more metadata.
  • Measured speed. The speedups of block-max WAND over WAND are measurements on large collections, not bounds. Ding and Suel (2011) reported them in their experiments, and they depend on the block size, the query length and kk.

Properties

  • Safe under the three conditions, with exact arithmetic or bounds that are rounded up.
  • Two-level bounds. The list bound picks the pivot; the block maxes confirm or reject it.
  • No random access. As WAND, it moves cursors only forward, with next, next_geq and shallow moves.
  • Online. Each scored document is final, and θ\theta only grows.
  • Block maxes depend on the scoring function. They are computed at index time, so a change of the weights or of BM25 parameters needs new block maxes.

Variants and improvements

  • Variable-sized blocks. Mallia and others (2017) cut each list into blocks of different sizes, chosen so that the block maxes are close to the weights inside the blocks.
  • Moving one cursor. On a failed block check, move only one cursor of the prefix to nn. This page moves all of them; both are safe.
  • Block maxes with MaxScore. The same block maxes can tighten the bounds of the nonessential lists in MaxScore.
  • Approximate versions. Multiplying θ\theta by a factor F>1F > 1 in lines L5 and L10 makes the method faster and unsafe, as in WAND.

When to use it

Use block-max WAND for disjunctive queries with small kk on a large docid-ordered index in memory, where the weights in a list vary a lot, so the list bound is loose and the block maxes are tight. It needs block metadata in the index, which most block-compressed indexes can store next to their skip data. For very small collections, or when kk is close to the number of matching documents, plain DAAT is simpler and does about the same work.

Pitfalls

  • Stale block pointer. The block check must use the block that can hold the pivot, after a shallow move to dd. Using the block of the cursor's current posting gives a wrong bound for cursors before dd.
  • No extension in line L8. If a cursor at dd after the pivot is left out of the prefix, its weight is missing from BB, and nn can equal dd, so the loop does not move.
  • Jumping too far. In line L15, nn must be at most the docid of the next cursor after the prefix. A jump past it would skip documents in lists that the block check did not bound.
  • Float bounds. Block maxes computed with other rounding than the weights can be a little too small. Round them up, or use exact weights.
  • Strict test. Line L10 must test B>θB > \theta, and line L12 must replace only on a strictly greater score, as in WAND.

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.

block_max_wand.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-max-wand/. The authors are listed in prov/MB0KJQ.jsonl.
"""Block-Max WAND top-k evaluation of a ranked query.

An index maps each term to its posting list: a list of (docid, weight)
pairs in increasing docid order, with weights at least 0. The score of a
document is the sum of the weights of the query terms that it contains.
A document matches when it contains at least one query term. Results rank
by score descending, then by docid ascending.

Each list is cut into blocks of b consecutive postings. For each block the
index stores its last docid and its largest weight, the block max. The
method first finds a WAND pivot with the list-wide upper bounds. Then it
checks the pivot again with the block maxes of the blocks that can hold
it. If that sum is not greater than the threshold, no document from the
pivot up to the end of the shortest of those blocks can enter the top k,
and the cursors jump past that range.

This version moves all the cursors up to the pivot when the block check
fails. Other implementations move only one cursor; both are safe. The
method is safe when the score arithmetic is exact.
"""

import heapq
import math
from bisect import bisect_left

END = math.inf  # the docid of a cursor that is past the end of its list


class Stats:
    """Work counters: documents fully scored and posting weights read."""

    def __init__(self):
        self.scored = 0
        self.postings = 0


class Cursor:
    """A cursor on one posting list, with block metadata.

    The block pointer moves on its own (a shallow move) and reads only the
    block metadata, not the postings.
    """

    def __init__(self, postings, stats, b):
        self.ids = [d for d, _ in postings]
        self.ws = [w for _, w in postings]
        self.ub = max(self.ws, default=0)
        self.last = [self.ids[min(i + b, len(self.ids)) - 1] for i in range(0, len(self.ids), b)]
        self.bmax = [max(self.ws[i:i + b]) for i in range(0, len(self.ids), b)]
        self.blk = 0
        self.i = 0
        self.stats = stats

    def docid(self):
        return self.ids[self.i] if self.i < len(self.ids) else END

    def weight(self):
        self.stats.postings += 1
        return self.ws[self.i]

    def next(self):
        self.i += 1

    def next_geq(self, d):
        """Move to the first posting with docid >= d."""
        self.i = bisect_left(self.ids, d, self.i)

    def shallow(self, d):
        """Move the block pointer to the first block whose last docid >= d."""
        self.blk = bisect_left(self.last, d, self.blk)

    def block_max(self):
        """The block max of the current block, or 0 past the last block."""
        return self.bmax[self.blk] if self.blk < len(self.bmax) else 0

    def block_last(self):
        """The last docid of the current block, or END past the last block."""
        return self.last[self.blk] if self.blk < len(self.last) else END


class TopK:
    """The best k (docid, score) pairs seen so far.

    The heap holds (score, -docid), so its minimum is the entry that the
    tie rule ranks last. A new document replaces it only on a strictly
    greater score.
    """

    def __init__(self, k):
        self.k = k
        self.heap = []

    def threshold(self):
        """The lowest score in a full heap, or None while it is not full."""
        return self.heap[0][0] if len(self.heap) == self.k else None

    def offer(self, d, s):
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, (s, -d))
        elif s > self.heap[0][0]:
            heapq.heapreplace(self.heap, (s, -d))

    def result(self):
        return sorted(((-nd, s) for s, nd in self.heap), key=lambda p: (-p[1], p[0]))


def find_pivot(cursors, theta):
    """The least p whose prefix bound sum beats the threshold, or None."""
    acc = 0
    for p, c in enumerate(cursors):
        if c.docid() == END:
            return None
        acc = acc + c.ub
        if theta is None or acc > theta:
            return p
    return None


def block_max_wand(index, query, k, b=64):
    """Return (the top k as a list of (docid, score), Stats).

    query is a list of distinct terms; b is the block size.
    """
    stats = Stats()
    if k <= 0:
        return [], stats
    by_query = [Cursor(index.get(t, []), stats, b) for t in query]  # @line L1
    cursors = list(by_query)
    top = TopK(k)  # @line L2
    while True:  # @line L3
        cursors.sort(key=lambda c: c.docid())  # @line L4
        theta = top.threshold()
        p = find_pivot(cursors, theta)  # @line L5
        if p is None:  # @line L6
            return top.result(), stats
        d = cursors[p].docid()  # @line L7
        while p + 1 < len(cursors) and cursors[p + 1].docid() == d:  # @line L8
            p += 1
        bsum = 0
        for c in cursors[:p + 1]:  # @line L9
            c.shallow(d)
            bsum = bsum + c.block_max()
        if theta is None or bsum > theta:  # @line L10
            if cursors[0].docid() == d:  # @line L11
                s = 0
                for c in by_query:
                    if c.docid() == d:
                        s = s + c.weight()
                        c.next()
                stats.scored += 1
                top.offer(d, s)  # @line L12
            else:  # @line L13
                j = p
                while cursors[j].docid() == d:
                    j -= 1
                cursors[j].next_geq(d)
        else:  # @line L14
            nxt = min(c.block_last() for c in cursors[:p + 1]) + 1  # @line L15
            if p + 1 < len(cursors):
                nxt = min(nxt, cursors[p + 1].docid())
            for c in cursors[:p + 1]:  # @line L16
                c.next_geq(nxt)


def bm25_index(docs, k1=1.2, b=0.75):
    """Build an index of BM25 term weights with the Lucene IDF.

    docs maps docid to a list of tokens. The weight of t in d is
    IDF(t) * tf (k1 + 1) / (tf + k1 (1 - b + b |d| / avgdl)) with
    IDF(t) = ln(1 + (N - df + 0.5) / (df + 0.5)), which is positive.
    """
    n = len(docs)
    avgdl = sum(len(toks) for toks in docs.values()) / n
    counts = {}
    for d in sorted(docs):
        seen = {}
        for tok in docs[d]:
            seen[tok] = seen.get(tok, 0) + 1
        for t, f in seen.items():
            counts.setdefault(t, []).append((d, f))
    index = {}
    for t, plist in counts.items():
        df = len(plist)
        idf = math.log(1 + (n - df + 0.5) / (df + 0.5))
        index[t] = [
            (d, idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(docs[d]) / avgdl)))
            for d, f in plist
        ]
    return index


def exhaustive_top_k(index, query, k, doc_ids):
    """Score every document of doc_ids, then sort. The reference method."""
    if k <= 0:
        return []
    lookup = [dict(index.get(t, [])) for t in query]
    scored = []
    for d in doc_ids:
        s = 0
        hit = False
        for table in lookup:
            if d in table:
                s = s + table[d]
                hit = True
        if hit:
            scored.append((d, s))
    scored.sort(key=lambda p: (-p[1], p[0]))
    return scored[:k]


def daat_scored(index, query):
    """The number of documents that plain DAAT scores: the matching ones."""
    union = set()
    for t in query:
        union.update(d for d, _ in index.get(t, []))
    return len(union)
irtoy.py 76 lines
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
test_block_max_wand.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-max-wand/. The authors are listed in prov/MB0KJQ.jsonl.

import random
from fractions import Fraction

import irtoy
from block_max_wand import bm25_index, block_max_wand, daat_scored, exhaustive_top_k


def toy_index():
    return bm25_index({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})


def random_index(rng, n, vocab, exact):
    """A random index on docids 1..n with nonnegative weights.

    exact selects Fraction weights; else small integers, which give many
    ties.
    """
    index = {}
    for t in range(vocab):
        density = rng.random() ** 2
        ids = [d for d in range(1, n + 1) if rng.random() < density]
        if exact:
            index[f"t{t}"] = [(d, Fraction(rng.randint(0, 40), rng.randint(1, 6))) for d in ids]
        else:
            index[f"t{t}"] = [(d, rng.randint(0, 5)) for d in ids]
    return index


def test_toy_check_values():
    index = toy_index()
    q1 = irtoy.tokenize(irtoy.QUERIES["q1"])
    got, stats = block_max_wand(index, q1, 5, b=2)
    assert [d for d, _ in got] == [1, 2, 8, 7, 4]
    want = [3.0283, 1.8893, 1.6292, 1.2743, 0.6896]
    assert all(abs(s - w) < 5e-5 for (_, s), w in zip(got, want))
    assert stats.scored == 5
    got, _ = block_max_wand(index, irtoy.tokenize(irtoy.QUERIES["q2"]), 3, b=2)
    assert [d for d, _ in got] == [4, 3, 5]
    assert block_max_wand(index, irtoy.tokenize(irtoy.QUERIES["q4"]), 5)[0] == []


def test_block_check_skips():
    # "a" has a block max of 9 only in its first block. With k = 1 the
    # threshold after d1 is 10. Every later pivot has a list bound sum of
    # 9 + 2 = 11 > 10, so WAND scores d3, d4 and d5, but the block maxes
    # 1 + 2 = 3 are not greater than 10, so BMW skips them.
    index = {"a": [(1, 9), (2, 1), (3, 1), (4, 1), (5, 1)], "b": [(1, 1), (3, 2), (4, 2), (5, 2)]}
    got, stats = block_max_wand(index, ["a", "b"], 1, b=2)
    assert got == [(1, 10)]
    assert stats.scored == 1


def test_toy_against_exhaustive():
    index = toy_index()
    for text in irtoy.QUERIES.values():
        q = irtoy.tokenize(text)
        for b in (1, 2, 3, 64):
            for k in range(0, 10):
                got, stats = block_max_wand(index, q, k, b)
                assert got == exhaustive_top_k(index, q, k, irtoy.DOCS)
                assert stats.scored <= daat_scored(index, q)


def test_edges():
    index = {"a": [(1, 3), (4, 1)], "b": [(4, 2)]}
    for b in (1, 2):
        assert block_max_wand(index, [], 3, b)[0] == []
        assert block_max_wand(index, ["a"], 0, b)[0] == []
        assert block_max_wand(index, ["zz"], 3, b)[0] == []
        assert block_max_wand(index, ["a", "b"], 1, b)[0] == [(1, 3)]
        assert block_max_wand(index, ["a", "b"], 5, b)[0] == [(1, 3), (4, 3)]
        assert block_max_wand({"a": [(1, 3), (2, 3), (3, 3)]}, ["a"], 2, b)[0] == [(1, 3), (2, 3)]


def test_random_against_exhaustive():
    rng = random.Random(20251118)
    total_bmw = total_daat = 0
    for trial in range(300):
        n = rng.randint(1, 200)
        index = random_index(rng, n, 8, exact=trial % 2 == 0)
        q = rng.sample(sorted(index), rng.randint(1, 5))
        if rng.random() < 0.2:
            q.append("missing")
        k = rng.randint(1, 12)
        b = rng.randint(1, 8)
        got, stats = block_max_wand(index, q, k, b)
        assert got == exhaustive_top_k(index, q, k, range(1, n + 1))
        assert stats.scored <= daat_scored(index, q)
        total_bmw += stats.scored
        total_daat += daat_scored(index, q)
    assert total_bmw < total_daat

History

Ding and Suel presented block-max indexes and block-max WAND at SIGIR 2011. They built on WAND of Broder and others (2003), which uses one bound for each list, and on compressed indexes in blocks, which already store the last docid of each block for skips. Mallia, Ottaviano, Porciani, Tonellotto and Venturini (2017) made the blocks variable in size to tighten the bounds.

References

  1. Shuai Ding and Torsten Suel, Faster top-k document retrieval using block-max indexes, SIGIR 2011, 993-1002, the block-max index, the block-max WAND algorithm with its shallow moves and block check, and the experiments against WAND
  2. Antonio Mallia, Giuseppe Ottaviano, Elia Porciani, Nicola Tonellotto and Rossano Venturini, Faster BlockMax WAND with variable-sized blocks, SIGIR 2017, the partition of each posting list into blocks of variable size, chosen so that the block maxes are tight
  3. Nicola Tonellotto, Craig Macdonald and Iadh Ounis, Efficient query processing for scalable web search, Foundations and Trends in Information Retrieval 12(4-5), 2018, 319-500, the chapter on dynamic pruning, with block-max indexes, block-max WAND and the safety of these methods

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.worst
  • a full proof of space.extra
  • a full proof of space.index
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
  • a scene preset for the example