"""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", "> 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"]))