From e33c4f3044e19254c094cee82e791109f818f5e8 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 01:05:49 +0300 Subject: [PATCH] =?UTF-8?q?mobile-api:=20MaiaPlayer=20=E2=80=94=20the=20sm?= =?UTF-8?q?all=20model's=20move=20at=20a=20strength,=20by=20the=20shared?= =?UTF-8?q?=20tables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/mobile-api/Cargo.toml | 1 + crates/mobile-api/src/lib.rs | 2 + crates/mobile-api/src/play.rs | 96 +++++++++++++++++++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 crates/mobile-api/src/play.rs diff --git a/Cargo.lock b/Cargo.lock index 2ea2b83..11ef8cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2466,6 +2466,7 @@ dependencies = [ "chess-core", "chess-import", "game-review", + "maia", "online-games", "releases", "shakmaty", diff --git a/crates/mobile-api/Cargo.toml b/crates/mobile-api/Cargo.toml index f3c5f89..85df13f 100644 --- a/crates/mobile-api/Cargo.toml +++ b/crates/mobile-api/Cargo.toml @@ -25,6 +25,7 @@ bindgen = ["uniffi/cli"] chess-core.workspace = true chess-import.workspace = true game-review.workspace = true +maia.workspace = true online-games.workspace = true releases.workspace = true shakmaty.workspace = true diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index bc52298..1eecdcc 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -14,6 +14,7 @@ use shakmaty::Position; mod engine; mod online; +mod play; mod review; mod session; mod train; @@ -24,6 +25,7 @@ pub use online::{ AccountLookup, DownloadState, OnlineAccount, OnlineDatabase, OnlineDownload, OnlineFailure, OnlineProblem, OnlineTarget, Site, }; +pub use play::{MaiaPlayer, maia_range}; pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview}; pub use session::{Edited, GameSession, own_create, own_remove, own_save}; pub use train::{TrainState, TrainStats, TrainVerdict, Trainer, trainer_set_file}; diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs new file mode 100644 index 0000000..28beaa9 --- /dev/null +++ b/crates/mobile-api/src/play.rs @@ -0,0 +1,96 @@ +//! A game against Maia on the phone (docs/design/android-play.md ยง31): the small model +//! (5M) chooses her moves at a strength on the Lichess blitz scale, by the same tables +//! and rule as on the desktop (`maia::strength`). No clocks on the phone. + +use std::sync::Arc; + +use maia::strength::{Model, choose, rating_input, temperature}; +use shakmaty::{CastlingMode, Chess}; + +use crate::ApiError; +use crate::session::GameSession; + +/// The weakest and strongest Maia on the phone (the small model's measured range). +pub const PHONE_MIN: u32 = 1100; +pub const PHONE_MAX: u32 = maia::strength::SMALL_MAX; + +/// The strengths the phone offers: (weakest, strongest). +#[uniffi::export] +pub fn maia_range() -> Vec { + vec![PHONE_MIN, PHONE_MAX] +} + +/// Maia, loaded once for a game. +#[derive(uniffi::Object)] +pub struct MaiaPlayer { + maia: maia::Maia, +} + +#[uniffi::export] +impl MaiaPlayer { + /// Reads the weights (`maia3-5m.pt`). + #[uniffi::constructor] + pub fn load(path: String) -> Result, ApiError> { + let maia = + maia::Maia::load(std::path::Path::new(&path)).map_err(|e| ApiError::Corrupt { + detail: e.to_string(), + })?; + Ok(Arc::new(MaiaPlayer { maia })) + } + + /// Maia's move (UCI) in the position at place `at` of the game, playing at + /// `strength` against a player rated `opponent` (her own strength when unknown). + /// `random` is in [0, 1). None when the game is over there. + pub fn choose( + &self, + game: Arc, + at: u32, + strength: u32, + opponent: Option, + random: f32, + ) -> Option { + let history: Vec = game.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + Some( + g.path(id) + .iter() + .filter_map(|n| g.position(*n).cloned()) + .collect(), + ) + })?; + let strength = strength.clamp(PHONE_MIN, PHONE_MAX); + let p = self.maia.predict( + &history, + rating_input(Model::Small, strength), + opponent.unwrap_or(strength), + ); + choose(&p, temperature(Model::Small, strength), random) + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Needs the weights: `MAIA_WEIGHTS=/path/maia3-5m.pt cargo test -p mobile-api -- --ignored`. + #[test] + #[ignore = "needs the weights file (MAIA_WEIGHTS)"] + fn maia_answers_with_a_legal_move() { + let path = std::env::var("MAIA_WEIGHTS").expect("MAIA_WEIGHTS"); + let m = MaiaPlayer::load(path).unwrap(); + let s = GameSession::from_pgn("1. e4 *".into()).unwrap(); + let e4 = s.data().nodes.iter().find(|n| n.san == "e4").unwrap().id; + let uci = m.choose(s.clone(), e4, 1500, None, 0.3).unwrap(); + assert!(s.legal_moves(e4).contains(&uci), "{uci}"); + let mated = GameSession::from_pgn("1. f3 e5 2. g4 Qh4# *".into()).unwrap(); + let end = mated + .data() + .nodes + .iter() + .find(|n| n.san == "Qh4#") + .unwrap() + .id; + assert!(m.choose(mated, end, 1500, None, 0.3).is_none()); + } +}