text stringlengths 21 60 |
|---|
# K_self K_opp DB_Type(win/draw) Compression_Type Block_Size |
24 24 win ZSTD 33554432 |
24 24 draw ZSTD 33554432 |
22 24 win ZSTD 33554432 |
22 24 draw ZSTD 33554432 |
24 22 win ZSTD 33554432 |
24 22 draw ZSTD 33554432 |
20 24 win ZSTD 33554432 |
20 24 draw ZSTD 33554432 |
22 22 win ZSTD 33554432 |
22 22 draw ZSTD 33554432 |
24 20 win ZSTD 33554432 |
24 20 draw ZSTD 33554432 |
18 24 win ZSTD 33554432 |
18 24 draw ZSTD 33554432 |
20 22 win ZSTD 33554432 |
20 22 draw ZSTD 33554432 |
22 20 win ZSTD 33554432 |
22 20 draw ZSTD 33554432 |
24 18 win ZSTD 33554432 |
24 18 draw ZSTD 33554432 |
16 24 win ZSTD 33554432 |
16 24 draw ZSTD 33554432 |
18 22 win ZSTD 33554432 |
18 22 draw ZSTD 33554432 |
20 20 win ZSTD 33554432 |
20 20 draw ZSTD 33554432 |
22 18 win ZSTD 33554432 |
22 18 draw ZSTD 33554432 |
24 16 win ZSTD 33554432 |
24 16 draw ZSTD 33554432 |
14 24 win ZSTD 33554432 |
14 24 draw ZSTD 33554432 |
16 22 win ZSTD 33554432 |
16 22 draw ZSTD 33554432 |
18 20 win ZSTD 33554432 |
18 20 draw ZSTD 33554432 |
20 18 win ZSTD 33554432 |
20 18 draw ZSTD 33554432 |
22 16 win ZSTD 33554432 |
22 16 draw ZSTD 33554432 |
24 14 win ZSTD 33554432 |
24 14 draw ZSTD 33554432 |
12 24 win ZSTD 33554432 |
12 24 draw ZSTD 33554432 |
14 22 win ZSTD 33554432 |
14 22 draw ZSTD 33554432 |
16 20 win ZSTD 33554432 |
16 20 draw ZSTD 33554432 |
18 18 win ZSTD 33554432 |
18 18 draw ZSTD 33554432 |
20 16 win ZSTD 33554432 |
20 16 draw ZSTD 33554432 |
22 14 win ZSTD 33554432 |
22 14 draw ZSTD 33554432 |
24 12 win ZSTD 33554432 |
24 12 draw ZSTD 33554432 |
10 24 win ZSTD 33554432 |
10 24 draw ZSTD 33554432 |
12 22 win ZSTD 33554432 |
12 22 draw ZSTD 33554432 |
14 20 win ZSTD 33554432 |
14 20 draw ZSTD 33554432 |
16 18 win ZSTD 33554432 |
16 18 draw ZSTD 33554432 |
18 16 win ZSTD 33554432 |
18 16 draw ZSTD 33554432 |
20 14 win ZSTD 33554432 |
20 14 draw ZSTD 33554432 |
22 12 win ZSTD 33554432 |
22 12 draw ZSTD 33554432 |
24 10 win ZSTD 33554432 |
24 10 draw ZSTD 33554432 |
8 24 win ZSTD 33554432 |
8 24 draw ZSTD 33554432 |
10 22 win ZSTD 33554432 |
10 22 draw ZSTD 33554432 |
12 20 win ZSTD 33554432 |
12 20 draw ZSTD 33554432 |
14 18 win ZSTD 33554432 |
14 18 draw ZSTD 33554432 |
16 16 win ZSTD 33554432 |
16 16 draw ZSTD 33554432 |
18 14 win ZSTD 33554432 |
18 14 draw ZSTD 33554432 |
20 12 win ZSTD 33554432 |
20 12 draw ZSTD 33554432 |
22 10 win ZSTD 33554432 |
22 10 draw ZSTD 33554432 |
24 8 win ZSTD 33554432 |
24 8 draw ZSTD 33554432 |
6 24 win ZSTD 33554432 |
6 24 draw ZSTD 33554432 |
8 22 win ZSTD 33554432 |
8 22 draw ZSTD 33554432 |
10 20 win ZSTD 33554432 |
10 20 draw ZSTD 33554432 |
12 18 win ZSTD 33554432 |
12 18 draw ZSTD 33554432 |
14 16 win ZSTD 33554432 |
Bestemshe TableBase — Strong Solution Proof
Authors: Ansar Zeinulla & Murat Manassov
Affiliation: Nazarbayev University, Kazakhstan
Code Repository: github.com/ansarzeinulla/Bestemshe
Live Interactive Explorer: huggingface.co/spaces/ansarzeinulla/bestemshe-god-algorithm
Bestemshe is a traditional Kazakh two-player mancala-style game (5 pits per player, 50 total stones). This artifact is a strong solution of the game: for every reachable, legal position the exact game-theoretic value (win / draw for the side to move) has been computed by retrograde analysis and stored, enabling perfect play via direct $O(1)$ lookup without runtime search.
Together with the solver that produced it, this tablebase constitutes a machine-verifiable proof of the game's outcome under optimal play: a forced win for the second player (Follower).
Technical Summary & Compression Mechanics
A position is described by the two Kazans (captured-stone stores) k1 (side to move) and k2 (opponent), and ten pits of 0..50 stones. Material is conserved:
Captures are strictly even, so each Kazan score is an even integer ($0 \le k_1, k_2 \le 24$). Positions are stored canonically from the side-to-move perspective.
Layer Layout & Storage
The dataset is sharded into 169 layers indexed by the Kazan pair (k1, k2). Each layer consists of two Zstandard-compressed bitset files:
layer_<k1>_<k2>_win.bin— WIN/LOSS bitset for that layer.layer_<k1>_<k2>_draw.bin— DRAW bitset for that layer.
Bitsets are indexed via a colexicographical ranking function ($I_B$) that maps multiset stone distributions directly to contiguous integer offsets. Each file contains a 4-byte header specifying the number of 4 MiB decompressed blocks, followed by block offsets.
| Metric | Value |
|---|---|
Layer pairs (k1, k2) |
169 |
| Total files | 338 (169 win + 169 draw) |
| WIN files total size | 6.0 GB |
| DRAW files total size | 2.4 GB |
| Grand Total Size | 8.3 GB (8,962,782,421 bytes) |
Remote O(1) HTTP Range Query Client (No Download Required)
You do not need to download the 8.3 GB dataset to query board evaluations. Using HTTP Range headers, the following Python script fetches only the specific 4 MiB compressed block containing the target bit over the network.
Prerequisites
pip install requests zstandard
Python Query Script
"""Query the Bestemshe endgame oracle on Hugging Face by (k1, k2, pits).
Needs only: pip install requests zstandard
"""
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from typing import Iterable, Literal, NamedTuple
import requests
import zstandard
BASE_URL = ("https://huggingface.co/datasets/ansarzeinulla/"
"bestemshe-tablebase/resolve/main/layers/compressed")
TOTAL_STONES = 50 # conserved: k1 + k2 + sum(pits)
NUM_PITS = 5 # pits per side
MAX_KAZAN = 24 # largest kazan the dataset stores
WIN_THRESHOLD = 26 # a kazan this large has already won
BYTES_PER_BLOCK = 33_554_432 // 8 # 4 MiB decompressed per block
Verdict = Literal["win", "loss", "draw", "unknown"]
@dataclass(frozen=True)
class Position:
"""Side-to-move relative. pits[0:5] are the mover's own pits."""
k1: int
k2: int
pits: tuple[int, ...] # length 10
def is_valid(self) -> bool:
if not (0 <= self.k1 <= MAX_KAZAN and self.k1 % 2 == 0):
return False
if not (0 <= self.k2 <= MAX_KAZAN and self.k2 % 2 == 0):
return False
if len(self.pits) != 10 or any(not 0 <= p < TOTAL_STONES for p in self.pits):
return False
return self.k1 + self.k2 + sum(self.pits) == TOTAL_STONES
# ---------------------------------------------------------------- indexing
@lru_cache(maxsize=None)
def n_c_r(n: int, r: int) -> int:
"""Exact binomial; 0 outside the domain, matching StateIndex.h's nCr."""
if n < 0 or r < 0 or n < r:
return 0
if r == 0 or n == r:
return 1
r = min(r, n - r)
result = 1
for i in range(r):
result = result * (n - i) // (i + 1)
return result
def min_kazan(m: int) -> int:
"""Smallest possible side-to-move kazan given m = k1 + k2 captured."""
return max(0, m - MAX_KAZAN)
def index_state(pos: Position) -> int:
"""The position's rank inside its (k1, k2) layer.
I_K selects the kazan slice, I_B ranks the board composition as a
multiset — the standard stars-and-bars combinatorial rank.
"""
m = pos.k1 + pos.k2
i_k = (pos.k1 - min_kazan(m)) // 2
i_b = 0
running = 0
for i in range(9): # 9, not 10: the last pit is implied
running += pos.pits[i]
i_b += n_c_r(i + running, i + 1)
remaining = TOTAL_STONES - m
return i_k * n_c_r(remaining + 9, 9) + i_b
class BitLocation(NamedTuple):
block_index: int
local_byte: int # byte offset inside the DECOMPRESSED block
bit_offset: int # 0..7, little-endian within the byte
def bit_location(rank: int) -> BitLocation:
byte_index = rank // 8
return BitLocation(
block_index=byte_index // BYTES_PER_BLOCK,
local_byte=byte_index % BYTES_PER_BLOCK,
bit_offset=rank % 8,
)
def layer_urls(pos: Position, base_url: str = BASE_URL) -> tuple[str, str]:
"""(win_url, draw_url) for this position's layer."""
return (f"{base_url}/layer_{pos.k1}_{pos.k2}_win.bin",
f"{base_url}/layer_{pos.k1}_{pos.k2}_draw.bin")
# ------------------------------------------------------------------ moves
class Child(NamedTuple):
pit: int # 0..4, the mover's own pit
position: Position | None # None when the move ends the game outright
wins_immediately: bool # opponent row emptied, or kazan >= 26
def legal_pits(pos: Position) -> list[int]:
return [i for i in range(NUM_PITS) if pos.pits[i] > 0]
def apply_move(pos: Position, pit: int) -> Child:
"""Sow one pit and return the child ALREADY FLIPPED to the opponent's view."""
pits = list(pos.pits)
stones = pits[pit]
if stones == 0:
raise ValueError(f"pit {pit} is empty")
pits[pit] = 0
if stones == 1:
last = (pit + 1) % 10
pits[last] += 1
else:
pits[pit] = 1
last = pit
for _ in range(stones - 1):
last = (last + 1) % 10
pits[last] += 1
captured = 0
if last >= NUM_PITS and pits[last] % 2 == 0:
captured, pits[last] = pits[last], 0
mover_kazan = pos.k1 + captured
opponent_starved = all(p == 0 for p in pits[NUM_PITS:])
if opponent_starved or mover_kazan >= WIN_THRESHOLD:
return Child(pit=pit, position=None, wins_immediately=True)
child = Position(
k1=pos.k2,
k2=mover_kazan,
pits=tuple(pits[NUM_PITS:] + pits[:NUM_PITS]),
)
return Child(pit=pit, position=child, wins_immediately=False)
# ----------------------------------------------------------------- oracle
INVERSE: dict[Verdict, Verdict] = {
"win": "loss", "loss": "win", "draw": "draw", "unknown": "unknown",
}
class Oracle:
"""Reads single bits out of the remote .bin layers via HTTP Range."""
def __init__(self, base_url: str = BASE_URL, session: requests.Session | None = None):
self.base_url = base_url
self.session = session or requests.Session()
self._headers: dict[str, list[int] | None] = {}
self._blocks: dict[tuple[str, int], bytes] = {}
def _range_get(self, url: str, start: int, end: int) -> bytes | None:
resp = self.session.get(url, headers={"Range": f"bytes={start}-{end}"})
if resp.status_code == 404:
return None
resp.raise_for_status()
return resp.content
def offsets(self, url: str) -> list[int] | None:
if url in self._headers:
return self._headers[url]
head = self._range_get(url, 0, 4095)
if head is None:
self._headers[url] = None
return None
num_blocks = int.from_bytes(head[:4], "little")
need = 4 + 4 * (num_blocks + 1)
if len(head) < need:
head = self._range_get(url, 0, need - 1)
table = [int.from_bytes(head[4 + 4 * i: 8 + 4 * i], "little")
for i in range(num_blocks + 1)]
self._headers[url] = table
return table
def block(self, url: str, block_index: int) -> bytes:
cached = self._blocks.get((url, block_index))
if cached is not None:
return cached
table = self.offsets(url)
if table is None or block_index + 1 >= len(table):
return b""
start, end = table[block_index], table[block_index + 1] - 1
compressed = self._range_get(url, start, end) or b""
data = zstandard.ZstdDecompressor().decompress(
compressed, max_output_size=BYTES_PER_BLOCK)
self._blocks[(url, block_index)] = data
return data
def locate(self, pos: Position) -> dict:
"""Resolve a position to its exact file + byte range without downloading."""
rank = index_state(pos)
loc = bit_location(rank)
win_url, draw_url = layer_urls(pos, self.base_url)
plan = {"rank": rank, "block_index": loc.block_index,
"local_byte": loc.local_byte, "bit_offset": loc.bit_offset,
"files": {}}
for name, url in (("win", win_url), ("draw", draw_url)):
table = self.offsets(url)
if table is None:
plan["files"][name] = {"url": url, "exists": False}
continue
plan["files"][name] = {
"url": url,
"exists": True,
"byte_range": (table[loc.block_index],
table[loc.block_index + 1] - 1),
"compressed_size": table[loc.block_index + 1] - table[loc.block_index],
}
return plan
def value(self, pos: Position) -> Verdict:
"""Verdict from the SIDE TO MOVE's perspective."""
if not pos.is_valid():
return "unknown"
rank = index_state(pos)
loc = bit_location(rank)
win_url, draw_url = layer_urls(pos, self.base_url)
if self.offsets(draw_url) is None or self.offsets(win_url) is None:
return self._derive(pos)
def read_bit(url: str) -> int:
data = self.block(url, loc.block_index)
if loc.local_byte >= len(data):
return 0
return (data[loc.local_byte] >> loc.bit_offset) & 1
if read_bit(draw_url):
return "draw"
return "win" if read_bit(win_url) else "loss"
def children_values(self, pos: Position) -> list[dict]:
"""Evaluate all legal child moves."""
out = []
for pit in legal_pits(pos):
child = apply_move(pos, pit)
if child.wins_immediately:
out.append({"pit": pit, "position": None,
"value": "loss", "value_for_mover": "win",
"terminal": True})
continue
child_value = self.value(child.position)
out.append({"pit": pit, "position": child.position,
"value": child_value,
"value_for_mover": INVERSE[child_value],
"terminal": False})
return out
def _derive(self, pos: Position) -> Verdict:
children = self.children_values(pos)
if not children:
return "loss"
if any(c["value_for_mover"] == "win" for c in children):
return "win"
if any(c["value"] == "unknown" for c in children):
return "unknown"
return "draw" if any(c["value"] == "draw" for c in children) else "loss"
if __name__ == "__main__":
start = Position(k1=0, k2=0, pits=(5,) * 10)
oracle = Oracle()
print("Position Byte Plan:", oracle.locate(start))
print("Initial Position Verdict:", oracle.value(start))
print("\nChild Move Analysis:")
for child in oracle.children_values(start):
print(f" Pit {child['pit'] + 1}: Mover gets {child['value_for_mover']}")
Citation
@misc{zeinulla2026bestemshe,
title={Strongly Solving Bestemshe: A 10-Gigabyte Retrograde Tablebase Proof},
author={Zeinulla, Ansar and Manassov, Murat},
year={2026},
publisher={Hugging Face Datasets},
howpublished={\url{https://huggingface.co/datasets/ansarzeinulla/bestemshe-tablebase}}
}
- Downloads last month
- 124