Skip to main content

nnue_rs/
lib.rs

1//! Load and evaluate NNUE (Efficiently Updatable Neural Network) chess networks.
2//!
3//! The crate is small, dependency-free and cross-platform, with an optional
4//! AVX2 fast path (used automatically at runtime when available, with a scalar
5//! fallback everywhere else).
6//!
7//! # Architectures
8//!
9//! The architecture is detected automatically from the network file's header:
10//!
11//! - `SFNNv10` — Stockfish 18 big nets with threat inputs.
12//! - `HalfKAv2_hm` — Stockfish SFNNv5-v9 (Stockfish 16/17 and SF 18 small nets).
13//! - `HalfKAv2` — the non-mirrored predecessor (Stockfish SFNNv2-v4, SF 14).
14//! - `HalfKP` — the classic Stockfish NNUE feature set (Stockfish 12-14 nets).
15//!
16//! # Integration
17//!
18//! Feed positions either by FEN or by implementing the [`Board`] trait on your
19//! own position type.
20//!
21//! By FEN:
22//!
23//! ```no_run
24//! use nnue_rs::Network;
25//!
26//! let net = Network::from_file("net.nnue")?;
27//! let cp = net.evaluate_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")?;
28//! # Ok::<(), nnue_rs::Error>(())
29//! ```
30//!
31//! By implementing [`Board`]:
32//!
33//! ```no_run
34//! use nnue_rs::{Board, Color, Piece, Network};
35//!
36//! # struct MyPosition;
37//! impl Board for MyPosition {
38//!     fn side_to_move(&self) -> Color { /* ... */ todo!() }
39//!     fn king_square(&self, color: Color) -> u8 { /* ... */ todo!() }
40//!     fn for_each_piece(&self, f: &mut dyn FnMut(u8, Piece)) { /* ... */ todo!() }
41//! }
42//!
43//! # let net: Network = unreachable!();
44//! # let position = MyPosition;
45//! let score = net.evaluate(&position);
46//! ```
47//!
48//! # Incremental evaluation
49//!
50//! For a search, advance an [`Accumulator`] as moves are made instead of
51//! recomputing from scratch. See [`Network::accumulator`], [`Network::update`]
52//! (or [`Network::update_changes`] for known piece changes) and
53//! [`Network::evaluate_accumulator`]. Common updates use fused arithmetic;
54//! HalfKAv2_hm and SFNNv10 inference uses a packed first layer on AVX2 CPUs.
55//! Public APIs and network-file formats are unchanged from 0.4.1.
56
57mod error;
58mod feature;
59mod fen;
60mod leb128;
61mod network;
62mod simd;
63mod threats;
64mod types;
65
66pub use error::{Error, Result};
67pub use feature::Arch;
68pub use fen::FenBoard;
69pub use network::{Accumulator, Network};
70pub use types::{Board, Color, Piece, PieceKind};
71
72impl Network {
73    /// Evaluate a position given as a FEN string.
74    ///
75    /// Convenience wrapper over [`FenBoard`] + [`Network::evaluate`].
76    pub fn evaluate_fen(&self, fen: &str) -> Result<i32> {
77        Ok(self.evaluate(&FenBoard::parse(fen)?))
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    #[test]
86    fn parses_startpos() {
87        let board = FenBoard::parse(
88            "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
89        )
90        .unwrap();
91        assert_eq!(board.side_to_move(), Color::White);
92        assert_eq!(board.king_square(Color::White), 4);
93        assert_eq!(board.king_square(Color::Black), 60);
94    }
95
96    #[test]
97    fn collects_active_features() {
98        let board =
99            FenBoard::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").unwrap();
100        let arch = feature::Arch::HalfKAv2Hm;
101        let mut white = Vec::new();
102        let mut black = Vec::new();
103        feature::active_indices(arch, &board, Color::White, &mut white);
104        feature::active_indices(arch, &board, Color::Black, &mut black);
105        assert_eq!(white.len(), 32);
106        assert_eq!(black.len(), 32);
107        for &idx in white.iter().chain(black.iter()) {
108            assert!(idx < arch.input_dimensions());
109        }
110    }
111}