Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions conformance/engine/evaluate-quiet-pieces-unsupported.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{"session": "evaluate-quiet-pieces-unsupported", "description": "a node that evaluates but offers neither quiet nor pieces refuses each with Unsupported (spec 6.1, 7.6)", "requires": ["engine", "engine.evaluate", "!engine.quiet", "!engine.pieces"]}
{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}}
{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}}
{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "quiet": true}}}
{"expect": {"id": 2, "error": {"code": -32014, "message": "$string"}}}
{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "pieces": true}}}
{"expect": {"id": 3, "error": {"code": -32014, "message": "$string"}}}
{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}}
{"expect": {"id": 99, "result": null}}
{"send": {"jsonrpc": "2.0", "method": "exit"}}
{"expectExit": 0}
15 changes: 15 additions & 0 deletions conformance/engine/evaluate-quiet-pieces.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{"session": "evaluate-quiet-pieces", "description": "engine/evaluate settles captures with quiet and values each piece with pieces: none to settle at the start, mate in 0 when checkmated, and each asked for alone (spec 7.6)", "requires": ["engine", "engine.evaluate", "engine.quiet", "engine.pieces"]}
{"send": {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocol": "1.0", "client": {"name": "cnp-conformance", "version": "1.0"}}}}
{"expect": {"id": 1, "result": {"protocol": "1.0", "node": {"name": "$string", "version": "$string", "license": "$string"}, "capabilities": "$object"}}}
{"send": {"jsonrpc": "2.0", "id": 2, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}, "quiet": true, "pieces": true}}}
{"expect": {"id": 2, "result": {"score": {"cp": "$integer"}, "terms": "$array", "quiet": [], "pieces": "$array"}}}
{"send": {"jsonrpc": "2.0", "id": 3, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["e2e4", "d7d5", "e4d5"]}, "quiet": true}}}
{"expect": {"id": 3, "result": {"score": {"cp": "$integer"}, "terms": "$array", "quiet": "$array", "pieces": "$absent"}}}
{"send": {"jsonrpc": "2.0", "id": 4, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["e2e4"]}, "pieces": true}}}
{"expect": {"id": 4, "result": {"score": {"cp": "$integer"}, "terms": "$array", "quiet": "$absent", "pieces": "$array"}}}
{"send": {"jsonrpc": "2.0", "id": 5, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["f2f3", "e7e5", "g2g4", "d8h4"]}, "quiet": true, "pieces": true}}}
{"expect": {"id": 5, "result": {"score": {"mate": 0}, "terms": "$array", "quiet": [], "searchScore": "$absent", "pieces": "$absent"}}}
{"send": {"jsonrpc": "2.0", "id": 99, "method": "shutdown"}}
{"expect": {"id": 99, "result": null}}
{"send": {"jsonrpc": "2.0", "method": "exit"}}
{"expectExit": 0}
74 changes: 72 additions & 2 deletions crates/cnp/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ pub struct EngineCapabilities {
/// A position's evaluation, term by term (`engine/evaluate`).
#[serde(default)]
pub evaluate: bool,
/// Settling captures before an evaluation (`quiet` on `engine/evaluate`).
#[serde(default)]
pub quiet: bool,
/// What each piece is worth to the search's evaluation (`pieces` on `engine/evaluate`),
/// and the search's own score (`searchScore`) when `terms` break down another evaluation.
#[serde(default)]
pub pieces: bool,
/// Searching on the opponent's time (`ponder`, `engine/ponderHit`).
#[serde(default)]
pub ponder: bool,
Expand Down Expand Up @@ -629,8 +636,14 @@ pub struct EloRange {
/// position as it stands, without a search, and what it is made of.
///
/// **Pitfall:** an evaluation doesn't search, so it misses a piece about to be captured and
/// doesn't know that a side is mated. To explain a search's score, evaluate the position at
/// the end of its `pv`, which is where the score came from.
/// doesn't know that a side is mated. A search's `pv` can end in the middle of an exchange,
/// since the search tries captures past its last move until the position is quiet. To explain
/// a search's score, evaluate the position at the end of its `pv` with
/// [`EvaluateParams::quiet`].
///
/// **Pitfall:** an engine may search with a neural network and break down another evaluation
/// in [`EvaluateResult::terms`]. Then [`EvaluateResult::search_score`] is the search's score,
/// and [`EvaluateResult::pieces`] the search's evaluation's view, piece by piece.
pub enum Evaluate {}

impl RequestMethod for Evaluate {
Expand All @@ -645,17 +658,74 @@ impl RequestMethod for Evaluate {
pub struct EvaluateParams {
/// The position.
pub position: Position,
/// Settle captures first, as the engine's search does at its leaves, and evaluate the
/// position where they stop (capability `quiet`). The moves come back in
/// [`EvaluateResult::quiet`].
#[serde(default, skip_serializing_if = "is_false")]
pub quiet: bool,
/// Also say what each piece is worth to the search's evaluation (capability `pieces`), in
/// [`EvaluateResult::pieces`].
#[serde(default, skip_serializing_if = "is_false")]
pub pieces: bool,
}

impl EvaluateParams {
/// An evaluation of `position` as it stands, with nothing more asked.
pub fn new(position: Position) -> EvaluateParams {
EvaluateParams {
position,
quiet: false,
pieces: false,
}
}
}

/// A position's evaluation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvaluateResult {
/// The evaluation, in centipawns from the side to move's point of view, always exact.
/// With [`EvaluateParams::quiet`], mate in 0 when the side to move is checkmated where the
/// captures stop.
pub score: Score,
/// What the score is made of. The side to move's terms less the other side's are the
/// score, give or take rounding.
pub terms: Vec<Term>,
/// When [`EvaluateParams::quiet`] was asked: the moves that settled the position, in
/// order, in coordinate notation, which may be none. The rest of the result is about the
/// position they reach. `None` when it wasn't asked.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quiet: Option<Vec<String>>,
/// From a node with capability `pieces`, when its search evaluates the position with
/// something other than the evaluation [`EvaluateResult::terms`] break down, such as a
/// neural network: the search's evaluation, from the side to move's point of view.
/// `None`: the search's evaluation is [`EvaluateResult::score`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_score: Option<Score>,
/// When [`EvaluateParams::pieces`] was asked: what each piece but the kings is worth to
/// the search's evaluation, in no set order. Left out when the side to move is
/// checkmated. `None` when it wasn't asked.
///
/// **Pitfall:** the values don't add up to the score, since pieces work together.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pieces: Option<Vec<PieceValue>>,
}

/// What one piece is worth to the search's evaluation of a position: the evaluation from its
/// own side's point of view, less the evaluation of the position with the piece taken off the
/// board.
///
/// It measures a neural network the way a person would test a position's piece: imagine it
/// gone and see how much worse things are. A position without the piece may be one that can't
/// arise in a game (a side left in check); the value is still the evaluation's view of that
/// piece there, and no more than that. The idea is the one Stockfish's `eval` shows.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PieceValue {
/// The piece's square, like `e4`.
pub square: String,
/// What it is worth to its own side here, in centipawns from its side's point of view.
pub value: i32,
}

/// One term of an evaluation, like material or mobility.
Expand Down
66 changes: 66 additions & 0 deletions crates/cnp/tests/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,9 @@ fn an_evaluation_is_a_score_and_its_terms_for_each_side() {
black: 0,
},
],
quiet: None,
search_score: None,
pieces: None,
};
let value = serde_json::to_value(&result).unwrap();
// A term without a description leaves it out.
Expand All @@ -308,6 +311,69 @@ fn an_evaluation_is_a_score_and_its_terms_for_each_side() {
assert!(!offered.evaluate);
}

#[test]
fn an_evaluation_can_settle_captures_and_value_each_piece() {
let position = engine::Position::start().with_moves(["e2e4", "d7d5", "e4d5"]);
// Nothing more asked: the flags stay out, as for a node that doesn't know them.
let plain = engine::EvaluateParams::new(position.clone());
let value = serde_json::to_value(&plain).unwrap();
assert_eq!(value.get("quiet"), None);
assert_eq!(value.get("pieces"), None);
let asked = engine::EvaluateParams {
quiet: true,
pieces: true,
..plain
};
let value = serde_json::to_value(&asked).unwrap();
assert_eq!(value["quiet"], json!(true));
assert_eq!(value["pieces"], json!(true));
assert_eq!(
serde_json::from_value::<engine::EvaluateParams>(value).unwrap(),
asked
);

let result = engine::EvaluateResult {
score: Score::cp(-17),
terms: vec![],
quiet: Some(vec!["d8d5".to_string()]),
search_score: Some(Score::cp(34)),
pieces: Some(vec![engine::PieceValue {
square: "d5".to_string(),
value: 912,
}]),
};
let value = serde_json::to_value(&result).unwrap();
assert_eq!(
value,
json!({"score": {"cp": -17}, "terms": [], "quiet": ["d8d5"],
"searchScore": {"cp": 34}, "pieces": [{"square": "d5", "value": 912}]})
);
assert_eq!(
serde_json::from_value::<engine::EvaluateResult>(value).unwrap(),
result
);
// Asked to settle an already quiet position: no moves, which isn't the same as not asked.
let settled: engine::EvaluateResult =
serde_json::from_value(json!({"score": {"cp": 5}, "terms": [], "quiet": []})).unwrap();
assert_eq!(settled.quiet, Some(vec![]));
let unasked: engine::EvaluateResult =
serde_json::from_value(json!({"score": {"cp": 5}, "terms": []})).unwrap();
assert_eq!(
(unasked.quiet, unasked.search_score, unasked.pieces),
(None, None, None)
);
// Checkmated where the captures stop: mate in 0, and no piece values.
let mated: engine::EvaluateResult =
serde_json::from_value(json!({"score": {"mate": 0}, "terms": [], "quiet": []})).unwrap();
assert_eq!(mated.score, Score::mate(0));
// The capabilities are off unless offered.
let offered: engine::EngineCapabilities = serde_json::from_value(json!({})).unwrap();
assert!(!offered.quiet && !offered.pieces);
let offered: engine::EngineCapabilities =
serde_json::from_value(json!({"quiet": true, "pieces": true})).unwrap();
assert!(offered.quiet && offered.pieces);
}

#[test]
fn versions_are_text_and_agree_on_the_major_version() {
let v: Version = serde_json::from_value(json!("1.3")).unwrap();
Expand Down
55 changes: 48 additions & 7 deletions spec/cnp.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ Every engine node answers `engine/search` with the limits `depth`, `nodes`, `tim
| `chess960` | Positions with `"chess960": true`: Chess960 starting positions and castling |
| `progress` | `progressMs`, and `engine/progress` |
| `evaluate` | `engine/evaluate` |
| `quiet` | `quiet` on `engine/evaluate`: settling captures before evaluating ([7.6](#76-engineevaluate)) |
| `pieces` | `pieces` on `engine/evaluate`, and `searchScore` in its result: what each piece is worth to the search's evaluation ([7.6](#76-engineevaluate)) |
| `ponder` | `ponder`, and `engine/ponderHit`: searching on the opponent's time ([7.7](#77-pondering)) |

### 6.3 Limits
Expand Down Expand Up @@ -406,9 +408,11 @@ With cb2026's measured levels (three of its twenty-one shown):
Needs `evaluate`. The engine's evaluation of a position as it stands, without a search, and
what it is made of, so that a client can say why the engine likes a position. Params:

| Field | Type | |
| --- | --- | --- |
| `position` | object | The position ([2](#2-conventions)) |
| Field | Type | Needs | |
| --- | --- | --- | --- |
| `position` | object | | The position ([2](#2-conventions)) |
| `quiet` | boolean | `quiet` | Settle captures first, as the engine's search does at its leaves, and evaluate the position where they stop (below). Missing: `false` |
| `pieces` | boolean | `pieces` | Also say what each piece is worth to the search's evaluation (`pieces` in the result, below). Missing: `false` |

A position whose FEN isn't valid, or with a move that isn't legal, is answered with
`InvalidPosition`.
Expand All @@ -417,8 +421,11 @@ Result:

| Field | Type | |
| --- | --- | --- |
| `score` | score | The evaluation, in centipawns from the side to move's point of view, always exact |
| `score` | score | The evaluation, in centipawns from the side to move's point of view, always exact. With `quiet`, `{"mate": 0}` when the side to move is checkmated where the captures stop |
| `terms` | array | What the score is made of, each with `id` (the engine's own, like `mobility`), `name` (for people), optionally `description` (a sentence), and `white` and `black`: what the term is worth to each side in this position, in centipawns, each from its own side's point of view. The side to move's terms less the other side's are the score, give or take rounding |
| `quiet` | array of moves | When `quiet` was asked: the moves that settled the position, in order, which may be none. The rest of the result is about the position they reach |
| `searchScore` | score | From a node with `pieces`, when its search evaluates this position with something other than the evaluation `terms` break down, such as a neural network: the search's evaluation, from the side to move's point of view, always exact. Missing: the search's evaluation is `score` |
| `pieces` | array | When `pieces` was asked: each piece but the kings, in no set order, with `square` and `value`: what the piece is worth to its own side in this position, by the search's evaluation, in centipawns from its side's point of view. That is the evaluation less the evaluation of the position with the piece taken off the board. Left out, with `searchScore`, when the side to move is checkmated |

With cb2026's evaluation (three of its eight terms shown):

Expand All @@ -431,8 +438,39 @@ Term ids are the engine's own, as technique ids are: two engines may split their
differently.

An evaluation doesn't search, so it misses a piece about to be captured and doesn't know that a
side is mated. To explain a search's score, evaluate the position at the end of its `pv`, which
is where the score came from.
side is mated. A search's score comes from the end of its `pv`, but not always from the
position the `pv` reaches: a search goes on past its line's last move, trying captures until
the position is quiet (a quiescence search), so a `pv` can end in the middle of an exchange,
with a piece about to be taken back. To explain a search's score, evaluate the position at the
end of its `pv` with `quiet`.

**`quiet`.** The node plays out captures (and queen promotions, and evasions when in check) as
its search does at its leaves, until the side to move does better to stop, and evaluates the
position there. `quiet` in the result lists the moves it played. A capture the side to move
needn't make is left alone when stopping is as good, as a search's leaf leaves it, so a
position with captures on offer may need none played. The moves settle what is hanging, as
the search would; they aren't a search of the position.

**`pieces`.** Some engines evaluate with a neural network, which judges a position as a whole
and has no terms to break it into; `terms` then come from another evaluation, which the search
doesn't use (`searchScore` says what the search's evaluation is). What each piece is worth to
the search's evaluation can still be measured: evaluate the position again without the piece.
The values don't add up to the score, since pieces work together: a piece that defends another
is worth what its loss would cost. A position without one of its pieces may be one that can't
arise in a game, such as a side left in check: the value is still what the evaluation thinks
of that piece there, and it is no more than that. Stockfish's `eval` shows the same measure.

With cb2026's network after 1.e4 d5 2.exd5, where Black's queen takes back on d5 (three of its
eight terms and three of its 28 pieces shown):

```cnp
→ {"jsonrpc": "2.0", "id": 14, "method": "engine/evaluate", "params": {"position": {"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["e2e4", "d7d5", "e4d5"]}, "quiet": true, "pieces": true}}
← {"jsonrpc": "2.0", "id": 14, "result": {"score": {"cp": -17}, "terms": [{"id": "material", "name": "Material", "white": 3850, "black": 3850}, {"id": "mobility", "name": "Mobility", "description": "Safe squares each piece can reach.", "white": -89, "black": -75}, {"id": "tempo", "name": "Tempo", "white": 10, "black": 0}], "quiet": ["d8d5"], "searchScore": {"cp": 34}, "pieces": [{"square": "d1", "value": 918}, {"square": "d5", "value": 912}, {"square": "f1", "value": 338}]}}
```

The hand-crafted evaluation that `terms` break down thinks White is slightly worse (−17), and
the network the search uses that White is better (+34): a client explaining the search's
choices uses `searchScore` and `pieces`.

### 7.7 Pondering

Expand Down Expand Up @@ -736,5 +774,8 @@ These names are reserved, so that nothing else uses them:
and how a short first word is kept, rather than the voice node knowing chess
(cjus/chessgui#226); and pondering (capability `ponder`, a search's `ponder` and its result's
`ponderMs`, and `engine/ponderHit`), so an engine can search on the opponent's time under a
game clock (#18, cjus/chessgui#319). Its design came from
game clock (#18, cjus/chessgui#319); and an evaluation's `quiet` and `pieces`, with
`searchScore` (capabilities `quiet` and `pieces`), so a client can explain the score of a
search that evaluates with a neural network, from the quiet position it came from
(cjus/chessgui#340). Its design came from
Solrac, a chess board that teaches, and cb2026, its engine.
Loading