Algorithm Search⌘K

Algorithmadvanced

WAND

Also called weak AND, Broder WAND.

Sorts posting cursors by docid and finds a pivot where the summed term upper bounds first exceed the heap threshold, skipping all earlier documents.

Time
O(T m log m) worst
Space
O(m + k) extra
Where
T = the total length of the m posting lists; k = the number of results; m = the number of query terms
Properties
deterministiconlineiterative
Origin
Andrei Z. Broder, David Carmel, Michael Herscovici, Aya Soffer, Jason Zien, 2003

WAND is a dynamic pruning method for ranked retrieval on a docid-ordered index. It works like document-at-a-time evaluation, but it does not score every matching document. Each query term ii has an upper bound UiU_i, the largest weight in its posting list. WAND keeps the cursors sorted by their current docid and adds up their bounds in that order. The first cursor at which the sum is greater than the threshold θ\theta, the least score in a full heap of size kk, is the pivot. No document before the pivot docid can enter the top kk, so WAND moves cursors forward to the pivot with a forward search and scores a document only when all the cursors before the pivot are on it. With the threshold used as is, WAND is safe: it returns exactly the top kk of exhaustive scoring. With a threshold factor F>1F > 1 it is faster but unsafe. Compared with MaxScore, which splits the terms into two fixed groups, WAND chooses the pivot again at each step. Block-max WAND adds a bound for each block of postings.

In plain words

Each query word has a best possible contribution: the most points it gives to any document. Line up the words by the next document that each one points to. Go down the line and add up the best contributions. As long as the sum is too small to beat the worst of the current top results, no document up to that point can make it. The document where the sum first gets large enough is the pivot. Every document before it can be skipped, so the words behind jump ahead to the pivot. When all the words before the pivot point to it, score it for real. The jumps skip whole runs of documents that a plain scan would score one by one.

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 supports next\mathit{next}, which moves one posting, and next_geq(d)\mathit{next\_geq}(d), which moves to the first posting with docid at least dd, for example with skip pointers or exponential search.

The algorithm

The heap is the one of DAAT: it holds the best kk pairs seen so far, and it replaces its least entry only on a strictly greater score. While it has fewer than kk entries, the threshold is θ=−∞\theta = -\infty. F=1F = 1 gives the safe method.

  1. WAND(q, k, F) ▷ F = 1 for the safe method
  2. 1for i ← 1 to m do c_i ← a cursor on list i, with U_i ← the largest weight in 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 > F θ
  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. 8if c_1.docid = d then
  10. 9s ← the sum of the weights of the cursors at d, in query order; move each of them by next
  11. 10offer (s, d) to H
  12. 11else
  13. 12j ← the largest index < p with c_j.docid < d; c_j.next_geq(d)

In line L5, U1,…,UpU_1, \ldots, U_p are the bounds of the cursors in their sorted order. Line L12 moves one cursor; Broder and others pick it by a heuristic, and any cursor before the pivot with a docid less than dd keeps the method safe. Line L10 is line L8 of DAAT.

Example

Take the toy collection with BM25 weights (k1=1.2k_1 = 1.2, b=0.75b = 0.75, the Lucene IDF with the natural log), q1 "sorted array search" and k=2k = 2. The bounds are U=0.9497U = 0.9497 for sorted, 0.980.98 for array and 1.32911.3291 for search. The lists are sorted: d1, d2, d4, d8; array: d1, d2, d8; search: d1, d7.

step cursors by docid θ\theta pivot action
1 sorted 1, array 1, search 1 −∞-\infty d1 score d1 = 3.0283
2 sorted 2, array 2, search 7 −∞-\infty d2 score d2 = 1.8893; the heap is full
3 sorted 4, search 7, array 8 1.8893 search at d7 move sorted to d7 or later: it lands on d8
4 search 7, sorted 8, array 8 1.8893 sorted at d8 move search to d8 or later: it ends
5 sorted 8, array 8, search ∞\infty 1.8893 array at d8 score d8 = 1.6292, not greater than 1.8893
6 all at ∞\infty 1.8893 none stop

In step 3 the bound of sorted alone, 0.9497, is not greater than 1.8893, so d4, which contains only sorted, is skipped without a score. In step 4 the bound of search alone, 1.3291, is too small, so d7 is skipped. WAND scored 3 of the 5 matching documents and returns d1 3.0283, d2 1.8893, as DAAT does. With k=1k = 1 it scores only d1: after it, θ=3.0283\theta = 3.0283, a pivot needs all three bounds (sum 3.2588), and two moves of line L12 push array and then search past the end, so no other document gets a score.

Ties: for q2 "posting list merge" with k=2k = 2, WAND scores d2, d3 and d4, and then θ=2.2139\theta = 2.2139, the score of d3. The cursors of posting and merge are at d5 with bounds 0.9396+1.2743=2.21390.9396 + 1.2743 = 2.2139, which is not greater than θ\theta, so d5 is never scored. This is right: d5 ties d3, and the tie rule puts the smaller docid d3 first.

Threshold factor: let list a be d1 1, d2 1 and list b be d2 1, with k=1k = 1. The true answer is d2 with score 2. After d1, θ=1\theta = 1. With F=1F = 1 the bound sum 2 at d2 is greater than 1, and WAND finds d2. With F=2F = 2 the test is 2>22 > 2, which fails, and WAND returns d1, a wrong answer.

Correctness

The proof needs three conditions. (1) Each bound UiU_i is at least every weight of list ii, and the sums in line L5 are at least the scores they bound, in the same arithmetic. (2) The heap replaces its least entry only on a strictly greater score, and 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. For (3): when a cursor moves past a document y<dy < d in line L12, only the cursors before the pivot can still contain yy, and their bounds sum to at most θ\theta, so s(y)≤θs(y) \le \theta. At that time the heap holds kk documents with scores at least θ\theta and docids less than yy, so each of them ranks before yy, and yy is not in the top kk. The pivots never decrease, so a skipped document is never scored with a missing term, and a scored document gets its exact score. With F>1F > 1 the argument gives only s(y)≤Fθs(y) \le F\theta, which is not enough. The full proof is in the proof file.

Proof: WAND with F = 1 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 L12. We say that list ii still holds xx if list ii contains xx and ci.docid≤xc_i.\mathit{docid} \le x.

The three conditions. The proof uses exactly these.

(C1) Each weight is at least 0, and for every list ii and posting (x,w)(x, w) of it, w≤Uiw \le U_i. Sums of bounds and sums of weights 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. Floating-point sums in different orders do not have this property.

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

(C3) F=1F = 1: each document that is skipped has a score of at most the current threshold θ\theta.

(C2) and (C3) are proved below from the code, given F=1F = 1; (C1) is an assumption on the index and the arithmetic.

Lemma 1 (bound of a prefix). At the start of a step, let pp be the value of line L5, or p=m+1p = m + 1 if there is none. Every document xx with x<cp.docidx < c_p.\mathit{docid} (with cm+1.docid=∞c_{m+1}.\mathit{docid} = \infty) has at most U1+⋯+Up−1U_1 + \cdots + U_{p-1} as the sum of the weights of the lists that still hold it, and this sum is at most θ\theta.

Proof. A list that still holds xx has ci.docid≤x<cp.docidc_i.\mathit{docid} \le x < c_p.\mathit{docid}, so its cursor is one of c1,…,cp−1c_1, \ldots, c_{p-1} in the sorted order. Each of its weights in xx is at most its bound by (C1), and weights are at least 0. If p−1≥1p - 1 \ge 1, the least index pp of line L5 means that the sum U1+⋯+Up−1U_1 + \cdots + U_{p-1} is not greater than θ\theta, or else p−1p - 1 would qualify (cursors c1,…,cp−1c_1, \ldots, c_{p-1} are not at ∞\infty, since they are less than cp.docidc_p.\mathit{docid}). If p=1p = 1 the sum is empty. □\square

Lemma 2 (the pivots do not decrease). Let dd be the pivot of a step. In each later step the pivot is at least dd, and after a step that scores dd every later pivot is greater than dd.

Proof. Consider the step with pivot dd and index pp. Before it, the cursors with docid less than dd are among c1,…,cp−1c_1, \ldots, c_{p-1}, and by the choice of pp their bounds sum to at most θ\theta. The step moves cursors only forward. In line L12 the moved cursor goes to a docid at least dd. In line L9, all the cursors at dd move forward, and since c1.docid=dc_1.\mathit{docid} = d no cursor is less than dd. So after the step, the cursors with docid less than dd are a subset of the old c1,…,cp−1c_1, \ldots, c_{p-1}, and after a scoring step there are none at dd or below. The threshold never decreases, since the heap only gets better. In the next sort these cursors form a prefix, every shorter prefix has a smaller or equal bound sum since bounds are at least 0, and the whole prefix sums to at most the old θ\theta, so to at most the new one. So line L5 cannot pick a cursor with docid less than dd, and after a scoring step it cannot pick one at dd or less. Induction on the steps gives the claim for all later steps. □\square

Lemma 3 (exact scores, increasing order). Each document scored in line L9 gets its exact score s(d)s(d), and the documents are scored in strictly increasing docid order.

Proof. The order follows from Lemma 2. For the score: in line L8, c1.docid=dc_1.\mathit{docid} = d is the least docid, so no cursor is before dd. Let list ii contain dd. Its cursor has not passed dd: a cursor moves past a docid only in line L9, past the pivot of that step, which is less than dd by Lemma 2, or in line L12 to the first docid at least the pivot of that step, which is at most dd by Lemma 2. So ci.docid=dc_i.\mathit{docid} = d, and line L9 adds its weight. No other list contributes. □\square

Lemma 4 (skipped documents). Call a matching document yy skipped if it is never scored. Then at some point of the run the heap holds kk documents, each with a score at least s(y)s(y) and a docid less than yy.

Proof. Let yy be skipped. Since yy is never scored, the run ends with some list that contains yy having its cursor past yy, or with no pivot while some list still holds yy.

Case A: a cursor first moves past yy in line L12 of some step with pivot dd and index pp. Then y<dy < d, since the cursor goes to the first docid at least dd, and it was at a docid at most yy. So y<cp.docidy < c_p.\mathit{docid}, and by Lemma 1 the lists that still hold yy at the start of this step have weights summing to at most θ\theta. Every list that contains yy still holds it at that time: a cursor moves past yy for the first time in this step, and line L9 never moves a cursor past yy without scoring yy, which does not happen. So s(y)≤θs(y) \le \theta. If ∣H∣<k|H| < k, then θ=−∞\theta = -\infty and line L5 picks p=1p = 1, so c1.docid=dc_1.\mathit{docid} = d and line L12 is not reached. So the heap is full, each entry has a score at least θ≥s(y)\theta \ge s(y), and each entry was scored before this step, at a docid less than yy: every scored docid zz was the least cursor docid at its time, and the cursor that moves past yy in this step was at a docid at most yy after zz was scored, so zz was less than that docid, which is at most yy. If z=yz = y then yy was scored, so z<yz < y.

Case B: the run ends in line L6 while some list still holds yy. Then p=m+1p = m + 1 in Lemma 1, and s(y)≤θs(y) \le \theta as in case A. If ∣H∣<k|H| < k then θ=−∞\theta = -\infty and line L5 picks c1c_1 whenever a cursor is not at ∞\infty; so ∣H∣=k|H| = k. Every entry was scored at a docid less than the least cursor docid, which is at most yy, so less than yy. □\square

In both cases the condition s(y)≤θs(y) \le \theta is (C3).

Theorem. With F=1F = 1 and (C1), 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 3 they are offered in increasing docid order with exact scores, so by Lemma 1 of the DAAT proof (the heap rule, which uses the strict replacement of (C2)) the final heap is topk(S)\mathrm{top}_k(S). Take a skipped yy. By Lemma 4, SS holds kk documents with a score at least s(y)s(y) and a smaller docid; each of them ranks before yy by ≺\prec. So y∉topk(M)y \notin \mathrm{top}_k(M), and every element of topk(M)\mathrm{top}_k(M) is in SS. Since S⊆MS \subseteq M, topk(M)=topk(S)\mathrm{top}_k(M) = \mathrm{top}_k(S). ■\blacksquare

Termination. Line L9 moves at least one cursor, and line L12 moves cjc_j from a docid less than dd to one at least dd. Each step moves a cursor past at least one posting, so there are at most TT steps.

Remark (the threshold factor). With F>1F > 1, Lemma 1 gives only s(y)≤Fθs(y) \le F\theta for a skipped document, and a document with θ<s(y)≤Fθ\theta < s(y) \le F\theta can be skipped although it belongs to the top kk. The example on the page, with lists a = (d1 1, d2 1) and b = (d2 1), k=1k = 1 and F=2F = 2, returns d1 in place of d2. The method is then approximate.

Remark (ties). Lemma 4 uses s(y)≤θs(y) \le \theta, not s(y)<θs(y) < \theta. A skipped document with s(y)=θs(y) = \theta is still correctly left out, because all heap entries have smaller docids and win the tie. This needs the docid order of (C2); a method that scored documents out of docid order would need the strict test s(y)<θs(y) < \theta to skip.

Complexity

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

  • Worst case. Each step moves at least one cursor by at least one posting, so there are at most TT steps. Each step sorts mm cursors, O(mlog⁡m)O(m \log m), or O(m)O(m) if one cursor moved and is put back in place. With the heap the time is O(Tmlog⁡m)O(T m \log m), not better than DAAT. When θ\theta stays low, for example when kk is close to the number of matching documents, WAND does all the work of DAAT plus the pivot tests.
  • Documents scored. At most the number of matching documents, and on the toy query above 3 of 5.
  • Postings read. At most TT. A forward search can skip postings that are never decoded, which saves work on compressed lists in blocks.
  • Space. O(m+k)O(m + k), as DAAT.
  • Measured speed. The speedups of WAND over exhaustive DAAT are measurements, not bounds. Broder and others measured large reductions in the number of full evaluations on their collection, and later studies such as Ding and Suel (2011) measured the query times of WAND against block-max WAND.

Properties

  • Safe for F=1F = 1 under the three conditions above, with exact or same-order arithmetic.
  • Unsafe for F>1F > 1. The returned documents have their true scores, but a document of the true top kk can be skipped.
  • No random access. WAND only moves cursors forward on each list with next and next_geq. It never looks up a document in a list out of order. This is the difference from the threshold algorithm of databases, which mixes sorted access with random access, and it puts WAND closer to the no random access algorithm. Fagin's algorithm is the older database method of the same family.
  • Online. Each scored document is final, and θ\theta only grows.
  • Needs nonnegative weights. The prefix sums of line L5 bound the score only if no term can lower it.

Variants and improvements

  • Block-max WAND. Checks the pivot again with the bound of the current block in each list, and skips whole blocks.
  • Threshold factor. Broder and others multiply θ\theta by F≥1F \ge 1 for faster, approximate results. A factor F<1F < 1, or a θ\theta that starts low, makes WAND score more documents, and it stays safe.
  • Initial threshold. A safe lower bound on the final θ\theta, for example from a previous query, lets pruning start before the heap is full.
  • Choice of the cursor in line L12. The cursor with the largest bound or the shortest list are common choices. Each choice before the pivot with a smaller docid is safe.
  • MaxScore. Uses the same bounds but a fixed split of the terms, which avoids the sort at each step.

When to use it

Use WAND for disjunctive queries with small kk on a docid-ordered index, when the bounds UiU_i differ a lot from term to term, so the pivot often lands deep in the list order. For very long queries, the sort in each step costs more, and MaxScore or block-max WAND may be faster. For an index sorted by impact, use score-at-a-time evaluation on an impact-ordered index.

Pitfalls

  • Float bounds. If UiU_i is computed with a different formula or rounding than the weights, or if the prefix sums in line L5 are added in another order than the scores, the computed bound can be a little less than a computed score. Then a document is skipped wrongly. Round the bounds up, or use the same arithmetic.
  • Equal scores. Line L10 must replace only on a strictly greater score. With "at least", d5 would push d3 out of the heap in the q2 example, against the tie rule.
  • Moving the wrong cursor. Line L12 must move a cursor with docid less than dd. Moving a cursor that is already at dd to dd does nothing, and the loop never ends.
  • Moving past the pivot. A cursor before the pivot must move to the first docid at least dd, not greater than dd, or the pivot document loses a term.
  • Calling WAND with F>1F > 1 exact. It is not; its results must be reported as approximate.

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.

irtoy.pyI0RawGitHub
# 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
wand.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wand/. The authors are listed in prov/F02PAM.jsonl.
"""WAND (weak AND) 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 term t has an upper bound U(t), the largest weight in its list. WAND
keeps the cursors sorted by docid and finds the pivot: the first cursor at
which the running sum of upper bounds is greater than the threshold, the
lowest score in a full heap. A document before the pivot cannot enter the
top k, so the cursors skip to the pivot with next_geq. WAND uses only
sequential cursor moves and no random access.

With factor = 1 the method is safe: it returns exactly the top k of an
exhaustive evaluation, provided that the score arithmetic is exact. With
factor > 1 it compares the bound sum with factor times the threshold, and
can lose true top-k documents.
"""

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 forward-only cursor on one posting list, with its upper bound."""

    def __init__(self, postings, stats):
        self.ids = [d for d, _ in postings]
        self.ws = [w for _, w in postings]
        self.ub = max(self.ws, default=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)


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, factor):
    """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 > factor * theta:
            return p
    return None


def wand(index, query, k, factor=1):
    """Return (the top k as a list of (docid, score), Stats).

    query is a list of distinct terms. Terms missing from the index have an
    empty posting list.
    """
    stats = Stats()
    if k <= 0:
        return [], stats
    by_query = [Cursor(index.get(t, []), stats) 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
        p = find_pivot(cursors, top.threshold(), factor)  # @line L5
        if p is None:  # @line L6
            return top.result(), stats
        d = cursors[p].docid()  # @line L7
        if cursors[0].docid() == d:  # @line L8
            s = 0  # @line L9
            for c in by_query:
                if c.docid() == d:
                    s = s + c.weight()
                    c.next()
            stats.scored += 1
            top.offer(d, s)  # @line L10
        else:  # @line L11
            j = p - 1
            while cursors[j].docid() == d:
                j -= 1
            cursors[j].next_geq(d)  # @line L12


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)
test_wand.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wand/. The authors are listed in prov/F02PAM.jsonl.

import random
from fractions import Fraction

import irtoy
from wand import bm25_index, daat_scored, exhaustive_top_k, wand


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 = wand(index, q1, 5)
    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
    # k = 1: after d1 the threshold is 3.0283, and no prefix of bounds
    # (at most 0.9497 + 0.98 + 1.3291) exceeds it.
    got, stats = wand(index, q1, 1)
    assert [d for d, _ in got] == [1] and stats.scored == 1
    got, _ = wand(index, irtoy.tokenize(irtoy.QUERIES["q2"]), 3)
    assert [d for d, _ in got] == [4, 3, 5]
    assert wand(index, irtoy.tokenize(irtoy.QUERIES["q4"]), 5)[0] == []


def test_toy_against_exhaustive():
    index = toy_index()
    for text in irtoy.QUERIES.values():
        q = irtoy.tokenize(text)
        for k in range(0, 10):
            got, stats = wand(index, q, k)
            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)]}
    assert wand(index, [], 3)[0] == []
    assert wand(index, ["a"], 0)[0] == []
    assert wand(index, ["zz"], 3)[0] == []
    assert wand(index, ["a", "b"], 1)[0] == [(1, 3)]
    assert wand(index, ["a", "b"], 5)[0] == [(1, 3), (4, 3)]
    assert wand({"a": [(1, 3), (2, 3), (3, 3)]}, ["a"], 2)[0] == [(1, 3), (2, 3)]


def test_factor_above_one_is_unsafe():
    # The true top 1 is d2 with score 2. After d1 the threshold is 1, and
    # with factor 2 the bound sum 2 at d2 is not greater than 2.
    index = {"a": [(1, 1), (2, 1)], "b": [(2, 1)]}
    assert wand(index, ["a", "b"], 1)[0] == [(2, 2)]
    assert wand(index, ["a", "b"], 1, factor=2)[0] == [(1, 1)]


def test_random_against_exhaustive():
    rng = random.Random(20251117)
    total_wand = 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)
        got, stats = wand(index, q, k)
        assert got == exhaustive_top_k(index, q, k, range(1, n + 1))
        assert stats.scored <= daat_scored(index, q)
        total_wand += stats.scored
        total_daat += daat_scored(index, q)
    assert total_wand < total_daat

History

Broder, Carmel, Herscovici, Soffer and Zien presented WAND at CIKM 2003, as the first level of a two-level retrieval process at IBM: the weak AND operator generalizes AND and OR with a threshold, and a cheap test on upper bounds decides which documents get a full evaluation. The idea of score bounds for each term goes back to the max_score optimization of Turtle and Flood (1995). Ding and Suel (2011) added bounds for each block and called the result block-max WAND.

References

  1. Andrei Z. Broder, David Carmel, Michael Herscovici, Aya Soffer and Jason Zien, Efficient query evaluation using a two-level retrieval process, CIKM 2003, 426-434, the WAND operator, the upper bound of each term, the pivot selection over cursors sorted by docid, the threshold from the heap, and the threshold factor F that trades accuracy for speed
  2. Shuai Ding and Torsten Suel, Faster top-k document retrieval using block-max indexes, SIGIR 2011, 993-1002, the description of WAND as the baseline of block-max WAND
  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 MaxScore, WAND and block-max WAND and their safety

Where this leads

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