Files
Rigby/train/value/src/main.rs
T
rektdieandclaude 79c866c77c feat: value network v2, 1024 hidden trained on linrock S2
Replaces the (768 -> 128)x2 value net with (768 -> 1024)x2 -> 1 SCReLU, same
inputs, quantisation and output scale, trained on much more data: the 12 S2
files of huggingface.co/datasets/linrock/bullet-training-data (6.6B positions,
already filtered and shuffled; v1 had one month of test80).

Training: 170 superbatches of 100M positions (17B positions, about 2.6
passes over S2), AdamW, LR 1e-3 cosine to 2.4e-6, target 0.4 * result +
0.6 * sigmoid(score / 400) as in v1. 1h34m on the RTX 3070 at ~3M
positions/s (GPU-bound); final running loss 0.01278 (not comparable to v1's
0.0220, other data). The width was picked for the 2 hour budget: 1024 trains
at 3-4M/s, and in the engine a random 1024 net cost only 16% nps against 128,
thanks to the SIMD kernels.

Trainer (train/value):
- --hidden N (default now 1024) and --batches N for speed tests
- reads bulletformat straight from .bin.zst (src/zstd_reader.rs), so the
  108 GB of S2 never has to be unpacked to 210 GB; training needs ~40 MB/s
  of compressed input, which the HDD holding it gives easily
- also reads raw .bin files (bullet's DirectSequentialDataLoader)

Engine:
- nnue::HIDDEN = 1024, Makefile EVALFILE = networks/rigby-value-v2.bin
- the output layer now sums in blocks of 128 that fit 32 bits and adds
  them up in 64, so it stays exact for any width (the single 32-bit sum was
  only provably safe up to 128)

Checked: evalfens against the trainer's --check on the final checkpoint:
same signs and sizes, within 6 cp on quiet positions and up to 7% on large
evaluations (quantisation; e.g. 553 vs 594 cp). Bench deterministic. UCI:
uci, isready, ucinewgame, go nodes / movetime / infinite + stop.
nps on bench: 4.6M -> 3.5M.

Bench: 663779

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:14:52 +01:00

187 lines
6.9 KiB
Rust

//! Rigby value network trainer.
//!
//! Architecture: (768 -> HIDDEN)x2 -> 1, SCReLU, dual perspective.
//! Data: Lc0-derived positions from linrock, either Stockfish binpacks (`.binpack`,
//! filtered here) or bulletformat files, raw (`.bin`) or zstd-compressed
//! (`.bin.zst`, read directly; e.g. the S2 set, already filtered and shuffled).
//! Target: WDL * game result + (1 - WDL) * sigmoid(score / SCALE).
//!
//! Usage:
//! cargo run --release -- [--data <file>]... [--superbatches N] [--hidden N] [--id NAME] [--batches N]
//! (--batches: batches of 16384 per superbatch, 6104 = 100M positions; smaller for speed tests)
//! cargo run --release -- --check checkpoints/<id>-<superbatch> [--hidden N]
//!
//! `--check` loads a checkpoint and prints the network's evaluation (centipawns,
//! side to move) of a few fixed positions, as a reference for the engine's own
//! inference (Rigby's `evalfens` command prints the same list).
//!
//! The network is written to checkpoints/<id>-<superbatch>/quantised.bin every
//! SAVE_RATE superbatches and at the end. Inference in Rigby has to use the same
//! HIDDEN, SCALE, QA and QB.
mod zstd_reader;
use bullet_lib::{
game::inputs::Chess768,
nn::optimiser::AdamW,
trainer::{
save::SavedFormat,
schedule::{TrainingSchedule, TrainingSteps, lr, wdl},
settings::LocalSettings,
},
value::{
ValueTrainerBuilder,
loader::{
DirectSequentialDataLoader,
sfbinpack::{MoveType, PieceType, SfBinpackLoader, TrainingDataEntry},
},
},
};
const DEFAULT_HIDDEN: usize = 1024;
const SCALE: i32 = 400;
const QA: i16 = 255;
const QB: i16 = 64;
const DEFAULT_DATA: &str = "../data/test80-2024-02-feb-2tb7p.min-v2.v6.binpack";
const DEFAULT_SUPERBATCHES: usize = 40;
const SAVE_RATE: usize = 10;
const WDL: f32 = 0.4;
const LOADER_THREADS: usize = 6;
/// Keep quiet, settled positions: past the opening, not in check, a quiet best
/// move and a sane score.
fn filter(entry: &TrainingDataEntry) -> bool {
entry.ply >= 16
&& !entry.pos.is_checked(entry.pos.side_to_move())
&& entry.score.unsigned_abs() <= 10000
&& entry.mv.mtype() == MoveType::Normal
&& entry.pos.piece_at(entry.mv.to()).piece_type() == PieceType::None
}
/// Positions for `--check`; keep in sync with Rigby's `evalfens` command.
const CHECK_FENS: [&str; 8] = [
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/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/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 b - - 0 1",
];
struct Args {
data: Vec<String>,
superbatches: usize,
hidden: usize,
batches: usize,
id: String,
check: Option<String>,
}
fn parse_args() -> Args {
let mut args = Args {
data: Vec::new(),
superbatches: DEFAULT_SUPERBATCHES,
hidden: DEFAULT_HIDDEN,
batches: 6104,
id: "rigby-value".to_string(),
check: None,
};
let mut it = std::env::args().skip(1);
while let Some(arg) = it.next() {
match arg.as_str() {
"--data" => args.data.push(it.next().expect("--data needs a path")),
"--superbatches" => {
args.superbatches = it.next().expect("--superbatches needs a number").parse().expect("not a number")
}
"--hidden" => args.hidden = it.next().expect("--hidden needs a number").parse().expect("not a number"),
"--batches" => args.batches = it.next().expect("--batches needs a number").parse().expect("not a number"),
"--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}"),
}
}
if args.check.is_some() {
return args;
}
if args.data.is_empty() {
args.data.push(DEFAULT_DATA.to_string());
}
for path in &args.data {
assert!(std::path::Path::new(path).exists(), "data file not found: {path}");
}
args
}
fn main() {
let args = parse_args();
let hidden = args.hidden;
let mut trainer = ValueTrainerBuilder::default()
.dual_perspective()
.optimiser(AdamW)
.inputs(Chess768)
.save_format(&[
SavedFormat::id("l0w").round().quantise::<i16>(QA),
SavedFormat::id("l0b").round().quantise::<i16>(QA),
SavedFormat::id("l1w").round().quantise::<i16>(QB),
SavedFormat::id("l1b").round().quantise::<i16>(QA * QB),
])
.loss_fn(|output, target| output.sigmoid().squared_error(target))
.build(|builder, stm_inputs, ntm_inputs| {
let l0 = builder.new_affine("l0", 768, hidden);
let l1 = builder.new_affine("l1", 2 * hidden, 1);
let stm_hidden = l0.forward(stm_inputs).screlu();
let ntm_hidden = l0.forward(ntm_inputs).screlu();
l1.forward(stm_hidden.concat(ntm_hidden))
});
if let Some(checkpoint) = &args.check {
trainer.load_from_checkpoint(checkpoint);
for fen in CHECK_FENS {
// bulletformat's text form: <fen> | <score> | <result>
let raw = trainer.eval(&format!("{fen} | 0 | 0.5"));
println!("{:6.0} cp {fen}", raw * SCALE as f32);
}
return;
}
let schedule = TrainingSchedule {
net_id: args.id.clone(),
eval_scale: SCALE as f32,
steps: TrainingSteps {
batch_size: 16_384,
batches_per_superbatch: args.batches,
start_superbatch: 1,
end_superbatch: args.superbatches,
},
wdl_scheduler: wdl::ConstantWDL { value: WDL },
lr_scheduler: lr::CosineDecayLR {
initial_lr: 0.001,
final_lr: 0.001 * 0.3f32.powi(5),
final_superbatch: args.superbatches,
},
save_rate: SAVE_RATE,
};
let settings =
LocalSettings { threads: LOADER_THREADS, test_set: None, output_directory: "checkpoints", batch_queue_size: 64 };
let paths: Vec<&str> = args.data.iter().map(String::as_str).collect();
if paths.iter().all(|p| p.ends_with(".bin.zst")) {
trainer.run(&schedule, &settings, &zstd_reader::ZstdBulletReader::new(&paths));
} else if paths.iter().all(|p| p.ends_with(".bin")) {
trainer.run(&schedule, &settings, &DirectSequentialDataLoader::new(&paths));
} else {
assert!(
paths.iter().all(|p| p.ends_with(".binpack")),
"--data files must be all .bin.zst, all .bin or all .binpack"
);
let data_loader = SfBinpackLoader::new_concat_multiple(&paths, 1024, LOADER_THREADS, filter);
trainer.run(&schedule, &settings, &data_loader);
}
}