File size: 4,561 Bytes
b37580f
 
 
 
2e0a1b0
 
 
 
 
 
 
 
 
b37580f
 
2e0a1b0
b37580f
2e0a1b0
 
b37580f
 
 
 
 
 
0272a42
 
 
bc9b170
0272a42
bc9b170
 
 
 
dbbec0d
6b5058c
dbbec0d
 
 
bc9b170
 
 
 
 
0272a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
---
dataset_info:
  features:
  - name: fen
    dtype: string
  - name: n_moves
    sequence: int64
  - name: term_n_moves
    sequence: int64
  - name: term_reason
    sequence: int64
  - name: term_white_wins
    sequence: bool
  splits:
  - name: train
    num_bytes: 9224260318
    num_examples: 100000054
  download_size: 4539320801
  dataset_size: 9224260318
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train-*
---

# 100M Random Chess Boards

This dataset contains 100 million randomly sampled chess board positions. The process to generate each board state is as follows:

1. **Game Simulation**
- 100 million games were played, with each move being randomly determined until the game ended (i.e., until checkmate, stalemate, or draw).
2. **Board Sampling**
- From each game, a single random board state was selected at some point in the game.

Columns other than **fen** represent statistics for the sample. Most boards are sampled only once, however for example, the most common board, the initial board, is sampled 378,310 times. This comprises a single row with each column other than **fen** being 378,310 long.

# Columns

- **fen**: The FEN (Forsyth-Edwards Notation) representing the randomly sampled board position.
- **n_moves**: The number of moves made from the start of the game to reach the sampled FEN position.
- **term_n_moves**: The total number of moves in the random game before it terminated.
- **term_reason**: The reason the game ended. ([Codes](https://python-chess.readthedocs.io/en/latest/core.html#chess.Termination))
- **term_white_wins**: Indicates whether white won the game (true/false). null indicates a tie. Note that all games are complete, but the sampled board position is from an intermediate point.

# Code

```python3
from tqdm import tqdm
import collections
import chess
import random
from datasets import Dataset

import os
from multiprocessing import Process, Queue


def random_fen():
    """
    Play random game to completion
    backtrack random uniform number of moves
    """
    board = chess.Board()
    num_moves = 0
    while True:
        board.push(random.choice(list(board.legal_moves)))
        num_moves += 1
        if board.is_game_over():
            outcome = board.outcome()
            revert_moves = random.randint(0, num_moves)
            for _ in range(revert_moves):
                board.pop()
            fen_num_moves = num_moves - revert_moves
            termination_reason = outcome.termination.value
            white_is_winner = outcome.winner
            return board.fen(), fen_num_moves, num_moves, termination_reason, white_is_winner


def batched_random_fen(queue, batch_size=100):
    while True:
        fens = []
        while len(fens) < batch_size:
            fens.append(random_fen())
        queue.put(fens)


def generate_fens_parallel(N):
    all_fens = collections.defaultdict(
        lambda: {"n_moves": [], "term_n_moves": [], "term_reason": [], "term_white_wins": []}
    )
    queue = Queue()
    num_workers = os.cpu_count() // 2

    # Start worker processes in advance
    workers = []
    for _ in range(num_workers):
        worker = Process(target=batched_random_fen, args=(queue,))
        worker.daemon = True  # Ensures the process terminates with the main process
        workers.append(worker)
        worker.start()

    with tqdm(total=N, desc="FENs Captured") as pbar:
        for i in range(1_000_000_000_000):
            for fen, board_num_moves, final_state_num_moves, final_result, final_is_white_winner in queue.get():
                all_fens[fen]["n_moves"].append(board_num_moves)
                all_fens[fen]["term_n_moves"].append(final_state_num_moves)
                all_fens[fen]["term_reason"].append(final_result)
                all_fens[fen]["term_white_wins"].append(final_is_white_winner)

            if i % 100 == 0:
                pbar.n = len(all_fens)
                pbar.last_print_n = len(all_fens)
                pbar.refresh()

            if len(all_fens) >= N:
                break

    # Terminate workers
    for worker in workers:
        worker.terminate()

    # flatten
    return [{"fen": k, **v} for k, v in all_fens.items()]


if __name__ == "__main__":
    board_dicts = list(generate_fens_parallel(100_000_000))
    ds = Dataset.from_dict({key: [dic[key] for dic in board_dicts] for key in board_dicts[0]})
    ds.save_to_disk("random_uniform_chess_boards.hf")
    # ds = datasets.load_from_disk("random_uniform_chess_boards.hf")
    # ds.push_to_hub(...)
```