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>
This commit is contained in:
rektdieandclaude committed 2026-11-16 18:14:52 +01:00
1 parent 2d3be1982c
commit 79c866c77c
9 files changed
+251 -50

No files matched your search

+70
View File
@@ -77,6 +77,18 @@ version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "cc"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -95,6 +107,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -169,6 +187,16 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom 0.4.3",
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.107"
@@ -226,6 +254,12 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -342,7 +376,9 @@ dependencies = [
name = "rigby-value"
version = "0.1.0"
dependencies = [
"bullet-trainer",
"bullet_lib",
"zstd",
]
[[package]]
@@ -403,6 +439,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "slab"
version = "0.4.12"
@@ -599,3 +641,31 @@ dependencies = [
"quote",
"syn 2.0.119",
]
[[package]]
name = "zstd"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.3+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d"
dependencies = [
"cc",
"pkg-config",
]
+2
View File
@@ -8,6 +8,8 @@ publish = false
# bullet comes from the local clone next to this repository (C:\Users\rektd\repos\bullet).
[dependencies]
bullet_lib = { path = "../../../bullet/crates/bullet_lib", features = ["cuda"] }
bullet_trainer = { package = "bullet-trainer", path = "../../../bullet/crates/trainer" }
zstd = "0.13"
[profile.release]
opt-level = 3
+41 -13
View File
@@ -1,12 +1,15 @@
//! Rigby value network trainer.
//!
//! Architecture: (768 -> HIDDEN)x2 -> 1, SCReLU, dual perspective.
//! Data: Lc0 self-play positions converted to Stockfish binpacks (linrock/test80).
//! 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.binpack>]... [--superbatches N] [--id NAME]
//! cargo run --release -- --check checkpoints/<id>-<superbatch>
//! 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
@@ -16,6 +19,8 @@
//! 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,
@@ -26,11 +31,14 @@ use bullet_lib::{
},
value::{
ValueTrainerBuilder,
loader::sfbinpack::{MoveType, PieceType, SfBinpackLoader, TrainingDataEntry},
loader::{
DirectSequentialDataLoader,
sfbinpack::{MoveType, PieceType, SfBinpackLoader, TrainingDataEntry},
},
},
};
const HIDDEN: usize = 128;
const DEFAULT_HIDDEN: usize = 1024;
const SCALE: i32 = 400;
const QA: i16 = 255;
const QB: i16 = 64;
@@ -66,13 +74,21 @@ const CHECK_FENS: [&str; 8] = [
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, id: "rigby-value".to_string(), check: None };
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() {
@@ -80,6 +96,8 @@ fn parse_args() -> Args {
"--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}"),
@@ -99,6 +117,7 @@ fn parse_args() -> Args {
fn main() {
let args = parse_args();
let hidden = args.hidden;
let mut trainer = ValueTrainerBuilder::default()
.dual_perspective()
@@ -112,8 +131,8 @@ fn main() {
])
.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 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();
@@ -135,7 +154,7 @@ fn main() {
eval_scale: SCALE as f32,
steps: TrainingSteps {
batch_size: 16_384,
batches_per_superbatch: 6104,
batches_per_superbatch: args.batches,
start_superbatch: 1,
end_superbatch: args.superbatches,
},
@@ -152,7 +171,16 @@ fn main() {
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();
let data_loader = SfBinpackLoader::new_concat_multiple(&paths, 1024, LOADER_THREADS, filter);
trainer.run(&schedule, &settings, &data_loader);
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);
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Reads bulletformat positions straight from zstd-compressed files (linrock's
//! `*.bullet.bin.zst`), so the data never has to be unpacked to disk: training
//! needs ~30 MB/s of compressed input, which even an HDD gives easily.
//!
//! Files are read one after the other and the list repeats forever, like bullet's
//! `DirectSequentialDataLoader`; each file must already be shuffled.
use std::{
fs::File,
io::{BufReader, Read},
};
use bullet_lib::game::formats::bulletformat::ChessBoard;
use bullet_trainer::reader::DataReader;
#[derive(Clone)]
pub struct ZstdBulletReader {
paths: Vec<String>,
}
impl ZstdBulletReader {
pub fn new(paths: &[&str]) -> Self {
for path in paths {
assert!(std::path::Path::new(path).exists(), "data file not found: {path}");
}
Self { paths: paths.iter().map(|p| p.to_string()).collect() }
}
}
/// Reads until `buf` is full or the stream ends; returns the bytes read.
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> usize {
let mut filled = 0;
while filled < buf.len() {
match reader.read(&mut buf[filled..]) {
Ok(0) => break,
Ok(n) => filled += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => panic!("reading training data: {e}"),
}
}
filled
}
impl DataReader<ChessBoard> for ZstdBulletReader {
fn read_chunks<F: FnMut(&[ChessBoard]) -> bool>(&self, mut skip: usize, mut f: F) {
const SIZE: usize = size_of::<ChessBoard>();
const CAP: usize = (64 << 20) / SIZE;
let mut buf = vec![ChessBoard::default(); CAP];
loop {
for path in &self.paths {
let file = BufReader::with_capacity(4 << 20, File::open(path).unwrap());
let mut decoder = zstd::stream::read::Decoder::with_buffer(file).unwrap();
loop {
// ChessBoard is plain bytes (bulletformat's 32-byte record).
let bytes = unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr().cast::<u8>(), CAP * SIZE) };
let n = read_full(&mut decoder, bytes);
if n == 0 {
break;
}
assert_eq!(n % SIZE, 0, "{path} is not a whole number of positions");
let mut chunk = &buf[..n / SIZE];
if skip > 0 {
let s = skip.min(chunk.len());
skip -= s;
chunk = &chunk[s..];
}
if !chunk.is_empty() && f(chunk) {
return;
}
}
}
}
}
}