//! Lc0 V6 training data (one gzipped file of 8356-byte records per game, //! packed in hourly tar files) converted to montyformat games. //! //! Each record holds the position as input planes, the search's visit //! fractions over Lc0's 1858 policy outputs (-1 for illegal moves) and the //! move that was played. A game is rebuilt from its first record and the //! played moves, and every record is checked against the rebuilt position: //! the pieces must match and the moves Lc0 gave a probability must be exactly //! the legal moves. A game is cut at the first record that fails; with the //! LC0_DEBUG environment variable set, the reason is printed to stderr. use montyformat::{ chess::{Castling, Flag, Move, Piece, Position, Right, Side}, MontyFormat, SearchData, }; use crate::lc0_policy::POLICY_INDEX; pub const RECORD_SIZE: usize = 8356; const OFF_PROBS: usize = 8; const OFF_PLANES: usize = 7440; const OFF_CASTLING: usize = 8272; const OFF_STM: usize = 8276; const OFF_RULE50: usize = 8277; const OFF_BEST_Q: usize = 8284; const OFF_RESULT_Q: usize = 8308; const OFF_PLAYED_IDX: usize = 8344; /// Why records were dropped, and how much was kept. #[derive(Default, Clone, Copy, Debug)] pub struct Stats { pub games: u64, pub positions: u64, pub bad_format: u64, pub bad_start: u64, pub cut_board: u64, pub cut_moves: u64, pub cut_played: u64, pub dropped_records: u64, } impl Stats { pub fn add(&mut self, o: &Stats) { self.games += o.games; self.positions += o.positions; self.bad_format += o.bad_format; self.bad_start += o.bad_start; self.cut_board += o.cut_board; self.cut_moves += o.cut_moves; self.cut_played += o.cut_played; self.dropped_records += o.dropped_records; } } /// (from, to, promotion piece or 0) -> Lc0 policy index, in the side to /// move's frame. Knight promotions are the plain move. pub struct PolicyMap { index: Vec, } fn key(from: usize, to: usize, promo: usize) -> usize { (from * 64 + to) * 8 + promo } impl Default for PolicyMap { fn default() -> Self { let mut index = vec![-1i16; 64 * 64 * 8]; for (i, uci) in POLICY_INDEX.iter().enumerate() { let b = uci.as_bytes(); let sq = |f: u8, r: u8| usize::from(r - b'1') * 8 + usize::from(f - b'a'); let from = sq(b[0], b[1]); let to = sq(b[2], b[3]); let promo = match b.get(4) { None => 0, Some(b'q') => Piece::QUEEN, Some(b'r') => Piece::ROOK, Some(b'b') => Piece::BISHOP, Some(_) => unreachable!(), }; index[key(from, to, promo)] = i as i16; } Self { index } } } impl PolicyMap { /// Lc0 index of a montyformat move. Lc0 encodes castling as the king /// taking its own rook (e1h1 / e1a1, or wherever the rook is in Chess960). pub fn index(&self, pos: &Position, castling: &Castling, mov: Move) -> Option { let flip = if pos.stm() == Side::BLACK { 56 } else { 0 }; let from = usize::from(mov.src()) ^ flip; let to = match mov.flag() { Flag::KS => usize::from(castling.rook_file(pos.stm(), 1)), Flag::QS => usize::from(castling.rook_file(pos.stm(), 0)), _ => usize::from(mov.to()) ^ flip, }; let promo = if mov.is_promo() && mov.promo_pc() != Piece::KNIGHT { mov.promo_pc() } else { 0 }; let idx = self.index[key(from, to, promo)]; (idx >= 0).then_some(idx as usize) } } fn f32_at(r: &[u8], off: usize) -> f32 { f32::from_le_bytes(r[off..off + 4].try_into().unwrap()) } fn u16_at(r: &[u8], off: usize) -> u16 { u16::from_le_bytes(r[off..off + 2].try_into().unwrap()) } fn u32_at(r: &[u8], off: usize) -> u32 { u32::from_le_bytes(r[off..off + 4].try_into().unwrap()) } /// Bit i of the result is square i (a1 = 0) on the real board. fn plane(r: &[u8], idx: usize, black: bool) -> u64 { let off = OFF_PLANES + 8 * idx; let stored = u64::from_le_bytes(r[off..off + 8].try_into().unwrap()); // Lc0 stores each plane with the bits of every byte reversed (a file // mirror), and from the side to move's point of view. let mut bytes = stored.to_le_bytes(); for b in &mut bytes { *b = b.reverse_bits(); } let oriented = u64::from_le_bytes(bytes); if black { oriented.swap_bytes() } else { oriented } } /// The current position's pieces: [white, black, pawn, knight, bishop, rook, queen, king]. fn board(r: &[u8]) -> ([u64; 8], bool) { let black = r[OFF_STM] != 0; let (us, them) = if black { (Side::BLACK, Side::WHITE) } else { (Side::WHITE, Side::BLACK) }; let mut bbs = [0u64; 8]; for pc in 0..6 { let ours = plane(r, pc, black); let theirs = plane(r, 6 + pc, black); bbs[us] |= ours; bbs[them] |= theirs; bbs[Piece::PAWN + pc] = ours | theirs; } (bbs, black) } fn rights(r: &[u8], black: bool) -> u8 { let c = &r[OFF_CASTLING..OFF_CASTLING + 4]; // us_ooo, us_oo, them_ooo, them_oo let (us_q, us_k, them_q, them_k) = if black { (Right::BQS, Right::BKS, Right::WQS, Right::WKS) } else { (Right::WQS, Right::WKS, Right::BQS, Right::BKS) }; let mut rights = 0; for (flag, right) in c.iter().zip([us_q, us_k, them_q, them_k]) { if *flag != 0 { rights |= right; } } rights } /// Castling rook files ([side][queenside, kingside]) for the given rights. /// Lc0's classical input format only stores which rights exist, so each one /// takes the outermost rook on its side of the king, as X-FEN does; the move /// check catches a wrong guess. None when a right has no king or rook for it. fn rook_files(bbs: &[u64; 8], rights: u8) -> Option<[[u8; 2]; 2]> { let mut files = [[0, 7]; 2]; for (side, rank, qs, ks) in [(Side::WHITE, 0, Right::WQS, Right::WKS), (Side::BLACK, 7, Right::BQS, Right::BKS)] { if rights & (qs | ks) == 0 { continue; } let back = |piece: usize| ((bbs[side] & bbs[piece]) >> (8 * rank)) as u8; let king = back(Piece::KING); if king == 0 { return None; } let kfile = king.trailing_zeros() as u8; let rooks = back(Piece::ROOK); let below = rooks & ((1u8 << kfile) - 1); let above = rooks & !((2u16 << kfile) - 1) as u8; if rights & qs != 0 { if below == 0 { return None; } files[side][0] = below.trailing_zeros() as u8; } if rights & ks != 0 { if above == 0 { return None; } files[side][1] = 7 - above.leading_zeros() as u8; } } Some(files) } /// Legal moves paired with their Lc0 probability, or None when the set of /// legal moves differs from the moves Lc0 gave a probability. fn match_moves(pos: &Position, castling: &Castling, r: &[u8], map: &PolicyMap) -> Option> { let mut legal = Vec::with_capacity(64); let mut ok = true; pos.map_legal_moves(castling, |mov| match map.index(pos, castling, mov) { Some(idx) => legal.push((mov, f32_at(r, OFF_PROBS + 4 * idx))), None => ok = false, }); if !ok || legal.iter().any(|&(_, p)| p < 0.0) { if std::env::var("LC0_DEBUG").is_ok() { let bad: Vec = legal.iter().filter(|&&(_, p)| p < 0.0).map(|&(m, _)| m.to_uci(castling)).collect(); eprintln!("{} ok={ok} negative: {:?}", pos.as_fen(), bad); } return None; } let with_prob = (0..1858).filter(|&i| f32_at(r, OFF_PROBS + 4 * i) >= 0.0).count(); if with_prob != legal.len() && std::env::var("LC0_DEBUG").is_ok() { let ours: Vec = legal.iter().filter_map(|&(m, _)| map.index(pos, castling, m)).collect(); let extra: Vec<&str> = (0..1858) .filter(|&i| f32_at(r, OFF_PROBS + 4 * i) >= 0.0 && !ours.contains(&i)) .map(|i| POLICY_INDEX[i]) .collect(); eprintln!("{} lc0-only: {:?}", pos.as_fen(), extra); } (with_prob == legal.len()).then_some(legal) } /// The game's first position. En passant is not stored, so each possible en /// passant square is tried and the one whose legal moves match Lc0's is kept. fn start_position(r: &[u8], map: &PolicyMap) -> Option<(Position, Castling)> { let (bbs, black) = board(r); let rights = rights(r, black); let files = rook_files(&bbs, rights)?; let halfm = r[OFF_RULE50]; let mut candidates = vec![0u8]; // A pawn of the side not to move that may just have made a double push. let (them, rank_from, rank_to) = if black { (Side::WHITE, 1, 3) } else { (Side::BLACK, 6, 4) }; let occ = bbs[0] | bbs[1]; let mut pawns = bbs[them] & bbs[Piece::PAWN] & (0xFFu64 << (8 * rank_to)); while pawns != 0 { let sq = pawns.trailing_zeros() as u8; pawns &= pawns - 1; let file = sq % 8; let mid = (rank_from + rank_to) / 2 * 8 + file; let from = rank_from * 8 + file; if occ & ((1u64 << mid) | (1u64 << from)) == 0 { candidates.push(mid); } } for enp in candidates { #[allow(deprecated)] let pos = Position::from_raw(bbs, black, enp, rights, halfm, 1); let castling = Castling::from_raw(&pos, files); if match_moves(&pos, &castling, r, map).is_some() { return Some((pos, castling)); } } None } /// Converts one game (the decompressed contents of one .gz file). pub fn convert_game(data: &[u8], map: &PolicyMap, stats: &mut Stats) -> Option { if data.len() < RECORD_SIZE || data.len() % RECORD_SIZE != 0 { stats.bad_format += 1; return None; } let records: Vec<&[u8]> = data.chunks_exact(RECORD_SIZE).collect(); if records.iter().any(|r| u32_at(r, 0) != 6 || u32_at(r, 4) != 1) { stats.bad_format += 1; stats.dropped_records += records.len() as u64; return None; } let Some((startpos, castling)) = start_position(records[0], map) else { stats.bad_start += 1; stats.dropped_records += records.len() as u64; return None; }; let mut game = MontyFormat::new(startpos, castling); // Lc0's result is from the side to move's point of view; montyformat's // from white's. let result_q = f32_at(records[0], OFF_RESULT_Q).clamp(-1.0, 1.0); let white_q = if startpos.stm() == Side::BLACK { -result_q } else { result_q }; game.result = (white_q + 1.0) / 2.0; let mut pos = startpos; for (i, r) in records.iter().enumerate() { let (bbs, black) = board(r); if bbs != pos.bbs() || black != (pos.stm() == Side::BLACK) { stats.cut_board += 1; stats.dropped_records += (records.len() - i) as u64; break; } let Some(moves) = match_moves(&pos, &castling, r, map) else { stats.cut_moves += 1; stats.dropped_records += (records.len() - i) as u64; break; }; let played_idx = usize::from(u16_at(r, OFF_PLAYED_IDX)); let Some(played) = moves.iter().map(|&(m, _)| m).find(|&m| map.index(&pos, &castling, m) == Some(played_idx)) else { stats.cut_played += 1; stats.dropped_records += (records.len() - i) as u64; break; }; let dist: Vec<(Move, u32)> = moves.iter().map(|&(m, p)| (m, (p * 1_000_000.0).round() as u32)).collect(); let score = ((f32_at(r, OFF_BEST_Q).clamp(-1.0, 1.0) + 1.0) / 2.0).clamp(0.0, 1.0); game.push(SearchData::new(played, score, Some(dist))); stats.positions += 1; pos.make(played, &castling); } if game.moves.is_empty() { return None; } stats.games += 1; Some(game) }