Algorithmcore
Term-at-a-time evaluation
Also called TAAT, accumulator-based evaluation.
Reads the posting lists one term after another and adds each term's contribution into a score accumulator per document.
- Solves
- Ranked retrieval
- Time
- O(T (1 + log k)) expected
- Space
- O(T) extra
- Where
- T = the total length of the m posting lists; k = the number of results; m = the number of query terms
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Howard Turtle, James Flood, 1995
Term-at-a-time evaluation, or TAAT, answers a ranked retrieval query by reading the posting lists of the query terms one after the other. It keeps an accumulator for each document seen so far, a partial score, and adds the weight of each posting into the accumulator of its document. After the last list every accumulator holds a full score, and the best are selected. It differs from document-at-a-time evaluation in the order of the work: DAAT finishes one document before it starts the next and needs only memory, while TAAT finishes one term before it starts the next and needs one accumulator for each matching document. TAAT reads each list in one sequential pass, which suits lists on disk, and it is the natural order for an impact-ordered index.
In plain words
Make an empty score sheet with a line for each document. Take the first word of the query and walk down its list of documents. For each document on the list, add the word's points to that document's line, and make a new line if the document has none yet. Then do the same with the next word, and so on. After the last word, every line holds the full score of its document, and you pick the best few lines. The sheet can get long: it has a line for every document that contains any query word. A smarter version reads the most valuable words first and, once the leaders are far enough ahead, stops adding new lines and only updates the old ones.
The problem
The input is a query of distinct terms, the posting list of each term, and . A posting gives the weight of the term in document , and each list is in strictly increasing order of . The score is the sum of the weights of the query terms that contains, and a document matches if it contains at least one of them. The output is the matching documents of highest score, ranked by score descending and then docid ascending. The upper bound of term is the largest weight in its list.
The algorithm
The plain method has five lines. The accumulator map is a hash table, or an array of numbers when is small.
TAAT(q, k) ▷ q has m terms, each with a posting list- 1
A ← an empty map from docid to score - 2
for i ← 1 to m do - 3
for each posting (d, w) of list i do - 4
if d ∈ A then A[d] ← A[d] + w else A[d] ← w - 5
return the k best entries of A, by score descending and then docid ascending
The max_score variant of Turtle and Flood reads the terms in decreasing order of . Before term , the remaining bound is the most that a document with no accumulator can still score. When the -th largest accumulator is greater than , the method stops creating accumulators and only adds weights to the ones it has.
TAAT-MAXSCORE(q, k)M1 order the terms so that U_1 ≥ U_2 ≥ … ≥ U_mM2 A ← an empty map, or_mode ← trueM3 for i ← 1 to m doM4 R ← U_i + … + U_m; if or_mode and |A| ≥ k and the k-th largest value in A > R then or_mode ← falseM5 if or_mode then for each posting (d, w) of list i do add w to A[d], creating it if neededM6 else for each d in A in docid order, find d in list i by a forward search, and if found add its weight to A[d]M7 return the k best entries of A, by score descending and then docid ascending
Line M6 uses forward searches in list i, for example with skip pointers, so it reads only the postings of documents that already have an accumulator.
Example
Take the toy collection with BM25 weights (, , the Lucene IDF with the natural log) and the query q1 "sorted array search". The accumulators after each list, rounded to 4 places:
| after list | d1 | d2 | d4 | d7 | d8 |
|---|---|---|---|---|---|
| sorted | 0.7192 | 0.9497 | 0.6896 | 0.6896 | |
| array | 1.6992 | 1.8893 | 0.6896 | 1.6292 | |
| search | 3.0283 | 1.8893 | 0.6896 | 1.2743 | 1.6292 |
Plain TAAT read 9 postings and made 5 accumulators. The top 2 are d1 3.0283 and d2 1.8893, and the top 5 is the same as with DAAT.
The max_score variant with orders the terms by their bounds: search (), array (), sorted (). After search, = {d1 1.3291, d7 1.2743}. Before array, , and the best accumulator 1.3291 is not greater, so it reads array in full: = {d1 2.3091, d2 0.9396, d7 1.2743, d8 0.9396}. Before sorted, and , so it switches to AND mode. It looks up d1, d2, d7 and d8 in the list of sorted and finds d1, d2 and d8; it never creates an accumulator for d4. It read 8 postings and made 4 accumulators, and it returns d1 3.0283.
Correctness
For plain TAAT, after list each accumulator is the sum of the weights of terms in , and a document has an accumulator if and only if one of these lists contains it. After the last list, maps each matching document to its exact score, and line L5 selects the top by the tie rule. For the max_score variant, let the switch happen before term . A document with no accumulator then contains none of the terms , so its final score is at most . The accumulators only grow, so at least documents end with a score greater than , and the document cannot enter the top . Every document with an accumulator gets all its remaining weights in line M6, so its score is exact. The top of is then the top of all documents. The full proof is in the proof file.
Proof: TAAT and its max_score variant return the exact top kfull
The rank order is score descending, then docid ascending. For a finite set of (docid, score) pairs, is the first pairs of in this order. Let be the set of matching documents and the score of . The weights are exact numbers and at least 0.
Lemma 1 (plain TAAT). After the iteration of line L2, the map has an entry for if and only if one of the lists contains , and then is the sum of the weights of terms in .
Proof. By induction on . For the map is empty and every sum is empty. In iteration , line L3 visits each posting of list once, since the list has distinct docids. Line L4 adds to the old entry or creates the entry with . Entries of documents not in list do not change.
Theorem 1. TAAT returns in the order .
Proof. By Lemma 1 with , the entries of are exactly the pairs for . Line L5 selects the first of them by .
Lemma 2 (the max_score variant before the switch). While or_mode is true at the start of iteration , the map is as in Lemma 1 for the terms in the order of line M1.
Proof. Line M5 is line L4.
Lemma 3. Let the switch happen in line M4 of iteration , and let . Every document with no entry in at that time has . At least documents have a final score greater than .
Proof. By Lemma 2, has no entry exactly when none of the lists contains . So is a sum of weights of terms in , and each weight of term is at most , the largest weight of its list. Weights are at least 0, so . At the switch, and the -th largest value in is greater than , so at least entries are greater than . Each entry is a partial sum of the final score of its document, and the remaining weights are at least 0, so these documents end with scores greater than .
Lemma 4. After the switch no entry is created, and each entry that exists at the switch ends with the exact score of its document.
Proof. Line M6 only updates entries. For an entry and a later list , line M6 finds in list if and only if list contains , since the forward search looks for among the postings at or after the last position, and the docids of are visited in increasing order, so no posting of is passed. It then adds the weight of term in . With Lemma 2, at the end is the sum over all terms.
Theorem 2. TAAT-MAXSCORE returns in the order .
Proof. If there is no switch, the method is plain TAAT on a reordered query, and Theorem 1 applies, since the sum does not depend on the order of exact additions. Else let be the set of documents with an entry at the switch. By Lemma 4, the final map is . Take . By Lemma 3, , and there are documents in with scores greater than , so greater than . Each of them ranks before by , whatever the docids, so is not in . So , which line M7 returns.
Remark 1 (strictness). Lemma 3 needs the -th accumulator strictly greater than . If it were only equal to , a document without an entry could end with and a docid smaller than that of the -th document, and would rank before it.
Remark 2 (floating point). The variant adds the weights in the order of line M1, not in query order. With floating-point weights its sums can differ from those of an exhaustive scan in the last bit, so the scores agree only to a tolerance, and a near tie can break the other way. Lemma 3 also needs the computed sum to be at least every computed partial score that it bounds; this holds with exact arithmetic and is the reason the tests use integers and fractions.
Complexity
Let be the total length of the query lists. The model is the word RAM, with the index and the accumulators in memory.
- Postings read. Plain TAAT reads exactly postings, one pass over each list.
- Accumulators. One for each matching document, at most . On a large collection this can be a large part of ; this is the cost that DAAT avoids.
- Time. With a hash table, each update costs expected, and the selection of the top from at most accumulators with a heap costs . The total is expected. With an array of accumulators the updates are in the worst case, but the array costs to clear and to scan.
- The variant. It makes at most as many accumulators and reads at most as many postings as plain TAAT. In AND mode it does at most forward searches in each later list.
- On disk. Each list is read once from start to end, so only one list needs to be in memory at a time.
Properties
- Exact. Both versions return the exact top . The variant uses only the bounds , which are true maximums of the lists.
- Not an online method. No score is final until the last list has been read, so a threshold test on a whole document, as in WAND, does not apply.
- Order free. The plain method gives the same accumulators in any term order, up to the order of the floating-point additions.
- Memory grows with the matches, not with .
Variants and improvements
- Accumulator limits. Moffat and Zobel (1996) fix a largest number of accumulators. The quit strategy stops when the limit is reached; the continue strategy then only updates existing accumulators, as line M6 does. Both are approximate, because they stop by a count and not by a score bound, so a document of the true top can be left out.
- Impact order. On an impact-ordered index the postings with the largest weights come first, and score-at-a-time evaluation can stop with a proven top or after a fixed budget.
- Frequency-sorted lists. Persin, Zobel and Sacks-Davis (1996) sort each list by term frequency and skip postings below thresholds that are set as the query runs.
- MaxScore. The same bound idea, applied document at a time, is the MaxScore page.
When to use it
Use TAAT when the lists are on disk and must be read in one pass each, when the index is impact ordered, or when the accumulators fit in memory and the code must stay simple. For a docid-ordered index in memory with small , DAAT with dynamic pruning usually does less work. Crane and others (WSDM 2017) compare the two families by measurement on large collections.
Pitfalls
- Missing accumulator. Line L4 must create the accumulator on the first posting of a document. Reading before it exists is an error in many languages.
- Bound from the wrong terms. In line M4, must be the sum of the bounds of the terms not yet read, including term . Using only the next term, or leaving out term , can switch too early and lose a document.
- Greater than, not at least. The switch needs the -th accumulator strictly greater than . With "at least", a new document could tie the -th one and should win by a smaller docid, but it never gets an accumulator.
- Selecting by score only. Line L5 must break ties by docid. A hash table has no docid order, so a selection by score alone returns an arbitrary member of a tie.
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
# 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
term_at_a_time_evaluation.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/term-at-a-time-evaluation/. The authors are listed in prov/AQAN27.jsonl.
"""Term-at-a-time (TAAT) 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.
taat is the plain method: one accumulator per matching document.
taat_maxscore is the max_score variant of Turtle and Flood: it reads the
terms in decreasing order of their upper bounds, and stops creating new
accumulators once no new document can reach the top k.
"""
import heapq
import math
from bisect import bisect_left
class Stats:
"""Work counters: accumulators created and posting weights read."""
def __init__(self):
self.scored = 0
self.postings = 0
def best_k(acc, k):
"""The k best (docid, score) pairs of the accumulators, by the tie rule."""
return heapq.nsmallest(k, acc.items(), key=lambda p: (-p[1], p[0]))
def taat(index, query, k):
"""Return (the top k as a list of (docid, score), Stats)."""
stats = Stats()
if k <= 0:
return [], stats
acc = {} # @line L1
for t in query: # @line L2
for d, w in index.get(t, []): # @line L3
stats.postings += 1
acc[d] = acc[d] + w if d in acc else w # @line L4
stats.scored = len(acc)
return best_k(acc, k), stats # @line L5
def taat_maxscore(index, query, k):
"""TAAT that stops creating accumulators when they cannot matter.
Before term i, R is the sum of the upper bounds of the terms not yet
read. A document with no accumulator has a final score of at most R.
Once the k-th largest accumulator is strictly greater than R, no such
document can enter the top k, so only the existing accumulators are
updated, by forward skips in the remaining lists.
"""
stats = Stats()
if k <= 0:
return [], stats
lists = [index.get(t, []) for t in query]
ub = [max((w for _, w in p), default=0) for p in lists]
order = sorted(range(len(query)), key=lambda i: -ub[i]) # @line M1
acc = {} # @line M2
or_mode = True
for pos, i in enumerate(order): # @line M3
rest = sum(ub[j] for j in order[pos:])
if or_mode and len(acc) >= k and best_k(acc, k)[-1][1] > rest: # @line M4
or_mode = False
if or_mode: # @line M5
for d, w in lists[i]:
stats.postings += 1
acc[d] = acc[d] + w if d in acc else w
else: # @line M6
ids = [d for d, _ in lists[i]]
j = 0
for d in sorted(acc):
j = bisect_left(ids, d, j)
if j < len(ids) and ids[j] == d:
stats.postings += 1
acc[d] = acc[d] + lists[i][j][1]
stats.scored = len(acc)
return best_k(acc, k), stats # @line M7
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]
test_term_at_a_time_evaluation.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/term-at-a-time-evaluation/. The authors are listed in prov/AQAN27.jsonl.
import random
from fractions import Fraction
import irtoy
from term_at_a_time_evaluation import bm25_index, exhaustive_top_k, taat, taat_maxscore
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 close(a, b):
"""Same docids in the same order, and scores equal within 1e-9."""
return [d for d, _ in a] == [d for d, _ in b] and all(abs(x - y) < 1e-9 for (_, x), (_, y) in zip(a, b))
def test_toy_check_values():
index = toy_index()
got, stats = taat(index, irtoy.tokenize(irtoy.QUERIES["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 and stats.postings == 9
got, _ = taat(index, irtoy.tokenize(irtoy.QUERIES["q2"]), 3)
assert [d for d, _ in got] == [4, 3, 5]
assert taat(index, irtoy.tokenize(irtoy.QUERIES["q4"]), 5)[0] == []
def test_toy_maxscore_trace():
# q1 with k = 1: after "search" and "array" the best accumulator,
# d1 = 2.3091, exceeds the bound 0.9497 of "sorted", so "sorted"
# creates no accumulator for d4.
index = toy_index()
got, stats = taat_maxscore(index, irtoy.tokenize(irtoy.QUERIES["q1"]), 1)
assert [d for d, _ in got] == [1] and abs(got[0][1] - 3.0283) < 5e-5
assert stats.scored == 4 and stats.postings == 8
def test_toy_against_exhaustive():
index = toy_index()
for text in irtoy.QUERIES.values():
q = irtoy.tokenize(text)
for k in range(0, 10):
want = exhaustive_top_k(index, q, k, irtoy.DOCS)
assert taat(index, q, k)[0] == want
assert close(taat_maxscore(index, q, k)[0], want)
def test_edges():
index = {"a": [(1, 3), (4, 1)], "b": [(4, 2)]}
for f in (taat, taat_maxscore):
assert f(index, [], 3)[0] == []
assert f(index, ["a"], 0)[0] == []
assert f(index, ["zz"], 3)[0] == []
assert f(index, ["a", "b"], 1)[0] == [(1, 3)]
assert f({"a": [(1, 3), (2, 3), (3, 3)]}, ["a"], 2)[0] == [(1, 3), (2, 3)]
def test_random_against_exhaustive():
rng = random.Random(20251116)
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)
want = exhaustive_top_k(index, q, k, range(1, n + 1))
got, stats = taat(index, q, k)
assert got == want
got2, stats2 = taat_maxscore(index, q, k)
assert got2 == want
union = set()
for t in q:
union.update(d for d, _ in index.get(t, []))
assert stats.scored == len(union)
# The variant never creates more accumulators or reads more weights.
assert stats2.scored <= stats.scored
assert stats2.postings <= stats.postings
History
Turtle and Flood (1995) described term-at-a-time and document-at-a-time evaluation and the max_score optimizations for both. Moffat and Zobel (1996) made accumulator limits practical with the quit and continue strategies and with skips inside compressed lists, and Persin, Zobel and Sacks-Davis (1996) used frequency-sorted lists with dynamic thresholds. Anh and Moffat later moved to impact-ordered indexes, where term-at-a-time and score-at-a-time evaluation are the natural order.
References
- Howard Turtle and James Flood, Query evaluation, strategies and optimizations, Information Processing and Management 31(6), 1995, 831-850, the term-at-a-time strategy with accumulators, its comparison with document-at-a-time evaluation, and the max_score optimization for term-at-a-time evaluation
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 6, Section 6.3.3 (computing vector scores, the accumulators and term-at-a-time scoring) and Chapter 7, Section 7.1 (efficient scoring and ranking)
- Alistair Moffat and Justin Zobel, Self-indexing inverted files for fast text retrieval, ACM Transactions on Information Systems 14(4), 1996, 349-379, the limit on the number of accumulators with the quit and continue strategies, and the skips that make the continue strategy fast
- Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 5, query processing for ranked retrieval (term-at-a-time methods and accumulator pruning)
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.
| 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 AQAN27 Edit this page History Report an error Markdown