feat: policy network trainer on Lc0 visit distributions

train/policy is a fork of montytrain's policy trainer (the one Monty,
Vine and Jackal use: bullet at a pinned revision plus two CUDA
operations, SelectAffine over the legal moves' output rows and a
softmax cross-entropy against the visit distribution). Rigby's
version drops Monty's SEE split of the outputs (3920 rows, as in
Vine), takes its arguments on the command line and checks a
checkpoint with --check.

The Stockfish binpacks used for the value net only keep the played
move, so the data comes from Lc0's raw V6 training tars instead.
lc02monty rebuilds each game from its first record and the played
moves and checks every record: pieces must match, and the moves Lc0
gave a probability must be exactly the legal moves. Lc0 writes
castling as king-takes-rook; Chess960 games keep their rook files.
On a test91 tar all 351,454 records convert. fetch.ps1 downloads a
run's hourly tars day by day, converts and deletes them, and
interleave shuffles the day files into one.

Defaults sized for a 20-minute run on the RTX 3070: 1024 hidden,
10 superbatches of 100M positions (~1M positions/s). The pinned
cudarc does not know CUDA 13.3, so env.ps1 sets
CUDARC_CUDA_VERSION=13000.

Checked: a smoke run on one tar lowers the loss from 2.89 to 2.38 and
gives plausible opening priors; a checkpoint reloads to identical
output; interleaved data trains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rektdieandclaude committed 2026-11-15 21:27:08 +01:00
1 parent 9643c7b0a5
commit 1c9d2beec3
23 files changed
+2850

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
//! Shuffles montyformat files into one, game by game, picking each next game
//! from a file chosen in proportion to the bytes it has left.
//!
//! interleave <out.binpack> <file or directory of .binpack files>...
use std::{
fs::{self, File},
io::{BufReader, BufWriter, Write},
};
use montyformat::{FastDeserialise, MontyFormat};
fn main() -> std::io::Result<()> {
let mut args = std::env::args().skip(1);
let output = args.next().expect("usage: interleave <out> <file|dir>...");
let mut inputs: Vec<String> = Vec::new();
for arg in args {
let path = std::path::Path::new(&arg);
if path.is_dir() {
let mut files: Vec<String> = fs::read_dir(path)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_file() && p.extension().and_then(|e| e.to_str()) == Some("binpack"))
.map(|p| p.to_string_lossy().into_owned())
.collect();
files.sort();
inputs.extend(files);
} else {
inputs.push(arg);
}
}
assert!(!inputs.is_empty(), "no input files");
assert!(!inputs.contains(&output), "the output must not be one of the inputs");
println!("Writing to {output:#?}");
println!("Reading from:\n{inputs:#?}");
let mut streams = Vec::new();
let mut total = 0;
let target = File::create(&output)?;
let mut writer = BufWriter::new(target);
for path in &inputs {
let file = File::open(path)?;
let count = file.metadata()?.len();
if count > 0 {
streams.push((count, BufReader::new(file)));
total += count;
}
}
let mut remaining = total;
let mut rng = RandU64::default();
const INTERVAL: u64 = 1024 * 1024 * 256;
let mut prev = remaining / INTERVAL;
let mut buffer = Vec::new();
while remaining > 0 {
let mut spot = rng.rand() % remaining;
let mut idx = 0;
while streams[idx].0 < spot {
spot -= streams[idx].0;
idx += 1;
}
let (count, reader) = &mut streams[idx];
MontyFormat::deserialise_fast_into_buffer(reader, &mut buffer)?;
writer.write_all(&buffer)?;
let size = buffer.len() as u64;
remaining -= size;
*count -= size;
if *count == 0 {
streams.swap_remove(idx);
}
if remaining / INTERVAL < prev {
prev = remaining / INTERVAL;
let written = total - remaining;
print!("Written {written}/{total} Bytes ({:.2}%)\r", written as f64 / total as f64 * 100.0);
let _ = std::io::stdout().flush();
}
}
Ok(())
}
struct RandU64(u64);
impl Default for RandU64 {
fn default() -> Self {
Self(
(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).expect("valid").as_nanos()
& 0xFFFF_FFFF_FFFF_FFFF) as u64,
)
}
}
impl RandU64 {
fn rand(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
+132
View File
@@ -0,0 +1,132 @@
//! Converts Lc0 V6 training data tars into one montyformat file.
//!
//! lc02monty <out.binpack> <tar or directory of tars>... [--threads N] [--delete]
//!
//! Games are appended to the output, so a run can be repeated with new tars.
//! `--delete` removes each tar once its games are written (for streaming
//! large downloads through a small disk).
use std::{
fs::{File, OpenOptions},
io::{BufWriter, Read, Write},
path::PathBuf,
sync::{mpsc, Arc, Mutex},
};
use flate2::read::GzDecoder;
use rigby_policy::lc0::{convert_game, PolicyMap, Stats};
fn convert_tar(path: &PathBuf, map: &PolicyMap) -> std::io::Result<(Vec<u8>, Stats)> {
let mut stats = Stats::default();
let mut out = Vec::new();
let mut archive = tar::Archive::new(File::open(path)?);
let mut raw = Vec::new();
let mut buf = Vec::new();
for entry in archive.entries()? {
let mut entry = entry?;
if !entry.path()?.to_string_lossy().ends_with(".gz") {
continue;
}
raw.clear();
entry.read_to_end(&mut raw)?;
let mut data = Vec::new();
if GzDecoder::new(&raw[..]).read_to_end(&mut data).is_err() {
stats.bad_format += 1;
continue;
}
if let Some(game) = convert_game(&data, map, &mut stats) {
buf.clear();
game.serialise_into_buffer(&mut buf)?;
out.extend_from_slice(&buf);
}
}
Ok((out, stats))
}
fn main() {
let mut args = std::env::args().skip(1);
let out_path = args.next().expect("usage: lc02monty <out> <tar|dir>... [--threads N] [--delete]");
let mut inputs = Vec::new();
let mut threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);
let mut delete = false;
while let Some(arg) = args.next() {
match arg.as_str() {
"--threads" => threads = args.next().expect("--threads needs a number").parse().expect("not a number"),
"--delete" => delete = true,
path => {
let p = PathBuf::from(path);
if p.is_dir() {
let mut tars: Vec<PathBuf> = std::fs::read_dir(&p)
.expect("cannot read directory")
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|e| e == "tar"))
.collect();
tars.sort();
inputs.extend(tars);
} else {
inputs.push(p);
}
}
}
}
assert!(!inputs.is_empty(), "no input tars");
let total_tars = inputs.len();
let queue = Arc::new(Mutex::new(inputs.into_iter()));
let map = Arc::new(PolicyMap::default());
let (sender, receiver) = mpsc::sync_channel::<(PathBuf, std::io::Result<(Vec<u8>, Stats)>)>(threads);
for _ in 0..threads {
let queue = queue.clone();
let map = map.clone();
let sender = sender.clone();
std::thread::spawn(move || loop {
let Some(path) = queue.lock().unwrap().next() else { break };
let result = convert_tar(&path, &map);
if sender.send((path, result)).is_err() {
break;
}
});
}
drop(sender);
let file = OpenOptions::new().create(true).append(true).open(&out_path).expect("cannot open output");
let mut writer = BufWriter::with_capacity(1 << 24, file);
let mut total = Stats::default();
let mut done = 0;
let mut bytes = 0u64;
for (path, result) in receiver {
done += 1;
match result {
Ok((data, stats)) => {
writer.write_all(&data).expect("write failed");
bytes += data.len() as u64;
total.add(&stats);
if delete {
writer.flush().expect("flush failed");
let _ = std::fs::remove_file(&path);
}
}
Err(e) => eprintln!("skipping {}: {e}", path.display()),
}
println!(
"[{done}/{total_tars}] {} games, {} positions, {:.1} MB written",
total.games,
total.positions,
bytes as f64 / 1e6
);
}
writer.flush().expect("flush failed");
let kept = total.positions as f64;
let dropped = total.dropped_records as f64;
println!("games kept : {}", total.games);
println!("positions kept : {}", total.positions);
println!("records dropped : {} ({:.3}%)", total.dropped_records, 100.0 * dropped / (kept + dropped).max(1.0));
println!(" bad format : {} games", total.bad_format);
println!(" bad start : {} games", total.bad_start);
println!(" board mismatch : {} cuts", total.cut_board);
println!(" move mismatch : {} cuts", total.cut_moves);
println!(" played not found: {} cuts", total.cut_played);
}