diff --git a/Makefile b/Makefile index 552d1dd..d257b19 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ OBJ_DIR := obj EXE ?= Rigby # The value network embedded into the binary -EVALFILE ?= networks/rigby-value-v1.bin +EVALFILE ?= networks/rigby-value-v2.bin # The policy network embedded into the binary; empty means move heuristics POLICYFILE ?= networks/rigby-policy-v1.bin CXX ?= clang++ diff --git a/networks/rigby-value-v2.bin b/networks/rigby-value-v2.bin new file mode 100644 index 0000000..5bee7e1 Binary files /dev/null and b/networks/rigby-value-v2.bin differ diff --git a/src/nnue.cpp b/src/nnue.cpp index 4b368e2..1394653 100644 --- a/src/nnue.cpp +++ b/src/nnue.cpp @@ -41,9 +41,10 @@ inline int feature(int perspective, int piece, int sq) { // must fit 16 bits, so the weights are checked on load. constexpr int MAX_L1W = 32767 / QA; -// Each half's dot product is summed in 32 bits. -static_assert(i64(HIDDEN) * QA * QA * MAX_L1W <= INT_MAX); -static_assert(HIDDEN % simd::LANES == 0); +// The output sum is taken in blocks that fit 32 bits, then added up in 64. +constexpr int BLOCK = 128; +static_assert(i64(2) * BLOCK * QA * QA * MAX_L1W <= INT_MAX); +static_assert(HIDDEN % BLOCK == 0 && BLOCK % simd::LANES == 0); } // namespace @@ -142,17 +143,20 @@ int evaluate(const Accumulator& acc, int stm) { const i16* them = acc.values[stm ^ 1]; // SCReLU as v * (v * w) with v clamped to [0, QA]: exact, since v * w fits - // 16 bits and each half's sum fits 32 (checked above). + // 16 bits and a block of both halves fits 32 (checked above). using namespace simd; const vi16 lo = set1(0), hi = set1(QA); - vi32 sum_us = zero32(), sum_them = zero32(); - for (int i = 0; i < HIDDEN; i += LANES) { - const vi16 u = clamp(load(us + i), lo, hi); - const vi16 t = clamp(load(them + i), lo, hi); - sum_us = dot(sum_us, mullo(u, load(net.l1w + i)), u); - sum_them = dot(sum_them, mullo(t, load(net.l1w + HIDDEN + i)), t); + i64 out = 0; + for (int b = 0; b < HIDDEN; b += BLOCK) { + vi32 sum_us = zero32(), sum_them = zero32(); + for (int i = b; i < b + BLOCK; i += LANES) { + const vi16 u = clamp(load(us + i), lo, hi); + const vi16 t = clamp(load(them + i), lo, hi); + sum_us = dot(sum_us, mullo(u, load(net.l1w + i)), u); + sum_them = dot(sum_them, mullo(t, load(net.l1w + HIDDEN + i)), t); + } + out += reduce(add32(sum_us, sum_them)); } - i64 out = i64(reduce(sum_us)) + reduce(sum_them); out /= QA; out += net.l1b; diff --git a/src/nnue.h b/src/nnue.h index fc80716..d39640f 100644 --- a/src/nnue.h +++ b/src/nnue.h @@ -6,7 +6,7 @@ namespace rigby::nnue { // Value network trained with bullet on Lc0 data (see train/README.md): // (768 -> HIDDEN)x2 -> 1, SCReLU, dual perspective, quantised i16. -constexpr int HIDDEN = 128; +constexpr int HIDDEN = 1024; constexpr int SCALE = 400; constexpr int QA = 255; constexpr int QB = 64; diff --git a/train/README.md b/train/README.md index 6051f78..4b86ebc 100644 --- a/train/README.md +++ b/train/README.md @@ -2,36 +2,41 @@ ## Value network (`value/`) -A small `(768 -> 128)x2 -> 1` SCReLU network trained with -[bullet](https://github.com/jw1912/bullet) on Lc0 self-play data. +A `(768 -> 1024)x2 -> 1` SCReLU network trained with +[bullet](https://github.com/jw1912/bullet) on Lc0-derived data from linrock. ### Run +How `rigby-value-v2` was trained (the 12 S2 files, see Data): + ``` -powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\value\train.ps1 +powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\value\train.ps1 --hidden 1024 --superbatches 170 --id rigby-value-v2 --data ... --data ``` -Default: 40 superbatches of 100M positions, about 12 minutes on the RTX 3070 -(5.8M positions/s). Arguments are passed to the trainer: +On the RTX 3070, 1024 hidden trains at 3-4M positions/s (bound by the GPU): about +33 s per superbatch of 100M positions. 512 hidden runs at ~6M/s, 1536 at ~2.6M/s. +Arguments are passed to the trainer: | Argument | Default | Meaning | | --- | --- | --- | | `--superbatches N` | 40 | Training length; the learning rate decays to the end | +| `--hidden N` | 1024 | Hidden width; the engine's `nnue::HIDDEN` must match | | `--id NAME` | `rigby-value` | Checkpoint name | -| `--data FILE` | the test80 Feb 2024 binpack | Repeatable; several files are read one after the other | +| `--data FILE` | the test80 Feb 2024 binpack | Repeatable; files are read one after the other, round and round. All `.bin.zst`, all `.bin` or all `.binpack` | +| `--batches N` | 6104 | Batches of 16384 per superbatch (smaller for speed tests) | Output: `value/checkpoints/-/quantised.bin` every 10 superbatches and at the end. That file is what the engine loads. ### Network format -`quantised.bin` (197,440 bytes for 128 hidden), little-endian `i16`: +`quantised.bin` (1,579,072 bytes for 1024 hidden), little-endian `i16`: | Part | Shape | Quantisation | | --- | --- | --- | -| `l0w` | 768 x 128, feature-major (`[feature][hidden]`) | QA = 255 | -| `l0b` | 128 | QA | -| `l1w` | 2 x 128 (side to move first, then the other side) | QB = 64 | +| `l0w` | 768 x H, feature-major (`[feature][hidden]`) | QA = 255 | +| `l0b` | H | QA | +| `l1w` | 2 x H (side to move first, then the other side) | QB = 64 | | `l1b` | 1 | QA * QB | Inputs (bullet's `Chess768`): `64 * piece + square`, with pieces relative to the @@ -40,34 +45,51 @@ and squares flipped vertically for black. The side to move's accumulator comes f Output: `((sum screlu(acc) * w) / QA + b) * 400 / (QA * QB)` in centipawns, side to move. The engine maps it to Q with the same 400 scale: `q = 2 * sigmoid(cp / 400) - 1 = tanh(cp / 800)` (`src/nnue.cpp`, `src/eval.cpp`). +The engine computes `screlu(v) * w` as `v * (v * w)` in 16 bits, so `|l1w|` must be +at most 128 (bullet's AdamW clips weights to ±1.98, i.e. 127); it refuses a net +that breaks this. ### Checking the engine's inference ``` -cargo run --release -- --check checkpoints/- +cargo run --release -- --check checkpoints/- --hidden ``` prints bullet's own (float) evaluation of fixed positions; the engine's `evalfens` command prints the same positions with the quantised network. Expect agreement -within a few centipawns (quantisation); a wrong feature mapping shows up as -differences of hundreds. +within a few centipawns (quantisation; v2 at superbatch 20: at most 13 cp); a +wrong feature mapping shows up as differences of hundreds. ### Networks -| File | Data | Superbatches | Final loss | -| --- | --- | --- | --- | -| `networks/rigby-value-v1.bin` | test80 2024-02 | 40 (10 min) | 0.0220 | +| File | Hidden | Data | Superbatches | Final loss | +| --- | --- | --- | --- | --- | +| `networks/rigby-value-v1.bin` | 128 | test80 2024-02 | 40 (10 min) | 0.0220 | +| `networks/rigby-value-v2.bin` | 1024 | linrock S2 (6.6B positions) | 170 (1h34m) | 0.01278 | + +Losses are not comparable across data sets. ### Data -Lc0 self-play data converted to Stockfish binpacks by linrock -([huggingface.co/datasets/linrock](https://huggingface.co/datasets/linrock)), here -`test80-2024-02-feb-2tb7p.min-v2.v6.binpack` (6.9 GB zstd, 8.3 GB unpacked). -bullet reads binpacks directly (`SfBinpackLoader`); no conversion is needed. -The filter keeps positions from ply 16 on that are not in check, with a quiet best -move and |score| <= 10000. Training target: `0.4 * result + 0.6 * sigmoid(score / 400)`. +v2: the `S2` folder of +[linrock/bullet-training-data](https://huggingface.co/datasets/linrock/bullet-training-data), +12 files `test77nov-unfilt-test79-maraprmay-v6-dd.skip-see-ge0.wdl-pdist.iter-N.bullet.bin.zst` +(~9 GB each, 108 GB in all; ~547M positions each, 6.6B in all, different positions +in every file, each already filtered and shuffled). The trainer reads the `.zst` +files directly (`value/src/zstd_reader.rs`): unpacked they would take 210 GB, and +training only needs ~40 MB/s of compressed input, which an HDD gives easily. They +live in `D:\rigby-data\s2\s2-1.parts\` on this machine. Hugging Face caps one connection at ~20 MB/s, so +download several files at once. -Data lives in `train/data/` and is not committed. +v1: Lc0 self-play data converted to Stockfish binpacks by linrock +([huggingface.co/datasets/linrock](https://huggingface.co/datasets/linrock)), +`test80-2024-02-feb-2tb7p.min-v2.v6.binpack` (6.9 GB zstd, 8.3 GB unpacked), read +directly (`SfBinpackLoader`). The filter keeps positions from ply 16 on that are not +in check, with a quiet best move and |score| <= 10000. + +Training target for both: `0.4 * result + 0.6 * sigmoid(score / 400)`. + +Data other than S2 lives in `train/data/` and is not committed. ### Setup on a new machine @@ -75,7 +97,7 @@ Data lives in `train/data/` and is not committed. 2. CUDA Toolkit 13.3 with `cudart`, `nvrtc`, `cublas` (bullet compiles its kernels at runtime with NVRTC, no nvcc needed). 3. `git clone https://github.com/jw1912/bullet` next to this repo. -4. `pip install zstandard` and a binpack from linrock's datasets in `train/data/`. +4. linrock's data (see Data); `pip install zstandard` to unpack a `.binpack.zst`. ## Policy network (`policy/`) diff --git a/train/value/Cargo.lock b/train/value/Cargo.lock index 84c7925..6a0aea4 100644 --- a/train/value/Cargo.lock +++ b/train/value/Cargo.lock @@ -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", +] diff --git a/train/value/Cargo.toml b/train/value/Cargo.toml index e9e65f5..199f904 100644 --- a/train/value/Cargo.toml +++ b/train/value/Cargo.toml @@ -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 diff --git a/train/value/src/main.rs b/train/value/src/main.rs index 0c8f34c..13b7eae 100644 --- a/train/value/src/main.rs +++ b/train/value/src/main.rs @@ -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 ]... [--superbatches N] [--id NAME] -//! cargo run --release -- --check checkpoints/- +//! cargo run --release -- [--data ]... [--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/- [--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, superbatches: usize, + hidden: usize, + batches: usize, id: String, check: Option, } 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); + } } diff --git a/train/value/src/zstd_reader.rs b/train/value/src/zstd_reader.rs new file mode 100644 index 0000000..59dadb0 --- /dev/null +++ b/train/value/src/zstd_reader.rs @@ -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, +} + +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 for ZstdBulletReader { + fn read_chunks bool>(&self, mut skip: usize, mut f: F) { + const SIZE: usize = size_of::(); + 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::(), 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; + } + } + } + } + } +}