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:
1 parent
9643c7b0a5
commit
1c9d2beec3
23 files changed
+2850
No files matched your search
@@ -0,0 +1,155 @@
|
||||
//! Rigby policy network trainer.
|
||||
//!
|
||||
//! Architecture: 3072 threat inputs -> HIDDEN -> CReLU -> pairwise multiply
|
||||
//! (HIDDEN / 2) -> one output row per legal move, softmax over the legal moves.
|
||||
//! Data: Lc0 self-play converted to montyformat by `lc02monty`, shuffled across
|
||||
//! files by `interleave`. Target: Lc0's visit distribution.
|
||||
//!
|
||||
//! Usage:
|
||||
//! rigby-policy [--data FILE] [--superbatches N] [--hidden N] [--id NAME] [--buffer-mb N] [--batches N]
|
||||
//!
|
||||
//! A superbatch is `--batches` batches of 16384 positions (default 6104, about
|
||||
//! 100M positions); fewer batches make quick test runs.
|
||||
//! rigby-policy --check checkpoints/<id>-<superbatch> [--hidden N]
|
||||
//!
|
||||
//! `--check` loads a checkpoint and prints the policy of a few fixed positions,
|
||||
//! as a reference for the engine's inference (Rigby's `policyfens` command
|
||||
//! prints the same list).
|
||||
//!
|
||||
//! checkpoints/<id>-<superbatch>/quantised.bin is written every SAVE_RATE
|
||||
//! superbatches and at the end; README.md describes its layout.
|
||||
|
||||
use acyclib::{
|
||||
device::Device,
|
||||
trainer::{
|
||||
optimiser::{
|
||||
adam::{AdamW, AdamWParams},
|
||||
Optimiser,
|
||||
},
|
||||
schedule::{TrainingSchedule, TrainingSteps},
|
||||
Trainer,
|
||||
},
|
||||
};
|
||||
use bullet_cuda_backend::CudaDevice;
|
||||
|
||||
use rigby_policy::{data::MontyDataLoader, model};
|
||||
|
||||
const DEFAULT_DATA: &str = "../data/lc0/policy.binpack";
|
||||
const DEFAULT_SUPERBATCHES: usize = 10;
|
||||
const DEFAULT_HIDDEN: usize = 1024;
|
||||
const DEFAULT_BUFFER_MB: usize = 4096;
|
||||
const SAVE_RATE: usize = 5;
|
||||
const BATCH_SIZE: usize = 16_384;
|
||||
const BATCHES_PER_SUPERBATCH: usize = 6104;
|
||||
const INITIAL_LR: f32 = 0.001;
|
||||
const FINAL_LR: f32 = 0.00001;
|
||||
|
||||
/// Positions for `--check`; keep in sync with Rigby's `policyfens` command.
|
||||
pub const CHECK_FENS: [&str; 6] = [
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1",
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1",
|
||||
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
|
||||
"8/2P2k2/8/8/8/8/5K2/8 w - - 0 1",
|
||||
];
|
||||
|
||||
struct Args {
|
||||
data: String,
|
||||
superbatches: usize,
|
||||
hidden: usize,
|
||||
id: String,
|
||||
buffer_mb: usize,
|
||||
batches: usize,
|
||||
check: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_args() -> Args {
|
||||
let mut args = Args {
|
||||
data: DEFAULT_DATA.to_string(),
|
||||
superbatches: DEFAULT_SUPERBATCHES,
|
||||
hidden: DEFAULT_HIDDEN,
|
||||
id: "rigby-policy".to_string(),
|
||||
buffer_mb: DEFAULT_BUFFER_MB,
|
||||
batches: BATCHES_PER_SUPERBATCH,
|
||||
check: None,
|
||||
};
|
||||
let mut it = std::env::args().skip(1);
|
||||
let number = |v: Option<String>, name: &str| -> usize {
|
||||
v.unwrap_or_else(|| panic!("{name} needs a number")).parse().expect("not a number")
|
||||
};
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--data" => args.data = it.next().expect("--data needs a path"),
|
||||
"--superbatches" => args.superbatches = number(it.next(), "--superbatches"),
|
||||
"--hidden" => args.hidden = number(it.next(), "--hidden"),
|
||||
"--buffer-mb" => args.buffer_mb = number(it.next(), "--buffer-mb"),
|
||||
"--batches" => args.batches = number(it.next(), "--batches"),
|
||||
"--id" => args.id = it.next().expect("--id needs a name"),
|
||||
"--check" => args.check = Some(it.next().expect("--check needs a checkpoint directory")),
|
||||
other => panic!("unknown argument: {other}"),
|
||||
}
|
||||
}
|
||||
assert!(args.hidden % 2 == 0, "--hidden must be even");
|
||||
if args.check.is_none() {
|
||||
assert!(std::path::Path::new(&args.data).exists(), "data file not found: {}", args.data);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = parse_args();
|
||||
|
||||
let device = CudaDevice::new(0).unwrap();
|
||||
let (graph, node) = model::make(device, args.hidden);
|
||||
|
||||
let params = AdamWParams { decay: 0.01, beta1: 0.9, beta2: 0.999, min_weight: -0.99, max_weight: 0.99 };
|
||||
let optimiser = Optimiser::<_, _, AdamW<_>>::new(graph, params).unwrap();
|
||||
let mut trainer = Trainer { optimiser, state: () };
|
||||
|
||||
if let Some(checkpoint) = &args.check {
|
||||
trainer.optimiser.load_from_checkpoint(&format!("{checkpoint}/optimiser_state")).unwrap();
|
||||
for fen in CHECK_FENS {
|
||||
model::eval(&mut trainer.optimiser.graph, node, fen);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let dataloader = MontyDataLoader::new(&args.data, args.buffer_mb, 4, 8);
|
||||
|
||||
let end_superbatch = args.superbatches;
|
||||
let steps =
|
||||
TrainingSteps { batch_size: BATCH_SIZE, batches_per_superbatch: args.batches, start_superbatch: 1, end_superbatch };
|
||||
|
||||
let schedule = TrainingSchedule {
|
||||
steps,
|
||||
log_rate: 64,
|
||||
lr_schedule: Box::new(move |_, sb| {
|
||||
if sb >= end_superbatch {
|
||||
return FINAL_LR;
|
||||
}
|
||||
let lambda = sb as f32 / end_superbatch as f32;
|
||||
INITIAL_LR * (FINAL_LR / INITIAL_LR).powf(lambda)
|
||||
}),
|
||||
};
|
||||
|
||||
let id = args.id.clone();
|
||||
trainer
|
||||
.train_custom(
|
||||
schedule,
|
||||
dataloader,
|
||||
|_, _, _, _| {},
|
||||
|trainer, superbatch| {
|
||||
if superbatch % SAVE_RATE == 0 || superbatch == end_superbatch {
|
||||
let dir = format!("checkpoints/{id}-{superbatch}");
|
||||
println!("Saving checkpoint {dir}");
|
||||
std::fs::create_dir_all(format!("{dir}/optimiser_state")).unwrap();
|
||||
trainer.optimiser.write_to_checkpoint(&format!("{dir}/optimiser_state")).unwrap();
|
||||
model::save_quantised(&trainer.optimiser.graph, &format!("{dir}/quantised.bin")).unwrap();
|
||||
}
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
model::eval(&mut trainer.optimiser.graph, node, CHECK_FENS[0]);
|
||||
}
|
||||
Reference in new issue
Block a user