Spaces:
Sleeping
Sleeping
Download rust/ct-bot/src/main.rs from tchauffi/ChessTransformer: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/spaces/tchauffi/ChessTransformer/resolve/main/rust/ct-bot/src/main.rs
- Command line
-
hf download hf://spaces/tchauffi/ChessTransformer/rust/ct-bot/src/main.rs
-
curl -L -o main.rs https://huggingface.co/spaces/tchauffi/ChessTransformer/resolve/main/rust/ct-bot/src/main.rs
9.94 kB
| //! ct-bot: standalone Rust bot for the ChessTransformer Pos2MoveV2 model. | |
| //! | |
| //! Subcommands: `uci` (engine for gauntlets/cutechess), `lichess` (Bot API | |
| //! client), `bench` (NN + search throughput), `eval` (single-position parity | |
| //! probe used by scripts/check_onnx_parity.py). | |
| mod bench; | |
| mod lichess; | |
| mod nn; | |
| mod search; | |
| mod serve; | |
| mod timeman; | |
| mod uci; | |
| use std::path::PathBuf; | |
| use std::sync::Arc; | |
| use anyhow::{Context, Result}; | |
| use clap::{Args, Parser, Subcommand}; | |
| use shakmaty::Chess; | |
| use shakmaty_syzygy::Tablebase; | |
| const DEFAULT_MODEL: &str = "data/models/pos2move_v2.1/model.int8.onnx"; | |
| struct Cli { | |
| cmd: Cmd, | |
| } | |
| struct ModelArgs { | |
| /// Path to the ONNX model | |
| model: PathBuf, | |
| /// Intra-op threads for ONNX Runtime (0 = auto) | |
| threads: usize, | |
| /// Inference device | |
| )] | |
| device: String, | |
| } | |
| impl ModelArgs { | |
| fn evaluator(&self) -> Result<nn::OnnxEvaluator> { | |
| nn::OnnxEvaluator::new(&self.model, self.threads, self.device == "cuda") | |
| } | |
| } | |
| /// Load Syzygy tables from a ':'-separated list of directories (the UCI | |
| /// `SyzygyPath` convention). Empty means none. | |
| pub fn load_syzygy(paths: &str) -> Result<Option<Arc<Tablebase<Chess>>>> { | |
| let dirs: Vec<&str> = paths.split(':').filter(|d| !d.trim().is_empty()).collect(); | |
| if dirs.is_empty() { | |
| return Ok(None); | |
| } | |
| let mut tb = Tablebase::new(); | |
| let mut n = 0; | |
| for dir in &dirs { | |
| n += tb.add_directory(dir).with_context(|| format!("syzygy path {dir}"))?; | |
| } | |
| log::info!("syzygy: {n} table files from {paths} (up to {} pieces)", tb.max_pieces()); | |
| Ok(Some(Arc::new(tb))) | |
| } | |
| enum Cmd { | |
| /// UCI engine mode | |
| Uci(UciArgs), | |
| /// Lichess bot client | |
| Lichess(LichessArgs), | |
| /// NN + search throughput benchmark | |
| Bench(BenchArgs), | |
| /// HTTP backend for the web frontend (replaces backend/api.py) | |
| Serve(ServeArgs), | |
| /// Evaluate one FEN; print value + per-move priors as JSON (parity probe) | |
| Eval(EvalArgs), | |
| /// Search one FEN from scratch at several budgets; print the top root | |
| /// moves (visits, Q, prior) per budget (search-behavior probe) | |
| Probe(ProbeArgs), | |
| } | |
| struct UciArgs { | |
| model: ModelArgs, | |
| /// Default simulations per move (when `go` has no nodes/time limits) | |
| sims: u32, | |
| /// Leaves per NN wave | |
| sim_batch: usize, | |
| c_puct: f64, | |
| fpu: f64, | |
| prior_temp: f32, | |
| /// Seed for the clock-mode sims/sec estimate (refined after every move) | |
| initial_sims_per_sec: f64, | |
| /// Syzygy tablebase directories, ':'-separated (UCI option SyzygyPath) | |
| syzygy_path: String, | |
| } | |
| struct LichessArgs { | |
| model: ModelArgs, | |
| /// API token of the BOT account (falls back to $LICHESS_BOT_TOKEN) | |
| token: String, | |
| /// Accept rated challenges (casual is always accepted) | |
| allow_rated: bool, | |
| /// Accepted challenge speeds | |
| )] | |
| speeds: Vec<String>, | |
| /// Maximum concurrent games | |
| max_games: usize, | |
| /// Leaves per NN wave | |
| sim_batch: usize, | |
| /// Opening variety: sample moves ∝ visits^(1/temp) for the first | |
| /// `--move-temp-plies` half-moves (0.0 = deterministic argmax) | |
| move_temp: f64, | |
| move_temp_plies: u32, | |
| /// Seed for the sims/sec estimate (refined after every move) | |
| initial_sims_per_sec: f64, | |
| /// Lichess server (override for testing) | |
| base_url: String, | |
| /// Syzygy tablebase directories, ':'-separated | |
| syzygy_path: String, | |
| } | |
| struct BenchArgs { | |
| model: ModelArgs, | |
| /// Simulation budgets for the search benchmark | |
| )] | |
| sims: Vec<u32>, | |
| /// Leaves per NN wave | |
| sim_batch: usize, | |
| } | |
| struct ServeArgs { | |
| model: ModelArgs, | |
| port: u16, | |
| /// MCTS simulations per /api/move request | |
| sims: u32, | |
| /// Leaves per NN wave | |
| sim_batch: usize, | |
| /// Reported in /api/health for the frontend display | |
| approx_elo: u32, | |
| /// Syzygy tablebase directories, ':'-separated | |
| syzygy_path: String, | |
| /// Also serve the web frontend's static build (Next.js `out/`) from this | |
| /// directory, so one process hosts the whole demo (Hugging Face Space). | |
| static_dir: Option<std::path::PathBuf>, | |
| } | |
| struct EvalArgs { | |
| model: ModelArgs, | |
| fen: String, | |
| } | |
| struct ProbeArgs { | |
| model: ModelArgs, | |
| fen: String, | |
| )] | |
| sims: Vec<u32>, | |
| sim_batch: usize, | |
| c_puct: f64, | |
| fpu: f64, | |
| prior_temp: f32, | |
| /// Root moves to print per budget | |
| top: usize, | |
| /// Syzygy tablebase directories, ':'-separated | |
| syzygy_path: String, | |
| } | |
| fn cmd_probe(args: &ProbeArgs) -> Result<()> { | |
| use shakmaty::{fen::Fen, CastlingMode, Chess}; | |
| use std::sync::atomic::AtomicBool; | |
| let fen: Fen = args.fen.parse()?; | |
| let pos: Chess = fen.into_position(CastlingMode::Standard)?; | |
| let params = search::SearchParams { | |
| c_puct: args.c_puct, | |
| fpu: args.fpu, | |
| prior_temp: args.prior_temp, | |
| sim_batch: args.sim_batch, | |
| syzygy: load_syzygy(&args.syzygy_path)?, | |
| ..search::SearchParams::default() | |
| }; | |
| let mut s = search::Search::new(args.model.evaluator()?, params); | |
| for &sims in &args.sims { | |
| s.new_game(); | |
| s.set_position(pos.clone(), &[]); | |
| let r = s.go(sims, None, &AtomicBool::new(false))?; | |
| println!( | |
| "sims {:>6} best {} value {:+.3} tb hits {} ({:.1}s)", | |
| r.sims, | |
| r.best.to_uci(CastlingMode::Standard), | |
| r.value, | |
| r.tb_hits, | |
| r.elapsed.as_secs_f64() | |
| ); | |
| let pv: Vec<String> = s | |
| .pv(16) | |
| .iter() | |
| .map(|(m, n, q)| format!("{}({n},{q:+.2})", m.to_uci(CastlingMode::Standard))) | |
| .collect(); | |
| println!(" pv {}", pv.join(" ")); | |
| for (m, n, q, p) in s.root_stats().into_iter().take(args.top) { | |
| println!( | |
| " {:<6} n {:>6} q {:+.3} prior {:.3}", | |
| m.to_uci(CastlingMode::Standard).to_string(), | |
| n, | |
| q, | |
| p | |
| ); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| fn cmd_eval(args: &EvalArgs) -> Result<()> { | |
| use chess_core::encoding::{action_plane, encode_position, move_coords, NUM_PLANES}; | |
| use nn::Evaluator; | |
| use shakmaty::{fen::Fen, CastlingMode, Chess, Position}; | |
| let fen: Fen = args.fen.parse()?; | |
| let pos: Chess = fen.into_position(CastlingMode::Standard)?; | |
| let (tokens, player, castling, ep) = encode_position(&pos); | |
| let mut eval = args.model.evaluator()?; | |
| let out = eval | |
| .eval_batch(&[nn::EvalRequest { tokens, player, castling, ep, legal: Vec::new() }])? | |
| .remove(0); | |
| let moves = pos.legal_moves(); | |
| let mut scores: Vec<f32> = moves | |
| .iter() | |
| .map(|m| { | |
| let (f, t, p) = move_coords(m); | |
| out.logits[f * NUM_PLANES + action_plane(f, t, p)] | |
| }) | |
| .collect(); | |
| chess_core::tree::softmax_priors(&mut scores, 1.0); | |
| let moves_json: Vec<serde_json::Value> = moves | |
| .iter() | |
| .zip(scores.iter()) | |
| .map(|(m, p)| { | |
| serde_json::json!({ | |
| "uci": m.to_uci(CastlingMode::Standard).to_string(), | |
| "prior": p, | |
| }) | |
| }) | |
| .collect(); | |
| println!( | |
| "{}", | |
| serde_json::json!({ "value": out.value, "moves": moves_json }) | |
| ); | |
| Ok(()) | |
| } | |
| fn main() -> Result<()> { | |
| env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init(); | |
| let cli = Cli::parse(); | |
| match &cli.cmd { | |
| Cmd::Eval(args) => cmd_eval(args), | |
| Cmd::Probe(args) => cmd_probe(args), | |
| Cmd::Bench(args) => bench::run(args), | |
| Cmd::Uci(args) => uci::run(args), | |
| Cmd::Lichess(args) => lichess::run(args), | |
| Cmd::Serve(args) => serve::run(args), | |
| } | |
| } | |