diff --git a/Cargo.lock b/Cargo.lock index 7689737..596fa47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,7 +214,7 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "cnp" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=968e7770a7d1021a243f4ddef1f87d64e78355cb#968e7770a7d1021a243f4ddef1f87d64e78355cb" +source = "git+https://github.com/cjus/chess-node-protocol?rev=3791c23d98303a5f541171fa6d23af5a6bb53b1b#3791c23d98303a5f541171fa6d23af5a6bb53b1b" dependencies = [ "serde", "serde_json", @@ -223,7 +223,7 @@ dependencies = [ [[package]] name = "cnp-conformance" version = "0.1.0" -source = "git+https://github.com/cjus/chess-node-protocol?rev=968e7770a7d1021a243f4ddef1f87d64e78355cb#968e7770a7d1021a243f4ddef1f87d64e78355cb" +source = "git+https://github.com/cjus/chess-node-protocol?rev=3791c23d98303a5f541171fa6d23af5a6bb53b1b#3791c23d98303a5f541171fa6d23af5a6bb53b1b" dependencies = [ "cnp", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 15a9011..3c584b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,8 +41,8 @@ cb2026-tools = { path = "crates/tools" } cb2026-trainer = { path = "crates/trainer" } # The Chess Node Protocol, how Solrac talks to cb2026 (`crates/cnp`), and its conformance # sessions (Solrac Chess AI #98). Pinned to a commit; bump both together. -cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "968e7770a7d1021a243f4ddef1f87d64e78355cb" } -cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "968e7770a7d1021a243f4ddef1f87d64e78355cb" } +cnp = { git = "https://github.com/cjus/chess-node-protocol", rev = "3791c23d98303a5f541171fa6d23af5a6bb53b1b" } +cnp-conformance = { git = "https://github.com/cjus/chess-node-protocol", rev = "3791c23d98303a5f541171fa6d23af5a6bb53b1b" } # Lints shared by every crate (each crate opts in with `[lints] workspace = true`). [workspace.lints.rust] diff --git a/crates/cli/tests/cnp.rs b/crates/cli/tests/cnp.rs index 28a2311..53b19eb 100644 --- a/crates/cli/tests/cnp.rs +++ b/crates/cli/tests/cnp.rs @@ -58,10 +58,12 @@ fn cb2026_passes_every_conformance_session_that_applies() { let (failed, skipped) = run_all(&node(&["--cnp"])); assert!(failed.is_empty(), "failed:\n{}", failed.join("\n\n")); // Of the engine's sessions, only the window's needs a capability cb2026 doesn't offer, and - // only one is for a node that doesn't ponder. + // two are for nodes without capabilities it has: pondering, and an evaluation's quiet line + // and piece values. assert_eq!( skipped, vec![ + "evaluate-quiet-pieces-unsupported (needs !engine.quiet, !engine.pieces)".to_string(), "ponder-unsupported (needs !engine.ponder)".to_string(), "window (needs engine.window)".to_string(), ] diff --git a/crates/cnp/src/lib.rs b/crates/cnp/src/lib.rs index ed5f7e2..9a1b873 100644 --- a/crates/cnp/src/lib.rs +++ b/crates/cnp/src/lib.rs @@ -59,7 +59,13 @@ //! whole numbers only, since a level's settings are whole steps. A rating within [`ELO_RANGE`] //! picks a level as `UCI_Elo` does. //! `engine/evaluate` answers with the shell's `eval`: [`eval::trace`]'s eight terms ([`TERMS`]), -//! each blended for the position's phase as the evaluation blends its total. +//! each blended for the position's phase as the evaluation blends its total. Those are the +//! hand-crafted evaluation's, while the search usually evaluates with the network, so its answer +//! also says the network's score (`searchScore`) and, asked, what each piece is worth to it +//! (`pieces`, [`Engine::piece_values`]). With `quiet` it first plays out the quiescence search's +//! line ([`Engine::quiet_line`]), which is where a search's score comes from when its line ends +//! mid-exchange. An engine of its own answers these ([`EVALUATOR_HASH_MB`]), cleared before each +//! request, so an evaluation is the same whether or not a search is running. //! //! ## Pitfalls //! @@ -98,7 +104,7 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use cb2026_chess::{Move, Position}; -use cb2026_engine::eval::{self, EvalParams, MAX_PHASE}; +use cb2026_engine::eval::{self, MAX_PHASE}; use cb2026_engine::levels::{ELO_RANGE, FULL_STRENGTH, RATINGS}; use cb2026_engine::search::MAX_PLY; use cb2026_engine::tablebase::TablebaseLoader; @@ -107,8 +113,8 @@ use cb2026_engine::{AUTHOR, Engine, Limits, NAME, Score, SearchInfo, SearchResul use cb2026_shell::SWITCHES; use cnp::engine::{ EloRange, EngineCapabilities, EngineProgress, Evaluate, EvaluateParams, EvaluateResult, Level, - Levels, LevelsResult, Line, PonderHit, Progress, Search, SearchParams, SearchStats, Stop, - Technique, Techniques, TechniquesResult, Term, + Levels, LevelsResult, Line, PieceValue, PonderHit, Progress, Search, SearchParams, SearchStats, + Stop, Technique, Techniques, TechniquesResult, Term, }; use cnp::lifecycle::{ CancelRequest, Capabilities, IncompatibleVersionData, Initialize, InitializeResult, @@ -133,6 +139,10 @@ pub const RATING_SCALE: &str = cb2026_engine::levels::RATING_SCALE; /// Where cb2026's source is. pub const SOURCE: &str = "https://github.com/cjus/chessengine"; +/// The hash table of the engine that answers `engine/evaluate`, in megabytes. Its quiescence +/// search never reads the table, so the smallest size does. +pub const EVALUATOR_HASH_MB: usize = 1; + /// The evaluation's terms as `engine/evaluate` names them: each one's id and what it measures, /// in [`eval::EvalTrace::terms`]' order (whose names are the terms' names). pub const TERMS: [(&str, &str); 8] = [ @@ -281,9 +291,9 @@ struct Node { threads: usize, /// Each switch's default, read once from a new engine (in [`SWITCHES`]' order). defaults: Vec, - /// The evaluation's parameters as the engine came configured, for `engine/evaluate` while a - /// search owns the engine. - eval_params: EvalParams, + /// The engine that answers `engine/evaluate`, configured as the engine came, with a small + /// hash table: the main engine may be busy with a search. + evaluator: Engine, /// The running search, if any. search: Option, /// The `game` hint of the last search, whose hash table the engine still holds. @@ -311,13 +321,18 @@ impl Node { fn new(output: Output, engine: Engine, config: Config) -> Node { let mut fresh = Engine::new(); let defaults = SWITCHES.iter().map(|s| *(s.flag)(&mut fresh)).collect(); + let mut evaluator = fresh; + evaluator.set_hash_size(EVALUATOR_HASH_MB); + evaluator.params = engine.params.clone(); + evaluator.techniques = engine.techniques; + evaluator.network = engine.network.clone(); Node { output, config, state: State::Starting, tablebase_loader: engine.tablebase_loader, threads: engine.threads, - eval_params: engine.params.clone(), + evaluator, engine: Some(engine), defaults, search: None, @@ -369,7 +384,7 @@ impl Node { (State::Running, Levels::NAME) => Response::ok::(id, &levels()), (State::Running, Evaluate::NAME) => match request .params::() - .and_then(|params| evaluate(¶ms, &self.eval_params)) + .and_then(|params| evaluate(¶ms, &mut self.evaluator)) { Ok(result) => Response::ok::(id, &result), Err(e) => Response::error(Some(id), e), @@ -435,6 +450,8 @@ impl Node { chess960: true, progress: true, evaluate: true, + quiet: true, + pieces: true, ponder: true, }), voice: None, @@ -938,11 +955,24 @@ fn read_position(wanted: &cnp::engine::Position) -> Result<(Position, Vec), /// `engine/evaluate`: the position's evaluation, term by term, each term blended for the /// position's phase as [`eval::trace`] blends the total (the shell's `eval` shows the same). +/// With `quiet`, of the position at the end of the quiescence search's line; the search's own +/// score when it evaluates with the network; and with `pieces`, each piece's value to it. fn evaluate( params: &EvaluateParams, - eval_params: &EvalParams, + evaluator: &mut Engine, ) -> Result { - let (position, _) = read_position(¶ms.position)?; + let (mut position, history) = read_position(¶ms.position)?; + let quiet = params.quiet.then(|| { + // From a clean slate, so the answer doesn't depend on earlier requests. + evaluator.new_game(); + let line = evaluator.quiet_line(&position, &history).moves; + for &mv in &line { + position.make_move(mv); + } + moves(&line, params.position.chess960) + }); + let mated = position.in_check() && position.legal_moves().is_empty(); + let eval_params = &evaluator.params; let trace = eval::trace(&position, eval_params); let blend = |(mg, eg): (i32, i32)| { if eval_params.tapered { @@ -963,9 +993,30 @@ fn evaluate( black: blend(black), }) .collect(); + // Only `quiet` promises a mate (spec 7.6); a plain evaluation stays static, as before. + let score = if quiet.is_some() && mated { + cnp::engine::Score::mate(0) + } else { + cnp::engine::Score::cp(eval::evaluate(&position, eval_params)) + }; + let search = evaluator.search_evaluation(&position); + let search_score = (search.network && !mated).then(|| cnp::engine::Score::cp(search.score)); + let pieces = (params.pieces && !mated).then(|| { + evaluator + .piece_values(&position) + .into_iter() + .map(|piece| PieceValue { + square: piece.square.to_string(), + value: piece.value, + }) + .collect() + }); Ok(EvaluateResult { - score: cnp::engine::Score::cp(eval::evaluate(&position, eval_params)), + score, terms, + quiet, + search_score, + pieces, }) } @@ -1156,10 +1207,8 @@ mod tests { fn an_evaluation_is_the_shell_s_eval_term_by_term() { // The Two Knights, as the spec's example has it: the shell's `eval` shows the same. let fen = "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4"; - let params = EvaluateParams { - position: CnpPosition::fen(fen), - }; - let result = evaluate(¶ms, &EvalParams::default()).unwrap(); + let params = EvaluateParams::new(CnpPosition::fen(fen)); + let result = evaluate(¶ms, &mut Engine::new()).unwrap(); assert_eq!(result.score, cnp::engine::Score::cp(-1)); let ids: Vec<&str> = result.terms.iter().map(|t| t.id.as_str()).collect(); assert_eq!(ids, TERMS.map(|(id, _)| id)); @@ -1177,16 +1226,16 @@ mod tests { #[test] fn an_evaluation_of_an_illegal_position_is_refused() { - let params = |position| EvaluateParams { position }; + let params = EvaluateParams::new; let illegal = params(CnpPosition::start().with_moves(["e2e5"])); let bad_fen = params(CnpPosition::fen("not a fen")); for wanted in [illegal, bad_fen] { - let error = evaluate(&wanted, &EvalParams::default()).unwrap_err(); + let error = evaluate(&wanted, &mut Engine::new()).unwrap_err(); assert_eq!(error.code, code::INVALID_POSITION); } // From Black's side, the score is Black's. let after_e4 = params(CnpPosition::start().with_moves(["e2e4"])); - let result = evaluate(&after_e4, &EvalParams::default()).unwrap(); + let result = evaluate(&after_e4, &mut Engine::new()).unwrap(); let net: i32 = result.terms.iter().map(|t| t.black - t.white).sum(); let cnp::engine::ScoreValue::Centipawns(cp) = result.score.value else { panic!("an evaluation is in centipawns"); @@ -1194,6 +1243,65 @@ mod tests { assert!((net - cp).abs() <= TERMS.len() as i32, "{net} against {cp}"); } + #[test] + fn an_evaluation_settles_captures_and_values_pieces_by_the_network() { + // The spec's example: after 1.e4 d5 2.exd5, Black's queen takes back. + let mut evaluator = Engine::new(); + let mut params = + EvaluateParams::new(CnpPosition::start().with_moves(["e2e4", "d7d5", "e4d5"])); + params.quiet = true; + params.pieces = true; + let result = evaluate(¶ms, &mut evaluator).unwrap(); + assert_eq!(result.quiet, Some(vec!["d8d5".to_string()])); + // The hand-crafted evaluation and its terms, of the position after 2...Qxd5. + assert_eq!(result.score, cnp::engine::Score::cp(-17)); + let term = |id: &str| { + let term = result.terms.iter().find(|t| t.id == id).unwrap(); + (term.white, term.black) + }; + assert_eq!(term("material"), (3850, 3850)); + assert_eq!(term("mobility"), (-89, -75)); + // The network the search evaluates with sees it otherwise. + assert_eq!(result.search_score, Some(cnp::engine::Score::cp(34))); + let pieces = result.pieces.as_ref().unwrap(); + assert_eq!(pieces.len(), 28); + let value = |square: &str| pieces.iter().find(|p| p.square == square).unwrap().value; + assert_eq!((value("d1"), value("d5"), value("f1")), (918, 912, 338)); + assert!(pieces.iter().all(|p| p.square != "e1" && p.square != "e8")); + // The same request gives the same answer, whatever came before. + let quiet_only = EvaluateParams { + pieces: false, + ..params.clone() + }; + let first = evaluate(&quiet_only, &mut evaluator).unwrap(); + assert_eq!(first.pieces, None); + assert_eq!(evaluate(¶ms, &mut evaluator).unwrap(), result); + // Not asked to settle: the position as it stands, a pawn down for Black, and no line. + let as_it_stands = EvaluateParams::new(params.position.clone()); + let unsettled = evaluate(&as_it_stands, &mut evaluator).unwrap(); + assert_eq!(unsettled.quiet, None); + assert!(unsettled.search_score.is_some()); + } + + #[test] + fn an_evaluation_settled_into_mate_is_mate_in_0_with_no_pieces() { + let mut params = + EvaluateParams::new(CnpPosition::start().with_moves(["f2f3", "e7e5", "g2g4", "d8h4"])); + params.quiet = true; + params.pieces = true; + let result = evaluate(¶ms, &mut Engine::new()).unwrap(); + assert_eq!(result.quiet, Some(vec![])); + assert_eq!(result.score, cnp::engine::Score::mate(0)); + assert_eq!((result.search_score, result.pieces), (None, None)); + // Without `quiet` the score stays static, as it always was. + params.quiet = false; + let plain = evaluate(¶ms, &mut Engine::new()).unwrap(); + assert!(matches!( + plain.score.value, + cnp::engine::ScoreValue::Centipawns(_) + )); + } + #[test] fn a_search_that_has_answered_doesn_t_make_the_next_busy() { let mut node = Node::new( diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 21b8959..fa9c5be 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -97,8 +97,9 @@ use std::sync::{Arc, OnceLock}; use std::thread; use std::time::{Duration, Instant}; -use cb2026_chess::{Move, Position}; +use cb2026_chess::{Move, Piece, PieceType, Position, Square}; /// The NNUE network type, for front ends that load one (stage 21; see `cb2026_nnue`). +use cb2026_nnue::Changes; pub use cb2026_nnue::Network; use book::OpeningBook; @@ -106,8 +107,8 @@ use correction::CorrectionHistory; use eval::EvalParams; use ordering::OrderingTables; use search::{ - DEFAULT_DEPTH, INFINITY, MATE, MAX_PLY, RootResult, SearchParams, Searcher, StopConditions, - Techniques, to_score, + DEFAULT_DEPTH, INFINITY, MATE, MAX_PLY, NNUE_EVAL_LIMIT, RootResult, SearchParams, Searcher, + StopConditions, Techniques, to_score, }; use stats::{SearchStats, SearchTree}; use tablebase::{Tablebase, TablebaseLoader, TablebaseParams}; @@ -284,6 +285,34 @@ impl fmt::Display for Score { } } +/// The quiescence search's line from a position ([`Engine::quiet_line`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct QuietLine { + /// Its score, from the side to move's point of view: the evaluation where the line ends, + /// or a mate when the line ends with a side checkmated. + pub score: Score, + /// The captures, promotions and evasions it plays, which may be none. + pub moves: Vec, +} + +/// A static evaluation as the search would make it ([`Engine::search_evaluation`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SearchEvaluation { + /// In centipawns from the side to move's point of view. + pub score: i32, + /// Whether it is the network's (otherwise the hand-crafted evaluation's). + pub network: bool, +} + +/// What one piece is worth to the search's evaluation of a position ([`Engine::piece_values`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PieceValue { + /// Where the piece stands. + pub square: Square, + /// What it is worth to its own side, in centipawns from that side's point of view. + pub value: i32, +} + /// Progress reported during a search. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SearchInfo { @@ -768,6 +797,191 @@ impl Engine { }; (searcher.take_tree().unwrap_or_default(), info) } + + /// The quiescence search from `position` alone, on one thread, as at a leaf of the main + /// search: the captures (and queen promotions, and every evasion in check) it plays until + /// the side to move does better to stop, and its score. + /// + /// A principal variation ends where the main search did, which can be in the middle of an + /// exchange, a piece about to be taken back. Its score comes from the position at the end + /// of this line, played on from the variation's last position (CNP's `engine/evaluate` + /// with `quiet`). The line settles what is hanging; it isn't a search of the position. + /// + /// **Pitfall:** the quiescence search stands on the evaluation as the correction history + /// corrects it, and orders captures by the history tables, so call [`Engine::new_game`] + /// first for an answer that doesn't depend on earlier searches. + pub fn quiet_line(&mut self, position: &Position, history: &[u64]) -> QuietLine { + let stop = AtomicBool::new(false); + let mut searcher = Searcher::new( + &self.params, + self.search_params, + &self.tt, + &mut self.ordering, + self.techniques, + StopConditions { + stop: &stop, + deadline: None, + max_nodes: None, + }, + history, + ); + searcher.use_correction(&mut self.correction); + if let Some(net) = self.network.as_deref().filter(|_| self.techniques.nnue) { + searcher.use_network(net); + } + let (score, moves) = searcher.quiet_line(position); + QuietLine { + score: to_score(score), + moves, + } + } + + /// The static evaluation the search would make of `position`: the network's, when there + /// is one, it is switched on and the position isn't an ending it leaves to the hand-crafted + /// evaluation ([`Techniques::lone_king`], [`Techniques::pawnless_endings`]); otherwise the + /// hand-crafted evaluation's. In centipawns from the side to move's point of view, without + /// the correction history a search adds to it. + /// + /// The shell's `eval` and CNP's `engine/evaluate` break down the hand-crafted evaluation, + /// term by term; at full strength, the search usually evaluates with the network instead. + /// This says which, and what it thinks. + pub fn search_evaluation(&self, position: &Position) -> SearchEvaluation { + match self.search_network(position) { + Some(net) => SearchEvaluation { + score: net + .evaluate_position(position) + .clamp(-NNUE_EVAL_LIMIT, NNUE_EVAL_LIMIT), + network: true, + }, + None => SearchEvaluation { + score: eval::evaluate(position, &self.params), + network: false, + }, + } + } + + /// What each piece but the kings is worth to the search's evaluation of `position` + /// ([`Engine::search_evaluation`]): the evaluation from the piece's side's point of view, + /// less the same evaluation of the position with the piece taken off the board. In square + /// order, a1 first. + /// + /// A network judges a position as a whole, with no terms to break its score into; taking + /// one piece off and evaluating again measures what it thinks that piece is worth there. + /// The idea is the one Stockfish's `eval` shows (GPL; only the idea, no code). The values + /// don't add up to the score: pieces work together, and a defender is worth what its loss + /// would cost. + /// + /// **Pitfall:** a position without one of its pieces may be one that can't arise in a + /// game, such as the side not to move left in check. The network still evaluates it, since + /// its inputs are only pieces on squares ([`cb2026_nnue::Changes::removing`]). The + /// hand-crafted evaluation needs a [`Position`], which refuses such a position, so when it + /// is the search's evaluation those pieces are left out. + pub fn piece_values(&self, position: &Position) -> Vec { + let us = position.side_to_move(); + // What a piece is worth to its own side, from the evaluations with and without it, + // both from the side to move's point of view. + let to_its_side = |piece: Piece, with: i32, without: i32| { + if piece.color == us { + with - without + } else { + without - with + } + }; + let pieces = position.occupied().squares().filter_map(|square| { + position + .piece_at(square) + .filter(|piece| piece.piece_type != PieceType::King) + .map(|piece| (square, piece)) + }); + match self.search_network(position) { + Some(net) => { + let clamp = |value: i32| value.clamp(-NNUE_EVAL_LIMIT, NNUE_EVAL_LIMIT); + let whole = net.accumulator(position); + let with = clamp(net.evaluate(&whole, us)); + let mut rest = net.empty_accumulator(); + pieces + .map(|(square, piece)| { + net.update_into(&whole, &mut rest, &Changes::removing(piece, square)); + let without = clamp(net.evaluate(&rest, us)); + PieceValue { + square, + value: to_its_side(piece, with, without), + } + }) + .collect() + } + None => { + let with = eval::evaluate(position, &self.params); + pieces + .filter_map(|(square, piece)| { + let rest = without_piece(position, square)?; + let without = eval::evaluate(&rest, &self.params); + Some(PieceValue { + square, + value: to_its_side(piece, with, without), + }) + }) + .collect() + } + } + } + + /// The network the search would evaluate `position` with, if any (see + /// [`Engine::search_evaluation`]). + fn search_network(&self, position: &Position) -> Option<&Network> { + self.network.as_deref().filter(|_| { + self.techniques.nnue && !search::hand_crafted_ending(&self.techniques, position) + }) + } +} + +/// `position` with the piece on `square` taken off, castling and en passant rights dropped +/// (the hand-crafted evaluation reads neither), or `None` when what is left is a position a +/// [`Position`] refuses, such as the side not to move in check. +fn without_piece(position: &Position, square: Square) -> Option { + let fen = position.to_fen(); + let mut fields = fen.split(' '); + let (placement, side) = (fields.next()?, fields.next()?); + // The placement lists rank 8 first, each rank from the a-file, digits counting empty + // squares. + let mut board: Vec> = placement + .split('/') + .map(|rank| { + rank.chars() + .flat_map(|c| match c.to_digit(10) { + Some(empty) => vec!['1'; empty as usize], + None => vec![c], + }) + .collect() + }) + .collect(); + *board + .get_mut(7 - square.rank().index())? + .get_mut(square.file().index())? = '1'; + let placement = board + .iter() + .map(|rank| { + let mut text = String::new(); + let mut empty = 0; + for &c in rank { + if c == '1' { + empty += 1; + } else { + if empty > 0 { + text.push_str(&empty.to_string()); + empty = 0; + } + text.push(c); + } + } + if empty > 0 { + text.push_str(&empty.to_string()); + } + text + }) + .collect::>() + .join("/"); + Position::from_fen(&format!("{placement} {side} - - 0 1")).ok() } /// What the main search thread needs besides its [`Searcher`]. @@ -1339,6 +1553,129 @@ mod tests { assert!(stats.reduction_researches <= stats.reduced); } + /// `moves` (coordinate text) played from the starting position. + fn after(moves: &[&str]) -> Position { + let mut pos = Position::startpos(); + for text in moves { + let mv = pos.parse_uci_move(text).unwrap(); + pos.make_move(mv); + } + pos + } + + fn uci(line: &[Move]) -> Vec { + line.iter().map(|mv| mv.to_uci(false)).collect() + } + + #[test] + fn a_quiet_line_settles_the_exchange_a_line_stops_in() { + let mut engine = Engine::new(); + // After 1.e4 d5 2.exd5 Black is a pawn down until its queen takes back. + let pos = after(&["e2e4", "d7d5", "e4d5"]); + engine.new_game(); + let line = engine.quiet_line(&pos, &[]); + assert_eq!(uci(&line.moves), ["d8d5"]); + // Its score is the search's evaluation where it ends, one ply on: the other side's. + let mut end = pos.clone(); + for &mv in &line.moves { + end.make_move(mv); + } + let at_end = engine.search_evaluation(&end); + assert!(at_end.network); + assert_eq!(line.score, Score::Centipawns(-at_end.score)); + // A capture the side to move needn't make is left alone: after 1.e4 d5 White may take + // on d5 or not, and does at least as well standing pat. + engine.new_game(); + let optional = engine.quiet_line(&after(&["e2e4", "d7d5"]), &[]); + assert!(optional.moves.is_empty(), "{:?}", uci(&optional.moves)); + // A quiet position needs nothing settled. + engine.new_game(); + let start = engine.quiet_line(&Position::startpos(), &[]); + assert!(start.moves.is_empty()); + let here = engine.search_evaluation(&Position::startpos()); + assert_eq!(start.score, Score::Centipawns(here.score)); + } + + #[test] + fn a_quiet_line_from_a_mated_position_is_mate() { + let mut engine = Engine::new(); + let mated = after(&["f2f3", "e7e5", "g2g4", "d8h4"]); + let line = engine.quiet_line(&mated, &[]); + assert!(line.moves.is_empty()); + assert_eq!(line.score, Score::Mate(0)); + } + + #[test] + fn the_search_evaluates_with_the_network_except_in_its_hand_crafted_endings() { + let mut engine = Engine::new(); + let start = Position::startpos(); + let by_net = engine.search_evaluation(&start); + assert!(by_net.network); + assert_eq!( + by_net.score, + engine.network.as_ref().unwrap().evaluate_position(&start) + ); + // A lone king: the hand-crafted evaluation, which drives it to the edge. + let lone = Position::from_fen("8/8/8/4k3/8/8/8/3QK3 w - - 0 1").unwrap(); + let by_hand = engine.search_evaluation(&lone); + assert!(!by_hand.network); + assert_eq!(by_hand.score, eval::evaluate(&lone, &engine.params)); + // The network switched off. + engine.techniques.nnue = false; + assert!(!engine.search_evaluation(&start).network); + } + + #[test] + fn a_piece_is_worth_what_the_evaluation_loses_without_it() { + let mut engine = Engine::new(); + let start = Position::startpos(); + let values = engine.piece_values(&start); + // Every piece but the kings, a1 first. + assert_eq!(values.len(), 30); + assert_eq!(values[0].square.to_string(), "a1"); + let d1 = |values: &[PieceValue]| { + values + .iter() + .find(|v| v.square.to_string() == "d1") + .unwrap() + .value + }; + let without_queen = + Position::from_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNB1KBNR w KQkq - 0 1").unwrap(); + let net = engine.network.clone().unwrap(); + assert_eq!( + d1(&values), + net.evaluate_position(&start) - net.evaluate_position(&without_queen) + ); + // Black's pieces are valued from Black's point of view: its queen is worth a lot to it. + let d8 = values + .iter() + .find(|v| v.square.to_string() == "d8") + .unwrap(); + assert!(d8.value > 500, "{d8:?}"); + // By the hand-crafted evaluation when it is the search's. + engine.techniques.nnue = false; + let by_hand = engine.piece_values(&start); + assert_eq!( + d1(&by_hand), + eval::evaluate(&start, &engine.params) - eval::evaluate(&without_queen, &engine.params) + ); + } + + #[test] + fn a_piece_whose_loss_would_leave_a_king_in_check_has_a_value_only_by_the_network() { + let mut engine = Engine::new(); + // White to move; Black's e7 pawn shields its king from the rook on e1. Without it, + // Black, not to move, would be in check, which no position allows. + let pos = Position::from_fen("4k3/4p3/8/8/8/8/3P1P2/4RK2 w - - 0 1").unwrap(); + let e7 = |values: &[PieceValue]| values.iter().any(|v| v.square.to_string() == "e7"); + assert!(e7(&engine.piece_values(&pos))); + engine.techniques.nnue = false; + let by_hand = engine.piece_values(&pos); + assert!(!e7(&by_hand)); + assert_eq!(by_hand.len(), 3); + } + #[test] fn search_trees_record_the_last_iteration() { let pos = Position::startpos(); diff --git a/crates/engine/src/search.rs b/crates/engine/src/search.rs index fc49e87..661066c 100644 --- a/crates/engine/src/search.rs +++ b/crates/engine/src/search.rs @@ -1026,6 +1026,14 @@ enum MoveSearch { }, } +/// Whether the search evaluates `pos` with the hand-crafted evaluation even when it has a +/// network: a lone king ([`Techniques::lone_king`]) or a small pawnless ending +/// ([`Techniques::pawnless_endings`]), which the hand-crafted evaluation plays better. +pub(crate) fn hand_crafted_ending(techniques: &Techniques, pos: &Position) -> bool { + (techniques.lone_king && lone_king(pos)) + || (techniques.pawnless_endings && pawnless_ending(pos)) +} + /// Whether exactly one side has only its king: an ending the side ahead wins by driving that /// king to the edge (see [`Techniques::lone_king`]). fn lone_king(pos: &Position) -> bool { @@ -1129,8 +1137,19 @@ impl<'a> Searcher<'a> { /// a lone king ([`Techniques::lone_king`]) or a small pawnless ending /// ([`Techniques::pawnless_endings`]). fn hand_crafted_ending(&self, pos: &Position) -> bool { - (self.techniques.lone_king && lone_king(pos)) - || (self.techniques.pawnless_endings && pawnless_ending(pos)) + hand_crafted_ending(&self.techniques, pos) + } + + /// The quiescence search from `pos` alone, as at a leaf of the main search: captures (and + /// queen promotions, and every evasion in check) until the side to move does better to stop. + /// Returns its score, from the side to move's point of view, and its line. CNP's + /// `engine/evaluate` with `quiet` evaluates the position at the end of that line, which is + /// where a search's score comes from when its principal variation ends mid-exchange. + pub(crate) fn quiet_line(&mut self, pos: &Position) -> (i32, Vec) { + self.refresh_accumulator(pos); + let mut line = Vec::new(); + let score = self.quiescence(pos, 0, -INFINITY, INFINITY, &mut line); + (score, line) } /// The static evaluation of `pos`, at `ply`: the network's, from the accumulator the diff --git a/crates/nnue/src/features.rs b/crates/nnue/src/features.rs index 4678f9c..bafdba6 100644 --- a/crates/nnue/src/features.rs +++ b/crates/nnue/src/features.rs @@ -137,6 +137,22 @@ impl Changes { } // ANCHOR_END: changes +impl Changes { + /// `piece` taken off `square` by no move at all, to see what the network thinks the + /// position is worth without it: how a piece's value to the network is measured (CNP's + /// `engine/evaluate` with `pieces`). + /// + /// The position without the piece may be one that can't arise in a game, such as the side + /// not to move left in check, which a `Position` refuses. The network's inputs are only + /// pieces on squares, so the accumulator still has an answer. + pub fn removing(piece: Piece, square: Square) -> Changes { + Changes { + removed: [Some((piece, square)), None], + added: [None, None], + } + } +} + #[cfg(test)] mod tests { use std::collections::HashSet; diff --git a/crates/nnue/src/network.rs b/crates/nnue/src/network.rs index 8d6bf17..8959d6b 100644 --- a/crates/nnue/src/network.rs +++ b/crates/nnue/src/network.rs @@ -609,7 +609,7 @@ fn fnv1a(bytes: &[u8]) -> u64 { #[cfg(test)] mod tests { - use cb2026_chess::{Move, STARTING_FEN}; + use cb2026_chess::{Move, STARTING_FEN, Square}; use super::*; use crate::float::WEIGHT_LIMIT; @@ -773,6 +773,27 @@ mod tests { ); } + #[test] + fn taking_a_piece_off_matches_the_position_without_it() { + let net = random_network(64, Activation::SquaredClippedRelu, 21); + let start = Position::from_fen(STARTING_FEN).unwrap(); + let without_queen = + Position::from_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNB1KBNR w KQkq - 0 1").unwrap(); + let d1 = Square::from_index(3).unwrap(); + let queen = start.piece_at(d1).unwrap(); + let mut child = net.empty_accumulator(); + net.update_into( + &net.accumulator(&start), + &mut child, + &Changes::removing(queen, d1), + ); + assert_eq!(child, net.accumulator(&without_queen)); + assert_eq!( + net.evaluate(&child, Color::White), + net.evaluate_position(&without_queen) + ); + } + #[test] fn a_game_played_out_keeps_its_accumulator_exact() { // A long line of updates, not just one: errors would pile up. diff --git a/docs/PRD.md b/docs/PRD.md index 6c8ba63..b87e353 100644 --- a/docs/PRD.md +++ b/docs/PRD.md @@ -408,7 +408,10 @@ whole position and every option, so cb2026 can one day be one node of a distribu MultiPV, root moves, technique switches (the shell's, by the same names), a deterministic mode and progress reports. `engine/techniques` and `engine/levels` list the switches and the measured levels, and `engine/evaluate` gives a position's evaluation term by term, as the shell's `eval` -does, so Solrac's chat can say why cb2026 likes a position (Solrac Chess AI #145). A search can +does, so Solrac's chat can say why cb2026 likes a position (Solrac Chess AI #145). Since the +search evaluates with the network and the terms are the hand-crafted evaluation's, its answer +also gives the network's score and, asked, what each piece is worth to it, and can first settle +captures as a search's leaf does (`quiet`), for Solrac's Engine Mind (cjus/chessgui#340). A search can ponder (`"ponder": true` and `engine/ponderHit`), as UCI's `go ponder` does, for Solrac's pondering switch (cjus/chess-node-protocol#18, cjus/chessgui#319). Every engine capability is offered except a root score window. Every conformance session in the diff --git a/docs/status.md b/docs/status.md index 5be686a..f6668ce 100644 --- a/docs/status.md +++ b/docs/status.md @@ -150,7 +150,15 @@ then to the time it would have had, keeping its tree, passing `ponder-hit`, `pon `ponder-hit-crossing`, for Solrac's pondering switch (cjus/chessgui#319; #242); UCI and XBoard ponder with the same `Limits::pondering`, no longer `infinite`, so a strength level keeps its horizon while pondering (it lost it on every move after a ponder hit), XBoard keeps `sd`, and the book answers a ponder -search (#243).* +search (#243). 2026-11-01: **CNP's `engine/evaluate` settles captures and values pieces by +the network** (capabilities `quiet` and `pieces`, cjus/chess-node-protocol#21), for Solrac's +Engine Mind (cjus/chessgui#340): its terms are the hand-crafted evaluation's, which ordered +three reported lines as the search did in 0 of 10 positions where the network did in 5, so the +answer now also has the network's score (`searchScore`) and, asked, each piece's value to it +(`Engine::piece_values`, the network's score without the piece, through +`Changes::removing`); with `quiet` it first plays the quiescence search's line +(`Engine::quiet_line`), since a line can end mid-exchange (2 lines in 30). An evaluator engine +of the node's own answers, cleared before each request; no functional change to the search.* ## Stages