File size: 3,878 Bytes
ac5beb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Encode the parquet shards into arrays for fast GPU training."""

from __future__ import annotations

import argparse
import glob
from pathlib import Path

import chess
import numpy as np
import pandas as pd
from tqdm import tqdm

PIECES = [chess.PAWN, chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN, chess.KING]


def encode_board(board: chess.Board) -> np.ndarray:
    x = np.zeros((20, 8, 8), dtype=np.uint8)
    for square, piece in board.piece_map().items():
        rank = chess.square_rank(square)
        file = chess.square_file(square)
        base = 0 if piece.color == chess.WHITE else 6
        x[base + piece.piece_type - 1, rank, file] = 1

    if board.turn == chess.WHITE:
        x[12, :, :] = 1

    if board.has_kingside_castling_rights(chess.WHITE):
        x[13, :, :] = 1
    if board.has_queenside_castling_rights(chess.WHITE):
        x[14, :, :] = 1
    if board.has_kingside_castling_rights(chess.BLACK):
        x[15, :, :] = 1
    if board.has_queenside_castling_rights(chess.BLACK):
        x[16, :, :] = 1

    if board.ep_square is not None:
        x[17, chess.square_rank(board.ep_square), chess.square_file(board.ep_square)] = 1

    x[18, :, :] = min(100, board.halfmove_clock)
    # No repetition history is stored in the FEN; plane 19 stays zero.
    return x


def legal_bits(board: chess.Board) -> np.ndarray:
    mask = np.zeros(4096, dtype=np.uint8)
    for move in board.legal_moves:
        mask[move.from_square * 64 + move.to_square] = 1
    return np.packbits(mask)


def value_target(cp, mate) -> float:
    if mate is not None and not pd.isna(mate):
        return 1.0 if float(mate) > 0 else -1.0
    if cp is not None and not pd.isna(cp):
        return float(np.tanh(float(cp) / 400.0))
    return 0.0


def build_split(paths: list[str], out_dir: Path, name: str) -> None:
    frames = [pd.read_parquet(path) for path in paths]
    df = pd.concat(frames, ignore_index=True)
    n = len(df)
    planes = np.empty((n, 20, 8, 8), dtype=np.uint8)
    legal = np.empty((n, 512), dtype=np.uint8)
    moves = np.empty(n, dtype=np.int32)
    values = np.empty(n, dtype=np.float16)
    wdls = np.empty(n, dtype=np.int8)

    kept = 0
    for _, row in tqdm(df.iterrows(), total=n, desc=name):
        try:
            board = chess.Board(row["fen"])
            move = chess.Move.from_uci(row["move_uci"])
        except Exception:
            continue
        if move not in board.legal_moves:
            continue
        planes[kept] = encode_board(board)
        legal[kept] = legal_bits(board)
        moves[kept] = move.from_square * 64 + move.to_square
        values[kept] = value_target(row.get("cp"), row.get("mate"))
        wdls[kept] = int(row.get("wdl", 1))
        kept += 1

    planes = planes[:kept]
    legal = legal[:kept]
    moves = moves[:kept]
    values = values[:kept]
    wdls = wdls[:kept]

    out_dir.mkdir(parents=True, exist_ok=True)
    np.save(out_dir / f"{name}_planes.npy", planes)
    np.save(out_dir / f"{name}_legal.npy", legal)
    np.save(out_dir / f"{name}_move.npy", moves)
    np.save(out_dir / f"{name}_value.npy", values)
    np.save(out_dir / f"{name}_wdl.npy", wdls)
    print(f"{name}: {kept:,} rows -> {out_dir}")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", default="data")
    parser.add_argument("--val", default="val")
    parser.add_argument("--out", default="prepared")
    args = parser.parse_args()

    out_dir = Path(args.out)
    train_files = sorted(glob.glob(str(Path(args.data) / "*.parquet")))
    val_files = sorted(glob.glob(str(Path(args.val) / "*.parquet")))
    if not train_files:
        raise SystemExit("no train parquet files")
    build_split(train_files, out_dir, "train")
    if val_files:
        build_split(val_files, out_dir, "val")


if __name__ == "__main__":
    main()