CodeRigor

LESSON

Zobrist keys and a transposition table

Hash a position with XORed random keys, update the hash move by move, and let alpha-beta reuse results through a fixed-size table with exact, lower and upper bounds.

A chess search reaches the same position again and again by different move orders, and searching it twice wastes the work. This lesson is about recognising a position cheaply and remembering what you found out about it. It pairs with Coding Adventure: Chess and Coding Adventure: Making a Better Chess Bot by Sebastian Lague, linked under Watch & read. The first has a chapter called The Transposition Table and the second one called Transposition Troubles. You build a Zobrist hash with incremental updates, a fixed-size table, and an alpha-beta search that uses the table.

After 1.Nf3 Nf6 2.Nc3 and after 1.Nc3 Nf6 2.Nf3 the board is the same, with the same side to move. A search tree draws these as two different nodes. The real structure is a graph in which several paths lead to one position, and a position you have already searched deserves to be searched once.

Two move orders, one position
start / 3
Both orders end in the same position. A table keyed on the position finds the second visit already searched.
Two move orders, one position
Both orders end in the same position. A table keyed on the position finds the second visit already searched.

The effect can be large. Take a toy game in which a point moves by (1, 0), (0, 1) or (1, 1) each turn. The snippet counts the move sequences and the distinct places they reach.

Python
from itertools import product

moves = [(1, 0), (0, 1), (1, 1)]
for plies in (4, 6, 8):
    seqs = list(product(moves, repeat=plies))
    spots = {(sum(m[0] for m in s), sum(m[1] for m in s)) for s in seqs}
    print(plies, len(seqs), len(spots))

To spot a repeat you need a name for a position that is quick to compute. Zobrist hashing gives every fact that can be true of a position a random 64-bit key: each piece on each square (12 × 64 keys), black to move, each castling right, each en passant file. The hash of a position is the XOR of the keys of the facts that hold. XOR is its own inverse and does not care about order, so a move changes the hash with a handful of XORs: remove the moving piece from its old square, add it on the new one, remove a captured piece, flip the side key, and toggle the castling and en passant keys that changed. You never rescan the board.

Here is the arithmetic with one-bit keys. A white pawn on square 12 is 000001, on square 28 is 000010, black to move is 000100, the rights K and Q are 001000 and 010000, and en passant on the e file is 100000. White pawn on 12 with both rights hashes to 011001. After 12 → 28 the update XORs out 000001, XORs in 000010 and 000100 (the side) and 100000 (the e file), giving 111110. Hashing the new position from scratch gives the same 111110. Real keys are 64 bits wide:

Python
import random

rng = random.Random(1)
piece = {(p, sq): rng.getrandbits(64) for p in "Pp" for sq in range(64)}
side = rng.getrandbits(64)

scratch = piece["P", 12] ^ piece["p", 52]         # white pawn e2, black pawn e7, white to move
after = piece["P", 28] ^ piece["p", 52] ^ side    # e2-e4, black to move
step = scratch ^ piece["P", 12] ^ piece["P", 28] ^ side
print(step == after, step & 1023)

The table is an array of fixed size. The slot of a key is its low bits, key & (size - 1), which is why the size must be a power of two. Each slot holds one entry: the full key, the depth searched, a flag, a value and the best move. Different positions land in the same slot far more often than people expect: 700 random keys fill only 510 of 1024 slots, so 190 of them share. When two positions want one slot, a depth-preferred rule keeps the entry that cost more to compute: a new entry replaces the old one only when its depth is at least as large.

Python
import random

rng = random.Random(3)
keys = [rng.getrandbits(64) for _ in range(700)]
slots = {k & 1023 for k in keys}
print(len(keys), len(slots), len(keys) - len(slots))

The flag matters because alpha-beta often does not find a value, only a bound. Remember alpha before the loop. If the best value never beat that alpha, every move was at most that good, and the value is an upper bound (UPPER). If best reached beta, the loop stopped early and the value is a lower bound (LOWER). Only a value strictly between the two is exact. When you probe, the entry is usable only if its depth is at least what you need and its flag settles the current window: EXACT always, LOWER when the value is at least beta, UPPER when it is at most alpha.

One slot, two positions
start / 4
Keys A and B have the same low bits. Probing B must compare the whole key and report a miss, and the deeper entry survives a shallower store.
One slot, two positions
Keys A and B have the same low bits. Probing B must compare the whole key and report a miss, and the deeper entry survives a shallower store.

Two numbers show what the table buys. In a graph where A and B both lead to a position C, searching C a second time from the table takes 7 nodes against 9 without it, and the value is the same. In a 6 by 6 version of the toy game searched 9 plies deep, plain alpha-beta visits 1017 nodes and the table version 209 with a 4096-slot table, again with the same value.

The mistakes are quiet because the program still runs. Storing every result as EXACT turns a bound into a claim, and a later search in a different window believes it. Probing without comparing the full key hands you the occupant of the slot, which belongs to another position: the answer looks plausible and is wrong. Two more are worth knowing: using an entry from a shallower search for a deeper one, and leaving the side to move out of the key.

The tests compare the table search with plain negamax on many seeded games, including a table with one slot where every probe collides, and compare incremental hashes with hashes from scratch over captures, castling and promotion. That shows the table does not change the value in those games. It does not show that two real positions never share a 64-bit key, which is only very unlikely. In these tests the ply is part of each key, so a matching key always means the same remaining depth. Engines usually accept an entry searched deeper than needed, which can change the result slightly.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A chess bot built from scratch in 29 minutes. Its chapter The Transposition Table is the part that matches this lesson: why the same position keeps coming back and what the bot stores about it.