chessbaseLinux/crates/maia/src/lib.rs
vrubelroman 9cd28b9039 Play against Maia: dialog, clocks, game screen, result strip
«⚔ Play» (Ctrl+G) opens «Play against the computer»: name and rating
(optional), strength 600–2600 (or weaker/as me/stronger), colour, Lichess time
controls, custom, no clock. The game screen in play mode: clock cards above
and below the notation (read-only), take back, resign (abort before the first
moves); no engine, analysis or editing. Maia answers in a background thread
with a human-like pause bounded so she never loses on time; stale answers are
dropped. Endings: mate, stalemate, no material, threefold, fifty moves, time
(draw when the other side cannot mate), resignation; then the result strip
(Analyse, Rematch, New game, Save to a database) and an ordinary game with the
tags of a played game and [%clk]. Leaving during a game asks (resign and add /
resign and leave / keep playing), the clocks wait meanwhile. maia reads the
published PyTorch checkpoint directly (zip + a small pickle reader that refuses
everything but tensors); maia_download fetches it on request (pinned revision,
SHA-256). Dev hooks CP_PLAY, CP_PLAY_AUTO, CP_MAIA. Russian texts; the other
languages follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 04:10:02 +03:00

80 lines
2.7 KiB
Rust

//! A human-like move predictor: the Maia-3 network (CSSLab, University of Toronto,
//! "Chessformer", ICLR 2026) computed in plain Rust, without a machine-learning runtime.
//!
//! The network sees the position (and up to seven positions before it) from the side to
//! move and the ratings of both players, and gives the probability of each legal move
//! as a player of that rating would play it, plus the chances of win, draw and loss.
//!
//! The weights are the published checkpoint itself (`maia3-5m.pt`, PyTorch's zip of a
//! pickle and raw f32 storages), read without PyTorch: the network shares one bias
//! tensor between its blocks.
mod checkpoint;
mod net;
mod weights;
pub use net::Prediction;
pub use weights::WeightsError;
use shakmaty::{Chess, Move, Position};
/// The network, loaded.
pub struct Maia {
net: net::Net,
}
impl Maia {
/// Reads the checkpoint (`maia3-5m.pt`).
pub fn load(path: &std::path::Path) -> Result<Maia, WeightsError> {
let bytes = std::fs::read(path).map_err(WeightsError::Io)?;
Maia::from_bytes(&bytes)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Maia, WeightsError> {
let w = weights::Weights::parse(bytes)?;
Ok(Maia {
net: net::Net::new(&w)?,
})
}
/// The moves a player rated `self_elo` would play in `history.last()` against one
/// rated `oppo_elo`, most likely first. `history`: the positions of the game up to
/// and including the current one (the last eight are used; fewer are padded with
/// the earliest given). Empty when there is no legal move.
pub fn predict(&self, history: &[Chess], self_elo: u32, oppo_elo: u32) -> Prediction {
self.net.predict(history, self_elo, oppo_elo)
}
}
/// A move to play from a prediction: the most likely one with `temperature` 0,
/// otherwise drawn at random with probabilities sharpened (< 1) or flattened (> 1).
/// `random` is a number in [0, 1).
pub fn pick(prediction: &Prediction, temperature: f32, random: f32) -> Option<Move> {
let moves = &prediction.moves;
if moves.is_empty() {
return None;
}
if temperature <= 0.0 {
return Some(moves[0].0);
}
let weights: Vec<f32> = moves
.iter()
.map(|(_, p)| p.max(1e-12).powf(1.0 / temperature))
.collect();
let total: f32 = weights.iter().sum();
let mut target = random.clamp(0.0, 0.999_999) * total;
for ((m, _), w) in moves.iter().zip(&weights) {
if target < *w {
return Some(*m);
}
target -= w;
}
moves.last().map(|(m, _)| *m)
}
/// The position after `m`, for building the history.
pub fn after(pos: &Chess, m: Move) -> Chess {
let mut p = pos.clone();
p.play_unchecked(m);
p
}