Transposition tables: cache what was proved
置换表
Reuse game-search results while preserving bound direction, depth, state identity and evaluation context.
transposition-tablesTwo routes can arrive at the same question
A game search reaches position S through move A, evaluates its continuations, and later reaches S through move B. If both visits ask the same question, the second search can reuse the first answer. A transposition table stores such results so different move sequences can share work.
The difficult part is deciding what the answer means. An alpha–beta call might return 5 after seeing only one reply. It may have proved “at most 5,” while an unseen reply would reduce the exact value to −9. Saving the number without its bound type turns an unfinished calculation into a false fact.
Zobrist’s April 1970 report already discusses repeated positions, storing search levels and value ranges, and distinguishing an incorrect retrieval from an overwritten entry that merely causes more work. Its hash construction addresses fast lookup; it does not remove the need to interpret the stored result. Technical Report 88, printed pages 1–3
This chapter adds a small table to alpha–beta. The examples use a finite graph and exact state keys, so the cache contract can be checked without building a chess engine.
A value belongs to a state, a horizon and a model
Let be the value of the depth- minimax problem, with complete state , acting player , and fixed context . Context includes the rules, terminal-utility convention, evaluator and cutoff policy. A real terminal uses its actual utility; an unfinished depth-zero node uses the configured estimate. Values always use the same Max-player perspective.
A table entry stores a value and one of three meanings:
“Exact” means exact for that particular horizon problem. It does not imply a solved game. With a requested alpha–beta window , a compatible entry can directly answer the call if it is exact, if its lower bound is at least , or if its upper bound is at most . In the last two cases it supplies the required cutoff information without pretending to be an exact value.
Otherwise the entry is insufficient to end the call. A more elaborate implementation can tighten the window using a lower or upper bound. Our code keeps the original window in that case and searches again. This simpler probe rule still uses both bound types for decisive cutoffs.
For a newly searched nonterminal node, retain its entry window before exploring children. The fail-soft return receives the conservative label
The comparison uses the entry window, not the updated alpha or beta at the end. At a MAX node, one inspected child at or above beta establishes a lower bound; at a MIN node, one child at or below alpha establishes an upper bound. Returns inside the original window are exact for the searched horizon. Reusing a valid entry only in one of the three permitted probe cases preserves the same window contract. An induction over remaining depth combines that observation with alpha–beta’s usual bounds.
For this implementation, the cache key is
The object holding the table supplies the fixed context . The complete state and context must stay unchanged during reuse. The player cannot be omitted merely because the board looks the same. Likewise, searching X to depth 2 can return exact 9, while depth 1 returns the evaluator’s −4. Both answers can be correct. A stored deeper value is not automatically equal to the shallower surrogate value.
Production engines may deliberately accept sufficiently deep entries under their search conventions. Stockfish 17.1 checks both depth and bound information before some table cutoffs, with additional conditions. Those rules belong to that engine’s selective search; they do not prove that two arbitrary fixed-depth minimax values are equal. Stockfish 17.1, search.cpp, TT cutoff block
Reuse a shared subtree without changing its value
The complete program uses Python’s standard library. The graph is a finite acyclic mapping from hashable state IDs to either integer terminal utilities or nonempty tuples of child IDs. Each edge consumes one depth unit and switches the acting player. The evaluator accepts (state, maximizing) and returns an integer in Max’s perspective. Inputs are small teaching graphs; there is no whole-graph or cycle validator. Only visited records and queried estimates are checked.
Depth must be a nonnegative integer and the player flag must be a Boolean. Window endpoints may be integers or floats, including infinities, but not booleans or NaNs. Scores remain integers. use_table=False disables both probes and writes while leaving any existing table untouched. A single search object must keep its graph, evaluator and utility/rule context fixed; create a new object or clear its table after a change.
The table stores full Python keys rather than truncated fingerprints. It caches scores and bound types, without move ordering or a best-move field. A terminal or depth-zero estimate can be stored as exact for its own key. The returned call label is still classified against the caller’s window, so a known exact value outside that window can be reported conservatively as an upper or lower result.
from dataclasses import dataclass
from math import inf
@dataclass(frozen=True)
class Entry:
value: int
bound: str
class TableSearch:
# Keep graph and evaluator unchanged while reusing this object's table.
def __init__(self, graph, evaluate=None):
if evaluate is not None and not callable(evaluate):
raise ValueError('evaluate must be callable or None')
self.graph, self.evaluate = graph, evaluate
self.table = {}
def search(self, node, depth, maximizing=True, alpha=-inf, beta=inf,
use_table=True):
if type(depth) is not int or depth < 0 or type(maximizing) is not bool:
raise ValueError('need nonnegative integer depth and Boolean player')
if type(use_table) is not bool:
raise ValueError('use_table must be Boolean')
if (any(type(v) not in (int, float) or v != v for v in (alpha, beta))
or alpha >= beta):
raise ValueError('need numeric non-NaN alpha < beta')
stats = {'calls': 0, 'evaluations': 0, 'hits': 0, 'cache_returns': 0}
def visit(state, left, is_max, a, b):
stats['calls'] += 1
key = state, left, is_max
if use_table and key in self.table:
stats['hits'] += 1
entry = self.table[key]
if (entry.bound == 'exact'
or entry.bound == 'lower' and entry.value >= b
or entry.bound == 'upper' and entry.value <= a):
stats['cache_returns'] += 1
return entry.value
# A nondecisive bound is valid, but this variant searches again.
data = self.graph[state]
if type(data) is int:
value, flag = data, 'exact'
stats['evaluations'] += 1
else:
if type(data) is not tuple or not data:
raise ValueError('nodes need nonempty successor tuples or integer utilities')
if left == 0:
if self.evaluate is None:
raise ValueError('nonterminal cutoff needs an evaluator')
value = self.evaluate(state, is_max)
if type(value) is not int:
raise ValueError('the evaluator must return an integer')
flag = 'exact' # Exact for this depth-zero surrogate only.
stats['evaluations'] += 1
else:
a0, b0 = a, b
value = -inf if is_max else inf
for child in data:
score = visit(child, left - 1, not is_max, a, b)
value = max(value, score) if is_max else min(value, score)
if is_max:
a = max(a, value)
else:
b = min(b, value)
if a >= b:
break
flag = 'upper' if value <= a0 else 'lower' if value >= b0 else 'exact'
if use_table:
self.table[key] = Entry(value, flag)
return value
value = visit(node, depth, maximizing, alpha, beta)
flag = 'upper' if value <= alpha else 'lower' if value >= beta else 'exact'
return {'value': value, 'bound': flag, **stats}
graph = {'R': ('A', 'B'), 'A': ('S', 'T'), 'B': ('S', 'U'),
'S': ('s1', 's2'), 'T': ('t1', 't2'), 'U': ('u1', 'u2'),
's1': 2, 's2': 5, 't1': 4, 't2': 8, 'u1': 6, 'u2': 7}
plain = TableSearch(graph).search('R', 3, use_table=False)
engine = TableSearch(graph)
cached = engine.search('R', 3)
assert plain['value'] == cached['value'] == 5
print('plain', plain)
print('cached', cached)
print('warm', engine.search('R', 3))
# A narrow MIN search observes 5, stops, and only proves an upper bound.
trap = TableSearch({'B': ('first', 'hidden'), 'first': 5, 'hidden': -9})
assert trap.search('B', 1, maximizing=False, alpha=5)['value'] == 5
assert trap.table['B', 1, False] == Entry(5, 'upper')
assert trap.search('B', 1, maximizing=False)['value'] == -9
# Deliberate corruption demonstrates the consequence of lying about the bound.
trap.table['B', 1, False] = Entry(5, 'exact')
assert trap.search('B', 1, maximizing=False)['value'] == 5
print('incorrect exact label returns 5 instead of -9')
# Deeper and shallower exact entries solve different horizon problems.
layered = TableSearch({'X': ('Y',), 'Y': ('Z',), 'Z': 9},
evaluate=lambda state, is_max: -4)
assert layered.search('X', 2)['value'] == 9
assert layered.search('X', 1)['value'] == -4
assert layered.table['X', 2, True].value != layered.table['X', 1, True].value
The shared graph has MAX root R, MIN children A and B, and MAX node S reachable from both. S has terminal children 2 and 5, so its value is 5. A also considers T, whose value is 8; A therefore has value 5. Once R knows that alternative, B’s first reply S suffices to show that B cannot exceed 5, so B’s other reply U is skipped.
The rows compare search without a table, a cold table, and a repeated query of the same root with a warm table. “Returns” counts calls ended directly by a cache lookup.
| Run | Value | Calls | Evals | Returns |
|---|---|---|---|---|
| No table | 5 | 12 | 6 | 0 |
| Cold | 5 | 10 | 4 | 1 |
| Warm | 5 | 1 | 0 | 1 |
A call includes a visit that immediately returns from the table. An evaluation is an actual terminal or cutoff evaluation. The empty-table run avoids S’s repeated leaf evaluations. The last run measures reuse of an already solved query; it is not a fresh-search benchmark. These counts concern this graph and order, not a universal speedup.
The next example first stores Entry(5, 'upper') for the MIN node B. A full-window retry cannot use that bound to stop, so it discovers −9. The deliberately corrupted Entry(5, 'exact') then produces the wrong result 5. Direct modification of the table demonstrates a bug; ordinary use must retain only entries proved by the search.
A table hit is not always a cache return. A nondecisive bound still needs more search in this variant. An exact hit can save an entire subtree, while an unsuccessful lookup adds overhead. If a run makes recursive calls and scans child entries, time is plus evaluator work under expected constant-time hashing and unit-cost score operations. Keys with expensive hashing or equality add their own costs. Collisions can also worsen dictionary lookup time. With stored keys and depth , auxiliary storage is , excluding the graph and the sizes of state keys or large integers. This table has no capacity limit and can keep entries for several depths; it is not an cache.
Identity errors, hash collisions and replacement
A complete chess state needs more than occupied squares: the player to move, legal rights and relevant history can affect the search. Repetition outcomes and move-count rules can make the same board layout behave differently after different paths. If these distinctions are absent from the key or handled by an incompatible reuse policy, a perfectly implemented hash table retrieves the wrong problem’s answer. Stockfish’s inspected search code explicitly calls its high move-count cutoff restriction a partial workaround for graph-history interaction. That is evidence of a complication, not a complete solution to all history cases. Stockfish 17.1, search.cpp, lines 731–734
Hash collisions are a separate issue. Two different full states may receive the same numeric fingerprint even when both states were modeled correctly. Zobrist hashing assigns a random bit string to each relevant feature and XORs the strings for active features:
If a move removes feature and adds feature , the fingerprint can be updated by
Also toggle any changed turn or rule features; captures can remove additional features. XORing the same string twice cancels it, which explains the update. It does not prove uniqueness across different states. For example, 0011 XOR 0101 and 0000 XOR 0110 both equal 0110. Zobrist’s report discusses both lookup clashes and dependencies between related clashes. TR88, printed pages 2–4
There are two common collisions to distinguish: different fingerprints mapping to the same table slot, and different positions sharing the stored fingerprint itself. A table can compare a stored tag to detect many slot collisions, but a shortened tag does not establish full state identity. The Python dictionary here retains the full key and performs equality checks; the tests force all custom state hashes to be equal and still obtain the correct values. A dictionary keyed only by hash(state) would lose that protection.
Stockfish 17.1’s table entry includes a 16-bit key fragment, depth, bound, move, evaluation and generation information. Its probe and replacement code illustrate a different space/performance tradeoff from our full-key dictionary. The inspected code also notes non-atomic updates and possible races; this article does not reproduce that concurrent implementation or its playing-strength results. Stockfish 17.1, tt.cpp
Evicting a correct entry normally removes an opportunity to reuse work; it must not turn the evicted value into evidence about another state. A fixed-capacity implementation needs a replacement policy and key verification on every probe. Replacing an exact entry with a weaker valid bound can be correct but less useful. The example always writes its latest proved result and leaves capacity management as a separate design choice.
Cached moves also need care. A move associated with a cutoff may be useful to search first, without being a proved optimal move. A score hit does not by itself reconstruct a principal variation, and stored moves must remain legal in the current state. Scores measured in distance from the root, such as mate-distance scores, also need compatible conversion before reuse at another ply. Stockfish provides position-relative and root-relative conversion functions for such scores; our utilities have no root-distance adjustment. Stockfish 17.1, value_to_tt/value_from_tt
Check which question an entry answers
- A same-depth entry stores lower bound 8. Can it end a call with beta 7? Can it end one with window
(0,12)? What does a same-depth upper bound 5 allow when alpha is 6? - Reproduce the MIN example with children 5 and −9. Why is its first result an upper bound, and why does relabeling it exact poison a later full-window search?
- X leads to Y, which leads to terminal value 9. Every unfinished cutoff estimates −4. X is MAX. What are its depth-1 and depth-2 values? May an entry for one be returned as the other’s exact value?
- Two different states share a hash, while two other records share a board layout but differ in relevant history. Which problem needs an equality check, and which needs a better state key? Does eviction create either error by itself?
Worked answers
- Answer: Lower bound 8 ends the beta-7 call because the value is at least 8 and therefore at least beta. It cannot end
(0,12)because the exact value might lie inside that window. Upper bound 5 ends an alpha-6 call because the value is at most 5. These answers assume the same state, depth, player and evaluation/rule context. - Answer: With alpha 5, the MIN node stops after reading 5: a minimum cannot exceed an already inspected child. The true minimum might be smaller, and here it is −9. An exact label tells the lookup to trust 5 regardless of window, which suppresses the missing calculation on the later call.
- Answer: At depth 1, Y is an unfinished cutoff, so the value is −4. At depth 2 the terminal is reached, so the value is 9. Both are exact for their own horizon. A deeper result can guide a different search policy, but it is not the shallow problem’s exact answer.
- Answer: A hash collision needs stored identity verification, such as comparing complete keys. Missing history means the key itself describes an incomplete state, so comparing it more carefully cannot recover the omitted information. With correct identity checks and bookkeeping, eviction merely causes a miss and possible recomputation; it does not justify returning another state’s value.
Test cache contracts before measuring speed
The primary report provides the hashing and retrieval-error context; the pinned Stockfish source shows how a production engine stores and interprets table records. The Python code is original teaching code, not a translation of Stockfish’s implementation. Its strict same-depth keys, one-thread execution and full identity checks make an explicit contract that can be verified against exact finite graphs.
The accompanying tests build exact horizon values bottom-up without alpha–beta or bound tags. They then warm tables through different windows and depths, checking every retained entry’s inequality against those values. Separate tests cover collisions, changed evaluator context, terminal precedence, corrupted labels and the displayed call counts. A speed result should report the initial table contents, capacity, replacement policy, move order, evaluator cost and hit definition. Without those details, a warm lookup and a fresh game search can look like the same experiment.
Make a prediction, then check
A compatible entry gives lower bound 8 at the same state, depth, player and context. With window (0,12), can 8 be returned as an exact answer?
Learning objectives
- Distinguish exact and bounded cache values, decide when a window permits direct reuse, and verify depth, player and context compatibility.
- Audit cache correctness with shared DAGs, false labels and forced hash collisions, separating incomplete identity from eviction.
Prerequisites & connections
Explore related knowledge →References
- A New Hashing Method With Application for Game Playing, Technical Report 88
Albert L. Zobrist · 1970 - Stockfish 17.1: transposition-table storage and probe source
The Stockfish developers - Stockfish 17.1: table-bound use, history safeguards and score conversion
The Stockfish developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.
- Reread both languages for the three entry types, entry-window classification, strict same-depth keys, fixed context, terminal precedence, shared-DAG counts, false exact labels, collision/identity distinction, history and root-distance conventions, complexity and four answers. Five display equations, complete Python code and six anchors match.
- Eight independent tests passed: 81 shared DAG assignments with 4,860 depth/player/window queries and 100 random ragged DAGs; every stored entry is checked against a bottom-up exact table without alpha/beta. Additional cases cover decisive bound probes, reported counts, false labels, depth/player/evaluator changes, forced collisions, history keys, XOR and invalid inputs.
- Both temporary MDX articles compiled individually with five display equations and no compiler messages or KaTeX errors; targeted prose scanning passed. Only /tmp/aiwiki-next-transposition was written; repository/shared tables were not changed and review remains written. This is a Codex technical check, not a whole-site build, rendered-page acceptance or independent human expert review.
- A second AI agent used complete strategy payoff matrices and pure-strategy saddle points to independently check 4,860 warm-table window queries, 143,142 stored bounds and 169 writes without reusing the author’s bottom-up oracle. Also confirmed 12/6 → 10/4 → 1/0 counts, visually read the Zobrist cover and printed pages 1–4, and inspected pinned Stockfish sources.
- Root integrated the complete bilingual drafts; migrated tests read only formal src/content/articles files. All 112 search checks and 109 article Python programs passed, with paired code, display formulas, major anchors and sources. Draft-stage written/temp-path notes describe their earlier phase; current hashes are registered after actual checking. No independent human peer review is claimed.
- An actual 390px screenshot showed long headers compressing value/call columns. Shortened both locales’ headers and no-table/cold/warm labels, defining run modes and cache returns above the table. Reread to confirm unchanged numbers, warm/cold premises, code and complexity.
Source locations checked:
- A New Hashing Method With Application for Game Playing, Technical Report 88 · University metadata identifies TR88 and 1970; local rendering of the original cover verifies April 1970. Visually read printed pages 1–4 (PDF pages 3–6) after PDF text extraction returned no text: repeated states, levels/value ranges, two kinds of table errors, XOR update and clustered collisions. Deeper-result reuse is explicitly separated from equality of fixed-horizon surrogate values.
- Stockfish 17.1: transposition-table storage and probe source · Release page resolves sf_17.1 to 03e27488f3d21d8ff4dbf3065603afa21dbd0ef3. Read downloaded tt.cpp physical lines 35–71 (entry fields), 91–112 (save and race note), 217–248 (probe, 16-bit tag and replacement). These are actual file line numbers; normalized browser output used different line counts. No engine strength or runtime benchmark claimed.
- Stockfish 17.1: table-bound use, history safeguards and score conversion · Read downloaded search.cpp physical lines 711–734: depth-qualified bound cutoff and explicitly partial graph-history workaround; lines 1780–1824: mate/TB score conversion between root-relative and position-relative values. The article deliberately implements strict same-depth, full-key, single-thread reuse instead of reproducing selective engine behavior.
Related topics