File size: 3,832 Bytes
6f2fca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read Snail Chess Data records.

The files are xz-compressed (partNN.bin.xz). Decompressed, each one is a flat array of
32-byte little-endian records:

    occupied  u64     bit i set = square i is occupied (a1 = 0, b1 = 1, ..., h8 = 63)
    pieces    16 B    one 4-bit piece code per occupied square, in ascending square order,
                      low nibble first
    score     i16     search score in centipawns, from White's point of view
    base      i16     lean base eval (material + piece-square tables + pawn structure), White's view
    eval      i16     the generating engine's full static eval, White's view, without tempo
    flags     u8      bit 0 = black to move, bit 1 = endgame scaling applies to the base eval
    result    u8      game result: 0 = black won, 1 = draw, 2 = white won

Piece codes are kind << 1 | colour, with colour 0 = white and kinds
1 pawn, 2 knight, 3 bishop, 4 rook, 5 queen, 6 king.
"""

import lzma

import numpy as np

RECORD = np.dtype([
    ("occupied", "<u8"),
    ("pieces", "u1", 16),
    ("score", "<i2"),
    ("base", "<i2"),
    ("eval", "<i2"),
    ("flags", "u1"),
    ("result", "u1"),
])
assert RECORD.itemsize == 32

LETTERS = " ?PpNnBbRrQqKk"


def read(path):
    """Return the records of one .bin.xz (or already decompressed .bin) file as a numpy structured array."""
    path = str(path)
    if path.endswith(".xz"):
        with lzma.open(path) as f:
            return np.frombuffer(f.read(), dtype=RECORD)
    return np.memmap(path, dtype=RECORD, mode="r")


def squares(record):
    """Yield (square, piece code) for every piece in one record."""
    occupied = int(record["occupied"])
    pieces = record["pieces"]
    i = 0
    while occupied:
        square = (occupied & -occupied).bit_length() - 1
        occupied &= occupied - 1
        yield square, (int(pieces[i >> 1]) >> (4 * (i & 1))) & 15
        i += 1


def to_fen(record):
    """FEN of one record. Castling rights and en passant are not stored, so they are always '-'."""
    board = [""] * 64
    for square, code in squares(record):
        board[square] = LETTERS[code]
    rows = []
    for rank in range(7, -1, -1):
        row, empty = "", 0
        for file in range(8):
            piece = board[rank * 8 + file]
            if piece:
                row += (str(empty) if empty else "") + piece
                empty = 0
            else:
                empty += 1
        rows.append(row + (str(empty) if empty else ""))
    side = "b" if record["flags"] & 1 else "w"
    return f"{'/'.join(rows)} {side} - - 0 1"


def planes(records):
    """12 x 64 one-hot piece planes (white P N B R Q K, then black), shape (n, 768), uint8."""
    n = len(records)
    occupied = np.ascontiguousarray(records["occupied"]).view(np.uint8).reshape(n, 8)
    bits = np.unpackbits(occupied, axis=1, bitorder="little").astype(bool)
    packed = np.asarray(records["pieces"])
    nibbles = np.empty((n, 32), dtype=np.uint8)
    nibbles[:, 0::2] = packed & 15
    nibbles[:, 1::2] = packed >> 4
    order = np.cumsum(bits, axis=1) - 1
    rows, squares_ = np.nonzero(bits)
    codes = nibbles[rows, order[rows, squares_]].astype(np.int64)
    out = np.zeros((n, 768), dtype=np.uint8)
    out[rows, ((codes & 1) * 6 + (codes >> 1) - 1) * 64 + squares_] = 1
    return out


def target(records, scale=120.0):
    """Training target used for Shell: sigmoid(search score / scale), White's view.

    The scale was fitted per training run: 140 for gen4, 125 for gen5, 120 for gen6.
    """
    return 1.0 / (1.0 + np.exp(-records["score"].astype(np.float32) / scale))


if __name__ == "__main__":
    import sys

    records = read(sys.argv[1])
    print(f"{len(records):,} records")
    for record in records[:5]:
        print(to_fen(record), "score", int(record["score"]), "result", int(record["result"]))