diff --git a/archbench/pro-decisions-1/puzzles.json b/archbench/pro-decisions-1/puzzles.json new file mode 100644 index 0000000..3812e52 --- /dev/null +++ b/archbench/pro-decisions-1/puzzles.json @@ -0,0 +1,26 @@ +{ + "suite": "pro-decisions@1", + "created": "2026-11-24", + "about": "Curated competitive MTG tournament decision suite split across 4 categories (aggro_race, control_stack, combat_math, tempo_open_mana) as an uncheatable external benchmark.", + "puzzles": [ + {"name": "aggro-prowess-burn-order", "category": "aggro_race", "about": "Sequence Play with Fire + Monstrous Rage on Swiftspear to trample for exact 7.", "seats": [{"life": 10, "battlefield": [{"name": "Mountain", "count": 2}, "Monastery Swiftspear"], "hand": ["Play with Fire", "Monstrous Rage"]}, {"life": 7, "battlefield": ["Plains", "Savannah Lions"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "aggro-two-turn-burn-over-angel", "category": "aggro_race", "about": "Ignore Serra Angel and send both Lightning Strikes face across 2 turns (win at 1 life).", "seats": [{"life": 5, "battlefield": [{"name": "Mountain", "count": 2}], "hand": ["Lightning Strike", "Lightning Strike"]}, {"life": 6, "battlefield": ["Plains", "Serra Angel"]}], "goal": {"kind": "win", "turns": 2}}, + {"name": "aggro-animate-mutavault-clock", "category": "aggro_race", "about": "Animate Mutavault + Monstrous Rage + Lions for Turn-0 lethal through Llanowar Elves.", "seats": [{"life": 10, "battlefield": ["Mutavault", {"name": "Mountain", "count": 2}, "Savannah Lions"], "hand": ["Monstrous Rage"]}, {"life": 5, "battlefield": ["Forest", "Llanowar Elves"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "aggro-instant-helix-race", "category": "aggro_race", "about": "Win on opponent's turn with Lightning Helix before opponent's Lightning Strike resolves.", "active": 1, "seats": [{"life": 2, "battlefield": ["Plains", "Mountain"], "hand": ["Lightning Helix"]}, {"life": 3, "battlefield": [{"name": "Mountain", "count": 2}], "hand": ["Lightning Strike"]}], "goal": {"kind": "win", "turns": 0}}, + + {"name": "control-bait-spell-pierce", "category": "control_stack", "about": "Pay/bait Spell Pierce with 4 Mountains so lethal Lightning Strike resolves.", "seats": [{"life": 5, "battlefield": [{"name": "Mountain", "count": 4}], "hand": ["Lightning Strike", "Play with Fire"]}, {"life": 3, "battlefield": ["Island"], "hand": ["Spell Pierce"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "control-counter-war-lethal", "category": "control_stack", "about": "Cast Lightning Strike and Negate opponent's Negate to win on the stack.", "seats": [{"life": 3, "battlefield": [{"name": "Mountain", "count": 2}, {"name": "Island", "count": 2}], "hand": ["Lightning Strike", "Negate"]}, {"life": 3, "battlefield": [{"name": "Island", "count": 2}], "hand": ["Negate"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "control-sunfall-over-wrath", "category": "control_stack", "about": "Choose Sunfall over Day of Judgment into opponent's open Heroic Intervention.", "seats": [{"life": 10, "battlefield": [{"name": "Plains", "count": 5}], "hand": ["Day of Judgment", "Sunfall"]}, {"life": 20, "battlefield": [{"name": "Forest", "count": 2}, "Serra Angel"], "hand": ["Heroic Intervention"]}], "goal": {"kind": "remove", "card": "Serra Angel", "turns": 0}}, + {"name": "control-nash-pass-burn-war", "category": "control_stack", "about": "Do not cast Lightning Strike first into opponent's Strike + Negate.", "seats": [{"life": 3, "battlefield": [{"name": "Mountain", "count": 2}, {"name": "Island", "count": 2}], "hand": ["Lightning Strike", "Negate"]}, {"life": 3, "battlefield": [{"name": "Mountain", "count": 2}, {"name": "Island", "count": 2}], "hand": ["Lightning Strike", "Negate"]}], "goal": {"kind": "survive", "turns": 0}}, + + {"name": "combat-growth-before-ram-through", "category": "combat_math", "about": "Giant Growth Gnarlback Rhino before Ram Through for exact trample excess lethal.", "seats": [{"life": 10, "battlefield": [{"name": "Forest", "count": 3}, "Gnarlback Rhino"], "hand": ["Giant Growth", "Ram Through"]}, {"life": 5, "battlefield": ["Forest", "Llanowar Elves"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "combat-double-block-lifelink", "category": "combat_math", "about": "Block Rhino with Nighthawk (lifelink) and Lions with Typhoid Rats to survive at 5 life.", "active": 1, "seats": [{"life": 5, "battlefield": ["Swamp", "Vampire Nighthawk", "Typhoid Rats"]}, {"life": 20, "battlefield": ["Forest", "Plains", "Gnarlback Rhino", "Savannah Lions"]}], "goal": {"kind": "survive", "turns": 0}}, + {"name": "combat-pump-unblocked-attacker", "category": "combat_math", "about": "Attack with two Lions and cast Giant Growth on the unblocked attacker after blocks.", "seats": [{"life": 10, "battlefield": ["Forest", "Savannah Lions", "Savannah Lions"], "hand": ["Giant Growth"]}, {"life": 5, "battlefield": ["Forest", "Llanowar Elves"]}], "goal": {"kind": "win", "turns": 0}}, + {"name": "combat-coil-nighthawk-precombat", "category": "combat_math", "about": "Lava Coil Nighthawk before attacking with Serra Angel.", "seats": [{"life": 10, "battlefield": [{"name": "Mountain", "count": 2}, "Serra Angel"], "hand": ["Lava Coil"]}, {"life": 4, "battlefield": ["Swamp", "Vampire Nighthawk"]}], "goal": {"kind": "win", "turns": 0}}, + + {"name": "tempo-hold-negate-not-drake", "category": "tempo_open_mana", "about": "Hold up 2 Islands for Negate instead of tapping out for Wind Drake at 3 life.", "seats": [{"life": 3, "battlefield": [{"name": "Island", "count": 3}, "Wind Drake"], "hand": ["Wind Drake", "Negate"]}, {"life": 20, "battlefield": [{"name": "Mountain", "count": 2}], "hand": ["Lightning Strike"]}], "goal": {"kind": "survive", "turns": 1}}, + {"name": "tempo-hold-intervention-not-rhino", "category": "tempo_open_mana", "about": "Hold up Heroic Intervention instead of tapping out for Gnarlback Rhino into Day of Judgment.", "seats": [{"life": 10, "battlefield": [{"name": "Forest", "count": 4}, "Serra Angel"], "hand": ["Gnarlback Rhino", "Heroic Intervention"]}, {"life": 20, "battlefield": [{"name": "Plains", "count": 4}], "hand": ["Day of Judgment"]}], "goal": {"kind": "keep", "card": "Serra Angel", "turns": 1}}, + {"name": "tempo-murder-not-cut-down-into-growth", "category": "tempo_open_mana", "about": "Cast Murder instead of Cut Down into opponent's open Forest + Giant Growth.", "seats": [{"life": 10, "battlefield": [{"name": "Swamp", "count": 3}], "hand": ["Cut Down", "Murder"]}, {"life": 20, "battlefield": ["Forest", "Vampire Nighthawk"], "hand": ["Giant Growth"]}], "goal": {"kind": "remove", "card": "Vampire Nighthawk", "turns": 0}}, + {"name": "tempo-hold-pierce-for-wrath", "category": "tempo_open_mana", "about": "Hold up 1 Island for Spell Pierce against Day of Judgment instead of tapping out for Wind Drake.", "seats": [{"life": 10, "battlefield": [{"name": "Island", "count": 3}, "Serra Angel"], "hand": ["Wind Drake", "Spell Pierce"]}, {"life": 20, "battlefield": [{"name": "Plains", "count": 4}], "hand": ["Day of Judgment"]}], "goal": {"kind": "keep", "card": "Serra Angel", "turns": 1}} + ] +} diff --git a/archbench/tactics-3/puzzles.json b/archbench/tactics-3/puzzles.json index 20f0d4d..f385fcc 100644 --- a/archbench/tactics-3/puzzles.json +++ b/archbench/tactics-3/puzzles.json @@ -37,7 +37,6 @@ } ], "hand": [ - "Lightning Strike", "Negate" ] } @@ -611,4 +610,4 @@ } } ] -} +} \ No newline at end of file diff --git a/archbench/tactics-4/puzzles.json b/archbench/tactics-4/puzzles.json new file mode 100644 index 0000000..4178147 --- /dev/null +++ b/archbench/tactics-4/puzzles.json @@ -0,0 +1,156 @@ +{ + "suite": "tactics@4", + "created": "2026-11-24", + "about": "Phase 3 tactical frontiers: Nash burn standoffs, double-counter stack wars, manland+pump math, unblocked-attacker tricks, exile vs indestructible, open-mana tempo, and lifelink/sheoldred timing.", + "puzzles": [ + { + "name": "nash-burn-standoff-dont-cast-first", + "about": "Both at 3 life with Lightning Strike + Negate. Casting first loses 0-3 to response Strike + Negate; passing survives.", + "seats": [ + {"life": 3, "battlefield": [{"name": "Mountain", "count": 2}, {"name": "Island", "count": 2}], "hand": ["Lightning Strike", "Negate"]}, + {"life": 3, "battlefield": [{"name": "Mountain", "count": 2}, {"name": "Island", "count": 2}], "hand": ["Lightning Strike", "Negate"]} + ], + "goal": {"kind": "survive", "turns": 0} + }, + { + "name": "double-counter-pay-pierce-negate", + "about": "Opp at 3 with Island x3, Spell Pierce, Negate. With 6 lands, cast Lightning Strike, pay Spell Pierce, and Negate opp's Negate to win.", + "seats": [ + {"life": 5, "battlefield": [{"name": "Mountain", "count": 3}, {"name": "Island", "count": 3}], "hand": ["Lightning Strike", "Negate"]}, + {"life": 3, "battlefield": [{"name": "Island", "count": 3}], "hand": ["Spell Pierce", "Negate"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "hold-spell-pierce-against-wrath", + "about": "Opp holds Day of Judgment on 4 Plains. Hold 1 Island for Spell Pierce instead of tapping out for Wind Drake so Serra Angel survives.", + "seats": [ + {"life": 10, "battlefield": [{"name": "Island", "count": 3}, "Serra Angel"], "hand": ["Wind Drake", "Spell Pierce"]}, + {"life": 20, "battlefield": [{"name": "Plains", "count": 4}], "hand": ["Day of Judgment"]} + ], + "goal": {"kind": "keep", "card": "Serra Angel", "turns": 1} + }, + { + "name": "exile-sunfall-beats-intervention-angel", + "about": "Opp has Serra Angel + 2 Forests + Heroic Intervention. Cast Sunfall (exile) instead of Day of Judgment (destroy) to remove Serra Angel.", + "seats": [ + {"life": 10, "battlefield": [{"name": "Plains", "count": 5}], "hand": ["Day of Judgment", "Sunfall"]}, + {"life": 20, "battlefield": [{"name": "Forest", "count": 2}, "Serra Angel"], "hand": ["Heroic Intervention"]} + ], + "goal": {"kind": "remove", "card": "Serra Angel", "turns": 0} + }, + { + "name": "mutavault-plus-growth-exact-5", + "about": "Opp at 5 on empty board. Animate Mutavault, attack, and cast Giant Growth for exact 5 lethal.", + "seats": [ + {"life": 10, "battlefield": ["Mutavault", {"name": "Forest", "count": 2}], "hand": ["Giant Growth"]}, + {"life": 5, "battlefield": ["Plains"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "pump-unblocked-lion-after-blocks", + "about": "Opp at 5 with Llanowar Elves. Attack with two Savannah Lions and cast Giant Growth on the UNBLOCKED one after blockers for exact 5.", + "seats": [ + {"life": 10, "battlefield": ["Forest", "Savannah Lions", "Savannah Lions"], "hand": ["Giant Growth"]}, + {"life": 5, "battlefield": ["Forest", "Llanowar Elves"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "kill-blocker-precombat-for-lethal", + "about": "Opp at 4 behind two Savannah Lions. Go for the Throat one Lions and attack with Serra Angel for exact 4 flying lethal? Wait: Angel flies; use Rhino + Lions vs Nighthawk + Lions.", + "seats": [ + {"life": 10, "battlefield": [{"name": "Swamp", "count": 2}, "Gnarlback Rhino"], "hand": ["Go for the Throat"]}, + {"life": 4, "battlefield": ["Swamp", "Vampire Nighthawk"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "prowess-double-burn-exact-8", + "about": "Opp at 8 on empty board. Swiftspear + Lightning Strike + Play with Fire = 3 + 2 + 3 (two prowess triggers) = exact 8 lethal.", + "seats": [ + {"life": 10, "battlefield": [{"name": "Mountain", "count": 3}, "Monastery Swiftspear"], "hand": ["Lightning Strike", "Play with Fire"]}, + {"life": 8, "battlefield": ["Plains"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "stabilize-helix-and-kill-angel", + "about": "At 3 life facing Serra Angel (4/4 flying). Kill Serra Angel with Go for the Throat and stay alive with Lightning Helix.", + "seats": [ + {"life": 3, "battlefield": [{"name": "Swamp", "count": 2}, "Mountain", "Plains"], "hand": ["Go for the Throat", "Lightning Helix"]}, + {"life": 12, "battlefield": ["Plains", "Serra Angel"]} + ], + "goal": {"kind": "survive", "turns": 2} + }, + { + "name": "chump-rhino-crackback-angel", + "about": "Opp turn, Seat 0 at 3 life vs opp at 4. Opp attacks with Gnarlback Rhino (4/4 trample). Block with Vampire Nighthawk (2/3 lifelink deathtouch) to survive and win next turn with Serra Angel.", + "active": 1, + "seats": [ + {"life": 3, "battlefield": ["Plains", "Vampire Nighthawk", "Serra Angel"]}, + {"life": 4, "battlefield": ["Forest", "Gnarlback Rhino"]} + ], + "goal": {"kind": "win", "turns": 1} + }, + { + "name": "two-turn-glorybringer-exert-angel", + "about": "Seat 0 at 4 life, opp at 7 with Serra Angel. Exert Glorybringer to kill Serra Angel (4 dmg + 4 to opp -> 3), survive and win with Lightning Strike.", + "seats": [ + {"life": 4, "battlefield": [{"name": "Mountain", "count": 2}, "Glorybringer"], "hand": ["Lightning Strike"]}, + {"life": 7, "battlefield": ["Plains", "Serra Angel"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "kill-sheoldred-on-opp-turn-before-draw", + "about": "Opp turn, Seat 0 at 2 life facing Sheoldred. Must Murder Sheoldred before Seat 0's draw step triggers 2 life loss.", + "active": 1, + "seats": [ + {"life": 2, "battlefield": [{"name": "Swamp", "count": 3}], "hand": ["Murder"]}, + {"life": 15, "battlefield": [{"name": "Swamp", "count": 4}, "Sheoldred, the Apocalypse"]} + ], + "goal": {"kind": "survive", "turns": 1} + }, + { + "name": "fog-alpha-strike-win-next-turn", + "about": "Opp turn, Seat 0 at 3 facing Serra Angel + Savannah Lions (opp at 5). Fog the attack, then win next turn with Glorybringer + Play with Fire.", + "active": 1, + "seats": [ + {"life": 3, "battlefield": ["Forest", "Mountain", "Glorybringer"], "hand": ["Fog", "Play with Fire"]}, + {"life": 5, "battlefield": ["Plains", "Serra Angel", "Savannah Lions"]} + ], + "goal": {"kind": "win", "turns": 1} + }, + { + "name": "lethal-strike-before-nighthawk-lifelink", + "about": "Opp turn, Seat 0 at 2 life, opp at 3 with Vampire Nighthawk attacking. Cast Lightning Strike at opp face before lifelink damage resolves.", + "active": 1, + "seats": [ + {"life": 2, "battlefield": [{"name": "Mountain", "count": 2}], "hand": ["Lightning Strike"]}, + {"life": 3, "battlefield": ["Swamp", "Vampire Nighthawk"]} + ], + "goal": {"kind": "win", "turns": 0} + }, + { + "name": "negate-lethal-burn-at-3", + "about": "Opp turn, Seat 0 at 3 life, opp holds Lightning Strike. Hold/cast Negate to survive.", + "active": 1, + "seats": [ + {"life": 3, "battlefield": [{"name": "Island", "count": 2}], "hand": ["Negate"]}, + {"life": 10, "battlefield": [{"name": "Mountain", "count": 2}], "hand": ["Lightning Strike"]} + ], + "goal": {"kind": "survive", "turns": 0} + }, + { + "name": "mutavault-double-strike-burn-exact-7", + "about": "Opp at 7 on empty board. Animate Mutavault (2) + attack with Lions (2) + Lightning Strike (3) = exact 7 lethal.", + "seats": [ + {"life": 10, "battlefield": ["Mutavault", {"name": "Mountain", "count": 3}, "Savannah Lions"], "hand": ["Lightning Strike"]}, + {"life": 7, "battlefield": ["Plains"]} + ], + "goal": {"kind": "win", "turns": 0} + } + ] +} diff --git a/rust/crates/playmat-ai/src/decision.rs b/rust/crates/playmat-ai/src/decision.rs index df5392c..47b3296 100644 --- a/rust/crates/playmat-ai/src/decision.rs +++ b/rust/crates/playmat-ai/src/decision.rs @@ -1,632 +1,640 @@ -//! One decision at a time: the interface every decider of the AI's seat answers through (docs/rust/Ai.md). -//! -//! The `Table` asks its seat's `DecisionPolicy` each question that has two or more answers worth trying. The policy -//! gets the game, the question, the quick answer, the candidates and a `Root` to play candidates out on copies; it -//! answers with one of the candidates (or anything the question accepts), or `None` to let the quick answer stand. -//! Shipped policies: `Playouts` (the default search), `Mcts`, `Quick` and `Random`. A Jev, LLM or ONNX decider is -//! another implementation, set on a table with `Table::set_policy`. - -use crate::eval; -use crate::policy::{Policy, Repeats}; -use crate::search::{candidates, Config}; -use playmat_engine::decide::{Answer, Decider, Query}; -use playmat_engine::rng::JavaRandom; -use playmat_engine::rules; -use playmat_engine::state::{Game, ObjId, Seat, Zone}; -use std::str::FromStr; -use std::sync::Arc; - -/// Which `DecisionPolicy` a seat's `Config` builds (`PLAYMAT_AI_POLICY`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum PolicyKind { - /// each candidate played once to the end of the turn, the best end of turn kept (`search::Playouts`) - #[default] - Playouts, - /// Monte Carlo tree search at the root, playouts on shuffled copies in parallel threads (`Mcts`) - Mcts, - /// the quick answers alone, no search - Quick, - /// a random answer among the candidates (Archbench's anchor) - Random, - /// the trained network's policy alone (`selfplay::NetPolicy`, #390 Track B) - Net, - /// the network's policy improved by playouts on samples scored by its value (`selfplay::NetSearch`) - NetSearch, - /// the network's policy searched by Gumbel sequential halving (`selfplay::Gumbel`) - Gumbel, - /// an open-loop information-set tree search over the network's policy (`tree::Ismcts`) - Ismcts, -} - -impl PolicyKind { - pub fn name(self) -> &'static str { - match self { - PolicyKind::Playouts => "playouts", - PolicyKind::Mcts => "mcts", - PolicyKind::Quick => "quick", - PolicyKind::Random => "random", - PolicyKind::Net => "net", - PolicyKind::NetSearch => "netsearch", - PolicyKind::Gumbel => "gumbel", - PolicyKind::Ismcts => "ismcts", - } - } - - /// The setting `PLAYMAT_AI_POLICY`, `playouts` when unset or unknown - pub fn from_env() -> PolicyKind { - std::env::var("PLAYMAT_AI_POLICY").ok().and_then(|v| v.parse().ok()).unwrap_or_default() - } - - pub fn build(self, seat: Seat) -> Box { - match self { - PolicyKind::Playouts => Box::new(crate::search::Playouts), - PolicyKind::Mcts => Box::new(Mcts), - PolicyKind::Quick => Box::new(Quick), - PolicyKind::Random => Box::new(Random::new(0x5eed_0000 + seat as u64)), - PolicyKind::Net => Box::new(crate::selfplay::NetPolicy::new(0x6e65_7400 + seat as u64)), - PolicyKind::NetSearch => Box::new(crate::selfplay::NetSearch::new(0x6e73_0000 + seat as u64)), - PolicyKind::Gumbel => Box::new(crate::selfplay::Gumbel::new(0x6762_0000 + seat as u64)), - PolicyKind::Ismcts => Box::new(crate::tree::Ismcts::new(0x6973_0000 + seat as u64)), - } - } -} - -impl FromStr for PolicyKind { - type Err = String; - fn from_str(s: &str) -> Result { - match s.trim().to_ascii_lowercase().as_str() { - "" | "playouts" | "search" | "default" => Ok(PolicyKind::Playouts), - "mcts" => Ok(PolicyKind::Mcts), - "quick" => Ok(PolicyKind::Quick), - "random" => Ok(PolicyKind::Random), - "net" => Ok(PolicyKind::Net), - "netsearch" => Ok(PolicyKind::NetSearch), - "gumbel" => Ok(PolicyKind::Gumbel), - "ismcts" => Ok(PolicyKind::Ismcts), - other => Err(format!("unknown AI policy {other:?} (playouts, mcts, quick, random, net, netsearch)")), - } - } -} - -/// One question for the AI's seat -pub struct Decision<'a> { - pub game: &'a Game, - pub seat: Seat, - pub query: &'a Query, - /// what the quick answers say (`policy::Policy`), always the first candidate - pub quick: &'a Answer, - /// the answers worth trying, at most `config.width` - pub candidates: &'a [Answer], - pub config: &'a Config, - /// where candidates can be played out; `None` before the game's first priority question - pub root: Option<&'a Root>, -} - -/// A policy's answer and the search nodes (answers in playouts) it spent -pub struct Choice { - pub answer: Answer, - pub nodes: u64, -} - -/// Answers single decisions for one seat. -pub trait DecisionPolicy: Send { - fn name(&self) -> &str; - /// The answer, or `None` for the quick one - fn decide(&mut self, d: &Decision) -> Option; - /// The chances the policy gave each candidate at its last decision (a network's policy, or a search's improved - /// one), when it has them: what self-play records (`selfplay::Recording`) - fn last_policy(&self) -> Option<&[f32]> { - None - } - /// The search's estimated win probability (0..1) at its last decision, when available (`qval.f16` target) - fn last_value(&self) -> Option { - None - } -} - -/// The game at the last priority question and the answers since: what a copy replays to reach the question. -#[derive(Clone)] -pub struct Root { - pub snapshot: Game, - pub since: Vec, - /// what the deciding seat can't see, for samples of the game it might be (`Root::sample`); `None` plays the - /// real game - pub hidden: Option, - /// the playouts' quick answers (`Config::playout`) - pub playout: u8, - /// a network that answers the playouts' questions in place of the quick answers (`Config::rollout`) - pub rollout: Option>, -} - -/// What a seat has seen of the game: objects it saw in a public zone or that were shown to it. Its own hand it -/// always knows; the order of any library and the cards of the opponent's hand it hasn't seen, it doesn't. -#[derive(Clone, Debug)] -pub struct Hidden { - pub seat: Seat, - /// by object id - pub seen: Arc>, -} - -impl Hidden { - pub fn new(seat: Seat) -> Hidden { - Hidden { seat, seen: Arc::new(Vec::new()) } - } - - /// Notes what the seat sees in `game` now: every object in a public zone or on the stack, cards revealed, and - /// cards the seat looked at - pub fn observe(&mut self, game: &Game) { - let seen = Arc::make_mut(&mut self.seen); - if seen.len() < game.objs.len() { - seen.resize(game.objs.len(), false); - } - let mut mark = |id: ObjId| { - if let Some(s) = seen.get_mut(id.0 as usize) { - *s = true; - } - }; - for id in game.battlefield.iter().chain(game.exile.iter()).chain(game.command.iter()) { - mark(*id); - } - for p in game.players.iter() { - for id in &p.graveyard { - mark(*id); - } - } - for item in game.stack.iter() { - mark(item.card); - } - for r in &game.revealed { - for (id, _) in &r.cards { - mark(*id); - } - } - for l in game.looked_at.iter().filter(|l| l.viewer == self.seat) { - for id in &l.cards { - mark(*id); - } - } - } - - /// Whether the seat has seen object `id` - pub fn seat_saw(&self, id: ObjId) -> bool { - self.seen(id) - } - - fn seen(&self, id: ObjId) -> bool { - self.seen.get(id.0 as usize).copied().unwrap_or(false) - } -} - -/// A played-out copy -pub struct Outcome { - pub game: Game, - /// answers given after the candidate (search nodes) - pub nodes: u64, -} - -impl Root { - /// The root's game as the deciding seat might find it: the opponent's hand cards it hasn't seen and every - /// library's order drawn at random from what it can't see, and a new random number generator. Cards the answers - /// since the snapshot name stay where they are, so the copy can replay them. Without `hidden`, the real game. - pub fn sample(&self, seed: u64) -> Game { - let mut g = self.snapshot.clone(); - let Some(h) = &self.hidden else { return g }; - let mut keep: Vec = Vec::new(); - for a in &self.since { - if let Answer::Obj(id) | Answer::Ability(id, _) = a { - keep.push(*id); - } - } - let mut rng = JavaRandom::new((seed ^ 0x5851_f42d_4c95_7f2d) as i64); - let looked: Vec = - g.looked_at.iter().filter(|l| l.viewer == h.seat).flat_map(|l| l.cards.iter().copied()).collect(); - for seat in 0..g.players.len() { - let mine = seat == h.seat; - let fixed_in_hand = |id: &ObjId| mine || h.seen(*id) || keep.contains(id); - let fixed_in_library = |id: &ObjId| keep.contains(id) || looked.contains(id); - let hand = g.player(seat).hand.clone(); - let library = g.player(seat).library.clone(); - let mut pool: Vec = hand - .iter() - .filter(|id| !fixed_in_hand(id)) - .chain(library.iter().filter(|id| !fixed_in_library(id))) - .copied() - .collect(); - if pool.len() < 2 { - continue; - } - rng.shuffle(&mut pool); - let mut next = pool.into_iter(); - let new_hand: Vec = - hand.iter().map(|id| if fixed_in_hand(id) { *id } else { next.next().unwrap() }).collect(); - let new_library: Vec = - library.iter().map(|id| if fixed_in_library(id) { *id } else { next.next().unwrap() }).collect(); - for id in &new_hand { - if g.obj(*id).zone != Zone::Hand { - g.obj_mut(*id).zone = Zone::Hand; - } - } - for id in &new_library { - if g.obj(*id).zone != Zone::Library { - g.obj_mut(*id).zone = Zone::Library; - } - } - let p = g.player_mut(seat); - p.hand = new_hand; - p.library = new_library; - } - g.rng = JavaRandom::new(seed.rotate_left(17) as i64); - g - } - - /// A sample of the game (`sample`) with `hidden`; without, the real game with every library shuffled and a new - /// random number generator - pub fn sample_or_shuffle(&self, seed: u64) -> Game { - if self.hidden.is_some() { - return self.sample(seed); - } - let mut g = self.snapshot.clone(); - let mut rng = JavaRandom::new(seed as i64); - for seat in 0..g.players.len() { - let mut library = g.player(seat).library.clone(); - rng.shuffle(&mut library); - g.player_mut(seat).library = library; - } - g.rng = JavaRandom::new(seed.rotate_left(17) as i64); - g - } - - /// Plays `candidate` on a copy until turn `stop_turn` starts or `cap` answers are given, both seats on the quick - /// answers. With `shuffle`, the copy is a sample (`sample`; without `hidden`, the libraries are shuffled) and one - /// answer in sixteen of the quick ones is a random candidate instead (MCTS). `Err` when the copy didn't reach - /// the question again. - pub fn play_out(&self, candidate: &Answer, cap: u64, stop_turn: u32, shuffle: Option) -> Result { - let mut g = match shuffle { - Some(seed) => self.sample_or_shuffle(seed), - None => self.snapshot.clone(), - }; - let mut script = self.since.clone(); - script.push(candidate.clone()); - let mut p = Playout::new(script, cap, stop_turn, shuffle, self.playout, self.rollout.clone()); - rules::play_from_priority_question(&mut g, &mut p, stop_turn); - if p.diverged { - Err(p.answers) - } else { - Ok(Outcome { game: g, nodes: p.answers }) - } - } - - /// Plays `game` (a `sample`, or the snapshot) from the question with `walk` answering where its tree reaches - /// (`tree::Ismcts`), then the playout's answers; gives the walk back for the backup - pub fn play_tree( - &self, - mut g: Game, - walk: crate::tree::Walk, - cap: u64, - stop_turn: u32, - ) -> (Result, crate::tree::Walk) { - let mut p = Playout::new(self.since.clone(), cap, stop_turn, None, self.playout, self.rollout.clone()); - p.walk = Some(Box::new(walk)); - rules::play_from_priority_question(&mut g, &mut p, stop_turn); - let walk = *p.walk.take().expect("the walk"); - let res = if p.diverged { Err(p.answers) } else { Ok(Outcome { game: g, nodes: p.answers }) }; - (res, walk) - } - - /// Plays `candidate` on `game` (a `sample`, or the snapshot) with the quick answers and no noise: the same as - /// `play_out` without a shuffle, from a given copy - pub fn play_on(&self, mut g: Game, candidate: &[Answer], cap: u64, stop_turn: u32) -> Result { - let mut script = self.since.clone(); - script.extend(candidate.iter().cloned()); - let mut p = Playout::new(script, cap, stop_turn, None, self.playout, self.rollout.clone()); - rules::play_from_priority_question(&mut g, &mut p, stop_turn); - if p.diverged { - Err(p.answers) - } else { - Ok(Outcome { game: g, nodes: p.answers }) - } - } -} -/// A playout: the recorded answers back to the question, the candidate, then quick answers for everyone until the -/// turn ends or the answers run out. -struct Playout { - script: Vec, - next: usize, - policy: [Policy; 2], - repeats: Repeats, - answers: u64, - cap: u64, - stop_turn: u32, - stopped: bool, - /// the copy asked something other than what was recorded: its result means nothing - diverged: bool, - noise: Option, - rollout: Option>, - /// `ismcts`: the tree answers the questions it has reached before - walk: Option>, -} - -impl Playout { - fn new( - script: Vec, - cap: u64, - stop_turn: u32, - noise: Option, - version: u8, - rollout: Option>, - ) -> Playout { - Playout { - script, - next: 0, - policy: [Policy::version(version), Policy::version(version)], - repeats: Repeats::default(), - answers: 0, - cap, - stop_turn, - stopped: false, - diverged: false, - noise: noise.map(|s| s | 1), - rollout, - walk: None, - } - } -} - -impl Decider for Playout { - fn answer(&mut self, game: &Game, seat: Seat, q: &Query) -> Answer { - if self.next < self.script.len() { - let a = self.script[self.next].clone(); - self.next += 1; - if !q.accepts(&a) { - self.diverged = true; - self.stopped = true; - return Answer::Stop; - } - return a; - } - self.answers += 1; - if self.answers > self.cap || game.turn >= self.stop_turn { - self.stopped = true; - return Answer::Stop; - } - let mut a = self.policy[seat.min(1)].answer(game, seat, q); - let mut by_tree = false; - if let Some(w) = self.walk.as_mut() { - if let Some(t) = w.step(game, seat, q, &a) { - if matches!(q, Query::Priority { .. }) { - self.policy[seat.min(1)].played(&t); - } - a = t; - by_tree = true; - } else if w.should_stop() { - self.stopped = true; - return Answer::Stop; - } - } - if let (false, Some(net)) = (by_tree, &self.rollout) { - if !crate::selfplay::skipped(q) { - let options = candidates(game, seat, q, &a, 12); - if options.len() > 1 { - let o = crate::obs::observe(game, seat, q, &options); - let out = net.forward(&o); - let best = (0..options.len()).max_by(|i, j| out.logits[*i].total_cmp(&out.logits[*j])).unwrap_or(0); - a = options[best].clone(); - if matches!(q, Query::Priority { .. }) { - self.policy[seat.min(1)].played(&a); - } - } - } - } - if let Some(state) = self.noise.as_mut() { - let r = xorshift(state); - if r.is_multiple_of(noise_rate()) && !matches!(q, Query::PlayMana { .. }) { - let options = candidates(game, seat, q, &a, usize::MAX); - a = options[(r >> 8) as usize % options.len()].clone(); - } - } - if self.repeats.is_repeat(seat, q) { - let options = candidates(game, seat, q, &a, usize::MAX); - return self.repeats.guard(seat, q, a, &options); - } - self.repeats.guard(seat, q, a, &[]) - } - - fn stopped(&self) -> bool { - self.stopped - } -} - -/// one quick answer in this many is random in a shuffled playout (`PLAYMAT_AI_MCTS_NOISE`, 0 for none) -fn noise_rate() -> u64 { - static RATE: std::sync::OnceLock = std::sync::OnceLock::new(); - *RATE.get_or_init(|| { - std::env::var("PLAYMAT_AI_MCTS_NOISE").ok().and_then(|v| v.parse().ok()).map_or(16, |v: u64| { - if v == 0 { - u64::MAX - } else { - v - } - }) - }) -} - -fn xorshift(state: &mut u64) -> u64 { - let mut x = *state; - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - *state = x; - x -} - -/// The quick answers alone -pub struct Quick; - -impl DecisionPolicy for Quick { - fn name(&self) -> &str { - "quick" - } - fn decide(&mut self, _: &Decision) -> Option { - None - } -} - -/// A random candidate (seeded, so a game replays the same) -pub struct Random { - state: u64, -} - -impl Random { - pub fn new(seed: u64) -> Random { - Random { state: seed | 1 } - } -} - -impl DecisionPolicy for Random { - fn name(&self) -> &str { - "random" - } - fn decide(&mut self, d: &Decision) -> Option { - // every option the question lists, not only the first `width` - let all = candidates(d.game, d.seat, d.query, d.quick, usize::MAX); - let i = (xorshift(&mut self.state) >> 8) as usize % all.len().max(1); - all.get(i).cloned().map(|answer| Choice { answer, nodes: 0 }) - } -} - -/// Monte Carlo tree search at the root: UCB1 over the candidates, each sample a playout on a copy whose libraries are -/// shuffled (and whose quick answers are now and then random), run on `config.threads` threads that each spend -/// `config.budget / threads` nodes and pool their counts at the end. A candidate's first sample is the plain playout -/// `Playouts` would make, on one of the threads, so MCTS sees at least what the default search sees. -pub struct Mcts; - -/// UCB1's exploration constant, on values in 0..1 -const EXPLORE: f64 = 0.5; -/// score difference (eval units) that counts as clearly better: a few life points or a good creature -const SCALE: f64 = 2500.0; - -impl DecisionPolicy for Mcts { - fn name(&self) -> &str { - "mcts" - } - - fn decide(&mut self, d: &Decision) -> Option { - let root = d.root?; - let k = d.candidates.len(); - let cfg = d.config; - let threads = cfg.threads.clamp(1, 16); - let base = eval::evaluate(d.game, d.seat) as f64; - let stop = d.game.turn + 1 + cfg.extra_turns; - let budget = (cfg.budget / threads as u64).max(1); - let cap = (cfg.budget / k as u64).clamp(50, cfg.playout_cap); - let seed = (d.game.turn as u64) << 32 ^ (root.since.len() as u64) << 8 ^ d.seat as u64; - let cands = d.candidates; - let seat = d.seat; - // a game copy can go to another thread but not be shared (its `Cell`s): each worker gets its own root - let results: Vec = if threads == 1 { - vec![worker(root, cands, seat, base, budget, cap, stop, 0, 1, seed)] - } else { - std::thread::scope(|s| { - let handles: Vec<_> = (0..threads) - .map(|t| { - let mine = root.clone(); - s.spawn(move || worker(&mine, cands, seat, base, budget, cap, stop, t, threads, seed)) - }) - .collect(); - handles.into_iter().map(|h| h.join().expect("mcts worker")).collect() - }) - }; - let mut visits = vec![0u64; k]; - let mut value = vec![0f64; k]; - let mut nodes = 0; - for r in &results { - nodes += r.nodes; - for i in 0..k { - visits[i] += r.visits[i]; - value[i] += r.value[i]; - } - } - let best = (0..k).filter(|i| visits[*i] > 0).max_by(|a, b| { - let (ma, mb) = (value[*a] / visits[*a] as f64, value[*b] / visits[*b] as f64); - ma.total_cmp(&mb).then(visits[*a].cmp(&visits[*b])).then(b.cmp(a)) - })?; - Some(Choice { answer: d.candidates[best].clone(), nodes }) - } -} - -struct Stats { - visits: Vec, - value: Vec, - nodes: u64, -} - -#[allow(clippy::too_many_arguments)] -fn worker( - root: &Root, - candidates: &[Answer], - seat: Seat, - base: f64, - budget: u64, - cap: u64, - stop: u32, - thread: usize, - threads: usize, - seed: u64, -) -> Stats { - let k = candidates.len(); - let mut s = Stats { visits: vec![0; k], value: vec![0.0; k], nodes: 0 }; - // a candidate whose copy goes another way can't be judged (dead), or only without shuffling (plain) - let mut dead = vec![false; k]; - let mut plain = vec![false; k]; - // judged once without shuffling, all a plain candidate can give: kept, not sampled again - let mut fixed = vec![false; k]; - let mut tried = vec![false; k]; - let mut iter = 0u64; - while s.nodes < budget { - iter += 1; - let total: u64 = s.visits.iter().sum(); - // first visits: this thread's share of the plain playouts, then the rest in order - let pick = (0..k) - .filter(|i| !dead[*i] && !fixed[*i] && !tried[*i]) - .min_by_key(|i| (*i % threads != thread, *i)) - .or_else(|| { - (0..k).filter(|i| !dead[*i] && !fixed[*i]).max_by(|a, b| { - let ucb = |i: usize| { - let n = s.visits[i].max(1) as f64; - s.value[i] / n + EXPLORE * ((total.max(1) as f64).ln() / n).sqrt() - }; - ucb(*a).total_cmp(&ucb(*b)).then(b.cmp(a)) - }) - }); - let Some(i) = pick else { break }; - let first = !tried[i]; - tried[i] = true; - let shuffle = if (first && i % threads == thread) || plain[i] { - None - } else { - Some(seed ^ (thread as u64) << 48 ^ iter.wrapping_mul(0x9E37_79B9_7F4A_7C15)) - }; - match root.play_out(&candidates[i], cap, stop, shuffle) { - Ok(o) => { - s.nodes += o.nodes.max(1); - let score = eval::evaluate(&o.game, seat) as f64; - let v = 0.5 + 0.5 * ((score - base) / SCALE).tanh(); - s.visits[i] += 1; - s.value[i] += v; - fixed[i] = plain[i]; - } - Err(n) => { - s.nodes += n.max(1); - if shuffle.is_some() { - plain[i] = true; - } else { - dead[i] = true; - } - } - } - if (0..k).all(|i| dead[i] || fixed[i]) { - break; - } - } - s -} +//! One decision at a time: the interface every decider of the AI's seat answers through (docs/rust/Ai.md). +//! +//! The `Table` asks its seat's `DecisionPolicy` each question that has two or more answers worth trying. The policy +//! gets the game, the question, the quick answer, the candidates and a `Root` to play candidates out on copies; it +//! answers with one of the candidates (or anything the question accepts), or `None` to let the quick answer stand. +//! Shipped policies: `Playouts` (the default search), `Mcts`, `Quick` and `Random`. A Jev, LLM or ONNX decider is +//! another implementation, set on a table with `Table::set_policy`. + +use crate::eval; +use crate::policy::{Policy, Repeats}; +use crate::search::{candidates, Config}; +use playmat_engine::decide::{Answer, Decider, Query}; +use playmat_engine::rng::JavaRandom; +use playmat_engine::rules; +use playmat_engine::state::{Game, ObjId, Seat, Zone}; +use std::str::FromStr; +use std::sync::Arc; + +/// Which `DecisionPolicy` a seat's `Config` builds (`PLAYMAT_AI_POLICY`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum PolicyKind { + /// each candidate played once to the end of the turn, the best end of turn kept (`search::Playouts`) + #[default] + Playouts, + /// Monte Carlo tree search at the root, playouts on shuffled copies in parallel threads (`Mcts`) + Mcts, + /// the quick answers alone, no search + Quick, + /// a random answer among the candidates (Archbench's anchor) + Random, + /// the trained network's policy alone (`selfplay::NetPolicy`, #390 Track B) + Net, + /// the network's policy improved by playouts on samples scored by its value (`selfplay::NetSearch`) + NetSearch, + /// the network's policy searched by Gumbel sequential halving (`selfplay::Gumbel`) + Gumbel, + /// an open-loop information-set tree search over the network's policy (`tree::Ismcts`) + Ismcts, +} + +impl PolicyKind { + pub fn name(self) -> &'static str { + match self { + PolicyKind::Playouts => "playouts", + PolicyKind::Mcts => "mcts", + PolicyKind::Quick => "quick", + PolicyKind::Random => "random", + PolicyKind::Net => "net", + PolicyKind::NetSearch => "netsearch", + PolicyKind::Gumbel => "gumbel", + PolicyKind::Ismcts => "ismcts", + } + } + + /// The setting `PLAYMAT_AI_POLICY`, `playouts` when unset or unknown + pub fn from_env() -> PolicyKind { + std::env::var("PLAYMAT_AI_POLICY").ok().and_then(|v| v.parse().ok()).unwrap_or_default() + } + + pub fn build(self, seat: Seat) -> Box { + match self { + PolicyKind::Playouts => Box::new(crate::search::Playouts), + PolicyKind::Mcts => Box::new(Mcts), + PolicyKind::Quick => Box::new(Quick), + PolicyKind::Random => Box::new(Random::new(0x5eed_0000 + seat as u64)), + PolicyKind::Net => Box::new(crate::selfplay::NetPolicy::new(0x6e65_7400 + seat as u64)), + PolicyKind::NetSearch => Box::new(crate::selfplay::NetSearch::new(0x6e73_0000 + seat as u64)), + PolicyKind::Gumbel => Box::new(crate::selfplay::Gumbel::new(0x6762_0000 + seat as u64)), + PolicyKind::Ismcts => Box::new(crate::tree::Ismcts::new(0x6973_0000 + seat as u64)), + } + } +} + +impl FromStr for PolicyKind { + type Err = String; + fn from_str(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "" | "playouts" | "search" | "default" => Ok(PolicyKind::Playouts), + "mcts" => Ok(PolicyKind::Mcts), + "quick" => Ok(PolicyKind::Quick), + "random" => Ok(PolicyKind::Random), + "net" => Ok(PolicyKind::Net), + "netsearch" => Ok(PolicyKind::NetSearch), + "gumbel" => Ok(PolicyKind::Gumbel), + "ismcts" => Ok(PolicyKind::Ismcts), + other => Err(format!("unknown AI policy {other:?} (playouts, mcts, quick, random, net, netsearch)")), + } + } +} + +/// One question for the AI's seat +pub struct Decision<'a> { + pub game: &'a Game, + pub seat: Seat, + pub query: &'a Query, + /// what the quick answers say (`policy::Policy`), always the first candidate + pub quick: &'a Answer, + /// the answers worth trying, at most `config.width` + pub candidates: &'a [Answer], + pub config: &'a Config, + /// where candidates can be played out; `None` before the game's first priority question + pub root: Option<&'a Root>, +} + +/// A policy's answer and the search nodes (answers in playouts) it spent +pub struct Choice { + pub answer: Answer, + pub nodes: u64, +} + +/// Answers single decisions for one seat. +pub trait DecisionPolicy: Send { + fn name(&self) -> &str; + /// The answer, or `None` for the quick one + fn decide(&mut self, d: &Decision) -> Option; + /// The chances the policy gave each candidate at its last decision (a network's policy, or a search's improved + /// one), when it has them: what self-play records (`selfplay::Recording`) + fn last_policy(&self) -> Option<&[f32]> { + None + } + /// The search's estimated win probability (0..1) at its last decision, when available (`qval.f16` target) + fn last_value(&self) -> Option { + None + } + /// Per-candidate search Q-values (0..1, or NaN for unvisited candidates) for v3 completed-Q training (`act_q.f16`) + fn last_action_qs(&self) -> Option<&[f32]> { + None + } + /// Per-candidate search visit counts for v3 shards (`act_n.u16`) + fn last_action_visits(&self) -> Option<&[u32]> { + None + } +} + +/// The game at the last priority question and the answers since: what a copy replays to reach the question. +#[derive(Clone)] +pub struct Root { + pub snapshot: Game, + pub since: Vec, + /// what the deciding seat can't see, for samples of the game it might be (`Root::sample`); `None` plays the + /// real game + pub hidden: Option, + /// the playouts' quick answers (`Config::playout`) + pub playout: u8, + /// a network that answers the playouts' questions in place of the quick answers (`Config::rollout`) + pub rollout: Option>, +} + +/// What a seat has seen of the game: objects it saw in a public zone or that were shown to it. Its own hand it +/// always knows; the order of any library and the cards of the opponent's hand it hasn't seen, it doesn't. +#[derive(Clone, Debug)] +pub struct Hidden { + pub seat: Seat, + /// by object id + pub seen: Arc>, +} + +impl Hidden { + pub fn new(seat: Seat) -> Hidden { + Hidden { seat, seen: Arc::new(Vec::new()) } + } + + /// Notes what the seat sees in `game` now: every object in a public zone or on the stack, cards revealed, and + /// cards the seat looked at + pub fn observe(&mut self, game: &Game) { + let seen = Arc::make_mut(&mut self.seen); + if seen.len() < game.objs.len() { + seen.resize(game.objs.len(), false); + } + let mut mark = |id: ObjId| { + if let Some(s) = seen.get_mut(id.0 as usize) { + *s = true; + } + }; + for id in game.battlefield.iter().chain(game.exile.iter()).chain(game.command.iter()) { + mark(*id); + } + for p in game.players.iter() { + for id in &p.graveyard { + mark(*id); + } + } + for item in game.stack.iter() { + mark(item.card); + } + for r in &game.revealed { + for (id, _) in &r.cards { + mark(*id); + } + } + for l in game.looked_at.iter().filter(|l| l.viewer == self.seat) { + for id in &l.cards { + mark(*id); + } + } + } + + /// Whether the seat has seen object `id` + pub fn seat_saw(&self, id: ObjId) -> bool { + self.seen(id) + } + + fn seen(&self, id: ObjId) -> bool { + self.seen.get(id.0 as usize).copied().unwrap_or(false) + } +} + +/// A played-out copy +pub struct Outcome { + pub game: Game, + /// answers given after the candidate (search nodes) + pub nodes: u64, +} + +impl Root { + /// The root's game as the deciding seat might find it: the opponent's hand cards it hasn't seen and every + /// library's order drawn at random from what it can't see, and a new random number generator. Cards the answers + /// since the snapshot name stay where they are, so the copy can replay them. Without `hidden`, the real game. + pub fn sample(&self, seed: u64) -> Game { + let mut g = self.snapshot.clone(); + let Some(h) = &self.hidden else { return g }; + let mut keep: Vec = Vec::new(); + for a in &self.since { + if let Answer::Obj(id) | Answer::Ability(id, _) = a { + keep.push(*id); + } + } + let mut rng = JavaRandom::new((seed ^ 0x5851_f42d_4c95_7f2d) as i64); + let looked: Vec = + g.looked_at.iter().filter(|l| l.viewer == h.seat).flat_map(|l| l.cards.iter().copied()).collect(); + for seat in 0..g.players.len() { + let mine = seat == h.seat; + let fixed_in_hand = |id: &ObjId| mine || h.seen(*id) || keep.contains(id); + let fixed_in_library = |id: &ObjId| keep.contains(id) || looked.contains(id); + let hand = g.player(seat).hand.clone(); + let library = g.player(seat).library.clone(); + let mut pool: Vec = hand + .iter() + .filter(|id| !fixed_in_hand(id)) + .chain(library.iter().filter(|id| !fixed_in_library(id))) + .copied() + .collect(); + if pool.len() < 2 { + continue; + } + rng.shuffle(&mut pool); + let mut next = pool.into_iter(); + let new_hand: Vec = + hand.iter().map(|id| if fixed_in_hand(id) { *id } else { next.next().unwrap() }).collect(); + let new_library: Vec = + library.iter().map(|id| if fixed_in_library(id) { *id } else { next.next().unwrap() }).collect(); + for id in &new_hand { + if g.obj(*id).zone != Zone::Hand { + g.obj_mut(*id).zone = Zone::Hand; + } + } + for id in &new_library { + if g.obj(*id).zone != Zone::Library { + g.obj_mut(*id).zone = Zone::Library; + } + } + let p = g.player_mut(seat); + p.hand = new_hand; + p.library = new_library; + } + g.rng = JavaRandom::new(seed.rotate_left(17) as i64); + g + } + + /// A sample of the game (`sample`) with `hidden`; without, the real game with every library shuffled and a new + /// random number generator + pub fn sample_or_shuffle(&self, seed: u64) -> Game { + if self.hidden.is_some() { + return self.sample(seed); + } + let mut g = self.snapshot.clone(); + let mut rng = JavaRandom::new(seed as i64); + for seat in 0..g.players.len() { + let mut library = g.player(seat).library.clone(); + rng.shuffle(&mut library); + g.player_mut(seat).library = library; + } + g.rng = JavaRandom::new(seed.rotate_left(17) as i64); + g + } + + /// Plays `candidate` on a copy until turn `stop_turn` starts or `cap` answers are given, both seats on the quick + /// answers. With `shuffle`, the copy is a sample (`sample`; without `hidden`, the libraries are shuffled) and one + /// answer in sixteen of the quick ones is a random candidate instead (MCTS). `Err` when the copy didn't reach + /// the question again. + pub fn play_out(&self, candidate: &Answer, cap: u64, stop_turn: u32, shuffle: Option) -> Result { + let mut g = match shuffle { + Some(seed) => self.sample_or_shuffle(seed), + None => self.snapshot.clone(), + }; + let mut script = self.since.clone(); + script.push(candidate.clone()); + let mut p = Playout::new(script, cap, stop_turn, shuffle, self.playout, self.rollout.clone()); + rules::play_from_priority_question(&mut g, &mut p, stop_turn); + if p.diverged { + Err(p.answers) + } else { + Ok(Outcome { game: g, nodes: p.answers }) + } + } + + /// Plays `game` (a `sample`, or the snapshot) from the question with `walk` answering where its tree reaches + /// (`tree::Ismcts`), then the playout's answers; gives the walk back for the backup + pub fn play_tree( + &self, + mut g: Game, + walk: crate::tree::Walk, + cap: u64, + stop_turn: u32, + ) -> (Result, crate::tree::Walk) { + let mut p = Playout::new(self.since.clone(), cap, stop_turn, None, self.playout, self.rollout.clone()); + p.walk = Some(Box::new(walk)); + rules::play_from_priority_question(&mut g, &mut p, stop_turn); + let walk = *p.walk.take().expect("the walk"); + let res = if p.diverged { Err(p.answers) } else { Ok(Outcome { game: g, nodes: p.answers }) }; + (res, walk) + } + + /// Plays `candidate` on `game` (a `sample`, or the snapshot) with the quick answers and no noise: the same as + /// `play_out` without a shuffle, from a given copy + pub fn play_on(&self, mut g: Game, candidate: &[Answer], cap: u64, stop_turn: u32) -> Result { + let mut script = self.since.clone(); + script.extend(candidate.iter().cloned()); + let mut p = Playout::new(script, cap, stop_turn, None, self.playout, self.rollout.clone()); + rules::play_from_priority_question(&mut g, &mut p, stop_turn); + if p.diverged { + Err(p.answers) + } else { + Ok(Outcome { game: g, nodes: p.answers }) + } + } +} +/// A playout: the recorded answers back to the question, the candidate, then quick answers for everyone until the +/// turn ends or the answers run out. +struct Playout { + script: Vec, + next: usize, + policy: [Policy; 2], + repeats: Repeats, + answers: u64, + cap: u64, + stop_turn: u32, + stopped: bool, + /// the copy asked something other than what was recorded: its result means nothing + diverged: bool, + noise: Option, + rollout: Option>, + /// `ismcts`: the tree answers the questions it has reached before + walk: Option>, +} + +impl Playout { + fn new( + script: Vec, + cap: u64, + stop_turn: u32, + noise: Option, + version: u8, + rollout: Option>, + ) -> Playout { + Playout { + script, + next: 0, + policy: [Policy::version(version), Policy::version(version)], + repeats: Repeats::default(), + answers: 0, + cap, + stop_turn, + stopped: false, + diverged: false, + noise: noise.map(|s| s | 1), + rollout, + walk: None, + } + } +} + +impl Decider for Playout { + fn answer(&mut self, game: &Game, seat: Seat, q: &Query) -> Answer { + if self.next < self.script.len() { + let a = self.script[self.next].clone(); + self.next += 1; + if !q.accepts(&a) { + self.diverged = true; + self.stopped = true; + return Answer::Stop; + } + return a; + } + self.answers += 1; + if self.answers > self.cap || game.turn >= self.stop_turn { + self.stopped = true; + return Answer::Stop; + } + let mut a = self.policy[seat.min(1)].answer(game, seat, q); + let mut by_tree = false; + if let Some(w) = self.walk.as_mut() { + if let Some(t) = w.step(game, seat, q, &a) { + if matches!(q, Query::Priority { .. }) { + self.policy[seat.min(1)].played(&t); + } + a = t; + by_tree = true; + } else if w.should_stop() { + self.stopped = true; + return Answer::Stop; + } + } + if let (false, Some(net)) = (by_tree, &self.rollout) { + if !crate::selfplay::skipped(q) { + let options = candidates(game, seat, q, &a, 12); + if options.len() > 1 { + let o = crate::obs::observe(game, seat, q, &options); + let out = net.forward(&o); + let best = (0..options.len()).max_by(|i, j| out.logits[*i].total_cmp(&out.logits[*j])).unwrap_or(0); + a = options[best].clone(); + if matches!(q, Query::Priority { .. }) { + self.policy[seat.min(1)].played(&a); + } + } + } + } + if let Some(state) = self.noise.as_mut() { + let r = xorshift(state); + if r.is_multiple_of(noise_rate()) && !matches!(q, Query::PlayMana { .. }) { + let options = candidates(game, seat, q, &a, usize::MAX); + a = options[(r >> 8) as usize % options.len()].clone(); + } + } + if self.repeats.is_repeat(seat, q) { + let options = candidates(game, seat, q, &a, usize::MAX); + return self.repeats.guard(seat, q, a, &options); + } + self.repeats.guard(seat, q, a, &[]) + } + + fn stopped(&self) -> bool { + self.stopped + } +} + +/// one quick answer in this many is random in a shuffled playout (`PLAYMAT_AI_MCTS_NOISE`, 0 for none) +fn noise_rate() -> u64 { + static RATE: std::sync::OnceLock = std::sync::OnceLock::new(); + *RATE.get_or_init(|| { + std::env::var("PLAYMAT_AI_MCTS_NOISE").ok().and_then(|v| v.parse().ok()).map_or(16, |v: u64| { + if v == 0 { + u64::MAX + } else { + v + } + }) + }) +} + +fn xorshift(state: &mut u64) -> u64 { + let mut x = *state; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + *state = x; + x +} + +/// The quick answers alone +pub struct Quick; + +impl DecisionPolicy for Quick { + fn name(&self) -> &str { + "quick" + } + fn decide(&mut self, _: &Decision) -> Option { + None + } +} + +/// A random candidate (seeded, so a game replays the same) +pub struct Random { + state: u64, +} + +impl Random { + pub fn new(seed: u64) -> Random { + Random { state: seed | 1 } + } +} + +impl DecisionPolicy for Random { + fn name(&self) -> &str { + "random" + } + fn decide(&mut self, d: &Decision) -> Option { + // every option the question lists, not only the first `width` + let all = candidates(d.game, d.seat, d.query, d.quick, usize::MAX); + let i = (xorshift(&mut self.state) >> 8) as usize % all.len().max(1); + all.get(i).cloned().map(|answer| Choice { answer, nodes: 0 }) + } +} + +/// Monte Carlo tree search at the root: UCB1 over the candidates, each sample a playout on a copy whose libraries are +/// shuffled (and whose quick answers are now and then random), run on `config.threads` threads that each spend +/// `config.budget / threads` nodes and pool their counts at the end. A candidate's first sample is the plain playout +/// `Playouts` would make, on one of the threads, so MCTS sees at least what the default search sees. +pub struct Mcts; + +/// UCB1's exploration constant, on values in 0..1 +const EXPLORE: f64 = 0.5; +/// score difference (eval units) that counts as clearly better: a few life points or a good creature +const SCALE: f64 = 2500.0; + +impl DecisionPolicy for Mcts { + fn name(&self) -> &str { + "mcts" + } + + fn decide(&mut self, d: &Decision) -> Option { + let root = d.root?; + let k = d.candidates.len(); + let cfg = d.config; + let threads = cfg.threads.clamp(1, 16); + let base = eval::evaluate(d.game, d.seat) as f64; + let stop = d.game.turn + 1 + cfg.extra_turns; + let budget = (cfg.budget / threads as u64).max(1); + let cap = (cfg.budget / k as u64).clamp(50, cfg.playout_cap); + let seed = (d.game.turn as u64) << 32 ^ (root.since.len() as u64) << 8 ^ d.seat as u64; + let cands = d.candidates; + let seat = d.seat; + // a game copy can go to another thread but not be shared (its `Cell`s): each worker gets its own root + let results: Vec = if threads == 1 { + vec![worker(root, cands, seat, base, budget, cap, stop, 0, 1, seed)] + } else { + std::thread::scope(|s| { + let handles: Vec<_> = (0..threads) + .map(|t| { + let mine = root.clone(); + s.spawn(move || worker(&mine, cands, seat, base, budget, cap, stop, t, threads, seed)) + }) + .collect(); + handles.into_iter().map(|h| h.join().expect("mcts worker")).collect() + }) + }; + let mut visits = vec![0u64; k]; + let mut value = vec![0f64; k]; + let mut nodes = 0; + for r in &results { + nodes += r.nodes; + for i in 0..k { + visits[i] += r.visits[i]; + value[i] += r.value[i]; + } + } + let best = (0..k).filter(|i| visits[*i] > 0).max_by(|a, b| { + let (ma, mb) = (value[*a] / visits[*a] as f64, value[*b] / visits[*b] as f64); + ma.total_cmp(&mb).then(visits[*a].cmp(&visits[*b])).then(b.cmp(a)) + })?; + Some(Choice { answer: d.candidates[best].clone(), nodes }) + } +} + +struct Stats { + visits: Vec, + value: Vec, + nodes: u64, +} + +#[allow(clippy::too_many_arguments)] +fn worker( + root: &Root, + candidates: &[Answer], + seat: Seat, + base: f64, + budget: u64, + cap: u64, + stop: u32, + thread: usize, + threads: usize, + seed: u64, +) -> Stats { + let k = candidates.len(); + let mut s = Stats { visits: vec![0; k], value: vec![0.0; k], nodes: 0 }; + // a candidate whose copy goes another way can't be judged (dead), or only without shuffling (plain) + let mut dead = vec![false; k]; + let mut plain = vec![false; k]; + // judged once without shuffling, all a plain candidate can give: kept, not sampled again + let mut fixed = vec![false; k]; + let mut tried = vec![false; k]; + let mut iter = 0u64; + while s.nodes < budget { + iter += 1; + let total: u64 = s.visits.iter().sum(); + // first visits: this thread's share of the plain playouts, then the rest in order + let pick = (0..k) + .filter(|i| !dead[*i] && !fixed[*i] && !tried[*i]) + .min_by_key(|i| (*i % threads != thread, *i)) + .or_else(|| { + (0..k).filter(|i| !dead[*i] && !fixed[*i]).max_by(|a, b| { + let ucb = |i: usize| { + let n = s.visits[i].max(1) as f64; + s.value[i] / n + EXPLORE * ((total.max(1) as f64).ln() / n).sqrt() + }; + ucb(*a).total_cmp(&ucb(*b)).then(b.cmp(a)) + }) + }); + let Some(i) = pick else { break }; + let first = !tried[i]; + tried[i] = true; + let shuffle = if (first && i % threads == thread) || plain[i] { + None + } else { + Some(seed ^ (thread as u64) << 48 ^ iter.wrapping_mul(0x9E37_79B9_7F4A_7C15)) + }; + match root.play_out(&candidates[i], cap, stop, shuffle) { + Ok(o) => { + s.nodes += o.nodes.max(1); + let score = eval::evaluate(&o.game, seat) as f64; + let v = 0.5 + 0.5 * ((score - base) / SCALE).tanh(); + s.visits[i] += 1; + s.value[i] += v; + fixed[i] = plain[i]; + } + Err(n) => { + s.nodes += n.max(1); + if shuffle.is_some() { + plain[i] = true; + } else { + dead[i] = true; + } + } + } + if (0..k).all(|i| dead[i] || fixed[i]) { + break; + } + } + s +} diff --git a/rust/crates/playmat-ai/src/entrants.rs b/rust/crates/playmat-ai/src/entrants.rs index 89b4230..1cdb6e1 100644 --- a/rust/crates/playmat-ai/src/entrants.rs +++ b/rust/crates/playmat-ai/src/entrants.rs @@ -59,6 +59,7 @@ pub fn entrant(name: &str) -> Result { /// `config` with `key=value` settings joined by `+` pub fn with(mut c: Config, settings: &str) -> Result { + let mut hide_explicit = false; for kv in settings.split('+').filter(|s| !s.is_empty()) { let (k, v) = kv.split_once('=').ok_or_else(|| format!("{kv}: key=value"))?; let n = || v.parse::().map_err(|_| format!("{kv}: not a number")); @@ -70,7 +71,7 @@ pub fn with(mut c: Config, settings: &str) -> Result { "playout_cap" => c.playout_cap = n()?, "policy" => c.policy = v.parse()?, "threads" => c.threads = n()? as usize, - "hide" => c.hide = b()?, + "hide" => { c.hide = b()?; hide_explicit = true; }, "samples" => c.samples = n()?.max(1) as usize, "playout" => c.playout = n()? as u8, "eval" => c.eval = n()? as u8, @@ -96,6 +97,9 @@ pub fn with(mut c: Config, settings: &str) -> Result { _ => return Err(format!("unknown config key {k}")), } } + if !hide_explicit && matches!(c.policy, PolicyKind::NetSearch | PolicyKind::Gumbel | PolicyKind::Ismcts) { + c.hide = true; + } Ok(c) } diff --git a/rust/crates/playmat-ai/src/net.rs b/rust/crates/playmat-ai/src/net.rs index 09c032a..e5c2234 100644 --- a/rust/crates/playmat-ai/src/net.rs +++ b/rust/crates/playmat-ai/src/net.rs @@ -1,1225 +1,1225 @@ -//! A small policy and value network, run on the CPU in plain Rust (#390 Track B). Trained by `rust/rl` (PyTorch), -//! written as a `.pmnet` file: one line of JSON naming each tensor and its shape, then the tensors as little-endian -//! f32 in that order. -//! -//! Fast CPU execution: -//! - Linear weights are repacked at load time into `[out_blocks, inp, 8]` panels (`wp`) for a 4x8 register-blocked -//! SIMD GEMM (`matmul_rows`) that vectorizes cleanly to AVX2 FMA on x86_64 and NEON FMLA on ARM64 without horizontal -//! reductions. -//! - `Tx::forward` and `Tx::state` reuse a thread-local flat `TxWorkspace` (zero per-layer heap allocations and no -//! `Vec>` Q/K/V copies). -//! - Supports both v1 `Tx` checkpoints (ReLU + linear value head) and upgraded `Tx` checkpoints (`val_mlp=1` dedicated -//! 2-layer value head reading `[t0, mean_ent, max_ent, glob]`, and `gelu=1` tanh-approx GELU). - -use crate::obs::{self, Obs, ACT_F, ENT_F, GLOB_F, GLOB_F_V1, NO_ENT, NUM_REL_TYPES}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::io::{Read, Write}; -use std::net::TcpStream; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; -use std::time::{Duration, Instant}; - -#[inline(always)] -fn act_val(x: f32, gelu: bool) -> f32 { - if gelu { - // Matches PyTorch F.gelu(x, approximate="tanh") - const K: f32 = 0.797_884_6; // sqrt(2 / pi) - 0.5 * x * (1.0 + (K * (x + 0.044_715 * x * x * x)).tanh()) - } else { - x.max(0.0) - } -} - -/// A dense layer: `w` is `[out][in]` flat, plus `wp` repacked into `[out/8][in][8]` panels for 4x8 SIMD GEMM. -#[derive(Clone, Debug, Default)] -pub struct Linear { - pub w: Vec, - pub b: Vec, - pub inp: usize, - pub out: usize, - /// Repacked weights: `blocks = out / 8` panels of `inp * 8` floats (contiguous 8 output lanes per `k`). - wp: Vec, -} - -impl Linear { - pub fn new(w: Vec, b: Vec, out: usize, inp: usize) -> Linear { - let blocks = out / 8; - let mut wp = vec![0f32; blocks * inp * 8]; - for blk in 0..blocks { - let ob = blk * 8; - let dst_blk = &mut wp[blk * inp * 8..(blk + 1) * inp * 8]; - for k in 0..inp { - let dst = &mut dst_blk[k * 8..(k + 1) * 8]; - for j in 0..8 { - dst[j] = w[(ob + j) * inp + k]; - } - } - } - Linear { w, b, inp, out, wp } - } - - /// Single-row apply into `y` (`y` resized to `self.out`). - #[inline] - fn apply(&self, x: &[f32], y: &mut Vec, relu: bool) { - self.apply_act(x, y, relu, false); - } - - fn apply_act(&self, x: &[f32], y: &mut Vec, do_act: bool, gelu: bool) { - debug_assert_eq!(x.len(), self.inp); - y.resize(self.out, 0.0); - let inp = self.inp; - let blocks = self.out / 8; - for blk in 0..blocks { - let ob = blk * 8; - let mut acc = [ - self.b[ob], - self.b[ob + 1], - self.b[ob + 2], - self.b[ob + 3], - self.b[ob + 4], - self.b[ob + 5], - self.b[ob + 6], - self.b[ob + 7], - ]; - let panel = &self.wp[blk * inp * 8..(blk + 1) * inp * 8]; - for (k, &xk) in x.iter().enumerate() { - let w = &panel[k * 8..(k + 1) * 8]; - for j in 0..8 { - acc[j] += xk * w[j]; - } - } - if do_act { - for j in 0..8 { - y[ob + j] = act_val(acc[j], gelu); - } - } else { - y[ob..ob + 8].copy_from_slice(&acc); - } - } - for o in blocks * 8..self.out { - let row = &self.w[o * inp..(o + 1) * inp]; - let s = self.b[o] + dot(row, x); - y[o] = if do_act { act_val(s, gelu) } else { s }; - } - } - - /// Flat batched matmul: `x` is `[rows, inp]`, writes `y` as `[rows, out]`. - /// Uses `matrixmultiply::sgemm` (AVX2+FMA / NEON cache-blocked microkernels) for multi-row projections, - /// and the packed 8-lane kernel for single rows. - fn matmul_rows(&self, x: &[f32], rows: usize, y: &mut Vec, do_act: bool, gelu: bool, add_to_y: bool) { - let inp = self.inp; - let out = self.out; - debug_assert_eq!(x.len(), rows * inp); - if rows == 0 { - if !add_to_y { - y.clear(); - } - return; - } - if rows == 1 && !add_to_y { - self.apply_act(x, y, do_act, gelu); - return; - } - if !add_to_y { - y.resize(rows * out, 0.0); - } else { - debug_assert_eq!(y.len(), rows * out); - debug_assert!(!do_act, "add_to_y with activation not supported"); - } - let beta = if add_to_y { 1.0 } else { 0.0 }; - unsafe { - matrixmultiply::sgemm( - rows, - inp, - out, - 1.0, - x.as_ptr(), - inp as isize, - 1, - self.w.as_ptr(), - 1, - inp as isize, - beta, - y.as_mut_ptr(), - out as isize, - 1, - ); - } - if do_act { - if gelu { - for r in 0..rows { - let row = &mut y[r * out..(r + 1) * out]; - for (dst, &b) in row.iter_mut().zip(&self.b) { - *dst = act_val(*dst + b, true); - } - } - } else { - for r in 0..rows { - let row = &mut y[r * out..(r + 1) * out]; - for (dst, &b) in row.iter_mut().zip(&self.b) { - *dst = (*dst + b).max(0.0); - } - } - } - } else { - for r in 0..rows { - let row = &mut y[r * out..(r + 1) * out]; - for (dst, &b) in row.iter_mut().zip(&self.b) { - *dst += b; - } - } - } - } -} - -/// A dot product in 8 lanes: the compiler vectorizes it (one running sum can't be reordered, so it doesn't) -#[inline] -pub fn dot(a: &[f32], b: &[f32]) -> f32 { - let n = a.len().min(b.len()); - let (a, b) = (&a[..n], &b[..n]); - let mut acc = [0f32; 8]; - let (ac, ar) = a.as_chunks::<8>(); - let (bc, br) = b.as_chunks::<8>(); - for (x, y) in ac.iter().zip(bc) { - for i in 0..8 { - acc[i] += x[i] * y[i]; - } - } - let mut s = acc.iter().sum::(); - for (x, y) in ar.iter().zip(br) { - s += x * y; - } - s -} - -/// The first network (#390): entities pooled by mean and max -#[derive(Debug, Clone)] -pub struct Mlp { - pub name: String, - pub emb: Vec, - pub dim: usize, - pub ent1: Linear, - pub ent2: Linear, - pub glob1: Linear, - pub trunk1: Linear, - pub trunk2: Linear, - pub value: Linear, - pub act1: Linear, - pub act2: Linear, - pub query: Linear, - pub abias: Linear, - pub belief: Option, -} - -/// The network's outputs for one observation -#[derive(Debug, Clone, Default)] -pub struct Output { - /// one logit per action - pub logits: Vec, - /// the logit of the seat winning - pub value: f32, - /// the state, for the belief - pub h: Vec, -} - -impl Mlp { - /// Reads a `.pmnet` file's bytes - pub fn parse(name: &str, bytes: &[u8]) -> Result { - let (_, mut tensors) = read(bytes)?; - let mut take = |base: &str| -> Result { take_linear(&mut tensors, base) }; - let ent1 = take("ent1")?; - let ent2 = take("ent2")?; - let glob1 = take("glob1")?; - let trunk1 = take("trunk1")?; - let trunk2 = take("trunk2")?; - let value = take("value")?; - let act1 = take("act1")?; - let act2 = take("act2")?; - let query = take("query")?; - let abias = take("abias")?; - let belief = take("belief").ok(); - let (es, emb) = tensors.remove("emb.weight").ok_or("no emb.weight")?; - let dim = es[1]; - if ent1.inp != dim + ENT_F || (glob1.inp != GLOB_F && glob1.inp != GLOB_F_V1) || act1.inp != dim + ACT_F { - return Err(format!( - "{name}: made for other features (entity {}, global {}, action {}; this build has {}, {} or {}, {})", - ent1.inp - dim, - glob1.inp, - act1.inp - dim, - ENT_F, - GLOB_F_V1, - GLOB_F, - ACT_F - )); - } - Ok(Mlp { - name: name.to_string(), - emb, - dim, - ent1, - ent2, - glob1, - trunk1, - trunk2, - value, - act1, - act2, - query, - abias, - belief, - }) - } - - fn embedding(&self, id: u32) -> &[f32] { - let i = (id as usize).min(self.emb.len() / self.dim - 1); - &self.emb[i * self.dim..(i + 1) * self.dim] - } - - /// The state `h` and the value - pub fn state(&self, o: &Obs) -> (Vec, f32) { - let h1 = self.ent2.out; - let mut mean = vec![0f32; h1]; - let mut max = vec![0f32; h1]; - let n = o.n_ents(); - let (mut x, mut y, mut z) = (Vec::with_capacity(self.ent1.inp), Vec::new(), Vec::new()); - for i in 0..n { - x.clear(); - x.extend_from_slice(self.embedding(o.ent_ids[i])); - x.extend_from_slice(&o.ents[i * ENT_F..(i + 1) * ENT_F]); - self.ent1.apply(&x, &mut y, true); - self.ent2.apply(&y, &mut z, true); - for k in 0..h1 { - mean[k] += z[k] / n as f32; - max[k] = if i == 0 { z[k] } else { max[k].max(z[k]) }; - } - } - let mut gbuf = [0f32; GLOB_F]; - let gn = self.glob1.inp.min(o.glob.len()); - gbuf[..gn].copy_from_slice(&o.glob[..gn]); - self.glob1.apply(&gbuf[..self.glob1.inp], &mut y, true); - let mut t = mean; - t.extend(max); - t.extend_from_slice(&y); - self.trunk1.apply(&t, &mut y, true); - let mut h = Vec::new(); - self.trunk2.apply(&y, &mut h, true); - self.value.apply(&h, &mut y, false); - (h, y[0]) - } - - /// Every action's logit, and the value - pub fn forward(&self, o: &Obs) -> Output { - let (h, value) = self.state(o); - let mut q = Vec::new(); - self.query.apply(&h, &mut q, false); - let (mut x, mut y, mut a, mut b) = (Vec::with_capacity(self.act1.inp), Vec::new(), Vec::new(), Vec::new()); - let mut logits = Vec::with_capacity(o.n_acts()); - for i in 0..o.n_acts() { - x.clear(); - x.extend_from_slice(self.embedding(o.act_ids[i])); - x.extend_from_slice(&o.acts[i * ACT_F..(i + 1) * ACT_F]); - self.act1.apply(&x, &mut y, true); - self.act2.apply(&y, &mut a, false); - self.abias.apply(&a, &mut b, false); - logits.push(dot(&q, &a) + b[0]); - } - Output { logits, value, h } - } - - /// Each card's logit of being in the opponent's hand, from the state `h` (0 for a net without a belief head) - pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { - let Some(bl) = &self.belief else { return vec![0.0; cards.len()] }; - let mut q = Vec::new(); - bl.apply(h, &mut q, false); - cards.iter().map(|c| dot(self.embedding(*c), &q)).collect() - } -} - -/// A `.pmnet` file's header and tensors by name -type Tensors = HashMap, Vec)>; - -fn read(bytes: &[u8]) -> Result<(serde_json::Value, Tensors), String> { - let nl = bytes.iter().position(|b| *b == b'\n').ok_or("no header line")?; - let header: serde_json::Value = serde_json::from_slice(&bytes[..nl]).map_err(|e| e.to_string())?; - let mut data = &bytes[nl + 1..]; - let mut tensors = HashMap::new(); - for t in header["tensors"].as_array().ok_or("no tensors")? { - let tname = t[0].as_str().ok_or("tensor name")?.to_string(); - let shape: Vec = - t[1].as_array().ok_or("tensor shape")?.iter().map(|v| v.as_u64().unwrap_or(0) as usize).collect(); - let n: usize = shape.iter().product(); - if data.len() < n * 4 { - return Err(format!("{tname}: file too short")); - } - let v = data[..n * 4].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); - data = &data[n * 4..]; - tensors.insert(tname, (shape, v)); - } - Ok((header, tensors)) -} - -#[derive(Clone, Debug, Default)] -pub struct LayerNorm { - pub w: Vec, - pub b: Vec, -} - -impl LayerNorm { - #[inline] - fn apply_slice(&self, x: &[f32], y: &mut [f32]) { - let n = x.len() as f32; - let mean = x.iter().sum::() / n; - let var = x.iter().map(|&v| { let d = v - mean; d * d }).sum::() / n; - let inv = 1.0 / (var + 1e-5).sqrt(); - for ((&v, (&w, &b)), dst) in x.iter().zip(self.w.iter().zip(&self.b)).zip(y.iter_mut()) { - *dst = (v - mean) * inv * w + b; - } - } - - fn apply_rows(&self, x: &[f32], rows: usize, y: &mut Vec) { - let d = self.w.len(); - y.resize(rows * d, 0.0); - for r in 0..rows { - self.apply_slice(&x[r * d..(r + 1) * d], &mut y[r * d..(r + 1) * d]); - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct Block { - pub ln1: LayerNorm, - pub qkv: Linear, - pub out: Linear, - pub ln2: LayerNorm, - pub ff1: Linear, - pub ff2: Linear, -} - -#[derive(Clone, Debug)] -pub struct ValMlp { - pub ln: LayerNorm, - pub fc1: Linear, - pub fc2: Linear, -} - -/// Reusable thread-local scratch buffers for `Tx::forward` / `Tx::state` (zero heap allocs in the hot loop). -#[derive(Default)] -struct TxWorkspace { - ent_in_buf: Vec, - x: Vec, - norm: Vec, - qkv: Vec, - att: Vec, - ff: Vec, - scores: Vec, - act_in_buf: Vec, - act: Vec, - act_norm: Vec, - act_q: Vec, - act_kv: Vec, - act_att: Vec, - act_bias: Vec, - tmp1: Vec, - tmp2: Vec, - tmp3: Vec, -} - -thread_local! { - static TX_WS: RefCell = RefCell::new(TxWorkspace::default()); -} - -/// The transformer network (#400 R2; `rust/rl/model.py` `Tx`): a global token and one per entity through pre-norm -/// self-attention blocks, then each candidate attending to the tokens once. -#[derive(Clone, Debug, Default)] -pub struct Tx { - pub name: String, - pub emb: Vec, - pub dim: usize, - pub d: usize, - pub heads: usize, - pub gelu: bool, - pub glob_f: usize, - pub rel_bias: Option>, - pub act_ent: bool, - pub ent_in: Linear, - pub glob_in: Linear, - pub blocks: Vec, - pub ln_f: LayerNorm, - pub trunk1: Linear, - pub value: Option, - pub val_mlp: Option, - pub belief: Linear, - pub act_in: Linear, - pub act_ln: LayerNorm, - pub act_q: Linear, - pub act_kv: Linear, - pub act_o: Linear, - pub act_ff: Linear, - pub query: Linear, - pub abias: Linear, -} - -/// Flat multi-head attention reading strided Q, K, V directly from buffers (`qkv` or `act_q`/`act_kv`). -#[allow(clippy::too_many_arguments)] -fn attend_strided( - q: &[f32], - q_stride: usize, - q_off: usize, - nq: usize, - k: &[f32], - k_stride: usize, - k_off: usize, - v: &[f32], - v_stride: usize, - v_off: usize, - nk: usize, - d: usize, - heads: usize, - rel: Option<(&[u8], &[u8], &[f32])>, - out: &mut Vec, - scores: &mut Vec, -) { - let hd = d / heads; - let scale = 1.0 / (hd as f32).sqrt(); - out.resize(nq * d, 0.0); - out.fill(0.0); - scores.resize(nk, 0.0); - for qi in 0..nq { - let q_base = qi * q_stride + q_off; - let out_base = qi * d; - for h in 0..heads { - let ho = h * hd; - let qr = &q[q_base + ho..q_base + ho + hd]; - let mut m = f32::MIN; - for j in 0..nk { - let kr = &k[j * k_stride + k_off + ho..j * k_stride + k_off + ho + hd]; - let s = dot(qr, kr) * scale; - scores[j] = s; - m = m.max(s); - } - if let Some((r_idx, r_typ, rb)) = rel { - if qi >= 1 { - let k_ent = qi - 1; - let ne = r_idx.len().min(nk.saturating_sub(1)); - if k_ent < ne { - let rt = r_typ[k_ent] as usize; - if rt >= 1 && rt <= NUM_REL_TYPES { - let tgt = r_idx[k_ent] as usize; - if tgt < ne { - let j = 1 + tgt; - scores[j] += rb[(rt - 1) * heads + h]; - m = m.max(scores[j]); - } - } - for j_ent in 0..ne { - let rt = r_typ[j_ent] as usize; - if rt >= 1 && rt <= NUM_REL_TYPES && r_idx[j_ent] as usize == k_ent { - let j = 1 + j_ent; - scores[j] += rb[(NUM_REL_TYPES + rt - 1) * heads + h]; - m = m.max(scores[j]); - } - } - } - } - } - let mut z = 0.0f32; - for s in scores.iter_mut() { - *s = (*s - m).exp(); - z += *s; - } - let inv_z = 1.0 / z; - let o = &mut out[out_base + ho..out_base + ho + hd]; - for j in 0..nk { - let p = scores[j] * inv_z; - let vr = &v[j * v_stride + v_off + ho..j * v_stride + v_off + ho + hd]; - for (oo, &vv) in o.iter_mut().zip(vr) { - *oo += p * vv; - } - } - } - } -} - -fn take_linear(t: &mut Tensors, b: &str) -> Result { - let (ws, w) = t.remove(&format!("{b}.weight")).ok_or(format!("no {b}.weight"))?; - let (_, bb) = t.remove(&format!("{b}.bias")).ok_or(format!("no {b}.bias"))?; - Ok(Linear::new(w, bb, ws[0], ws[1])) -} - -fn take_norm(t: &mut Tensors, b: &str) -> Result { - let (_, w) = t.remove(&format!("{b}.weight")).ok_or(format!("no {b}.weight"))?; - let (_, bb) = t.remove(&format!("{b}.bias")).ok_or(format!("no {b}.bias"))?; - Ok(LayerNorm { w, b: bb }) -} - -impl Tx { - pub fn parse(name: &str, bytes: &[u8]) -> Result { - let (header, mut t) = read(bytes)?; - let cfg = &header["config"]; - let d = cfg["d"].as_u64().ok_or("no d")? as usize; - let heads = cfg["heads"].as_u64().ok_or("no heads")? as usize; - let layers = cfg["layers"].as_u64().ok_or("no layers")? as usize; - let gelu = cfg["gelu"].as_u64().unwrap_or(0) != 0; - let use_val_mlp = cfg["val_mlp"].as_u64().unwrap_or(0) != 0; - let use_rel = cfg["rel"].as_u64().unwrap_or(0) != 0; - let act_ent = cfg["act_ent"].as_u64().unwrap_or(0) != 0; - let t = &mut t; - let mut blocks = Vec::new(); - for i in 0..layers { - let p = format!("blocks.{i}"); - blocks.push(Block { - ln1: take_norm(t, &format!("{p}.ln1"))?, - qkv: take_linear(t, &format!("{p}.qkv"))?, - out: take_linear(t, &format!("{p}.out"))?, - ln2: take_norm(t, &format!("{p}.ln2"))?, - ff1: take_linear(t, &format!("{p}.ff1"))?, - ff2: take_linear(t, &format!("{p}.ff2"))?, - }); - } - let (es, emb) = t.remove("emb.weight").ok_or("no emb.weight")?; - let rel_bias = if use_rel { - let (rs, rb) = t.remove("rel_bias").ok_or("no rel_bias")?; - if rs != vec![2 * NUM_REL_TYPES, heads] { - return Err(format!("{name}: bad rel_bias shape {rs:?}")); - } - Some(rb) - } else { - None - }; - let (value, val_mlp) = if use_val_mlp { - ( - None, - Some(ValMlp { - ln: take_norm(t, "val_ln")?, - fc1: take_linear(t, "val_fc1")?, - fc2: take_linear(t, "val_fc2")?, - }), - ) - } else { - (Some(take_linear(t, "value")?), None) - }; - let glob_in = take_linear(t, "glob_in")?; - let glob_f = glob_in.inp; - let net = Tx { - name: name.to_string(), - emb, - dim: es[1], - d, - heads, - gelu, - glob_f, - rel_bias, - act_ent, - ent_in: take_linear(t, "ent_in")?, - glob_in, - blocks, - ln_f: take_norm(t, "ln_f")?, - trunk1: take_linear(t, "trunk1")?, - value, - val_mlp, - belief: take_linear(t, "belief")?, - act_in: take_linear(t, "act_in")?, - act_ln: take_norm(t, "act_ln")?, - act_q: take_linear(t, "act_q")?, - act_kv: take_linear(t, "act_kv")?, - act_o: take_linear(t, "act_o")?, - act_ff: take_linear(t, "act_ff")?, - query: take_linear(t, "query")?, - abias: take_linear(t, "abias")?, - }; - let want_act = net.dim + ACT_F + if net.act_ent { net.d } else { 0 }; - if net.ent_in.inp != net.dim + ENT_F || (net.glob_f != GLOB_F && net.glob_f != GLOB_F_V1) || net.act_in.inp != want_act { - return Err(format!("{name}: made for other features than this build's")); - } - Ok(net) - } - - #[inline] - fn embedding(&self, id: u32) -> &[f32] { - let i = (id as usize).min(self.emb.len() / self.dim - 1); - &self.emb[i * self.dim..(i + 1) * self.dim] - } - - /// Runs the transformer encoder into `ws.norm` (shape `[1 + n_ents, d]`), returning `nt = 1 + n_ents`. - fn run_tokens(&self, o: &Obs, ws: &mut TxWorkspace) -> usize { - let n_ents = o.n_ents(); - let nt = 1 + n_ents; - let d = self.d; - ws.x.resize(nt * d, 0.0); - // Row 0: global token (slice/pad to self.glob_f so v1=65 and v2=81 models both work) - let mut gbuf = [0f32; GLOB_F]; - let gn = self.glob_f.min(o.glob.len()); - gbuf[..gn].copy_from_slice(&o.glob[..gn]); - self.glob_in.apply_act(&gbuf[..self.glob_f], &mut ws.tmp1, false, false); - ws.x[..d].copy_from_slice(&ws.tmp1); - // Rows 1..nt: entity tokens (when an Obs v2 81-glob obs is fed to a legacy v1 glob_f=65 model, skip - // graveyard/exile tokens that v1 never saw during training, while keeping legacy 65-glob parity fixtures exact) - let v1_filter = self.glob_f == GLOB_F_V1 && o.glob.len() > GLOB_F_V1; - let mut kept = 0usize; - if n_ents > 0 { - let ein = self.dim + ENT_F; - ws.ent_in_buf.clear(); - ws.ent_in_buf.reserve(n_ents * ein); - for i in 0..n_ents { - let ef = &o.ents[i * ENT_F..(i + 1) * ENT_F]; - if v1_filter && (ef[4] > 0.5 || ef[5] > 0.5) { - continue; - } - ws.ent_in_buf.extend_from_slice(self.embedding(o.ent_ids[i])); - ws.ent_in_buf.extend_from_slice(ef); - kept += 1; - } - if kept > 0 { - self.ent_in.matmul_rows(&ws.ent_in_buf, kept, &mut ws.tmp2, false, false, false); - ws.x.resize((1 + kept) * d, 0.0); - ws.x[d..(1 + kept) * d].copy_from_slice(&ws.tmp2); - } else { - ws.x.resize(d, 0.0); - } - } - let nt = 1 + kept; - let rel = self.rel_bias.as_deref().and_then(|rb| { - if o.ent_rel_idx.len() == n_ents && o.ent_rel_type.len() == n_ents { - Some((o.ent_rel_idx.as_slice(), o.ent_rel_type.as_slice(), rb)) - } else { - None - } - }); - for b in &self.blocks { - b.ln1.apply_rows(&ws.x, nt, &mut ws.norm); - b.qkv.matmul_rows(&ws.norm, nt, &mut ws.qkv, false, false, false); - attend_strided( - &ws.qkv, - 3 * d, - 0, - nt, - &ws.qkv, - 3 * d, - d, - &ws.qkv, - 3 * d, - 2 * d, - nt, - d, - self.heads, - rel, - &mut ws.att, - &mut ws.scores, - ); - b.out.matmul_rows(&ws.att, nt, &mut ws.x, false, false, true); - b.ln2.apply_rows(&ws.x, nt, &mut ws.norm); - b.ff1.matmul_rows(&ws.norm, nt, &mut ws.ff, true, self.gelu, false); - b.ff2.matmul_rows(&ws.ff, nt, &mut ws.x, false, false, true); - } - self.ln_f.apply_rows(&ws.x, nt, &mut ws.norm); - nt - } - - /// Computes state `h` and value logit from final normed tokens in `ws.norm` (`[nt, d]`). - fn run_head(&self, o: &Obs, nt: usize, ws: &mut TxWorkspace) -> (Vec, f32) { - let d = self.d; - let t = &ws.norm; - let n_ents = nt - 1; - ws.tmp1.resize(2 * d, 0.0); - ws.tmp1[..d].copy_from_slice(&t[..d]); - let mean = &mut ws.tmp1[d..2 * d]; - mean.fill(0.0); - if n_ents > 0 { - let inv = 1.0 / n_ents as f32; - for i in 1..nt { - let row = &t[i * d..(i + 1) * d]; - for (m, &r) in mean.iter_mut().zip(row) { - *m += r * inv; - } - } - } - let mut h = Vec::with_capacity(self.trunk1.out); - self.trunk1.apply_act(&ws.tmp1, &mut h, true, self.gelu); - let value = if let Some(vm) = &self.val_mlp { - let vin = 3 * d + self.glob_f; - ws.tmp2.resize(vin, 0.0); - ws.tmp2[..2 * d].copy_from_slice(&ws.tmp1[..2 * d]); - let mx = &mut ws.tmp2[2 * d..3 * d]; - if n_ents > 0 { - mx.copy_from_slice(&t[d..2 * d]); - for i in 2..nt { - let row = &t[i * d..(i + 1) * d]; - for (m, &r) in mx.iter_mut().zip(row) { - if r > *m { - *m = r; - } - } - } - } else { - mx.fill(0.0); - } - let gn = self.glob_f.min(o.glob.len()); - ws.tmp2[3 * d..3 * d + gn].copy_from_slice(&o.glob[..gn]); - if gn < self.glob_f { - ws.tmp2[3 * d + gn..vin].fill(0.0); - } - ws.tmp3.resize(vin, 0.0); - vm.ln.apply_slice(&ws.tmp2, &mut ws.tmp3); - vm.fc1.apply_act(&ws.tmp3, &mut ws.tmp1, true, self.gelu); - vm.fc2.apply_act(&ws.tmp1, &mut ws.tmp2, false, false); - ws.tmp2[0] - } else { - self.value.as_ref().unwrap().apply_act(&h, &mut ws.tmp2, false, false); - ws.tmp2[0] - }; - (h, value) - } - - pub fn state(&self, o: &Obs) -> (Vec, f32) { - TX_WS.with(|cell| { - let mut guard = cell.borrow_mut(); - let ws = &mut *guard; - let nt = self.run_tokens(o, ws); - self.run_head(o, nt, ws) - }) - } - - pub fn forward(&self, o: &Obs) -> Output { - TX_WS.with(|cell| { - let mut guard = cell.borrow_mut(); - let ws = &mut *guard; - let nt = self.run_tokens(o, ws); - let (h, value) = self.run_head(o, nt, ws); - let na = o.n_acts(); - if na == 0 { - return Output { logits: Vec::new(), value, h }; - } - let d = self.d; - // Key/Value over all tokens - self.act_kv.matmul_rows(&ws.norm, nt, &mut ws.act_kv, false, false, false); - // Query from state h - self.query.apply_act(&h, &mut ws.tmp1, false, false); - // Action inputs (optionally concatenated with contextualized entity token `ws.norm[1 + act_ent_idx[i]]`) - let n_ents = nt - 1; - let ain = self.dim + ACT_F + if self.act_ent { d } else { 0 }; - ws.act_in_buf.resize(na * ain, 0.0); - for i in 0..na { - let dst = &mut ws.act_in_buf[i * ain..(i + 1) * ain]; - dst[..self.dim].copy_from_slice(self.embedding(o.act_ids[i])); - dst[self.dim..self.dim + ACT_F].copy_from_slice(&o.acts[i * ACT_F..(i + 1) * ACT_F]); - if self.act_ent { - let ei = o.act_ent_idx.get(i).copied().unwrap_or(NO_ENT) as usize; - let ctx = &mut dst[self.dim + ACT_F..]; - if ei < n_ents { - ctx.copy_from_slice(&ws.norm[(1 + ei) * d..(2 + ei) * d]); - } else { - ctx.fill(0.0); - } - } - } - self.act_in.matmul_rows(&ws.act_in_buf, na, &mut ws.act, false, false, false); - self.act_ln.apply_rows(&ws.act, na, &mut ws.act_norm); - self.act_q.matmul_rows(&ws.act_norm, na, &mut ws.act_q, false, false, false); - attend_strided( - &ws.act_q, - d, - 0, - na, - &ws.act_kv, - 2 * d, - 0, - &ws.act_kv, - 2 * d, - d, - nt, - d, - self.heads, - None, - &mut ws.act_att, - &mut ws.scores, - ); - self.act_o.matmul_rows(&ws.act_att, na, &mut ws.act, false, false, true); - // Residual FFN: a = a + act(act_ff(a)) - self.act_ff.matmul_rows(&ws.act, na, &mut ws.act_norm, true, self.gelu, false); - for (dst, &u) in ws.act.iter_mut().zip(&ws.act_norm) { - *dst += u; - } - self.abias.matmul_rows(&ws.act, na, &mut ws.act_bias, false, false, false); - let mut logits = Vec::with_capacity(na); - for i in 0..na { - logits.push(dot(&ws.tmp1, &ws.act[i * d..(i + 1) * d]) + ws.act_bias[i]); - } - Output { logits, value, h } - }) - } - - pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { - let mut q = Vec::new(); - self.belief.apply_act(h, &mut q, false, false); - cards.iter().map(|c| dot(self.embedding(*c), &q)).collect() - } -} - -struct PendingReq { - obs: Obs, - reply: Arc<(Mutex>, Condvar)>, -} - -struct BatchQueue { - reqs: Vec, - closed: bool, -} - -/// Batched TCP client for `rust/rl/infer_server.py` (GPU-accelerated self-play). -pub struct RemoteNet { - pub name: String, - queue: Arc<(Mutex, Condvar)>, - emb: Vec, - dim: usize, - belief: Option, -} - -impl std::fmt::Debug for RemoteNet { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("RemoteNet").field("name", &self.name).field("dim", &self.dim).finish() - } -} - -fn read_u32(s: &mut TcpStream) -> std::io::Result { - let mut b = [0u8; 4]; - s.read_exact(&mut b)?; - Ok(u32::from_le_bytes(b)) -} - -fn read_f32s(s: &mut TcpStream, n: usize) -> std::io::Result> { - let mut bytes = vec![0u8; n * 4]; - s.read_exact(&mut bytes)?; - Ok(bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()) -} - -impl RemoteNet { - pub fn connect(url: &str) -> Result { - let addr = url.strip_prefix("tcp://").ok_or("expected tcp://host:port")?; - let mut stream = TcpStream::connect(addr).map_err(|e| format!("{url}: {e}"))?; - stream.set_nodelay(true).ok(); - let dim = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; - let buckets = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; - let trunk = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; - let mut has_b = [0u8; 1]; - stream.read_exact(&mut has_b).map_err(|e| format!("{url} handshake: {e}"))?; - let (emb, belief) = if has_b[0] != 0 { - let emb = read_f32s(&mut stream, buckets * dim).map_err(|e| format!("{url} emb: {e}"))?; - let bw = read_f32s(&mut stream, dim * trunk).map_err(|e| format!("{url} bw: {e}"))?; - let bb = read_f32s(&mut stream, dim).map_err(|e| format!("{url} bb: {e}"))?; - (emb, Some(Linear::new(bw, bb, dim, trunk))) - } else { - (Vec::new(), None) - }; - - let queue = Arc::new((Mutex::new(BatchQueue { reqs: Vec::new(), closed: false }), Condvar::new())); - let q_bg = Arc::clone(&queue); - let max_batch: usize = std::env::var("PLAYMAT_GPU_BATCH").ok().and_then(|v| v.parse().ok()).unwrap_or(64); - // Default 0: never call wait_timeout on Windows (where sub-15.6ms sleeps round up to 15.6ms!); - // natural coalescing happens while the previous GPU batch is in flight. - let wait_us: u64 = std::env::var("PLAYMAT_GPU_WAIT_US").ok().and_then(|v| v.parse().ok()).unwrap_or(0); - - std::thread::spawn(move || { - let mut payload = Vec::::with_capacity(2 << 20); - let mut resp_buf = Vec::::with_capacity(1 << 18); - loop { - let batch = { - let (lock, cv) = &*q_bg; - let mut g = lock.lock().unwrap(); - while g.reqs.is_empty() && !g.closed { - g = cv.wait(g).unwrap(); - } - if g.reqs.is_empty() && g.closed { - break; - } - if g.reqs.len() < max_batch && wait_us > 0 { - let deadline = Instant::now() + Duration::from_micros(wait_us); - while g.reqs.len() < max_batch && !g.closed { - let rem = deadline.saturating_duration_since(Instant::now()); - if rem.is_zero() { - break; - } - let (ng, to) = cv.wait_timeout(g, rem).unwrap(); - g = ng; - if to.timed_out() { - break; - } - } - } - let take = g.reqs.len().min(max_batch); - g.reqs.drain(..take).collect::>() - }; - - let b = batch.len(); - let max_e = batch.iter().map(|r| r.obs.n_ents()).max().unwrap_or(0); - let max_a = batch.iter().map(|r| r.obs.n_acts()).max().unwrap_or(0); - let w_e = ((max_e + 7) / 8 * 8).max(8); - let w_a = ((max_a + 3) / 4 * 4).max(4); - - // Pre-pack 10 flat contiguous arrays so Python infer_server.py runs with ZERO Python loops - let glob_bytes = b * GLOB_F * 4; - let eids_bytes = b * w_e * 2; - let ents_bytes = b * w_e * ENT_F * 4; - let em_bytes = b * w_e; - let eridx_bytes = b * w_e; - let ertyp_bytes = b * w_e; - let aids_bytes = b * w_a * 2; - let acts_bytes = b * w_a * ACT_F * 4; - let am_bytes = b * w_a; - let aent_bytes = b * w_a; - let total_bytes = 12 - + glob_bytes - + eids_bytes - + ents_bytes - + em_bytes - + eridx_bytes - + ertyp_bytes - + aids_bytes - + acts_bytes - + am_bytes - + aent_bytes; - payload.clear(); - payload.resize(total_bytes, 0); - payload[0..4].copy_from_slice(&(b as u32).to_le_bytes()); - payload[4..8].copy_from_slice(&(w_e as u32).to_le_bytes()); - payload[8..12].copy_from_slice(&(w_a as u32).to_le_bytes()); - - let o_glob = 12; - let o_eids = o_glob + glob_bytes; - let o_ents = o_eids + eids_bytes; - let o_em = o_ents + ents_bytes; - let o_eridx = o_em + em_bytes; - let o_ertyp = o_eridx + eridx_bytes; - let o_aids = o_ertyp + ertyp_bytes; - let o_acts = o_aids + aids_bytes; - let o_am = o_acts + acts_bytes; - let o_aent = o_am + am_bytes; - // Default sentinel NO_ENT (255) for entity/action indices - payload[o_eridx..o_eridx + eridx_bytes].fill(NO_ENT); - payload[o_aent..o_aent + aent_bytes].fill(NO_ENT); - - for (i, req) in batch.iter().enumerate() { - let o = &req.obs; - // glob - let gd = &mut payload[o_glob + i * GLOB_F * 4..o_glob + (i + 1) * GLOB_F * 4]; - for (k, &v) in o.glob.iter().take(GLOB_F).enumerate() { - gd[k * 4..(k + 1) * 4].copy_from_slice(&v.to_le_bytes()); - } - // entities - let ne = o.n_ents().min(w_e); - if ne > 0 { - let id_base = o_eids + i * w_e * 2; - for k in 0..ne { - payload[id_base + k * 2..id_base + k * 2 + 2] - .copy_from_slice(&(o.ent_ids[k] as u16).to_le_bytes()); - } - let ef_base = o_ents + i * w_e * ENT_F * 4; - for (k, &v) in o.ents[..ne * ENT_F].iter().enumerate() { - payload[ef_base + k * 4..ef_base + k * 4 + 4].copy_from_slice(&v.to_le_bytes()); - } - let em_base = o_em + i * w_e; - payload[em_base..em_base + ne].fill(1); - if o.ent_rel_idx.len() >= ne && o.ent_rel_type.len() >= ne { - payload[o_eridx + i * w_e..o_eridx + i * w_e + ne].copy_from_slice(&o.ent_rel_idx[..ne]); - payload[o_ertyp + i * w_e..o_ertyp + i * w_e + ne].copy_from_slice(&o.ent_rel_type[..ne]); - } - } - // actions - let na = o.n_acts().min(w_a); - if na > 0 { - let id_base = o_aids + i * w_a * 2; - for k in 0..na { - payload[id_base + k * 2..id_base + k * 2 + 2] - .copy_from_slice(&(o.act_ids[k] as u16).to_le_bytes()); - } - let af_base = o_acts + i * w_a * ACT_F * 4; - for (k, &v) in o.acts[..na * ACT_F].iter().enumerate() { - payload[af_base + k * 4..af_base + k * 4 + 4].copy_from_slice(&v.to_le_bytes()); - } - let am_base = o_am + i * w_a; - payload[am_base..am_base + na].fill(1); - if o.act_ent_idx.len() >= na { - payload[o_aent + i * w_a..o_aent + i * w_a + na].copy_from_slice(&o.act_ent_idx[..na]); - } - } - } - if stream.write_all(&payload).is_err() { - break; - } - let Ok(rb) = read_u32(&mut stream) else { break }; - let Ok(rtrunk) = read_u32(&mut stream) else { break }; - debug_assert_eq!(rb as usize, b); - let trunk = rtrunk as usize; - let need = (b + b * w_a + b * trunk) * 4; - resp_buf.resize(need, 0); - if stream.read_exact(&mut resp_buf).is_err() { - break; - } - let floats: Vec = resp_buf.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); - let vs = &floats[..b]; - let all_logits = &floats[b..b + b * w_a]; - let all_h = &floats[b + b * w_a..]; - for (i, req) in batch.into_iter().enumerate() { - let na = req.obs.n_acts().min(w_a); - let logits = all_logits[i * w_a..i * w_a + na].to_vec(); - let h = all_h[i * trunk..(i + 1) * trunk].to_vec(); - let (rlock, rcv) = &*req.reply; - *rlock.lock().unwrap() = Some(Output { logits, value: vs[i], h }); - rcv.notify_one(); - } - } - }); - - Ok(RemoteNet { name: url.to_string(), queue, emb, dim, belief }) - } - - pub fn forward(&self, o: &Obs) -> Output { - let reply = Arc::new((Mutex::new(None), Condvar::new())); - { - let (lock, cv) = &*self.queue; - let mut g = lock.lock().unwrap(); - g.reqs.push(PendingReq { obs: o.clone(), reply: Arc::clone(&reply) }); - cv.notify_one(); - } - let (rlock, rcv) = &*reply; - let mut rg = rlock.lock().unwrap(); - while rg.is_none() { - rg = rcv.wait(rg).unwrap(); - } - rg.take().unwrap() - } - - pub fn state(&self, o: &Obs) -> (Vec, f32) { - let out = self.forward(o); - (out.h, out.value) - } - - pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { - let Some(bl) = &self.belief else { return vec![0.0; cards.len()] }; - let mut q = Vec::new(); - bl.apply(h, &mut q, false); - let n_emb = self.emb.len() / self.dim.max(1); - cards - .iter() - .map(|c| { - let i = (*c as usize).min(n_emb.saturating_sub(1)); - dot(&self.emb[i * self.dim..(i + 1) * self.dim], &q) - }) - .collect() - } -} - -/// A network: the first, pooled one, the transformer, or a GPU-batched remote server (`tcp://...`) -#[derive(Clone, Debug)] -pub enum Net { - Mlp(Mlp), - Tx(Tx), - Remote(Arc), -} - -impl Net { - /// Reads a `.pmnet` file's bytes (the header's `arch` says which network) - pub fn parse(name: &str, bytes: &[u8]) -> Result { - let (header, _) = read(bytes)?; - if header["arch"].as_str() == Some("tx") { - Ok(Net::Tx(Tx::parse(name, bytes)?)) - } else { - Ok(Net::Mlp(Mlp::parse(name, bytes)?)) - } - } - - pub fn name(&self) -> &str { - match self { - Net::Mlp(n) => &n.name, - Net::Tx(n) => &n.name, - Net::Remote(n) => &n.name, - } - } - - /// The state `h` and the value - pub fn state(&self, o: &Obs) -> (Vec, f32) { - match self { - Net::Mlp(n) => n.state(o), - Net::Tx(n) => n.state(o), - Net::Remote(n) => n.state(o), - } - } - - /// Every action's logit, and the value - pub fn forward(&self, o: &Obs) -> Output { - match self { - Net::Mlp(n) => n.forward(o), - Net::Tx(n) => n.forward(o), - Net::Remote(n) => n.forward(o), - } - } - - pub fn has_belief(&self) -> bool { - match self { - Net::Mlp(n) => n.belief.is_some(), - Net::Tx(_) => true, - Net::Remote(n) => n.belief.is_some(), - } - } - - /// Each card's logit of being in the opponent's hand - pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { - match self { - Net::Mlp(n) => n.belief(h, cards), - Net::Tx(n) => n.belief(h, cards), - Net::Remote(n) => n.belief(h, cards), - } - } -} - -/// Softmax of `logits / temp` -pub fn softmax(logits: &[f32], temp: f32) -> Vec { - let t = temp.max(1e-3); - let m = logits.iter().copied().fold(f32::MIN, f32::max); - let e: Vec = logits.iter().map(|l| ((l - m) / t).exp()).collect(); - let s: f32 = e.iter().sum(); - e.iter().map(|v| v / s).collect() -} - -static CACHE: OnceLock>>> = OnceLock::new(); - -/// The network at `path`, read once per process (`builtin`: shipped net; `tcp://host:port`: GPU inference server) -pub fn load(path: &str) -> Result, String> { - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - // Hold the cache lock while loading/connecting so `--jobs 64` worker threads share ONE RemoteNet - // TCP connection and coalesce into true B=32..64 GPU batches instead of opening 64 separate B=1 sockets! - let mut map = cache.lock().unwrap(); - if let Some(n) = map.get(path) { - return Ok(Arc::clone(n)); - } - let net = if path == "builtin" { - Net::parse("builtin", BUILTIN)? - } else if path.starts_with("tcp://") { - Net::Remote(Arc::new(RemoteNet::connect(path)?)) - } else { - let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; - Net::parse(path, &bytes)? - }; - let net = Arc::new(net); - map.insert(path.to_string(), Arc::clone(&net)); - Ok(net) -} - -/// The network this build ships (`rust/rl` writes it): what `net=builtin` and an unset `Config::net` load -pub const BUILTIN: &[u8] = include_bytes!("net.pmnet"); - -/// The net a config names (`Config::net`, else the built-in one) -pub fn of(net: &Option) -> Arc { - let path = net.as_deref().unwrap_or("builtin"); - load(path).unwrap_or_else(|e| panic!("AI network: {e}")) -} - -/// The value head as a score on the fitted score's scale (a logit times 1000), `WIN`/`LOSE` for a finished game -pub fn score(net: &Net, game: &playmat_engine::state::Game, seat: playmat_engine::state::Seat) -> i64 { - let over = crate::eval::evaluate(game, seat); - if over >= crate::eval::WIN || over <= crate::eval::LOSE { - return over; - } - let q = playmat_engine::decide::Query::Priority { playable: Vec::new() }; - let o = obs::observe(game, seat, &q, &[]); - (net.state(&o).1 as f64 * 1000.0).clamp(-30_000.0, 30_000.0) as i64 -} +//! A small policy and value network, run on the CPU in plain Rust (#390 Track B). Trained by `rust/rl` (PyTorch), +//! written as a `.pmnet` file: one line of JSON naming each tensor and its shape, then the tensors as little-endian +//! f32 in that order. +//! +//! Fast CPU execution: +//! - Linear weights are repacked at load time into `[out_blocks, inp, 8]` panels (`wp`) for a 4x8 register-blocked +//! SIMD GEMM (`matmul_rows`) that vectorizes cleanly to AVX2 FMA on x86_64 and NEON FMLA on ARM64 without horizontal +//! reductions. +//! - `Tx::forward` and `Tx::state` reuse a thread-local flat `TxWorkspace` (zero per-layer heap allocations and no +//! `Vec>` Q/K/V copies). +//! - Supports both v1 `Tx` checkpoints (ReLU + linear value head) and upgraded `Tx` checkpoints (`val_mlp=1` dedicated +//! 2-layer value head reading `[t0, mean_ent, max_ent, glob]`, and `gelu=1` tanh-approx GELU). + +use crate::obs::{self, Obs, ACT_F, ENT_F, GLOB_F, GLOB_F_V1, GLOB_F_V2, NO_ENT, NUM_REL_TYPES}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +#[inline(always)] +fn act_val(x: f32, gelu: bool) -> f32 { + if gelu { + // Matches PyTorch F.gelu(x, approximate="tanh") + const K: f32 = 0.797_884_6; // sqrt(2 / pi) + 0.5 * x * (1.0 + (K * (x + 0.044_715 * x * x * x)).tanh()) + } else { + x.max(0.0) + } +} + +/// A dense layer: `w` is `[out][in]` flat, plus `wp` repacked into `[out/8][in][8]` panels for 4x8 SIMD GEMM. +#[derive(Clone, Debug, Default)] +pub struct Linear { + pub w: Vec, + pub b: Vec, + pub inp: usize, + pub out: usize, + /// Repacked weights: `blocks = out / 8` panels of `inp * 8` floats (contiguous 8 output lanes per `k`). + wp: Vec, +} + +impl Linear { + pub fn new(w: Vec, b: Vec, out: usize, inp: usize) -> Linear { + let blocks = out / 8; + let mut wp = vec![0f32; blocks * inp * 8]; + for blk in 0..blocks { + let ob = blk * 8; + let dst_blk = &mut wp[blk * inp * 8..(blk + 1) * inp * 8]; + for k in 0..inp { + let dst = &mut dst_blk[k * 8..(k + 1) * 8]; + for j in 0..8 { + dst[j] = w[(ob + j) * inp + k]; + } + } + } + Linear { w, b, inp, out, wp } + } + + /// Single-row apply into `y` (`y` resized to `self.out`). + #[inline] + fn apply(&self, x: &[f32], y: &mut Vec, relu: bool) { + self.apply_act(x, y, relu, false); + } + + fn apply_act(&self, x: &[f32], y: &mut Vec, do_act: bool, gelu: bool) { + debug_assert_eq!(x.len(), self.inp); + y.resize(self.out, 0.0); + let inp = self.inp; + let blocks = self.out / 8; + for blk in 0..blocks { + let ob = blk * 8; + let mut acc = [ + self.b[ob], + self.b[ob + 1], + self.b[ob + 2], + self.b[ob + 3], + self.b[ob + 4], + self.b[ob + 5], + self.b[ob + 6], + self.b[ob + 7], + ]; + let panel = &self.wp[blk * inp * 8..(blk + 1) * inp * 8]; + for (k, &xk) in x.iter().enumerate() { + let w = &panel[k * 8..(k + 1) * 8]; + for j in 0..8 { + acc[j] += xk * w[j]; + } + } + if do_act { + for j in 0..8 { + y[ob + j] = act_val(acc[j], gelu); + } + } else { + y[ob..ob + 8].copy_from_slice(&acc); + } + } + for o in blocks * 8..self.out { + let row = &self.w[o * inp..(o + 1) * inp]; + let s = self.b[o] + dot(row, x); + y[o] = if do_act { act_val(s, gelu) } else { s }; + } + } + + /// Flat batched matmul: `x` is `[rows, inp]`, writes `y` as `[rows, out]`. + /// Uses `matrixmultiply::sgemm` (AVX2+FMA / NEON cache-blocked microkernels) for multi-row projections, + /// and the packed 8-lane kernel for single rows. + fn matmul_rows(&self, x: &[f32], rows: usize, y: &mut Vec, do_act: bool, gelu: bool, add_to_y: bool) { + let inp = self.inp; + let out = self.out; + debug_assert_eq!(x.len(), rows * inp); + if rows == 0 { + if !add_to_y { + y.clear(); + } + return; + } + if rows == 1 && !add_to_y { + self.apply_act(x, y, do_act, gelu); + return; + } + if !add_to_y { + y.resize(rows * out, 0.0); + } else { + debug_assert_eq!(y.len(), rows * out); + debug_assert!(!do_act, "add_to_y with activation not supported"); + } + let beta = if add_to_y { 1.0 } else { 0.0 }; + unsafe { + matrixmultiply::sgemm( + rows, + inp, + out, + 1.0, + x.as_ptr(), + inp as isize, + 1, + self.w.as_ptr(), + 1, + inp as isize, + beta, + y.as_mut_ptr(), + out as isize, + 1, + ); + } + if do_act { + if gelu { + for r in 0..rows { + let row = &mut y[r * out..(r + 1) * out]; + for (dst, &b) in row.iter_mut().zip(&self.b) { + *dst = act_val(*dst + b, true); + } + } + } else { + for r in 0..rows { + let row = &mut y[r * out..(r + 1) * out]; + for (dst, &b) in row.iter_mut().zip(&self.b) { + *dst = (*dst + b).max(0.0); + } + } + } + } else { + for r in 0..rows { + let row = &mut y[r * out..(r + 1) * out]; + for (dst, &b) in row.iter_mut().zip(&self.b) { + *dst += b; + } + } + } + } +} + +/// A dot product in 8 lanes: the compiler vectorizes it (one running sum can't be reordered, so it doesn't) +#[inline] +pub fn dot(a: &[f32], b: &[f32]) -> f32 { + let n = a.len().min(b.len()); + let (a, b) = (&a[..n], &b[..n]); + let mut acc = [0f32; 8]; + let (ac, ar) = a.as_chunks::<8>(); + let (bc, br) = b.as_chunks::<8>(); + for (x, y) in ac.iter().zip(bc) { + for i in 0..8 { + acc[i] += x[i] * y[i]; + } + } + let mut s = acc.iter().sum::(); + for (x, y) in ar.iter().zip(br) { + s += x * y; + } + s +} + +/// The first network (#390): entities pooled by mean and max +#[derive(Debug, Clone)] +pub struct Mlp { + pub name: String, + pub emb: Vec, + pub dim: usize, + pub ent1: Linear, + pub ent2: Linear, + pub glob1: Linear, + pub trunk1: Linear, + pub trunk2: Linear, + pub value: Linear, + pub act1: Linear, + pub act2: Linear, + pub query: Linear, + pub abias: Linear, + pub belief: Option, +} + +/// The network's outputs for one observation +#[derive(Debug, Clone, Default)] +pub struct Output { + /// one logit per action + pub logits: Vec, + /// the logit of the seat winning + pub value: f32, + /// the state, for the belief + pub h: Vec, +} + +impl Mlp { + /// Reads a `.pmnet` file's bytes + pub fn parse(name: &str, bytes: &[u8]) -> Result { + let (_, mut tensors) = read(bytes)?; + let mut take = |base: &str| -> Result { take_linear(&mut tensors, base) }; + let ent1 = take("ent1")?; + let ent2 = take("ent2")?; + let glob1 = take("glob1")?; + let trunk1 = take("trunk1")?; + let trunk2 = take("trunk2")?; + let value = take("value")?; + let act1 = take("act1")?; + let act2 = take("act2")?; + let query = take("query")?; + let abias = take("abias")?; + let belief = take("belief").ok(); + let (es, emb) = tensors.remove("emb.weight").ok_or("no emb.weight")?; + let dim = es[1]; + if ent1.inp != dim + ENT_F || (glob1.inp != GLOB_F && glob1.inp != GLOB_F_V2 && glob1.inp != GLOB_F_V1) || act1.inp != dim + ACT_F { + return Err(format!( + "{name}: made for other features (entity {}, global {}, action {}; this build has {}, {} or {}, {})", + ent1.inp - dim, + glob1.inp, + act1.inp - dim, + ENT_F, + GLOB_F_V1, + GLOB_F, + ACT_F + )); + } + Ok(Mlp { + name: name.to_string(), + emb, + dim, + ent1, + ent2, + glob1, + trunk1, + trunk2, + value, + act1, + act2, + query, + abias, + belief, + }) + } + + fn embedding(&self, id: u32) -> &[f32] { + let i = (id as usize).min(self.emb.len() / self.dim - 1); + &self.emb[i * self.dim..(i + 1) * self.dim] + } + + /// The state `h` and the value + pub fn state(&self, o: &Obs) -> (Vec, f32) { + let h1 = self.ent2.out; + let mut mean = vec![0f32; h1]; + let mut max = vec![0f32; h1]; + let n = o.n_ents(); + let (mut x, mut y, mut z) = (Vec::with_capacity(self.ent1.inp), Vec::new(), Vec::new()); + for i in 0..n { + x.clear(); + x.extend_from_slice(self.embedding(o.ent_ids[i])); + x.extend_from_slice(&o.ents[i * ENT_F..(i + 1) * ENT_F]); + self.ent1.apply(&x, &mut y, true); + self.ent2.apply(&y, &mut z, true); + for k in 0..h1 { + mean[k] += z[k] / n as f32; + max[k] = if i == 0 { z[k] } else { max[k].max(z[k]) }; + } + } + let mut gbuf = [0f32; GLOB_F]; + let gn = self.glob1.inp.min(o.glob.len()); + gbuf[..gn].copy_from_slice(&o.glob[..gn]); + self.glob1.apply(&gbuf[..self.glob1.inp], &mut y, true); + let mut t = mean; + t.extend(max); + t.extend_from_slice(&y); + self.trunk1.apply(&t, &mut y, true); + let mut h = Vec::new(); + self.trunk2.apply(&y, &mut h, true); + self.value.apply(&h, &mut y, false); + (h, y[0]) + } + + /// Every action's logit, and the value + pub fn forward(&self, o: &Obs) -> Output { + let (h, value) = self.state(o); + let mut q = Vec::new(); + self.query.apply(&h, &mut q, false); + let (mut x, mut y, mut a, mut b) = (Vec::with_capacity(self.act1.inp), Vec::new(), Vec::new(), Vec::new()); + let mut logits = Vec::with_capacity(o.n_acts()); + for i in 0..o.n_acts() { + x.clear(); + x.extend_from_slice(self.embedding(o.act_ids[i])); + x.extend_from_slice(&o.acts[i * ACT_F..(i + 1) * ACT_F]); + self.act1.apply(&x, &mut y, true); + self.act2.apply(&y, &mut a, false); + self.abias.apply(&a, &mut b, false); + logits.push(dot(&q, &a) + b[0]); + } + Output { logits, value, h } + } + + /// Each card's logit of being in the opponent's hand, from the state `h` (0 for a net without a belief head) + pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { + let Some(bl) = &self.belief else { return vec![0.0; cards.len()] }; + let mut q = Vec::new(); + bl.apply(h, &mut q, false); + cards.iter().map(|c| dot(self.embedding(*c), &q)).collect() + } +} + +/// A `.pmnet` file's header and tensors by name +type Tensors = HashMap, Vec)>; + +fn read(bytes: &[u8]) -> Result<(serde_json::Value, Tensors), String> { + let nl = bytes.iter().position(|b| *b == b'\n').ok_or("no header line")?; + let header: serde_json::Value = serde_json::from_slice(&bytes[..nl]).map_err(|e| e.to_string())?; + let mut data = &bytes[nl + 1..]; + let mut tensors = HashMap::new(); + for t in header["tensors"].as_array().ok_or("no tensors")? { + let tname = t[0].as_str().ok_or("tensor name")?.to_string(); + let shape: Vec = + t[1].as_array().ok_or("tensor shape")?.iter().map(|v| v.as_u64().unwrap_or(0) as usize).collect(); + let n: usize = shape.iter().product(); + if data.len() < n * 4 { + return Err(format!("{tname}: file too short")); + } + let v = data[..n * 4].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + data = &data[n * 4..]; + tensors.insert(tname, (shape, v)); + } + Ok((header, tensors)) +} + +#[derive(Clone, Debug, Default)] +pub struct LayerNorm { + pub w: Vec, + pub b: Vec, +} + +impl LayerNorm { + #[inline] + fn apply_slice(&self, x: &[f32], y: &mut [f32]) { + let n = x.len() as f32; + let mean = x.iter().sum::() / n; + let var = x.iter().map(|&v| { let d = v - mean; d * d }).sum::() / n; + let inv = 1.0 / (var + 1e-5).sqrt(); + for ((&v, (&w, &b)), dst) in x.iter().zip(self.w.iter().zip(&self.b)).zip(y.iter_mut()) { + *dst = (v - mean) * inv * w + b; + } + } + + fn apply_rows(&self, x: &[f32], rows: usize, y: &mut Vec) { + let d = self.w.len(); + y.resize(rows * d, 0.0); + for r in 0..rows { + self.apply_slice(&x[r * d..(r + 1) * d], &mut y[r * d..(r + 1) * d]); + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct Block { + pub ln1: LayerNorm, + pub qkv: Linear, + pub out: Linear, + pub ln2: LayerNorm, + pub ff1: Linear, + pub ff2: Linear, +} + +#[derive(Clone, Debug)] +pub struct ValMlp { + pub ln: LayerNorm, + pub fc1: Linear, + pub fc2: Linear, +} + +/// Reusable thread-local scratch buffers for `Tx::forward` / `Tx::state` (zero heap allocs in the hot loop). +#[derive(Default)] +struct TxWorkspace { + ent_in_buf: Vec, + x: Vec, + norm: Vec, + qkv: Vec, + att: Vec, + ff: Vec, + scores: Vec, + act_in_buf: Vec, + act: Vec, + act_norm: Vec, + act_q: Vec, + act_kv: Vec, + act_att: Vec, + act_bias: Vec, + tmp1: Vec, + tmp2: Vec, + tmp3: Vec, +} + +thread_local! { + static TX_WS: RefCell = RefCell::new(TxWorkspace::default()); +} + +/// The transformer network (#400 R2; `rust/rl/model.py` `Tx`): a global token and one per entity through pre-norm +/// self-attention blocks, then each candidate attending to the tokens once. +#[derive(Clone, Debug, Default)] +pub struct Tx { + pub name: String, + pub emb: Vec, + pub dim: usize, + pub d: usize, + pub heads: usize, + pub gelu: bool, + pub glob_f: usize, + pub rel_bias: Option>, + pub act_ent: bool, + pub ent_in: Linear, + pub glob_in: Linear, + pub blocks: Vec, + pub ln_f: LayerNorm, + pub trunk1: Linear, + pub value: Option, + pub val_mlp: Option, + pub belief: Linear, + pub act_in: Linear, + pub act_ln: LayerNorm, + pub act_q: Linear, + pub act_kv: Linear, + pub act_o: Linear, + pub act_ff: Linear, + pub query: Linear, + pub abias: Linear, +} + +/// Flat multi-head attention reading strided Q, K, V directly from buffers (`qkv` or `act_q`/`act_kv`). +#[allow(clippy::too_many_arguments)] +fn attend_strided( + q: &[f32], + q_stride: usize, + q_off: usize, + nq: usize, + k: &[f32], + k_stride: usize, + k_off: usize, + v: &[f32], + v_stride: usize, + v_off: usize, + nk: usize, + d: usize, + heads: usize, + rel: Option<(&[u8], &[u8], &[f32])>, + out: &mut Vec, + scores: &mut Vec, +) { + let hd = d / heads; + let scale = 1.0 / (hd as f32).sqrt(); + out.resize(nq * d, 0.0); + out.fill(0.0); + scores.resize(nk, 0.0); + for qi in 0..nq { + let q_base = qi * q_stride + q_off; + let out_base = qi * d; + for h in 0..heads { + let ho = h * hd; + let qr = &q[q_base + ho..q_base + ho + hd]; + let mut m = f32::MIN; + for j in 0..nk { + let kr = &k[j * k_stride + k_off + ho..j * k_stride + k_off + ho + hd]; + let s = dot(qr, kr) * scale; + scores[j] = s; + m = m.max(s); + } + if let Some((r_idx, r_typ, rb)) = rel { + if qi >= 1 { + let k_ent = qi - 1; + let ne = r_idx.len().min(nk.saturating_sub(1)); + if k_ent < ne { + let rt = r_typ[k_ent] as usize; + if rt >= 1 && rt <= NUM_REL_TYPES { + let tgt = r_idx[k_ent] as usize; + if tgt < ne { + let j = 1 + tgt; + scores[j] += rb[(rt - 1) * heads + h]; + m = m.max(scores[j]); + } + } + for j_ent in 0..ne { + let rt = r_typ[j_ent] as usize; + if rt >= 1 && rt <= NUM_REL_TYPES && r_idx[j_ent] as usize == k_ent { + let j = 1 + j_ent; + scores[j] += rb[(NUM_REL_TYPES + rt - 1) * heads + h]; + m = m.max(scores[j]); + } + } + } + } + } + let mut z = 0.0f32; + for s in scores.iter_mut() { + *s = (*s - m).exp(); + z += *s; + } + let inv_z = 1.0 / z; + let o = &mut out[out_base + ho..out_base + ho + hd]; + for j in 0..nk { + let p = scores[j] * inv_z; + let vr = &v[j * v_stride + v_off + ho..j * v_stride + v_off + ho + hd]; + for (oo, &vv) in o.iter_mut().zip(vr) { + *oo += p * vv; + } + } + } + } +} + +fn take_linear(t: &mut Tensors, b: &str) -> Result { + let (ws, w) = t.remove(&format!("{b}.weight")).ok_or(format!("no {b}.weight"))?; + let (_, bb) = t.remove(&format!("{b}.bias")).ok_or(format!("no {b}.bias"))?; + Ok(Linear::new(w, bb, ws[0], ws[1])) +} + +fn take_norm(t: &mut Tensors, b: &str) -> Result { + let (_, w) = t.remove(&format!("{b}.weight")).ok_or(format!("no {b}.weight"))?; + let (_, bb) = t.remove(&format!("{b}.bias")).ok_or(format!("no {b}.bias"))?; + Ok(LayerNorm { w, b: bb }) +} + +impl Tx { + pub fn parse(name: &str, bytes: &[u8]) -> Result { + let (header, mut t) = read(bytes)?; + let cfg = &header["config"]; + let d = cfg["d"].as_u64().ok_or("no d")? as usize; + let heads = cfg["heads"].as_u64().ok_or("no heads")? as usize; + let layers = cfg["layers"].as_u64().ok_or("no layers")? as usize; + let gelu = cfg["gelu"].as_u64().unwrap_or(0) != 0; + let use_val_mlp = cfg["val_mlp"].as_u64().unwrap_or(0) != 0; + let use_rel = cfg["rel"].as_u64().unwrap_or(0) != 0; + let act_ent = cfg["act_ent"].as_u64().unwrap_or(0) != 0; + let t = &mut t; + let mut blocks = Vec::new(); + for i in 0..layers { + let p = format!("blocks.{i}"); + blocks.push(Block { + ln1: take_norm(t, &format!("{p}.ln1"))?, + qkv: take_linear(t, &format!("{p}.qkv"))?, + out: take_linear(t, &format!("{p}.out"))?, + ln2: take_norm(t, &format!("{p}.ln2"))?, + ff1: take_linear(t, &format!("{p}.ff1"))?, + ff2: take_linear(t, &format!("{p}.ff2"))?, + }); + } + let (es, emb) = t.remove("emb.weight").ok_or("no emb.weight")?; + let rel_bias = if use_rel { + let (rs, rb) = t.remove("rel_bias").ok_or("no rel_bias")?; + if rs != vec![2 * NUM_REL_TYPES, heads] { + return Err(format!("{name}: bad rel_bias shape {rs:?}")); + } + Some(rb) + } else { + None + }; + let (value, val_mlp) = if use_val_mlp { + ( + None, + Some(ValMlp { + ln: take_norm(t, "val_ln")?, + fc1: take_linear(t, "val_fc1")?, + fc2: take_linear(t, "val_fc2")?, + }), + ) + } else { + (Some(take_linear(t, "value")?), None) + }; + let glob_in = take_linear(t, "glob_in")?; + let glob_f = glob_in.inp; + let net = Tx { + name: name.to_string(), + emb, + dim: es[1], + d, + heads, + gelu, + glob_f, + rel_bias, + act_ent, + ent_in: take_linear(t, "ent_in")?, + glob_in, + blocks, + ln_f: take_norm(t, "ln_f")?, + trunk1: take_linear(t, "trunk1")?, + value, + val_mlp, + belief: take_linear(t, "belief")?, + act_in: take_linear(t, "act_in")?, + act_ln: take_norm(t, "act_ln")?, + act_q: take_linear(t, "act_q")?, + act_kv: take_linear(t, "act_kv")?, + act_o: take_linear(t, "act_o")?, + act_ff: take_linear(t, "act_ff")?, + query: take_linear(t, "query")?, + abias: take_linear(t, "abias")?, + }; + let want_act = net.dim + ACT_F + if net.act_ent { net.d } else { 0 }; + if net.ent_in.inp != net.dim + ENT_F || (net.glob_f != GLOB_F && net.glob_f != GLOB_F_V2 && net.glob_f != GLOB_F_V1) || net.act_in.inp != want_act { + return Err(format!("{name}: made for other features than this build's")); + } + Ok(net) + } + + #[inline] + fn embedding(&self, id: u32) -> &[f32] { + let i = (id as usize).min(self.emb.len() / self.dim - 1); + &self.emb[i * self.dim..(i + 1) * self.dim] + } + + /// Runs the transformer encoder into `ws.norm` (shape `[1 + n_ents, d]`), returning `nt = 1 + n_ents`. + fn run_tokens(&self, o: &Obs, ws: &mut TxWorkspace) -> usize { + let n_ents = o.n_ents(); + let nt = 1 + n_ents; + let d = self.d; + ws.x.resize(nt * d, 0.0); + // Row 0: global token (slice/pad to self.glob_f so v1=65 and v2=81 models both work) + let mut gbuf = [0f32; GLOB_F]; + let gn = self.glob_f.min(o.glob.len()); + gbuf[..gn].copy_from_slice(&o.glob[..gn]); + self.glob_in.apply_act(&gbuf[..self.glob_f], &mut ws.tmp1, false, false); + ws.x[..d].copy_from_slice(&ws.tmp1); + // Rows 1..nt: entity tokens (when an Obs v2 81-glob obs is fed to a legacy v1 glob_f=65 model, skip + // graveyard/exile tokens that v1 never saw during training, while keeping legacy 65-glob parity fixtures exact) + let v1_filter = self.glob_f == GLOB_F_V1 && o.glob.len() > GLOB_F_V1; + let mut kept = 0usize; + if n_ents > 0 { + let ein = self.dim + ENT_F; + ws.ent_in_buf.clear(); + ws.ent_in_buf.reserve(n_ents * ein); + for i in 0..n_ents { + let ef = &o.ents[i * ENT_F..(i + 1) * ENT_F]; + if v1_filter && (ef[4] > 0.5 || ef[5] > 0.5) { + continue; + } + ws.ent_in_buf.extend_from_slice(self.embedding(o.ent_ids[i])); + ws.ent_in_buf.extend_from_slice(ef); + kept += 1; + } + if kept > 0 { + self.ent_in.matmul_rows(&ws.ent_in_buf, kept, &mut ws.tmp2, false, false, false); + ws.x.resize((1 + kept) * d, 0.0); + ws.x[d..(1 + kept) * d].copy_from_slice(&ws.tmp2); + } else { + ws.x.resize(d, 0.0); + } + } + let nt = 1 + kept; + let rel = self.rel_bias.as_deref().and_then(|rb| { + if o.ent_rel_idx.len() == n_ents && o.ent_rel_type.len() == n_ents { + Some((o.ent_rel_idx.as_slice(), o.ent_rel_type.as_slice(), rb)) + } else { + None + } + }); + for b in &self.blocks { + b.ln1.apply_rows(&ws.x, nt, &mut ws.norm); + b.qkv.matmul_rows(&ws.norm, nt, &mut ws.qkv, false, false, false); + attend_strided( + &ws.qkv, + 3 * d, + 0, + nt, + &ws.qkv, + 3 * d, + d, + &ws.qkv, + 3 * d, + 2 * d, + nt, + d, + self.heads, + rel, + &mut ws.att, + &mut ws.scores, + ); + b.out.matmul_rows(&ws.att, nt, &mut ws.x, false, false, true); + b.ln2.apply_rows(&ws.x, nt, &mut ws.norm); + b.ff1.matmul_rows(&ws.norm, nt, &mut ws.ff, true, self.gelu, false); + b.ff2.matmul_rows(&ws.ff, nt, &mut ws.x, false, false, true); + } + self.ln_f.apply_rows(&ws.x, nt, &mut ws.norm); + nt + } + + /// Computes state `h` and value logit from final normed tokens in `ws.norm` (`[nt, d]`). + fn run_head(&self, o: &Obs, nt: usize, ws: &mut TxWorkspace) -> (Vec, f32) { + let d = self.d; + let t = &ws.norm; + let n_ents = nt - 1; + ws.tmp1.resize(2 * d, 0.0); + ws.tmp1[..d].copy_from_slice(&t[..d]); + let mean = &mut ws.tmp1[d..2 * d]; + mean.fill(0.0); + if n_ents > 0 { + let inv = 1.0 / n_ents as f32; + for i in 1..nt { + let row = &t[i * d..(i + 1) * d]; + for (m, &r) in mean.iter_mut().zip(row) { + *m += r * inv; + } + } + } + let mut h = Vec::with_capacity(self.trunk1.out); + self.trunk1.apply_act(&ws.tmp1, &mut h, true, self.gelu); + let value = if let Some(vm) = &self.val_mlp { + let vin = 3 * d + self.glob_f; + ws.tmp2.resize(vin, 0.0); + ws.tmp2[..2 * d].copy_from_slice(&ws.tmp1[..2 * d]); + let mx = &mut ws.tmp2[2 * d..3 * d]; + if n_ents > 0 { + mx.copy_from_slice(&t[d..2 * d]); + for i in 2..nt { + let row = &t[i * d..(i + 1) * d]; + for (m, &r) in mx.iter_mut().zip(row) { + if r > *m { + *m = r; + } + } + } + } else { + mx.fill(0.0); + } + let gn = self.glob_f.min(o.glob.len()); + ws.tmp2[3 * d..3 * d + gn].copy_from_slice(&o.glob[..gn]); + if gn < self.glob_f { + ws.tmp2[3 * d + gn..vin].fill(0.0); + } + ws.tmp3.resize(vin, 0.0); + vm.ln.apply_slice(&ws.tmp2, &mut ws.tmp3); + vm.fc1.apply_act(&ws.tmp3, &mut ws.tmp1, true, self.gelu); + vm.fc2.apply_act(&ws.tmp1, &mut ws.tmp2, false, false); + ws.tmp2[0] + } else { + self.value.as_ref().unwrap().apply_act(&h, &mut ws.tmp2, false, false); + ws.tmp2[0] + }; + (h, value) + } + + pub fn state(&self, o: &Obs) -> (Vec, f32) { + TX_WS.with(|cell| { + let mut guard = cell.borrow_mut(); + let ws = &mut *guard; + let nt = self.run_tokens(o, ws); + self.run_head(o, nt, ws) + }) + } + + pub fn forward(&self, o: &Obs) -> Output { + TX_WS.with(|cell| { + let mut guard = cell.borrow_mut(); + let ws = &mut *guard; + let nt = self.run_tokens(o, ws); + let (h, value) = self.run_head(o, nt, ws); + let na = o.n_acts(); + if na == 0 { + return Output { logits: Vec::new(), value, h }; + } + let d = self.d; + // Key/Value over all tokens + self.act_kv.matmul_rows(&ws.norm, nt, &mut ws.act_kv, false, false, false); + // Query from state h + self.query.apply_act(&h, &mut ws.tmp1, false, false); + // Action inputs (optionally concatenated with contextualized entity token `ws.norm[1 + act_ent_idx[i]]`) + let n_ents = nt - 1; + let ain = self.dim + ACT_F + if self.act_ent { d } else { 0 }; + ws.act_in_buf.resize(na * ain, 0.0); + for i in 0..na { + let dst = &mut ws.act_in_buf[i * ain..(i + 1) * ain]; + dst[..self.dim].copy_from_slice(self.embedding(o.act_ids[i])); + dst[self.dim..self.dim + ACT_F].copy_from_slice(&o.acts[i * ACT_F..(i + 1) * ACT_F]); + if self.act_ent { + let ei = o.act_ent_idx.get(i).copied().unwrap_or(NO_ENT) as usize; + let ctx = &mut dst[self.dim + ACT_F..]; + if ei < n_ents { + ctx.copy_from_slice(&ws.norm[(1 + ei) * d..(2 + ei) * d]); + } else { + ctx.fill(0.0); + } + } + } + self.act_in.matmul_rows(&ws.act_in_buf, na, &mut ws.act, false, false, false); + self.act_ln.apply_rows(&ws.act, na, &mut ws.act_norm); + self.act_q.matmul_rows(&ws.act_norm, na, &mut ws.act_q, false, false, false); + attend_strided( + &ws.act_q, + d, + 0, + na, + &ws.act_kv, + 2 * d, + 0, + &ws.act_kv, + 2 * d, + d, + nt, + d, + self.heads, + None, + &mut ws.act_att, + &mut ws.scores, + ); + self.act_o.matmul_rows(&ws.act_att, na, &mut ws.act, false, false, true); + // Residual FFN: a = a + act(act_ff(a)) + self.act_ff.matmul_rows(&ws.act, na, &mut ws.act_norm, true, self.gelu, false); + for (dst, &u) in ws.act.iter_mut().zip(&ws.act_norm) { + *dst += u; + } + self.abias.matmul_rows(&ws.act, na, &mut ws.act_bias, false, false, false); + let mut logits = Vec::with_capacity(na); + for i in 0..na { + logits.push(dot(&ws.tmp1, &ws.act[i * d..(i + 1) * d]) + ws.act_bias[i]); + } + Output { logits, value, h } + }) + } + + pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { + let mut q = Vec::new(); + self.belief.apply_act(h, &mut q, false, false); + cards.iter().map(|c| dot(self.embedding(*c), &q)).collect() + } +} + +struct PendingReq { + obs: Obs, + reply: Arc<(Mutex>, Condvar)>, +} + +struct BatchQueue { + reqs: Vec, + closed: bool, +} + +/// Batched TCP client for `rust/rl/infer_server.py` (GPU-accelerated self-play). +pub struct RemoteNet { + pub name: String, + queue: Arc<(Mutex, Condvar)>, + emb: Vec, + dim: usize, + belief: Option, +} + +impl std::fmt::Debug for RemoteNet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RemoteNet").field("name", &self.name).field("dim", &self.dim).finish() + } +} + +fn read_u32(s: &mut TcpStream) -> std::io::Result { + let mut b = [0u8; 4]; + s.read_exact(&mut b)?; + Ok(u32::from_le_bytes(b)) +} + +fn read_f32s(s: &mut TcpStream, n: usize) -> std::io::Result> { + let mut bytes = vec![0u8; n * 4]; + s.read_exact(&mut bytes)?; + Ok(bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()) +} + +impl RemoteNet { + pub fn connect(url: &str) -> Result { + let addr = url.strip_prefix("tcp://").ok_or("expected tcp://host:port")?; + let mut stream = TcpStream::connect(addr).map_err(|e| format!("{url}: {e}"))?; + stream.set_nodelay(true).ok(); + let dim = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; + let buckets = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; + let trunk = read_u32(&mut stream).map_err(|e| format!("{url} handshake: {e}"))? as usize; + let mut has_b = [0u8; 1]; + stream.read_exact(&mut has_b).map_err(|e| format!("{url} handshake: {e}"))?; + let (emb, belief) = if has_b[0] != 0 { + let emb = read_f32s(&mut stream, buckets * dim).map_err(|e| format!("{url} emb: {e}"))?; + let bw = read_f32s(&mut stream, dim * trunk).map_err(|e| format!("{url} bw: {e}"))?; + let bb = read_f32s(&mut stream, dim).map_err(|e| format!("{url} bb: {e}"))?; + (emb, Some(Linear::new(bw, bb, dim, trunk))) + } else { + (Vec::new(), None) + }; + + let queue = Arc::new((Mutex::new(BatchQueue { reqs: Vec::new(), closed: false }), Condvar::new())); + let q_bg = Arc::clone(&queue); + let max_batch: usize = std::env::var("PLAYMAT_GPU_BATCH").ok().and_then(|v| v.parse().ok()).unwrap_or(64); + // Default 0: never call wait_timeout on Windows (where sub-15.6ms sleeps round up to 15.6ms!); + // natural coalescing happens while the previous GPU batch is in flight. + let wait_us: u64 = std::env::var("PLAYMAT_GPU_WAIT_US").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + + std::thread::spawn(move || { + let mut payload = Vec::::with_capacity(2 << 20); + let mut resp_buf = Vec::::with_capacity(1 << 18); + loop { + let batch = { + let (lock, cv) = &*q_bg; + let mut g = lock.lock().unwrap(); + while g.reqs.is_empty() && !g.closed { + g = cv.wait(g).unwrap(); + } + if g.reqs.is_empty() && g.closed { + break; + } + if g.reqs.len() < max_batch && wait_us > 0 { + let deadline = Instant::now() + Duration::from_micros(wait_us); + while g.reqs.len() < max_batch && !g.closed { + let rem = deadline.saturating_duration_since(Instant::now()); + if rem.is_zero() { + break; + } + let (ng, to) = cv.wait_timeout(g, rem).unwrap(); + g = ng; + if to.timed_out() { + break; + } + } + } + let take = g.reqs.len().min(max_batch); + g.reqs.drain(..take).collect::>() + }; + + let b = batch.len(); + let max_e = batch.iter().map(|r| r.obs.n_ents()).max().unwrap_or(0); + let max_a = batch.iter().map(|r| r.obs.n_acts()).max().unwrap_or(0); + let w_e = ((max_e + 7) / 8 * 8).max(8); + let w_a = ((max_a + 3) / 4 * 4).max(4); + + // Pre-pack 10 flat contiguous arrays so Python infer_server.py runs with ZERO Python loops + let glob_bytes = b * GLOB_F * 4; + let eids_bytes = b * w_e * 2; + let ents_bytes = b * w_e * ENT_F * 4; + let em_bytes = b * w_e; + let eridx_bytes = b * w_e; + let ertyp_bytes = b * w_e; + let aids_bytes = b * w_a * 2; + let acts_bytes = b * w_a * ACT_F * 4; + let am_bytes = b * w_a; + let aent_bytes = b * w_a; + let total_bytes = 12 + + glob_bytes + + eids_bytes + + ents_bytes + + em_bytes + + eridx_bytes + + ertyp_bytes + + aids_bytes + + acts_bytes + + am_bytes + + aent_bytes; + payload.clear(); + payload.resize(total_bytes, 0); + payload[0..4].copy_from_slice(&(b as u32).to_le_bytes()); + payload[4..8].copy_from_slice(&(w_e as u32).to_le_bytes()); + payload[8..12].copy_from_slice(&(w_a as u32).to_le_bytes()); + + let o_glob = 12; + let o_eids = o_glob + glob_bytes; + let o_ents = o_eids + eids_bytes; + let o_em = o_ents + ents_bytes; + let o_eridx = o_em + em_bytes; + let o_ertyp = o_eridx + eridx_bytes; + let o_aids = o_ertyp + ertyp_bytes; + let o_acts = o_aids + aids_bytes; + let o_am = o_acts + acts_bytes; + let o_aent = o_am + am_bytes; + // Default sentinel NO_ENT (255) for entity/action indices + payload[o_eridx..o_eridx + eridx_bytes].fill(NO_ENT); + payload[o_aent..o_aent + aent_bytes].fill(NO_ENT); + + for (i, req) in batch.iter().enumerate() { + let o = &req.obs; + // glob + let gd = &mut payload[o_glob + i * GLOB_F * 4..o_glob + (i + 1) * GLOB_F * 4]; + for (k, &v) in o.glob.iter().take(GLOB_F).enumerate() { + gd[k * 4..(k + 1) * 4].copy_from_slice(&v.to_le_bytes()); + } + // entities + let ne = o.n_ents().min(w_e); + if ne > 0 { + let id_base = o_eids + i * w_e * 2; + for k in 0..ne { + payload[id_base + k * 2..id_base + k * 2 + 2] + .copy_from_slice(&(o.ent_ids[k] as u16).to_le_bytes()); + } + let ef_base = o_ents + i * w_e * ENT_F * 4; + for (k, &v) in o.ents[..ne * ENT_F].iter().enumerate() { + payload[ef_base + k * 4..ef_base + k * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + let em_base = o_em + i * w_e; + payload[em_base..em_base + ne].fill(1); + if o.ent_rel_idx.len() >= ne && o.ent_rel_type.len() >= ne { + payload[o_eridx + i * w_e..o_eridx + i * w_e + ne].copy_from_slice(&o.ent_rel_idx[..ne]); + payload[o_ertyp + i * w_e..o_ertyp + i * w_e + ne].copy_from_slice(&o.ent_rel_type[..ne]); + } + } + // actions + let na = o.n_acts().min(w_a); + if na > 0 { + let id_base = o_aids + i * w_a * 2; + for k in 0..na { + payload[id_base + k * 2..id_base + k * 2 + 2] + .copy_from_slice(&(o.act_ids[k] as u16).to_le_bytes()); + } + let af_base = o_acts + i * w_a * ACT_F * 4; + for (k, &v) in o.acts[..na * ACT_F].iter().enumerate() { + payload[af_base + k * 4..af_base + k * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + let am_base = o_am + i * w_a; + payload[am_base..am_base + na].fill(1); + if o.act_ent_idx.len() >= na { + payload[o_aent + i * w_a..o_aent + i * w_a + na].copy_from_slice(&o.act_ent_idx[..na]); + } + } + } + if stream.write_all(&payload).is_err() { + break; + } + let Ok(rb) = read_u32(&mut stream) else { break }; + let Ok(rtrunk) = read_u32(&mut stream) else { break }; + debug_assert_eq!(rb as usize, b); + let trunk = rtrunk as usize; + let need = (b + b * w_a + b * trunk) * 4; + resp_buf.resize(need, 0); + if stream.read_exact(&mut resp_buf).is_err() { + break; + } + let floats: Vec = resp_buf.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + let vs = &floats[..b]; + let all_logits = &floats[b..b + b * w_a]; + let all_h = &floats[b + b * w_a..]; + for (i, req) in batch.into_iter().enumerate() { + let na = req.obs.n_acts().min(w_a); + let logits = all_logits[i * w_a..i * w_a + na].to_vec(); + let h = all_h[i * trunk..(i + 1) * trunk].to_vec(); + let (rlock, rcv) = &*req.reply; + *rlock.lock().unwrap() = Some(Output { logits, value: vs[i], h }); + rcv.notify_one(); + } + } + }); + + Ok(RemoteNet { name: url.to_string(), queue, emb, dim, belief }) + } + + pub fn forward(&self, o: &Obs) -> Output { + let reply = Arc::new((Mutex::new(None), Condvar::new())); + { + let (lock, cv) = &*self.queue; + let mut g = lock.lock().unwrap(); + g.reqs.push(PendingReq { obs: o.clone(), reply: Arc::clone(&reply) }); + cv.notify_one(); + } + let (rlock, rcv) = &*reply; + let mut rg = rlock.lock().unwrap(); + while rg.is_none() { + rg = rcv.wait(rg).unwrap(); + } + rg.take().unwrap() + } + + pub fn state(&self, o: &Obs) -> (Vec, f32) { + let out = self.forward(o); + (out.h, out.value) + } + + pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { + let Some(bl) = &self.belief else { return vec![0.0; cards.len()] }; + let mut q = Vec::new(); + bl.apply(h, &mut q, false); + let n_emb = self.emb.len() / self.dim.max(1); + cards + .iter() + .map(|c| { + let i = (*c as usize).min(n_emb.saturating_sub(1)); + dot(&self.emb[i * self.dim..(i + 1) * self.dim], &q) + }) + .collect() + } +} + +/// A network: the first, pooled one, the transformer, or a GPU-batched remote server (`tcp://...`) +#[derive(Clone, Debug)] +pub enum Net { + Mlp(Mlp), + Tx(Tx), + Remote(Arc), +} + +impl Net { + /// Reads a `.pmnet` file's bytes (the header's `arch` says which network) + pub fn parse(name: &str, bytes: &[u8]) -> Result { + let (header, _) = read(bytes)?; + if header["arch"].as_str() == Some("tx") { + Ok(Net::Tx(Tx::parse(name, bytes)?)) + } else { + Ok(Net::Mlp(Mlp::parse(name, bytes)?)) + } + } + + pub fn name(&self) -> &str { + match self { + Net::Mlp(n) => &n.name, + Net::Tx(n) => &n.name, + Net::Remote(n) => &n.name, + } + } + + /// The state `h` and the value + pub fn state(&self, o: &Obs) -> (Vec, f32) { + match self { + Net::Mlp(n) => n.state(o), + Net::Tx(n) => n.state(o), + Net::Remote(n) => n.state(o), + } + } + + /// Every action's logit, and the value + pub fn forward(&self, o: &Obs) -> Output { + match self { + Net::Mlp(n) => n.forward(o), + Net::Tx(n) => n.forward(o), + Net::Remote(n) => n.forward(o), + } + } + + pub fn has_belief(&self) -> bool { + match self { + Net::Mlp(n) => n.belief.is_some(), + Net::Tx(_) => true, + Net::Remote(n) => n.belief.is_some(), + } + } + + /// Each card's logit of being in the opponent's hand + pub fn belief(&self, h: &[f32], cards: &[u32]) -> Vec { + match self { + Net::Mlp(n) => n.belief(h, cards), + Net::Tx(n) => n.belief(h, cards), + Net::Remote(n) => n.belief(h, cards), + } + } +} + +/// Softmax of `logits / temp` +pub fn softmax(logits: &[f32], temp: f32) -> Vec { + let t = temp.max(1e-3); + let m = logits.iter().copied().fold(f32::MIN, f32::max); + let e: Vec = logits.iter().map(|l| ((l - m) / t).exp()).collect(); + let s: f32 = e.iter().sum(); + e.iter().map(|v| v / s).collect() +} + +static CACHE: OnceLock>>> = OnceLock::new(); + +/// The network at `path`, read once per process (`builtin`: shipped net; `tcp://host:port`: GPU inference server) +pub fn load(path: &str) -> Result, String> { + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + // Hold the cache lock while loading/connecting so `--jobs 64` worker threads share ONE RemoteNet + // TCP connection and coalesce into true B=32..64 GPU batches instead of opening 64 separate B=1 sockets! + let mut map = cache.lock().unwrap(); + if let Some(n) = map.get(path) { + return Ok(Arc::clone(n)); + } + let net = if path == "builtin" { + Net::parse("builtin", BUILTIN)? + } else if path.starts_with("tcp://") { + Net::Remote(Arc::new(RemoteNet::connect(path)?)) + } else { + let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + Net::parse(path, &bytes)? + }; + let net = Arc::new(net); + map.insert(path.to_string(), Arc::clone(&net)); + Ok(net) +} + +/// The network this build ships (`rust/rl` writes it): what `net=builtin` and an unset `Config::net` load +pub const BUILTIN: &[u8] = include_bytes!("net.pmnet"); + +/// The net a config names (`Config::net`, else the built-in one) +pub fn of(net: &Option) -> Arc { + let path = net.as_deref().unwrap_or("builtin"); + load(path).unwrap_or_else(|e| panic!("AI network: {e}")) +} + +/// The value head as a score on the fitted score's scale (a logit times 1000), `WIN`/`LOSE` for a finished game +pub fn score(net: &Net, game: &playmat_engine::state::Game, seat: playmat_engine::state::Seat) -> i64 { + let over = crate::eval::evaluate(game, seat); + if over >= crate::eval::WIN || over <= crate::eval::LOSE { + return over; + } + let q = playmat_engine::decide::Query::Priority { playable: Vec::new() }; + let o = obs::observe(game, seat, &q, &[]); + (net.state(&o).1 as f64 * 1000.0).clamp(-30_000.0, 30_000.0) as i64 +} diff --git a/rust/crates/playmat-ai/src/obs.rs b/rust/crates/playmat-ai/src/obs.rs index e54844b..40eec80 100644 --- a/rust/crates/playmat-ai/src/obs.rs +++ b/rust/crates/playmat-ai/src/obs.rs @@ -23,8 +23,12 @@ use playmat_engine::state::{Game, ObjId, Seat, StackItem, Step, Target, Zone}; pub const ENT_F: usize = 49; /// Legacy v1 global feature width (prefix of `GLOB_F` for backward-compatible `.pmnet` loading) pub const GLOB_F_V1: usize = 17 + 22 + 13 + 13; -/// Global features (v1 65 + 12 colored untapped mana sources + 2 unblocked clocks + 2 stack flags) -pub const GLOB_F: usize = GLOB_F_V1 + 16; +/// Legacy v2 global feature width (prefix of `GLOB_F` for backward-compatible `.pmnet` loading) +pub const GLOB_F_V2: usize = GLOB_F_V1 + 16; +/// Global features (v2 81 + 8 opponent archetype/decklist conditioning features inferred from public zones) +pub const GLOB_F: usize = GLOB_F_V2 + 8; +/// Width of v3 structured public-belief summary vector (`belief_meta.f16`) +pub const BELIEF_META_F: usize = 8; /// Features per action pub const ACT_F: usize = 16 + ENT_F; /// Most entities in one observation (stack, battlefields, own hand, playable exile, top-K graveyards) @@ -392,10 +396,120 @@ pub fn global(game: &Game, seat: Seat, q: &Query) -> Vec { let top_is_spell = game.stack.last().is_some_and(|s| s.ability.is_none()); g.push(top_targets_me as u8 as f32); g.push(top_is_spell as u8 as f32); + debug_assert_eq!(g.len(), GLOB_F_V2); + + // Obs v3 opponent archetype / decklist conditioning (indices 81..89): + // Strictly computed from legally visible opponent cards (battlefield, graveyard, stack, face-up exile) + // so there is zero hidden-information leakage in Bo1, and ready for open-decklist Bo3 conditioning. + g.extend(opponent_archetype_features(game, seat)); debug_assert_eq!(g.len(), GLOB_F); g } +/// 8 opponent archetype & interaction-threat features computed strictly from publicly visible opponent cards: +/// [sweeper, counterspell, face_burn, spot_removal, combat_trick_or_instant, avg_nonland_mv/5, creature_ratio, seen_frac] +pub fn opponent_archetype_features(game: &Game, seat: Seat) -> [f32; 8] { + let opp = game.opponent(seat); + let mut sweeper = 0.0f32; + let mut counter = 0.0f32; + let mut burn = 0.0f32; + let mut removal = 0.0f32; + let mut trick = 0.0f32; + let mut mv_sum = 0.0f32; + let mut creatures = 0.0f32; + let mut nonlands = 0.0f32; + let mut total_seen = 0.0f32; + + let mut inspect = |id: ObjId| { + let o = game.obj(id); + if o.owner != opp || o.token { + return; + } + total_seen += 1.0; + let def = &o.def; + if def.types.contains(&CardType::Land) { + return; + } + nonlands += 1.0; + mv_sum += def.mana_value() as f32; + if def.types.contains(&CardType::Creature) { + creatures += 1.0; + } + let k = crate::policy::spell_kind(def); + if k.sweeper { + sweeper += 1.0; + } + if k.removal { + removal += 1.0; + } + if k.face && k.damage.is_some() { + burn += 1.0; + } + if k.pump || (def.types.contains(&CardType::Instant) && !k.removal && !k.face) { + trick += 1.0; + } + let rule_l = def.spell.rule.to_ascii_lowercase(); + if rule_l.contains("counter target") { + counter += 1.0; + } + }; + + for &id in game.battlefield.iter() { + inspect(id); + } + for &id in game.player(opp).graveyard.iter() { + inspect(id); + } + for st in game.stack.iter() { + if st.controller == opp { + inspect(st.card); + } + } + for &id in game.exile.iter() { + if !game.obj(id).exiled_face_down { + inspect(id); + } + } + let denom = nonlands.max(1.0); + let opp_total = (total_seen + game.player(opp).hand.len() as f32 + game.player(opp).library.len() as f32).max(1.0); + [ + (sweeper / 2.0).min(1.0), + (counter / 3.0).min(1.0), + (burn / 4.0).min(1.0), + (removal / 4.0).min(1.0), + (trick / 3.0).min(1.0), + (mv_sum / denom / 5.0).min(2.0), + creatures / denom, + (total_seen / opp_total).min(1.0), + ] +} + +/// 8-float structured public-belief summary written to v3 shards (`belief_meta.f16`) for Phase 3 ReBeL / GT-CFR: +/// [opp_unseen_hand/7, opp_untapped_lands/6, opp_W, opp_U, opp_B, opp_R, opp_G, opp_seen_frac] +pub fn belief_meta(game: &Game, seat: Seat, unseen_hand_count: usize) -> [f32; BELIEF_META_F] { + let opp = game.opponent(seat); + let opp_mana = untapped_mana_sources(game, opp); + let opp_untapped_lands = game + .battlefield + .iter() + .filter(|id| { + let o = game.obj(**id); + o.controller == opp && game.has_type(**id, CardType::Land) && !o.tapped + }) + .count() as f32; + let arch = opponent_archetype_features(game, seat); + [ + (unseen_hand_count as f32 / 7.0).min(2.0), + (opp_untapped_lands / 6.0).min(2.0), + opp_mana[0], + opp_mana[1], + opp_mana[2], + opp_mana[3], + opp_mana[4], + arch[7], + ] +} + /// The objects the seat sees (legacy helper kept for callers): stack, permanents, own hand, playable exile, top-K GY pub fn visible(game: &Game, seat: Seat) -> Vec { let mut out: Vec = game.stack.iter().rev().map(|s| s.card).collect(); diff --git a/rust/crates/playmat-ai/src/policy.rs b/rust/crates/playmat-ai/src/policy.rs index 3d93822..88cf78b 100644 --- a/rust/crates/playmat-ai/src/policy.rs +++ b/rust/crates/playmat-ai/src/policy.rs @@ -1,947 +1,960 @@ -//! The quick answers: what a seat says when nothing is searched. Searches play their games out with these, for -//! both seats, so they must be cheap and never get stuck (the engine asks again after an answer it can't use, and -//! the search's answer budget ends any loop). - -use crate::eval; -use playmat_engine::card::{CardType, ManaCost}; -use playmat_engine::decide::{Answer, Query}; -use playmat_engine::rules; -use playmat_engine::state::{Game, Obj, ObjId, Seat, Step, Zone}; -use std::collections::HashMap; -use std::sync::Arc; - -/// Effects whose text says they hurt what they target -const HARMFUL: [&str; 16] = [ - "destroy", - "exile", - "damage", - "to its owner's hand", - "tap target", - "counter target", - "sacrifice", - "fights", - "fight ", - "loses", - "lose ", - "discard", - "gets -", - "get -", - "-1/-1", - "can't block", -]; - -#[derive(Default)] -pub struct Policy { - /// whether a spell or ability (by its card, and ability) hurts its targets - harmful: HashMap<(usize, Option), bool>, - /// blockers declared this combat, so a refused block isn't tried again - tried_blockers: Vec, - blocker: Option, - /// the game at the last priority question, roughly, and what was played then: a play that comes straight back - /// to the same priority (a cancelled cast) isn't tried again until something changes - last: Option<(Progress, Option)>, - banned: Vec, - /// the stronger answers (`Config::playout` 2): instant-speed play, abilities, removal and burn by the effect - v2: bool, -} - -#[derive(Clone, PartialEq, Eq)] -struct Progress([u64; 9]); - -/// A yes/no question the AI always declines, as Java's `Outcome.AIDontUseIt` makes `ComputerPlayer.chooseUse` say no: -/// replicate's "Pay N times Replicate {1} ?" (`ReplicateAbility`), which is asked again after each yes and never -/// checks the mana for the copies (game 5b6e1d86 on 2026-11-16: an AI that said yes was asked forever) -pub fn declines(message: &str) -> bool { - message.starts_with("Pay ") && message.contains(" Replicate ") -} - -fn progress(game: &Game, seat: Seat) -> Progress { - let p = game.player(seat); - let tapped = game.battlefield.iter().filter(|id| game.obj(**id).tapped).count() as u64; - Progress([ - game.turn as u64, - game.step.map(|s| s as u64).unwrap_or(99), - game.stack.len() as u64, - game.battlefield.len() as u64, - p.hand.len() as u64, - p.graveyard.len() as u64, - p.mana_pool.total() as u64, - tapped, - (p.life as i64 + 1000) as u64 * 1000 + (game.player(game.opponent(seat)).life as i64 + 1000) as u64, - ]) -} - -impl Policy { - /// The quick answers of a `Config::playout` version (1, or 2 for the stronger ones) - pub fn version(v: u8) -> Policy { - Policy { v2: v >= 2, ..Policy::default() } - } - - pub fn answer(&mut self, game: &Game, seat: Seat, q: &Query) -> Answer { - match q { - Query::Priority { playable } => { - self.tried_blockers.clear(); - let playable = self.playable(game, seat, playable); - let a = self.priority(game, seat, &playable); - self.played(&a); - a - } - Query::PlayMana { cost, sources } => pay(game, seat, cost, sources), - Query::Target { players, objs, required } => self.target(game, seat, players, objs, *required), - Query::Attackers { creatures } => attack(game, seat, creatures), - Query::Blockers { creatures } => self.block(game, seat, creatures), - Query::BlockTarget { attackers } => self.block_target(game, attackers), - Query::Cards { objs, required } => cards(game, seat, objs, *required), - Query::MultiAmount { defaults, .. } => { - Answer::Text(defaults.iter().map(|d| d.to_string()).collect::>().join(" ")) - } - Query::ChooseAbility { source, abilities } if self.v2 => loyalty_ability(game, seat, *source, abilities) - .or_else(|| { - // activated at priority, not paying for something: an ability that does more than make mana - let paying = game.unpaid.is_some() || game.mana_paid.is_some(); - let def = &game.obj(*source).def; - (!paying) - .then(|| { - abilities - .iter() - .copied() - .find(|i| def.abilities.get(*i).is_some_and(|a| a.mana().is_none())) - }) - .flatten() - .map(|i| Answer::Ability(*source, i)) - }) - .unwrap_or_else(|| choose_ability(game, seat, *source, abilities)), - Query::ChooseAbility { source, abilities } => choose_ability(game, seat, *source, abilities), - Query::PickTrigger { .. } => Answer::Trigger(0), - Query::YesNo { message } => Answer::Bool(!declines(message)), - Query::ChooseMode { modes } => modes.first().map(|m| Answer::Mode(*m)).unwrap_or(Answer::ModeDone), - Query::Amount { min, max } => Answer::Int(x_amount(game, seat).clamp(*min, (*max).max(*min))), - Query::Choice { message, choices } => choice(game, seat, message, choices), - } - } - - /// The playable objects less those that came straight back last time. Call once per priority question. - pub fn playable(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Vec { - let now = progress(game, seat); - match self.last.take() { - Some((before, Some(played))) if before == now => self.banned.push(played), - Some((before, _)) if before == now => {} - _ => self.banned.clear(), - } - self.last = Some((now, None)); - playable.iter().copied().filter(|id| !self.banned.contains(id)).collect() - } - - /// What was answered at the priority question `playable` was called for. - pub fn played(&mut self, a: &Answer) { - if let Some((_, played)) = self.last.as_mut() { - *played = match a { - Answer::Obj(id) | Answer::Ability(id, _) => Some(*id), - _ => None, - }; - } - } - - /// A land first, then the costliest spell in hand, in a main phase of the seat's own turn with nothing on the - /// stack; otherwise pass. Abilities of permanents are left to the search. - pub fn priority(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Answer { - if self.v2 { - return self.priority_v2(game, seat, playable); - } - let main = game.step.is_some_and(|s| s.is_main()); - if game.active != Some(seat) || !main || !game.stack.is_empty() { - return Answer::Bool(false); - } - let in_hand: Vec = playable.iter().copied().filter(|id| game.obj(*id).zone == Zone::Hand).collect(); - if let Some(land) = in_hand.iter().find(|id| game.obj(**id).def.types.contains(&CardType::Land)) { - return Answer::Obj(*land); - } - in_hand - .iter() - .chain(playable.iter().filter(|id| matches!(game.obj(**id).zone, Zone::Graveyard | Zone::Exile))) - .max_by_key(|id| game.obj(**id).def.mana_value()) - .map(|id| Answer::Obj(*id)) - .unwrap_or(Answer::Bool(false)) - } - - /// Whether what is being cast or put on the stack (the top) hurts its targets. - fn harmful(&mut self, game: &Game) -> bool { - let Some(top) = game.stack.last() else { return true }; - let key = (top.card.0 as usize, top.ability.map(|(i, _)| i)); - if let Some(h) = self.harmful.get(&key) { - return *h; - } - let def = game.item_def(top); - let text = match top.ability { - Some((i, _)) => def.abilities.get(i).map(|a| format!("{:?}", a)).unwrap_or_default().to_lowercase(), - None => def.spell.rule.to_lowercase(), - }; - let h = HARMFUL.iter().any(|w| text.contains(w)) - || ["destroy", "exile", "damage", "bounce", "tap", "counterunless", "sacrifice", "fight", "loselife"] - .iter() - .any(|w| text.contains(w)); - self.harmful.insert(key, h); - h - } - - fn target(&mut self, game: &Game, seat: Seat, players: &[Seat], objs: &[ObjId], required: bool) -> Answer { - // nothing left to choose ("up to one" with no legal target): done - if players.is_empty() && objs.is_empty() { - return Answer::Bool(false); - } - let opp = game.opponent(seat); - let harmful = self.harmful(game); - if self.v2 { - if let Some(a) = self.target_v2(game, seat, players, objs, harmful) { - return a; - } - } - let value = |id: &ObjId| { - let o = game.obj(*id); - if o.zone == Zone::Battlefield { - eval::permanent_score(game, *id) - } else { - eval::hand_card_score(game, *id) - } - }; - let whose = |id: &ObjId| game.obj(*id).controller; - if harmful { - if let Some(best) = objs.iter().filter(|o| whose(o) == opp).max_by_key(|o| value(o)) { - return Answer::Obj(*best); - } - if players.contains(&opp) { - return Answer::Player(opp); - } - } else { - if let Some(best) = objs.iter().filter(|o| whose(o) == seat).max_by_key(|o| value(o)) { - return Answer::Obj(*best); - } - if players.contains(&seat) { - return Answer::Player(seat); - } - } - let _ = required; - // only the wrong side (the AI picks whenever it can: a done means different things to Java's dialogs): the least the choice costs - if harmful { - objs.iter().min_by_key(|o| value(o)).map(|o| Answer::Obj(*o)) - } else { - objs.iter().max_by_key(|o| if whose(o) == seat { value(o) } else { -value(o) }).map(|o| Answer::Obj(*o)) - } - .or_else(|| players.first().map(|p| Answer::Player(*p))) - .unwrap_or(Answer::Stop) - } - - /// Blocks that kill the attacker or survive it, and chump blocks when the attack is lethal. - fn block(&mut self, game: &Game, seat: Seat, creatures: &[ObjId]) -> Answer { - let attackers = rules::attackers(game); - let unblocked: Vec = attackers.iter().copied().filter(|a| !game.obj(*a).blocked).collect(); - let incoming: i32 = unblocked.iter().map(|a| game.power_toughness(*a).0.max(0)).sum(); - let lethal = incoming >= game.player(seat).life; - for b in creatures { - if self.tried_blockers.contains(b) || !game.obj(*b).blocking.is_empty() { - continue; - } - let (bp, bt) = game.power_toughness(*b); - let good = unblocked.iter().copied().filter(|a| rules::can_block(game, *b, *a)).find(|a| { - let (ap, at) = game.power_toughness(*a); - bt > ap || (bp >= at && eval::permanent_score(game, *a) >= eval::permanent_score(game, *b)) - }); - let chump = if lethal { - unblocked - .iter() - .copied() - .filter(|a| rules::can_block(game, *b, *a)) - .max_by_key(|a| game.power_toughness(*a).0) - } else { - None - }; - if let Some(a) = good.or(chump) { - self.tried_blockers.push(*b); - self.blocker = Some(a); - return Answer::Obj(*b); - } - } - Answer::Bool(true) - } - - fn block_target(&mut self, game: &Game, attackers: &[ObjId]) -> Answer { - match self.blocker.take() { - Some(a) if attackers.contains(&a) => Answer::Obj(a), - _ => attackers - .iter() - .max_by_key(|a| game.power_toughness(**a).0) - .map(|a| Answer::Obj(*a)) - .unwrap_or(Answer::Bool(false)), - } - } -} - -/// Attacks with a creature no untapped opposing creature can block and kill, or with everything when that's lethal. -fn attack(game: &Game, seat: Seat, creatures: &[ObjId]) -> Answer { - let opp = game.opponent(seat); - let blockers: Vec = game - .battlefield - .iter() - .copied() - .filter(|b| { - let o = game.obj(*b); - o.controller == opp && !o.tapped && game.has_type(*b, CardType::Creature) - }) - .collect(); - let power: i32 = - creatures.iter().chain(rules::attackers(game).iter()).map(|c| game.power_toughness(*c).0.max(0)).sum(); - if blockers.is_empty() && !creatures.is_empty() { - return Answer::Text("special".into()); - } - if power >= game.player(opp).life + blockers.len() as i32 * 2 && !creatures.is_empty() { - return Answer::Text("special".into()); - } - for c in creatures { - let (cp, ct) = game.power_toughness(*c); - if cp <= 0 { - continue; - } - let dies = blockers.iter().any(|b| rules::can_block(game, *b, *c) && game.power_toughness(*b).0 >= ct); - if !dies { - return Answer::Obj(*c); - } - } - Answer::Bool(true) -} - -/// A mana source that makes a color still owed, else any; Cancel when none helps. -fn pay(game: &Game, seat: Seat, cost: &str, sources: &[ObjId]) -> Answer { - let owed = ManaCost::parse(cost).unwrap_or_default(); - let makes = |id: &ObjId| -> [u32; 6] { - let mut m = [0u32; 6]; - for a in game.obj(*id).def.abilities.iter() { - if let Some(mana) = a.mana() { - for (k, n) in mana.colored.iter().enumerate() { - m[k] += n; - } - m[5] += mana.colorless; - } - } - m - }; - let mut mine: Vec = sources.iter().copied().filter(|s| game.obj(*s).controller == seat).collect(); - // the permanent whose ability this pays for doesn't tap for it while another source can (Mutavault animated - // and then tapped for its own {1} can't attack) - if let Some(top) = game.stack.last().filter(|t| t.ability.is_some()) { - if mine.len() > 1 { - mine.retain(|s| *s != top.card); - } - } - // a color owed: the source making the fewest other colors, so flexible lands stay for later - for (k, n) in owed.colored.iter().enumerate() { - if *n > 0 { - if let Some(s) = - mine.iter().filter(|s| makes(s)[k] > 0).min_by_key(|s| makes(s).iter().filter(|n| **n > 0).count()) - { - return Answer::Obj(*s); - } - } - } - if owed.colorless > 0 { - if let Some(s) = mine.iter().find(|s| makes(s)[5] > 0) { - return Answer::Obj(*s); - } - } - if owed.snow > 0 { - // a snow symbol: only a snow permanent's mana pays it - if let Some(s) = mine.iter().find(|s| game.is_snow(**s)) { - return Answer::Obj(*s); - } - } - if owed.generic > 0 || owed.x > 0 { - // generic: the least useful source (colorless first, then the fewest colors) - if let Some(s) = mine.iter().min_by_key(|s| { - let m = makes(s); - // lands that can become creatures pay last, after creatures - let animates = game - .obj(**s) - .def - .abilities - .iter() - .enumerate() - .any(|(i, _)| ability_kind(&game.obj(**s).def, i).animate); - ( - animates as usize, - m[..5].iter().filter(|n| **n > 0).count(), - game.has_type(**s, CardType::Creature) as usize, - ) - }) { - return Answer::Obj(*s); - } - } - Answer::Bool(false) -} - -/// Of a permanent's abilities: for mana, one making a color the spell being paid for needs. -fn choose_ability(game: &Game, _seat: Seat, source: ObjId, abilities: &[usize]) -> Answer { - let def = &game.obj(source).def; - let need = game.stack.last().map(|t| game.item_def(t).cost.colored).unwrap_or_default(); - let best = abilities.iter().copied().find(|i| { - def.abilities.get(*i).and_then(|a| a.mana()).is_some_and(|m| (0..5).any(|k| m.colored[k] > 0 && need[k] > 0)) - }); - Answer::Ability(source, best.or(abilities.first().copied()).unwrap_or(0)) -} - -/// Cards from the seat's own hand go least valuable first (discards); other cards most valuable first. -fn cards(game: &Game, seat: Seat, objs: &[ObjId], required: bool) -> Answer { - let own_hand = objs.iter().all(|o| game.obj(*o).zone == Zone::Hand && game.obj(*o).owner == seat); - if !required && own_hand { - return Answer::Bool(false); - } - let pick = if own_hand { - objs.iter().min_by_key(|o| eval::hand_card_score(game, **o)) - } else { - objs.iter().max_by_key(|o| { - let v = if game.obj(**o).zone == Zone::Battlefield { - eval::permanent_score(game, **o) - } else { - eval::hand_card_score(game, **o) - }; - if game.obj(**o).controller == seat { - v - } else { - -v - } - }) - }; - pick.map(|o| Answer::Obj(*o)).unwrap_or(Answer::Bool(false)) -} - -/// X: what the seat's untapped mana sources make beyond the rest of the spell's cost. -fn x_amount(game: &Game, seat: Seat) -> i32 { - let sources = game - .battlefield - .iter() - .filter(|id| { - let o = game.obj(**id); - o.controller == seat && !o.tapped && o.def.abilities.iter().any(|a| a.mana().is_some()) - }) - .count() as i32 - + game.player(seat).mana_pool.total() as i32; - let rest = game - .stack - .last() - .map(|t| game.item_def(t).cost.clone()) - .map(|c| (c.generic + c.colorless + c.colored.iter().sum::()) as i32) - .unwrap_or(0); - let per = game.stack.last().map(|t| game.item_def(t).cost.x.max(1) as i32).unwrap_or(1); - ((sources - rest) / per).max(0) -} - -fn choice(game: &Game, seat: Seat, message: &str, choices: &[String]) -> Answer { - if !choices.is_empty() { - // a color of mana: one the spell being paid for needs - let need = game.stack.last().map(|t| game.item_def(t).cost.colored).unwrap_or_default(); - let names = ["White", "Blue", "Black", "Red", "Green"]; - for (k, n) in names.iter().enumerate() { - if need[k] > 0 { - if let Some(c) = choices.iter().find(|c| c.eq_ignore_ascii_case(n)) { - return Answer::Text(c.clone()); - } - } - } - return Answer::Text(choices[0].clone()); - } - if message.contains("creature type") { - // the type most of the seat's creatures share - let mut counts: HashMap<&str, usize> = HashMap::new(); - for o in game.objs.iter().filter(|o| o.owner == seat && o.def.types.contains(&CardType::Creature)) { - for s in o.def.subtypes.iter() { - *counts.entry(s.as_str()).or_default() += 1; - } - } - let best = counts.into_iter().max_by_key(|(n, c)| (*c, std::cmp::Reverse(*n))).map(|(n, _)| n.to_string()); - return Answer::Text(best.unwrap_or_else(|| "Human".into())); - } - if let Some(name) = card_name(game, seat, message) { - return Answer::Text(name); - } - Answer::Text(String::new()) -} - -/// "Choose a card name" (Pithing Needle, Phyrexian Revoker: the chosen name's activated abilities other than mana -/// abilities can't be activated): an opponent's card that fits the question, seen in a public zone, best one whose -/// abilities it could activate from where it is, then their lands, and never one of the seat's own. Nothing seen: -/// Island when a land fits, else any fitting card that isn't the seat's. None when the message isn't a card name -/// question. -fn card_name(game: &Game, seat: Seat, message: &str) -> Option { - game.objs.first()?.def.fits_name_question(message)?; - let fits = |o: &Obj| o.def.fits_name_question(message) == Some(true); - let mine: Vec<&str> = - game.objs.iter().filter(|o| o.owner == seat && o.zone != Zone::Library).map(|o| o.def.name.as_str()).collect(); - let theirs = |o: &&Arc| o.owner != seat && fits(o) && !mine.contains(&o.def.name.as_str()); - let mut scores: HashMap<&str, usize> = HashMap::new(); - for o in game.objs.iter().filter(theirs) { - if !matches!(o.zone, Zone::Battlefield | Zone::Graveyard | Zone::Exile) { - continue; - } - let usable = o.def.abilities.iter().filter(|a| a.activated().is_some()).any(|a| match o.zone { - Zone::Battlefield => !a.from_hand() && !a.from_graveyard(), - Zone::Graveyard => a.from_graveyard(), - _ => false, - }); - let any = o.def.abilities.iter().any(|a| a.activated().is_some()); - let land = o.def.is(CardType::Land) && o.zone == Zone::Battlefield; - let score = if usable { - 100 - } else if any { - 10 - } else if land { - 1 - } else { - 0 - }; - if score > 0 { - *scores.entry(o.def.name.as_str()).or_default() += score; - } - } - let best = scores.into_iter().max_by_key(|(n, c)| (*c, std::cmp::Reverse(*n))).map(|(n, _)| n.to_string()); - let island = ["Card name", "Choose a card name", "Land card name", "Choose a land card name"].contains(&message); - best.or_else(|| island.then(|| "Island".to_string())) - .or_else(|| game.objs.iter().filter(theirs).map(|o| o.def.name.clone()).min()) - .or_else(|| Some(String::new())) -} - -/// Catches a question asked again since the last priority question (an answer the engine ignored, one that toggles, -/// or two questions taking turns): each repeat gets an answer not given to it yet, then one that ends it. -#[derive(Default)] -pub struct Repeats { - asked: Vec<(Seat, Query, Vec)>, -} - -impl Repeats { - /// Whether `q` was asked since the last priority question - pub fn is_repeat(&self, seat: Seat, q: &Query) -> bool { - self.asked.iter().any(|(s, l, _)| *s == seat && l == q) - } - - pub fn guard(&mut self, seat: Seat, q: &Query, proposed: Answer, options: &[Answer]) -> Answer { - // a priority question coming back is normal (each play comes back to it): the policy's own check handles it - if matches!(q, Query::Priority { .. }) { - self.asked.clear(); - return proposed; - } - let Some(i) = self.asked.iter().position(|(s, l, _)| *s == seat && l == q) else { - self.asked.push((seat, q.clone(), vec![proposed.clone()])); - return proposed; - }; - let given = &mut self.asked[i].2; - let a = std::iter::once(proposed) - .chain(options.iter().cloned()) - .find(|a| !given.contains(a)) - .unwrap_or_else(|| finish(q, given.len(), options)); - given.push(a.clone()); - a - } -} - -/// An answer that ends a question: done, cancel, or (asked too often) stop. -fn finish(q: &Query, tries: usize, options: &[Answer]) -> Answer { - if tries > 40 { - return Answer::Stop; - } - match q { - Query::Attackers { .. } | Query::Blockers { .. } => Answer::Bool(true), - Query::ChooseMode { .. } => Answer::ModeDone, - Query::Amount { min, .. } => Answer::Int(*min), - Query::Choice { choices, .. } => choices.first().map(|c| Answer::Text(c.clone())).unwrap_or(Answer::Stop), - // a required choice can't be left: pick again (Java asks until the choice is made) - Query::Target { required: true, .. } | Query::Cards { required: true, .. } => { - options.get(tries % options.len().max(1)).cloned().unwrap_or(Answer::Stop) - } - _ => Answer::Bool(false), - } -} - -/// What a card's spell (or an ability) does, as far as the quick answers care: read from its rule text and the names -/// of its effects -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Kind { - /// counters a spell - pub counter: bool, - /// destroys, exiles, damages, shrinks, bounces or fights a creature - pub removal: bool, - /// fixed damage it deals, and whether a player can be its target - pub damage: Option, - pub face: bool, - /// makes a creature bigger or better for the turn - pub pump: bool, - /// draws or looks for cards - pub draw: bool, - /// a land or permanent that becomes a creature (Mutavault) - pub animate: bool, - /// destroys or damages every creature - pub sweeper: bool, -} - -/// The kind of a card's spell -pub fn spell_kind(def: &playmat_engine::card::CardDef) -> Kind { - kind_of(&def.spell.rule.to_lowercase(), &format!("{:?}", def.spell.effects)) -} - -/// The kind of a card's ability, by its index -pub fn ability_kind(def: &playmat_engine::card::CardDef, i: usize) -> Kind { - match def.abilities.get(i) { - Some(a) => { - let debug = format!("{a:?}"); - let rule = a.activated().map(|(r, ..)| r.to_lowercase()).unwrap_or_default(); - kind_of(&rule, &debug) - } - None => Kind::default(), - } -} - -fn kind_of(rule: &str, effects: &str) -> Kind { - let damage = rule.find(" deals ").and_then(|at| { - let rest = &rule[at + 7..]; - let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); - n.parse::().ok().filter(|_| rest.contains("damage")) - }); - let face = damage.is_some() - && (rule.contains("any target") - || rule.contains("target player") - || rule.contains("target opponent") - || rule.contains("each opponent")); - let sweeper = rule.contains("destroy all creatures") - || rule.contains("each creature") - || effects.contains("DestroyAllEffect") - || effects.contains("DamageAllEffect"); - Kind { - counter: rule.contains("counter target") || effects.contains("CounterTargetEffect"), - removal: !sweeper - && (rule.contains("destroy target") - || rule.contains("exile target") - || (damage.is_some() && (rule.contains("target creature") || rule.contains("any target"))) - || rule.contains("target creature an opponent controls gets -") - || rule.contains("target creature gets -") - || rule.contains("fights") - || rule.contains("to its owner's hand") - || effects.contains("DestroyTargetEffect") - || effects.contains("ExileTargetEffect") - || effects.contains("FightTargetsEffect")), - damage, - face, - pump: (rule.contains("target creature gets +") || effects.contains("BoostTargetEffect")) - && !rule.contains("gets -"), - draw: rule.contains("draw") || rule.contains("look at the top"), - animate: effects.contains("BecomesCreatureSourceEffect"), - sweeper, - } -} - -impl Policy { - /// The stronger quick answers (`Config::playout` 2): - /// - with an opponent's spell on the stack: a counterspell when the spell is worth one, else pass; - /// - in its own main phase with an empty stack: a land, burn to the face when that's lethal, its most expensive - /// spell (counters, tricks and sweepers that would hit more of its own creatures held back), a planeswalker's - /// loyalty ability, an equip, and before combat a land that becomes a creature when it can attack; - /// - in combat: removal on an attacker, a pump on a blocked attacker or on a blocker; - /// - at the end of the opponent's turn: flash creatures, removal and card draw with the mana left. - fn priority_v2(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Answer { - let opp = game.opponent(seat); - let mine = game.active == Some(seat); - let step = game.step; - let own: Vec = playable - .iter() - .copied() - .filter(|id| { - let o = game.obj(*id); - o.controller == seat || o.owner == seat - }) - .collect(); - let castable: Vec = own - .iter() - .copied() - .filter(|id| matches!(game.obj(*id).zone, Zone::Hand | Zone::Graveyard | Zone::Exile)) - .collect(); - let kind = |id: ObjId| spell_kind(&game.obj(id).def); - let is = |id: ObjId, t: CardType| game.obj(id).def.types.contains(&t); - let instant_speed = |id: ObjId| { - is(id, CardType::Instant) - || game - .obj(id) - .def - .abilities - .iter() - .any(|a| matches!(a, playmat_engine::card::AbilityDef::FlashAbility)) - }; - let creatures = |s: Seat| -> Vec { - game.battlefield - .iter() - .copied() - .filter(|id| game.obj(*id).controller == s && game.has_type(*id, CardType::Creature)) - .collect() - }; - - // the stack: answer an opponent's spell, or let it resolve - if let Some(top) = game.stack.last() { - if top.controller == opp && top.ability.is_none() { - let spell = &game.obj(top.card).def; - let worth = spell.mana_value() >= 2 || spell_kind(spell).removal || spell_kind(spell).sweeper; - if worth { - if let Some(c) = castable.iter().copied().find(|c| kind(*c).counter) { - return Answer::Obj(c); - } - } - } - return Answer::Bool(false); - } - - let combat = matches!(step, Some(Step::DeclareAttackers) | Some(Step::DeclareBlockers)); - if combat { - let attackers = rules::attackers(game); - if !mine && !attackers.is_empty() { - // removal on an attacker - if let Some(c) = castable.iter().copied().find(|c| instant_speed(*c) && kind(*c).removal) { - return Answer::Obj(c); - } - } - if step == Some(Step::DeclareBlockers) { - let fighting = attackers.iter().any(|a| { - let o = game.obj(*a); - (mine && o.blocked) || (!mine && !o.blocked_by.is_empty()) - }); - if fighting { - if let Some(c) = castable.iter().copied().find(|c| instant_speed(*c) && kind(*c).pump) { - return Answer::Obj(c); - } - } - } - return Answer::Bool(false); - } - - if !mine { - // the opponent's end step: use the mana left - if step == Some(Step::EndTurn) { - let opp_creatures = !creatures(opp).is_empty(); - let pick = castable - .iter() - .copied() - .filter(|c| instant_speed(*c) && !is(*c, CardType::Land)) - .filter(|c| { - let k = kind(*c); - (k.removal && opp_creatures) || k.draw || is(*c, CardType::Creature) - }) - .max_by_key(|c| game.obj(*c).def.mana_value()); - if let Some(c) = pick { - return Answer::Obj(c); - } - } - return Answer::Bool(false); - } - - // its own turn, outside combat - if !step.is_some_and(|s| s.is_main()) { - return Answer::Bool(false); - } - if let Some(land) = - castable.iter().copied().find(|id| is(*id, CardType::Land) && game.obj(*id).zone == Zone::Hand) - { - return Answer::Obj(land); - } - // burn to the face when it's lethal - let opp_life = game.player(opp).life; - let burn: Vec = - castable.iter().copied().filter(|c| kind(*c).face && kind(*c).damage.is_some()).collect(); - let total: i32 = burn.iter().map(|c| kind(*c).damage.unwrap_or(0)).sum(); - if total >= opp_life { - if let Some(c) = burn.iter().copied().max_by_key(|c| kind(*c).damage) { - return Answer::Obj(c); - } - } - let my_count = creatures(seat).len(); - let opp_count = creatures(opp).len(); - let spell = castable - .iter() - .copied() - .filter(|c| { - let k = kind(*c); - if is(*c, CardType::Land) || k.counter { - return false; - } - // tricks wait for combat - if k.pump && !is(*c, CardType::Creature) { - return false; - } - // a sweeper only when it costs the opponent more creatures than it costs us - if k.sweeper && opp_count <= my_count { - return false; - } - // removal needs something to remove - if k.removal && !k.face && opp_count == 0 && !is(*c, CardType::Creature) { - return false; - } - true - }) - .max_by_key(|c| game.obj(*c).def.mana_value()); - if let Some(c) = spell { - return Answer::Obj(c); - } - // permanents' abilities: planeswalkers, equipment, lands that become creatures before combat - for id in own.iter().copied().filter(|id| game.obj(*id).zone == Zone::Battlefield) { - let o = game.obj(id); - if o.def.types.contains(&CardType::Planeswalker) && o.loyalty_used == 0 { - return Answer::Obj(id); - } - if game.has_subtype(id, "Equipment") && game.attached(id).is_none() && my_count > 0 { - return Answer::Obj(id); - } - let animates = o.def.abilities.iter().enumerate().any(|(i, _)| ability_kind(&o.def, i).animate); - if animates - && step == Some(Step::PrecombatMain) - && !game.has_type(id, CardType::Creature) - && !o.tapped - && game.turn > o.entered_turn - { - return Answer::Obj(id); - } - } - Answer::Bool(false) - } - - /// Targets the stronger answers pick differently: lethal burn to the face, damage to a creature it kills (the - /// best such, attacking first), and in combat help for its own creature that is fighting. `None`: as before. - fn target_v2( - &mut self, - game: &Game, - seat: Seat, - players: &[Seat], - objs: &[ObjId], - harmful: bool, - ) -> Option { - let opp = game.opponent(seat); - let top = game.stack.last()?; - let def = game.item_def(top); - let k = match top.ability { - Some((i, _)) => ability_kind(def, i), - None => spell_kind(def), - }; - let theirs: Vec = objs.iter().copied().filter(|o| game.obj(*o).controller == opp).collect(); - if harmful { - if let Some(n) = k.damage { - if players.contains(&opp) && n >= game.player(opp).life { - return Some(Answer::Player(opp)); - } - // the best creature the damage kills, an attacker first - let kills = theirs - .iter() - .copied() - .filter(|o| game.obj(*o).zone == Zone::Battlefield && game.has_type(*o, CardType::Creature)) - .filter(|o| game.power_toughness(*o).1 - game.obj(*o).damage <= n) - .max_by_key(|o| (game.obj(*o).attacking.is_some(), eval::permanent_score(game, *o))); - if let Some(o) = kills { - return Some(Answer::Obj(o)); - } - if players.contains(&opp) { - return Some(Answer::Player(opp)); - } - } - // in combat, an attacker first - let attacking = theirs - .iter() - .copied() - .filter(|o| game.obj(*o).attacking.is_some()) - .max_by_key(|o| eval::permanent_score(game, *o)); - return attacking.map(Answer::Obj); - } - // help: its own creature in a fight - let fighting = objs - .iter() - .copied() - .filter(|o| { - let x = game.obj(*o); - x.controller == seat && (x.attacking.is_some() || !x.blocking.is_empty()) - }) - .max_by_key(|o| { - let x = game.obj(*o); - (x.blocked || !x.blocking.is_empty(), eval::permanent_score(game, *o)) - }); - fighting.map(Answer::Obj) - } -} - -/// A planeswalker's loyalty ability: the minus one that keeps it alive when the opponent has a creature for it to -/// remove, else its plus ability, else the first -fn loyalty_ability(game: &Game, seat: Seat, source: ObjId, abilities: &[usize]) -> Option { - let o = game.obj(source); - if !o.def.types.contains(&CardType::Planeswalker) { - return None; - } - let loyalty = o.counter("loyalty"); - let cost = |i: usize| -> Option { - match o.def.abilities.get(i)? { - playmat_engine::card::AbilityDef::LoyaltyAbility { cost, .. } => cost.iter().find_map(|c| match c { - playmat_engine::card::CostDef::PayLoyaltyCost { amount } => Some(*amount), - _ => None, - }), - _ => None, - } - }; - let opp = game.opponent(seat); - let opp_creatures = - game.battlefield.iter().any(|id| game.obj(*id).controller == opp && game.has_type(*id, CardType::Creature)); - let minus = abilities - .iter() - .copied() - .filter(|i| cost(*i).is_some_and(|c| c < 0 && loyalty + c > 0)) - .filter(|i| ability_kind(&o.def, *i).removal && opp_creatures) - .min_by_key(|i| cost(*i)); - let plus = abilities.iter().copied().filter(|i| cost(*i).is_some_and(|c| c >= 0)).max_by_key(|i| cost(*i)); - minus.or(plus).or(abilities.first().copied()).map(|i| Answer::Ability(source, i)) -} -#[cfg(test)] -mod tests { - use super::*; - use crate::duel::{new_duel, Deck}; - - /// A card name goes to the opponent's card with an activated ability, never one of the seat's own - #[test] - fn names_the_opponents_activated_card() { - let db = playmat_engine::cards(); - let mine = Deck::parse("a", "20 Plains\n1 Aether Vial"); - let theirs = Deck::parse("b", "20 Plains\n1 Aether Vial\n1 Arid Mesa"); - let mut game = new_duel(&db, [&mine, &theirs], 1, 0).unwrap(); - let on = |game: &Game, seat: Seat, name: &str| { - game.objs.iter().find(|o| o.owner == seat && o.def.name == name && o.zone != Zone::Battlefield).unwrap().id - }; - let id = on(&game, 0, "Aether Vial"); - game.move_to(id, Zone::Library); - for name in ["Aether Vial", "Arid Mesa", "Plains"] { - let id = on(&game, 1, name); - game.move_to(id, Zone::Battlefield); - } - assert_eq!(card_name(&game, 0, "Card name").unwrap(), "Aether Vial"); - assert_eq!(card_name(&game, 0, "Land card name").unwrap(), "Arid Mesa"); - assert_eq!(card_name(&game, 0, "Choose a nonland card name").unwrap(), "Aether Vial"); - // the seat's own Aether Vial, in its hand, isn't named - let id = on(&game, 0, "Aether Vial"); - game.move_to(id, Zone::Hand); - assert_eq!(card_name(&game, 0, "Card name").unwrap(), "Arid Mesa"); - // nothing of theirs seen: Island - assert_eq!(card_name(&game, 1, "Card name").unwrap(), "Island"); - // not a name question: none - assert_eq!(card_name(&game, 0, "Choose a color"), None); - } - - /// Replicate's question is declined, by the quick answer and by the search (`Outcome.AIDontUseIt`): the engine - /// asks again after every yes, so an AI that says yes is asked forever (game 5b6e1d86 on 2026-11-16) - #[test] - fn the_ai_declines_to_replicate() { - use playmat_engine::decide::Decider; - let db = playmat_engine::cards(); - let deck = Deck::parse("d", "20 Island\n4 Consign to Memory"); - let game = new_duel(&db, [&deck, &deck], 1, 0).unwrap(); - let q = Query::YesNo { message: "Pay 1 time Replicate {1} ?".into() }; - assert_eq!(Policy::default().answer(&game, 0, &q), Answer::Bool(false)); - let mut table = crate::search::Table::new(vec![Some(crate::search::Config::default()), None]); - assert_eq!(table.answer(&game, 0, &q), Answer::Bool(false)); - // other questions still get a yes - let other = Query::YesNo { message: "Pay Kicker {2} ?".into() }; - assert_eq!(Policy::default().answer(&game, 0, &other), Answer::Bool(true)); - } -} +//! The quick answers: what a seat says when nothing is searched. Searches play their games out with these, for +//! both seats, so they must be cheap and never get stuck (the engine asks again after an answer it can't use, and +//! the search's answer budget ends any loop). + +use crate::eval; +use playmat_engine::card::{CardType, ManaCost}; +use playmat_engine::decide::{Answer, Query}; +use playmat_engine::rules; +use playmat_engine::state::{Game, Obj, ObjId, Seat, Step, Zone}; +use std::collections::HashMap; +use std::sync::Arc; + +/// Effects whose text says they hurt what they target +const HARMFUL: [&str; 16] = [ + "destroy", + "exile", + "damage", + "to its owner's hand", + "tap target", + "counter target", + "sacrifice", + "fights", + "fight ", + "loses", + "lose ", + "discard", + "gets -", + "get -", + "-1/-1", + "can't block", +]; + +#[derive(Default)] +pub struct Policy { + /// whether a spell or ability (by its card, and ability) hurts its targets + harmful: HashMap<(usize, Option), bool>, + /// blockers declared this combat, so a refused block isn't tried again + tried_blockers: Vec, + blocker: Option, + /// the game at the last priority question, roughly, and what was played then: a play that comes straight back + /// to the same priority (a cancelled cast) isn't tried again until something changes + last: Option<(Progress, Option)>, + banned: Vec, + /// the stronger answers (`Config::playout` 2): instant-speed play, abilities, removal and burn by the effect + v2: bool, +} + +#[derive(Clone, PartialEq, Eq)] +struct Progress([u64; 9]); + +/// A yes/no question the AI always declines, as Java's `Outcome.AIDontUseIt` makes `ComputerPlayer.chooseUse` say no: +/// replicate's "Pay N times Replicate {1} ?" (`ReplicateAbility`), which is asked again after each yes and never +/// checks the mana for the copies (game 5b6e1d86 on 2026-11-16: an AI that said yes was asked forever) +pub fn declines(message: &str) -> bool { + message.starts_with("Pay ") && message.contains(" Replicate ") +} + +fn progress(game: &Game, seat: Seat) -> Progress { + let p = game.player(seat); + let tapped = game.battlefield.iter().filter(|id| game.obj(**id).tapped).count() as u64; + Progress([ + game.turn as u64, + game.step.map(|s| s as u64).unwrap_or(99), + game.stack.len() as u64, + game.battlefield.len() as u64, + p.hand.len() as u64, + p.graveyard.len() as u64, + p.mana_pool.total() as u64, + tapped, + (p.life as i64 + 1000) as u64 * 1000 + (game.player(game.opponent(seat)).life as i64 + 1000) as u64, + ]) +} + +impl Policy { + /// The quick answers of a `Config::playout` version (1, or 2 for the stronger ones) + pub fn version(v: u8) -> Policy { + Policy { v2: v >= 2, ..Policy::default() } + } + + pub fn answer(&mut self, game: &Game, seat: Seat, q: &Query) -> Answer { + match q { + Query::Priority { playable } => { + self.tried_blockers.clear(); + let playable = self.playable(game, seat, playable); + let a = self.priority(game, seat, &playable); + self.played(&a); + a + } + Query::PlayMana { cost, sources } => pay(game, seat, cost, sources), + Query::Target { players, objs, required } => self.target(game, seat, players, objs, *required), + Query::Attackers { creatures } => attack(game, seat, creatures), + Query::Blockers { creatures } => self.block(game, seat, creatures), + Query::BlockTarget { attackers } => self.block_target(game, attackers), + Query::Cards { objs, required } => cards(game, seat, objs, *required), + Query::MultiAmount { defaults, .. } => { + Answer::Text(defaults.iter().map(|d| d.to_string()).collect::>().join(" ")) + } + Query::ChooseAbility { source, abilities } if self.v2 => loyalty_ability(game, seat, *source, abilities) + .or_else(|| { + // activated at priority, not paying for something: an ability that does more than make mana + let paying = game.unpaid.is_some() || game.mana_paid.is_some(); + let def = &game.obj(*source).def; + (!paying) + .then(|| { + abilities + .iter() + .copied() + .find(|i| def.abilities.get(*i).is_some_and(|a| a.mana().is_none())) + }) + .flatten() + .map(|i| Answer::Ability(*source, i)) + }) + .unwrap_or_else(|| choose_ability(game, seat, *source, abilities)), + Query::ChooseAbility { source, abilities } => { + let paying = game.unpaid.is_some() || game.mana_paid.is_some(); + let def = &game.obj(*source).def; + (!paying) + .then(|| { + abilities + .iter() + .copied() + .find(|i| def.abilities.get(*i).is_some_and(|a| a.mana().is_none())) + }) + .flatten() + .map(|i| Answer::Ability(*source, i)) + .unwrap_or_else(|| choose_ability(game, seat, *source, abilities)) + } + Query::PickTrigger { .. } => Answer::Trigger(0), + Query::YesNo { message } => Answer::Bool(!declines(message)), + Query::ChooseMode { modes } => modes.first().map(|m| Answer::Mode(*m)).unwrap_or(Answer::ModeDone), + Query::Amount { min, max } => Answer::Int(x_amount(game, seat).clamp(*min, (*max).max(*min))), + Query::Choice { message, choices } => choice(game, seat, message, choices), + } + } + + /// The playable objects less those that came straight back last time. Call once per priority question. + pub fn playable(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Vec { + let now = progress(game, seat); + match self.last.take() { + Some((before, Some(played))) if before == now => self.banned.push(played), + Some((before, _)) if before == now => {} + _ => self.banned.clear(), + } + self.last = Some((now, None)); + playable.iter().copied().filter(|id| !self.banned.contains(id)).collect() + } + + /// What was answered at the priority question `playable` was called for. + pub fn played(&mut self, a: &Answer) { + if let Some((_, played)) = self.last.as_mut() { + *played = match a { + Answer::Obj(id) | Answer::Ability(id, _) => Some(*id), + _ => None, + }; + } + } + + /// A land first, then the costliest spell in hand, in a main phase of the seat's own turn with nothing on the + /// stack; otherwise pass. Abilities of permanents are left to the search. + pub fn priority(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Answer { + if self.v2 { + return self.priority_v2(game, seat, playable); + } + let main = game.step.is_some_and(|s| s.is_main()); + if game.active != Some(seat) || !main || !game.stack.is_empty() { + return Answer::Bool(false); + } + let in_hand: Vec = playable.iter().copied().filter(|id| game.obj(*id).zone == Zone::Hand).collect(); + if let Some(land) = in_hand.iter().find(|id| game.obj(**id).def.types.contains(&CardType::Land)) { + return Answer::Obj(*land); + } + in_hand + .iter() + .chain(playable.iter().filter(|id| matches!(game.obj(**id).zone, Zone::Graveyard | Zone::Exile))) + .max_by_key(|id| game.obj(**id).def.mana_value()) + .map(|id| Answer::Obj(*id)) + .unwrap_or(Answer::Bool(false)) + } + + /// Whether what is being cast or put on the stack (the top) hurts its targets. + fn harmful(&mut self, game: &Game) -> bool { + let Some(top) = game.stack.last() else { return true }; + let key = (top.card.0 as usize, top.ability.map(|(i, _)| i)); + if let Some(h) = self.harmful.get(&key) { + return *h; + } + let def = game.item_def(top); + let text = match top.ability { + Some((i, _)) => def.abilities.get(i).map(|a| format!("{:?}", a)).unwrap_or_default().to_lowercase(), + None => def.spell.rule.to_lowercase(), + }; + let h = HARMFUL.iter().any(|w| text.contains(w)) + || ["destroy", "exile", "damage", "bounce", "tap", "counterunless", "sacrifice", "fight", "loselife"] + .iter() + .any(|w| text.contains(w)); + self.harmful.insert(key, h); + h + } + + fn target(&mut self, game: &Game, seat: Seat, players: &[Seat], objs: &[ObjId], required: bool) -> Answer { + // nothing left to choose ("up to one" with no legal target): done + if players.is_empty() && objs.is_empty() { + return Answer::Bool(false); + } + let opp = game.opponent(seat); + let harmful = self.harmful(game); + if self.v2 { + if let Some(a) = self.target_v2(game, seat, players, objs, harmful) { + return a; + } + } + let value = |id: &ObjId| { + let o = game.obj(*id); + if o.zone == Zone::Battlefield { + eval::permanent_score(game, *id) + } else { + eval::hand_card_score(game, *id) + } + }; + let whose = |id: &ObjId| game.obj(*id).controller; + if harmful { + if let Some(best) = objs.iter().filter(|o| whose(o) == opp).max_by_key(|o| value(o)) { + return Answer::Obj(*best); + } + if players.contains(&opp) { + return Answer::Player(opp); + } + } else { + if let Some(best) = objs.iter().filter(|o| whose(o) == seat).max_by_key(|o| value(o)) { + return Answer::Obj(*best); + } + if players.contains(&seat) { + return Answer::Player(seat); + } + } + let _ = required; + // only the wrong side (the AI picks whenever it can: a done means different things to Java's dialogs): the least the choice costs + if harmful { + objs.iter().min_by_key(|o| value(o)).map(|o| Answer::Obj(*o)) + } else { + objs.iter().max_by_key(|o| if whose(o) == seat { value(o) } else { -value(o) }).map(|o| Answer::Obj(*o)) + } + .or_else(|| players.first().map(|p| Answer::Player(*p))) + .unwrap_or(Answer::Stop) + } + + /// Blocks that kill the attacker or survive it, and chump blocks when the attack is lethal. + fn block(&mut self, game: &Game, seat: Seat, creatures: &[ObjId]) -> Answer { + let attackers = rules::attackers(game); + let unblocked: Vec = attackers.iter().copied().filter(|a| !game.obj(*a).blocked).collect(); + let incoming: i32 = unblocked.iter().map(|a| game.power_toughness(*a).0.max(0)).sum(); + let lethal = incoming >= game.player(seat).life; + for b in creatures { + if self.tried_blockers.contains(b) || !game.obj(*b).blocking.is_empty() { + continue; + } + let (bp, bt) = game.power_toughness(*b); + let good = unblocked.iter().copied().filter(|a| rules::can_block(game, *b, *a)).find(|a| { + let (ap, at) = game.power_toughness(*a); + bt > ap || (bp >= at && eval::permanent_score(game, *a) >= eval::permanent_score(game, *b)) + }); + let chump = if lethal { + unblocked + .iter() + .copied() + .filter(|a| rules::can_block(game, *b, *a)) + .max_by_key(|a| game.power_toughness(*a).0) + } else { + None + }; + if let Some(a) = good.or(chump) { + self.tried_blockers.push(*b); + self.blocker = Some(a); + return Answer::Obj(*b); + } + } + Answer::Bool(true) + } + + fn block_target(&mut self, game: &Game, attackers: &[ObjId]) -> Answer { + match self.blocker.take() { + Some(a) if attackers.contains(&a) => Answer::Obj(a), + _ => attackers + .iter() + .max_by_key(|a| game.power_toughness(**a).0) + .map(|a| Answer::Obj(*a)) + .unwrap_or(Answer::Bool(false)), + } + } +} + +/// Attacks with a creature no untapped opposing creature can block and kill, or with everything when that's lethal. +fn attack(game: &Game, seat: Seat, creatures: &[ObjId]) -> Answer { + let opp = game.opponent(seat); + let blockers: Vec = game + .battlefield + .iter() + .copied() + .filter(|b| { + let o = game.obj(*b); + o.controller == opp && !o.tapped && game.has_type(*b, CardType::Creature) + }) + .collect(); + let power: i32 = + creatures.iter().chain(rules::attackers(game).iter()).map(|c| game.power_toughness(*c).0.max(0)).sum(); + if blockers.is_empty() && !creatures.is_empty() { + return Answer::Text("special".into()); + } + if power >= game.player(opp).life + blockers.len() as i32 * 2 && !creatures.is_empty() { + return Answer::Text("special".into()); + } + for c in creatures { + let (cp, ct) = game.power_toughness(*c); + if cp <= 0 { + continue; + } + let dies = blockers.iter().any(|b| rules::can_block(game, *b, *c) && game.power_toughness(*b).0 >= ct); + if !dies { + return Answer::Obj(*c); + } + } + Answer::Bool(true) +} + +/// A mana source that makes a color still owed, else any; Cancel when none helps. +fn pay(game: &Game, seat: Seat, cost: &str, sources: &[ObjId]) -> Answer { + let owed = ManaCost::parse(cost).unwrap_or_default(); + let makes = |id: &ObjId| -> [u32; 6] { + let mut m = [0u32; 6]; + for a in game.obj(*id).def.abilities.iter() { + if let Some(mana) = a.mana() { + for (k, n) in mana.colored.iter().enumerate() { + m[k] += n; + } + m[5] += mana.colorless; + } + } + m + }; + let mut mine: Vec = sources.iter().copied().filter(|s| game.obj(*s).controller == seat).collect(); + // the permanent whose ability this pays for doesn't tap for it while another source can (Mutavault animated + // and then tapped for its own {1} can't attack) + if let Some(top) = game.stack.last().filter(|t| t.ability.is_some()) { + if mine.len() > 1 { + mine.retain(|s| *s != top.card); + } + } + // a color owed: the source making the fewest other colors, so flexible lands stay for later + for (k, n) in owed.colored.iter().enumerate() { + if *n > 0 { + if let Some(s) = + mine.iter().filter(|s| makes(s)[k] > 0).min_by_key(|s| makes(s).iter().filter(|n| **n > 0).count()) + { + return Answer::Obj(*s); + } + } + } + if owed.colorless > 0 { + if let Some(s) = mine.iter().find(|s| makes(s)[5] > 0) { + return Answer::Obj(*s); + } + } + if owed.snow > 0 { + // a snow symbol: only a snow permanent's mana pays it + if let Some(s) = mine.iter().find(|s| game.is_snow(**s)) { + return Answer::Obj(*s); + } + } + if owed.generic > 0 || owed.x > 0 { + // generic: the least useful source (colorless first, then the fewest colors) + if let Some(s) = mine.iter().min_by_key(|s| { + let m = makes(s); + // lands that can become creatures pay last, after creatures + let animates = game + .obj(**s) + .def + .abilities + .iter() + .enumerate() + .any(|(i, _)| ability_kind(&game.obj(**s).def, i).animate); + ( + animates as usize, + m[..5].iter().filter(|n| **n > 0).count(), + game.has_type(**s, CardType::Creature) as usize, + ) + }) { + return Answer::Obj(*s); + } + } + Answer::Bool(false) +} + +/// Of a permanent's abilities: for mana, one making a color the spell being paid for needs. +fn choose_ability(game: &Game, _seat: Seat, source: ObjId, abilities: &[usize]) -> Answer { + let def = &game.obj(source).def; + let need = game.stack.last().map(|t| game.item_def(t).cost.colored).unwrap_or_default(); + let best = abilities.iter().copied().find(|i| { + def.abilities.get(*i).and_then(|a| a.mana()).is_some_and(|m| (0..5).any(|k| m.colored[k] > 0 && need[k] > 0)) + }); + Answer::Ability(source, best.or(abilities.first().copied()).unwrap_or(0)) +} + +/// Cards from the seat's own hand go least valuable first (discards); other cards most valuable first. +fn cards(game: &Game, seat: Seat, objs: &[ObjId], required: bool) -> Answer { + let own_hand = objs.iter().all(|o| game.obj(*o).zone == Zone::Hand && game.obj(*o).owner == seat); + if !required && own_hand { + return Answer::Bool(false); + } + let pick = if own_hand { + objs.iter().min_by_key(|o| eval::hand_card_score(game, **o)) + } else { + objs.iter().max_by_key(|o| { + let v = if game.obj(**o).zone == Zone::Battlefield { + eval::permanent_score(game, **o) + } else { + eval::hand_card_score(game, **o) + }; + if game.obj(**o).controller == seat { + v + } else { + -v + } + }) + }; + pick.map(|o| Answer::Obj(*o)).unwrap_or(Answer::Bool(false)) +} + +/// X: what the seat's untapped mana sources make beyond the rest of the spell's cost. +fn x_amount(game: &Game, seat: Seat) -> i32 { + let sources = game + .battlefield + .iter() + .filter(|id| { + let o = game.obj(**id); + o.controller == seat && !o.tapped && o.def.abilities.iter().any(|a| a.mana().is_some()) + }) + .count() as i32 + + game.player(seat).mana_pool.total() as i32; + let rest = game + .stack + .last() + .map(|t| game.item_def(t).cost.clone()) + .map(|c| (c.generic + c.colorless + c.colored.iter().sum::()) as i32) + .unwrap_or(0); + let per = game.stack.last().map(|t| game.item_def(t).cost.x.max(1) as i32).unwrap_or(1); + ((sources - rest) / per).max(0) +} + +fn choice(game: &Game, seat: Seat, message: &str, choices: &[String]) -> Answer { + if !choices.is_empty() { + // a color of mana: one the spell being paid for needs + let need = game.stack.last().map(|t| game.item_def(t).cost.colored).unwrap_or_default(); + let names = ["White", "Blue", "Black", "Red", "Green"]; + for (k, n) in names.iter().enumerate() { + if need[k] > 0 { + if let Some(c) = choices.iter().find(|c| c.eq_ignore_ascii_case(n)) { + return Answer::Text(c.clone()); + } + } + } + return Answer::Text(choices[0].clone()); + } + if message.contains("creature type") { + // the type most of the seat's creatures share + let mut counts: HashMap<&str, usize> = HashMap::new(); + for o in game.objs.iter().filter(|o| o.owner == seat && o.def.types.contains(&CardType::Creature)) { + for s in o.def.subtypes.iter() { + *counts.entry(s.as_str()).or_default() += 1; + } + } + let best = counts.into_iter().max_by_key(|(n, c)| (*c, std::cmp::Reverse(*n))).map(|(n, _)| n.to_string()); + return Answer::Text(best.unwrap_or_else(|| "Human".into())); + } + if let Some(name) = card_name(game, seat, message) { + return Answer::Text(name); + } + Answer::Text(String::new()) +} + +/// "Choose a card name" (Pithing Needle, Phyrexian Revoker: the chosen name's activated abilities other than mana +/// abilities can't be activated): an opponent's card that fits the question, seen in a public zone, best one whose +/// abilities it could activate from where it is, then their lands, and never one of the seat's own. Nothing seen: +/// Island when a land fits, else any fitting card that isn't the seat's. None when the message isn't a card name +/// question. +fn card_name(game: &Game, seat: Seat, message: &str) -> Option { + game.objs.first()?.def.fits_name_question(message)?; + let fits = |o: &Obj| o.def.fits_name_question(message) == Some(true); + let mine: Vec<&str> = + game.objs.iter().filter(|o| o.owner == seat && o.zone != Zone::Library).map(|o| o.def.name.as_str()).collect(); + let theirs = |o: &&Arc| o.owner != seat && fits(o) && !mine.contains(&o.def.name.as_str()); + let mut scores: HashMap<&str, usize> = HashMap::new(); + for o in game.objs.iter().filter(theirs) { + if !matches!(o.zone, Zone::Battlefield | Zone::Graveyard | Zone::Exile) { + continue; + } + let usable = o.def.abilities.iter().filter(|a| a.activated().is_some()).any(|a| match o.zone { + Zone::Battlefield => !a.from_hand() && !a.from_graveyard(), + Zone::Graveyard => a.from_graveyard(), + _ => false, + }); + let any = o.def.abilities.iter().any(|a| a.activated().is_some()); + let land = o.def.is(CardType::Land) && o.zone == Zone::Battlefield; + let score = if usable { + 100 + } else if any { + 10 + } else if land { + 1 + } else { + 0 + }; + if score > 0 { + *scores.entry(o.def.name.as_str()).or_default() += score; + } + } + let best = scores.into_iter().max_by_key(|(n, c)| (*c, std::cmp::Reverse(*n))).map(|(n, _)| n.to_string()); + let island = ["Card name", "Choose a card name", "Land card name", "Choose a land card name"].contains(&message); + best.or_else(|| island.then(|| "Island".to_string())) + .or_else(|| game.objs.iter().filter(theirs).map(|o| o.def.name.clone()).min()) + .or_else(|| Some(String::new())) +} + +/// Catches a question asked again since the last priority question (an answer the engine ignored, one that toggles, +/// or two questions taking turns): each repeat gets an answer not given to it yet, then one that ends it. +#[derive(Default)] +pub struct Repeats { + asked: Vec<(Seat, Query, Vec)>, +} + +impl Repeats { + /// Whether `q` was asked since the last priority question + pub fn is_repeat(&self, seat: Seat, q: &Query) -> bool { + self.asked.iter().any(|(s, l, _)| *s == seat && l == q) + } + + pub fn guard(&mut self, seat: Seat, q: &Query, proposed: Answer, options: &[Answer]) -> Answer { + // a priority question coming back is normal (each play comes back to it): the policy's own check handles it + if matches!(q, Query::Priority { .. }) { + self.asked.clear(); + return proposed; + } + let Some(i) = self.asked.iter().position(|(s, l, _)| *s == seat && l == q) else { + self.asked.push((seat, q.clone(), vec![proposed.clone()])); + return proposed; + }; + let given = &mut self.asked[i].2; + let a = std::iter::once(proposed) + .chain(options.iter().cloned()) + .find(|a| !given.contains(a)) + .unwrap_or_else(|| finish(q, given.len(), options)); + given.push(a.clone()); + a + } +} + +/// An answer that ends a question: done, cancel, or (asked too often) stop. +fn finish(q: &Query, tries: usize, options: &[Answer]) -> Answer { + if tries > 40 { + return Answer::Stop; + } + match q { + Query::Attackers { .. } | Query::Blockers { .. } => Answer::Bool(true), + Query::ChooseMode { .. } => Answer::ModeDone, + Query::Amount { min, .. } => Answer::Int(*min), + Query::Choice { choices, .. } => choices.first().map(|c| Answer::Text(c.clone())).unwrap_or(Answer::Stop), + // a required choice can't be left: pick again (Java asks until the choice is made) + Query::Target { required: true, .. } | Query::Cards { required: true, .. } => { + options.get(tries % options.len().max(1)).cloned().unwrap_or(Answer::Stop) + } + _ => Answer::Bool(false), + } +} + +/// What a card's spell (or an ability) does, as far as the quick answers care: read from its rule text and the names +/// of its effects +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Kind { + /// counters a spell + pub counter: bool, + /// destroys, exiles, damages, shrinks, bounces or fights a creature + pub removal: bool, + /// fixed damage it deals, and whether a player can be its target + pub damage: Option, + pub face: bool, + /// makes a creature bigger or better for the turn + pub pump: bool, + /// draws or looks for cards + pub draw: bool, + /// a land or permanent that becomes a creature (Mutavault) + pub animate: bool, + /// destroys or damages every creature + pub sweeper: bool, +} + +/// The kind of a card's spell +pub fn spell_kind(def: &playmat_engine::card::CardDef) -> Kind { + kind_of(&def.spell.rule.to_lowercase(), &format!("{:?}", def.spell.effects)) +} + +/// The kind of a card's ability, by its index +pub fn ability_kind(def: &playmat_engine::card::CardDef, i: usize) -> Kind { + match def.abilities.get(i) { + Some(a) => { + let debug = format!("{a:?}"); + let rule = a.activated().map(|(r, ..)| r.to_lowercase()).unwrap_or_default(); + kind_of(&rule, &debug) + } + None => Kind::default(), + } +} + +fn kind_of(rule: &str, effects: &str) -> Kind { + let damage = rule.find(" deals ").and_then(|at| { + let rest = &rule[at + 7..]; + let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + n.parse::().ok().filter(|_| rest.contains("damage")) + }); + let face = damage.is_some() + && (rule.contains("any target") + || rule.contains("target player") + || rule.contains("target opponent") + || rule.contains("each opponent")); + let sweeper = rule.contains("destroy all creatures") + || rule.contains("each creature") + || effects.contains("DestroyAllEffect") + || effects.contains("DamageAllEffect"); + Kind { + counter: rule.contains("counter target") || effects.contains("CounterTargetEffect"), + removal: !sweeper + && (rule.contains("destroy target") + || rule.contains("exile target") + || (damage.is_some() && (rule.contains("target creature") || rule.contains("any target"))) + || rule.contains("target creature an opponent controls gets -") + || rule.contains("target creature gets -") + || rule.contains("fights") + || rule.contains("to its owner's hand") + || effects.contains("DestroyTargetEffect") + || effects.contains("ExileTargetEffect") + || effects.contains("FightTargetsEffect")), + damage, + face, + pump: (rule.contains("target creature gets +") || effects.contains("BoostTargetEffect")) + && !rule.contains("gets -"), + draw: rule.contains("draw") || rule.contains("look at the top"), + animate: effects.contains("BecomesCreatureSourceEffect"), + sweeper, + } +} + +impl Policy { + /// The stronger quick answers (`Config::playout` 2): + /// - with an opponent's spell on the stack: a counterspell when the spell is worth one, else pass; + /// - in its own main phase with an empty stack: a land, burn to the face when that's lethal, its most expensive + /// spell (counters, tricks and sweepers that would hit more of its own creatures held back), a planeswalker's + /// loyalty ability, an equip, and before combat a land that becomes a creature when it can attack; + /// - in combat: removal on an attacker, a pump on a blocked attacker or on a blocker; + /// - at the end of the opponent's turn: flash creatures, removal and card draw with the mana left. + fn priority_v2(&mut self, game: &Game, seat: Seat, playable: &[ObjId]) -> Answer { + let opp = game.opponent(seat); + let mine = game.active == Some(seat); + let step = game.step; + let own: Vec = playable + .iter() + .copied() + .filter(|id| { + let o = game.obj(*id); + o.controller == seat || o.owner == seat + }) + .collect(); + let castable: Vec = own + .iter() + .copied() + .filter(|id| matches!(game.obj(*id).zone, Zone::Hand | Zone::Graveyard | Zone::Exile)) + .collect(); + let kind = |id: ObjId| spell_kind(&game.obj(id).def); + let is = |id: ObjId, t: CardType| game.obj(id).def.types.contains(&t); + let instant_speed = |id: ObjId| { + is(id, CardType::Instant) + || game + .obj(id) + .def + .abilities + .iter() + .any(|a| matches!(a, playmat_engine::card::AbilityDef::FlashAbility)) + }; + let creatures = |s: Seat| -> Vec { + game.battlefield + .iter() + .copied() + .filter(|id| game.obj(*id).controller == s && game.has_type(*id, CardType::Creature)) + .collect() + }; + + // the stack: answer an opponent's spell, or let it resolve + if let Some(top) = game.stack.last() { + if top.controller == opp && top.ability.is_none() { + let spell = &game.obj(top.card).def; + let worth = spell.mana_value() >= 2 || spell_kind(spell).removal || spell_kind(spell).sweeper; + if worth { + if let Some(c) = castable.iter().copied().find(|c| kind(*c).counter) { + return Answer::Obj(c); + } + } + } + return Answer::Bool(false); + } + + let combat = matches!(step, Some(Step::DeclareAttackers) | Some(Step::DeclareBlockers)); + if combat { + let attackers = rules::attackers(game); + if !mine && !attackers.is_empty() { + // removal on an attacker + if let Some(c) = castable.iter().copied().find(|c| instant_speed(*c) && kind(*c).removal) { + return Answer::Obj(c); + } + } + if step == Some(Step::DeclareBlockers) { + let fighting = attackers.iter().any(|a| { + let o = game.obj(*a); + (mine && o.blocked) || (!mine && !o.blocked_by.is_empty()) + }); + if fighting { + if let Some(c) = castable.iter().copied().find(|c| instant_speed(*c) && kind(*c).pump) { + return Answer::Obj(c); + } + } + } + return Answer::Bool(false); + } + + if !mine { + // the opponent's end step: use the mana left + if step == Some(Step::EndTurn) { + let opp_creatures = !creatures(opp).is_empty(); + let pick = castable + .iter() + .copied() + .filter(|c| instant_speed(*c) && !is(*c, CardType::Land)) + .filter(|c| { + let k = kind(*c); + (k.removal && opp_creatures) || k.draw || is(*c, CardType::Creature) + }) + .max_by_key(|c| game.obj(*c).def.mana_value()); + if let Some(c) = pick { + return Answer::Obj(c); + } + } + return Answer::Bool(false); + } + + // its own turn, outside combat + if !step.is_some_and(|s| s.is_main()) { + return Answer::Bool(false); + } + if let Some(land) = + castable.iter().copied().find(|id| is(*id, CardType::Land) && game.obj(*id).zone == Zone::Hand) + { + return Answer::Obj(land); + } + // burn to the face when it's lethal + let opp_life = game.player(opp).life; + let burn: Vec = + castable.iter().copied().filter(|c| kind(*c).face && kind(*c).damage.is_some()).collect(); + let total: i32 = burn.iter().map(|c| kind(*c).damage.unwrap_or(0)).sum(); + if total >= opp_life { + if let Some(c) = burn.iter().copied().max_by_key(|c| kind(*c).damage) { + return Answer::Obj(c); + } + } + let my_count = creatures(seat).len(); + let opp_count = creatures(opp).len(); + let spell = castable + .iter() + .copied() + .filter(|c| { + let k = kind(*c); + if is(*c, CardType::Land) || k.counter { + return false; + } + // tricks wait for combat + if k.pump && !is(*c, CardType::Creature) { + return false; + } + // a sweeper only when it costs the opponent more creatures than it costs us + if k.sweeper && opp_count <= my_count { + return false; + } + // removal needs something to remove + if k.removal && !k.face && opp_count == 0 && !is(*c, CardType::Creature) { + return false; + } + true + }) + .max_by_key(|c| game.obj(*c).def.mana_value()); + if let Some(c) = spell { + return Answer::Obj(c); + } + // permanents' abilities: planeswalkers, equipment, lands that become creatures before combat + for id in own.iter().copied().filter(|id| game.obj(*id).zone == Zone::Battlefield) { + let o = game.obj(id); + if o.def.types.contains(&CardType::Planeswalker) && o.loyalty_used == 0 { + return Answer::Obj(id); + } + if game.has_subtype(id, "Equipment") && game.attached(id).is_none() && my_count > 0 { + return Answer::Obj(id); + } + let animates = o.def.abilities.iter().enumerate().any(|(i, _)| ability_kind(&o.def, i).animate); + if animates + && step == Some(Step::PrecombatMain) + && !game.has_type(id, CardType::Creature) + && !o.tapped + && game.turn > o.entered_turn + { + return Answer::Obj(id); + } + } + Answer::Bool(false) + } + + /// Targets the stronger answers pick differently: lethal burn to the face, damage to a creature it kills (the + /// best such, attacking first), and in combat help for its own creature that is fighting. `None`: as before. + fn target_v2( + &mut self, + game: &Game, + seat: Seat, + players: &[Seat], + objs: &[ObjId], + harmful: bool, + ) -> Option { + let opp = game.opponent(seat); + let top = game.stack.last()?; + let def = game.item_def(top); + let k = match top.ability { + Some((i, _)) => ability_kind(def, i), + None => spell_kind(def), + }; + let theirs: Vec = objs.iter().copied().filter(|o| game.obj(*o).controller == opp).collect(); + if harmful { + if let Some(n) = k.damage { + if players.contains(&opp) && n >= game.player(opp).life { + return Some(Answer::Player(opp)); + } + // the best creature the damage kills, an attacker first + let kills = theirs + .iter() + .copied() + .filter(|o| game.obj(*o).zone == Zone::Battlefield && game.has_type(*o, CardType::Creature)) + .filter(|o| game.power_toughness(*o).1 - game.obj(*o).damage <= n) + .max_by_key(|o| (game.obj(*o).attacking.is_some(), eval::permanent_score(game, *o))); + if let Some(o) = kills { + return Some(Answer::Obj(o)); + } + if players.contains(&opp) { + return Some(Answer::Player(opp)); + } + } + // in combat, an attacker first + let attacking = theirs + .iter() + .copied() + .filter(|o| game.obj(*o).attacking.is_some()) + .max_by_key(|o| eval::permanent_score(game, *o)); + return attacking.map(Answer::Obj); + } + // help: its own creature in a fight + let fighting = objs + .iter() + .copied() + .filter(|o| { + let x = game.obj(*o); + x.controller == seat && (x.attacking.is_some() || !x.blocking.is_empty()) + }) + .max_by_key(|o| { + let x = game.obj(*o); + (x.blocked || !x.blocking.is_empty(), eval::permanent_score(game, *o)) + }); + fighting.map(Answer::Obj) + } +} + +/// A planeswalker's loyalty ability: the minus one that keeps it alive when the opponent has a creature for it to +/// remove, else its plus ability, else the first +fn loyalty_ability(game: &Game, seat: Seat, source: ObjId, abilities: &[usize]) -> Option { + let o = game.obj(source); + if !o.def.types.contains(&CardType::Planeswalker) { + return None; + } + let loyalty = o.counter("loyalty"); + let cost = |i: usize| -> Option { + match o.def.abilities.get(i)? { + playmat_engine::card::AbilityDef::LoyaltyAbility { cost, .. } => cost.iter().find_map(|c| match c { + playmat_engine::card::CostDef::PayLoyaltyCost { amount } => Some(*amount), + _ => None, + }), + _ => None, + } + }; + let opp = game.opponent(seat); + let opp_creatures = + game.battlefield.iter().any(|id| game.obj(*id).controller == opp && game.has_type(*id, CardType::Creature)); + let minus = abilities + .iter() + .copied() + .filter(|i| cost(*i).is_some_and(|c| c < 0 && loyalty + c > 0)) + .filter(|i| ability_kind(&o.def, *i).removal && opp_creatures) + .min_by_key(|i| cost(*i)); + let plus = abilities.iter().copied().filter(|i| cost(*i).is_some_and(|c| c >= 0)).max_by_key(|i| cost(*i)); + minus.or(plus).or(abilities.first().copied()).map(|i| Answer::Ability(source, i)) +} +#[cfg(test)] +mod tests { + use super::*; + use crate::duel::{new_duel, Deck}; + + /// A card name goes to the opponent's card with an activated ability, never one of the seat's own + #[test] + fn names_the_opponents_activated_card() { + let db = playmat_engine::cards(); + let mine = Deck::parse("a", "20 Plains\n1 Aether Vial"); + let theirs = Deck::parse("b", "20 Plains\n1 Aether Vial\n1 Arid Mesa"); + let mut game = new_duel(&db, [&mine, &theirs], 1, 0).unwrap(); + let on = |game: &Game, seat: Seat, name: &str| { + game.objs.iter().find(|o| o.owner == seat && o.def.name == name && o.zone != Zone::Battlefield).unwrap().id + }; + let id = on(&game, 0, "Aether Vial"); + game.move_to(id, Zone::Library); + for name in ["Aether Vial", "Arid Mesa", "Plains"] { + let id = on(&game, 1, name); + game.move_to(id, Zone::Battlefield); + } + assert_eq!(card_name(&game, 0, "Card name").unwrap(), "Aether Vial"); + assert_eq!(card_name(&game, 0, "Land card name").unwrap(), "Arid Mesa"); + assert_eq!(card_name(&game, 0, "Choose a nonland card name").unwrap(), "Aether Vial"); + // the seat's own Aether Vial, in its hand, isn't named + let id = on(&game, 0, "Aether Vial"); + game.move_to(id, Zone::Hand); + assert_eq!(card_name(&game, 0, "Card name").unwrap(), "Arid Mesa"); + // nothing of theirs seen: Island + assert_eq!(card_name(&game, 1, "Card name").unwrap(), "Island"); + // not a name question: none + assert_eq!(card_name(&game, 0, "Choose a color"), None); + } + + /// Replicate's question is declined, by the quick answer and by the search (`Outcome.AIDontUseIt`): the engine + /// asks again after every yes, so an AI that says yes is asked forever (game 5b6e1d86 on 2026-11-16) + #[test] + fn the_ai_declines_to_replicate() { + use playmat_engine::decide::Decider; + let db = playmat_engine::cards(); + let deck = Deck::parse("d", "20 Island\n4 Consign to Memory"); + let game = new_duel(&db, [&deck, &deck], 1, 0).unwrap(); + let q = Query::YesNo { message: "Pay 1 time Replicate {1} ?".into() }; + assert_eq!(Policy::default().answer(&game, 0, &q), Answer::Bool(false)); + let mut table = crate::search::Table::new(vec![Some(crate::search::Config::default()), None]); + assert_eq!(table.answer(&game, 0, &q), Answer::Bool(false)); + // other questions still get a yes + let other = Query::YesNo { message: "Pay Kicker {2} ?".into() }; + assert_eq!(Policy::default().answer(&game, 0, &other), Answer::Bool(true)); + } +} diff --git a/rust/crates/playmat-ai/src/search.rs b/rust/crates/playmat-ai/src/search.rs index b1e262e..78b1128 100644 --- a/rust/crates/playmat-ai/src/search.rs +++ b/rust/crates/playmat-ai/src/search.rs @@ -261,7 +261,7 @@ impl Table { } let candidates = candidates(game, seat, q, &quick, cfg.width); if candidates.len() < 2 { - return quick; + return candidates.into_iter().next().unwrap_or(quick); } // a lower skill's mistakes: now and then a candidate at random instead of the search (never a payment) if cfg.blunder > 0 && !matches!(q, Query::PlayMana { .. }) { @@ -624,8 +624,26 @@ pub fn candidates(game: &Game, seat: Seat, q: &Query, quick: &Answer, width: usi } } Query::ChooseAbility { source, abilities } => { + drop(add); + let paying = game.unpaid.is_some() || game.mana_paid.is_some(); + let def = &game.obj(*source).def; + let has_non_mana = + !paying && abilities.iter().any(|i| def.abilities.get(*i).is_some_and(|a| a.mana().is_none())); + if has_non_mana { + if let Some(Answer::Ability(src, qi)) = out.first() { + if src == source && def.abilities.get(*qi).is_some_and(|a| a.mana().is_some()) { + out.clear(); + } + } + } for i in abilities { - add(Answer::Ability(*source, *i)); + if has_non_mana && def.abilities.get(*i).is_some_and(|a| a.mana().is_some()) { + continue; + } + let a = Answer::Ability(*source, *i); + if !out.contains(&a) { + out.push(a); + } } } Query::YesNo { message } if !message.contains("mana pool") && !crate::policy::declines(message) => { diff --git a/rust/crates/playmat-ai/src/selfplay.rs b/rust/crates/playmat-ai/src/selfplay.rs index f1278d1..1dc1b84 100644 --- a/rust/crates/playmat-ai/src/selfplay.rs +++ b/rust/crates/playmat-ai/src/selfplay.rs @@ -10,7 +10,7 @@ use crate::decision::{Choice, Decision, DecisionPolicy, PolicyKind}; use crate::net::{self, softmax}; -use crate::obs::{self, Obs, ACT_F, ENT_F, GLOB_F}; +use crate::obs::{self, Obs, ACT_F, BELIEF_META_F, ENT_F, GLOB_F}; use crate::search::Config; use playmat_engine::decide::Query; use playmat_engine::state::{Game, ObjId, Seat, Zone}; @@ -157,8 +157,21 @@ pub(crate) fn sample_games_weighted( ) -> Vec<(Game, f64)> { let seed = ((d.game.turn as u64) << 40) ^ ((root.since.len() as u64) << 16) ^ d.seat as u64 ^ *rng; mix(rng); - match &root.hidden { - Some(h) if net.has_belief() => { + let Some(h) = &root.hidden else { + return vec![(root.snapshot.clone(), 1.0)]; + }; + let opp_unseen_hand = root + .snapshot + .player(root.snapshot.opponent(d.seat)) + .hand + .iter() + .filter(|id| !h.seat_saw(**id)) + .count(); + // When opponent has no hidden hand cards (hellbent / fully revealed), cap world count to 2 so + // multi-tree search focuses depth instead of splitting iters across 16 near-identical trees. + let eff_k = if opp_unseen_hand == 0 { k.min(2).max(1) } else { k.max(1) }; + match Some(h) { + Some(h) if net.has_belief() && opp_unseen_hand > 0 => { let seen = |id: ObjId| h.seat_saw(id); let pool: Vec = unseen(&root.snapshot, d.seat, seen) .iter() @@ -166,7 +179,7 @@ pub(crate) fn sample_games_weighted( .collect(); let z = net.belief(state, &pool); let logit: std::collections::HashMap = pool.iter().copied().zip(z).collect(); - let mut drawn: Vec<(f32, Game)> = (0..k * 3) + let mut drawn: Vec<(f32, Game)> = (0..eff_k * 3) .map(|j| { let g = root.sample(seed.wrapping_add(j as u64 * 0x9E37)); (hand_likelihood(&g, d.seat, &logit, &seen), g) @@ -176,7 +189,7 @@ pub(crate) fn sample_games_weighted( let w: Vec = drawn.iter().map(|(l, _)| (l - m).exp()).collect(); let s: f32 = w.iter().sum(); let w: Vec = w.iter().map(|v| v / s).collect(); - let mut picks: Vec = (0..k).map(|_| draw(&w, rng)).collect(); + let mut picks: Vec = (0..eff_k).map(|_| draw(&w, rng)).collect(); picks.sort(); let mut groups: Vec<(usize, u32)> = Vec::new(); for p in picks { @@ -194,7 +207,7 @@ pub(crate) fn sample_games_weighted( } keep } - _ => (0..k).map(|j| (root.sample(seed.wrapping_add(j as u64 * 0x9E37)), 1.0)).collect(), + _ => (0..eff_k).map(|j| (root.sample(seed.wrapping_add(j as u64 * 0x9E37)), 1.0)).collect(), } } @@ -427,6 +440,12 @@ pub struct Step { pub logp: f32, /// search's estimated root win probability (0..1), or NaN if none pub qval: f32, + /// v3: per-candidate search Q-value (0..1, or NaN for unvisited candidates) + pub act_q: Vec, + /// v3: per-candidate search visit counts + pub act_n: Vec, + /// v3: structured 8-float public-belief summary (`belief_meta.f16`) + pub belief_meta: [f32; BELIEF_META_F], } /// The seats' recorded decisions, shared with the game's runner @@ -521,6 +540,16 @@ impl DecisionPolicy for Recording { let (hidden, hidden_ids) = obs::hidden_entities(d.game, d.seat); let seen = |id: ObjId| self.seen.seat_saw(id); let pool = unseen(d.game, d.seat, seen); + let act_q: Vec = match self.inner.last_action_qs() { + Some(qs) if qs.len() == k => qs.to_vec(), + _ => vec![f32::NAN; k], + }; + let act_n: Vec = match self.inner.last_action_visits() { + Some(ns) if ns.len() == k => ns.to_vec(), + _ => vec![0u32; k], + }; + let unseen_hand_count = pool.iter().filter(|(_, h)| *h).count(); + let belief_meta = obs::belief_meta(d.game, d.seat, unseen_hand_count); let step = Step { seat: d.seat, turn: d.game.turn, @@ -534,6 +563,9 @@ impl DecisionPolicy for Recording { logp: target[chosen].max(1e-8).ln(), qval: self.inner.last_value().unwrap_or(f32::NAN), target, + act_q, + act_n, + belief_meta, }; self.sink.lock().unwrap().push(step); choice @@ -546,6 +578,14 @@ impl DecisionPolicy for Recording { fn last_value(&self) -> Option { self.inner.last_value() } + + fn last_action_qs(&self) -> Option<&[f32]> { + self.inner.last_action_qs() + } + + fn last_action_visits(&self) -> Option<&[u32]> { + self.inner.last_action_visits() + } } /// f32 to IEEE half, rounded to nearest (no NaN payloads) @@ -584,7 +624,7 @@ pub struct Shard { } pub const META: usize = 10; -const COLUMNS: [&str; 17] = [ +const COLUMNS: [&str; 20] = [ "meta.i32", "logp.f32", "glob.f16", @@ -601,6 +641,9 @@ const COLUMNS: [&str; 17] = [ "ent_rel_idx.u8", "ent_rel_type.u8", "act_ent_idx.u8", + "act_q.f16", + "act_n.u16", + "belief_meta.f16", "games.jsonl", ]; @@ -609,10 +652,10 @@ impl Shard { std::fs::create_dir_all(dir)?; let open = |c: &str| std::fs::File::create(format!("{dir}/{name}.{c}")).map(std::io::BufWriter::new); let mut files = Vec::new(); - for c in &COLUMNS[..16] { + for c in &COLUMNS[..19] { files.push(open(c)?); } - Ok(Shard { files, games: open(COLUMNS[16])?, steps: 0 }) + Ok(Shard { files, games: open(COLUMNS[19])?, steps: 0 }) } /// Writes one game's decisions and its result (`result[seat]`: 1 won, 0 lost, 0.5 a draw) @@ -659,6 +702,19 @@ impl Shard { f[13].write_all(&s.obs.ent_rel_idx)?; f[14].write_all(&s.obs.ent_rel_type)?; f[15].write_all(&s.obs.act_ent_idx)?; + let aq = if s.act_q.len() == s.obs.n_acts() { + h(&s.act_q) + } else { + h(&vec![f32::NAN; s.obs.n_acts()]) + }; + let an: Vec = if s.act_n.len() == s.obs.n_acts() { + s.act_n.iter().flat_map(|x| ((*x).min(u16::MAX as u32) as u16).to_le_bytes()).collect() + } else { + vec![0u8; s.obs.n_acts() * 2] + }; + f[16].write_all(&aq)?; + f[17].write_all(&an)?; + f[18].write_all(&h(&s.belief_meta))?; } self.steps += steps.len(); let mut line = info; diff --git a/rust/crates/playmat-ai/src/tree.rs b/rust/crates/playmat-ai/src/tree.rs index dd0d2af..a11396f 100644 --- a/rust/crates/playmat-ai/src/tree.rs +++ b/rust/crates/playmat-ai/src/tree.rs @@ -105,10 +105,10 @@ fn quiescent(game: &Game) -> bool { /// while non-terminal moves (`0.02..=0.98`) keep policy-prior regularization against value noise. fn sigma_gumbel(q: f32, most: usize, c_scale: f32) -> f32 { let base = (50.0 + most as f32) * c_scale * q; - if q >= 0.999 { - base + 10.0 - } else if q <= 0.001 { - base - 10.0 + if q > 0.9801 { + base + 500.0 * (q - 0.98) + } else if q < 0.0199 { + base - 500.0 * (0.02 - q) } else { base } @@ -360,7 +360,7 @@ impl Walk { // a question with one answer worth trying passes through without moving let options = candidates(game, seat, q, quick, self.width); if options.len() < 2 { - return None; + return options.first().filter(|a| *a != quick).cloned(); } if self.tree.nodes[at].kids.is_empty() { if self.expanded { @@ -447,13 +447,16 @@ impl Walk { } } -fn eval_iteration(game: &Game, walk: &Walk, seat: Seat, base: i64, cfg: &Config, net: &Net) -> f64 { +fn eval_iteration(game: &Game, walk: &Walk, seat: Seat, root_turn: u32, base: i64, cfg: &Config, net: &Net) -> f64 { let over = crate::eval::evaluate(game, seat); + // Fastest-win / longest-survival discipline: immediate lethal (1.000) beats slow wins (0.996..0.984) + // while staying strictly separated from non-terminal clamped leaves [0.020, 0.980]. + let dt = game.turn.saturating_sub(root_turn).min(4) as f64; if over >= crate::eval::WIN { - return 1.0; + return 1.0 - 0.004 * dt; } if over <= crate::eval::LOSE { - return 0.0; + return 0.004 * dt; } if cfg.leaf_blend >= 1000 { if let Some((ls, lv)) = walk.leaf_value { @@ -476,6 +479,8 @@ pub struct Ismcts { rng: u64, last: Vec, last_val: Option, + last_qs: Vec, + last_visits: Vec, /// Warm subtree from the previous decision for state-hash-guarded tree reuse saved: Option, /// Exact neural-evaluation memoization cache shared across worlds and consecutive moves @@ -489,6 +494,8 @@ impl Ismcts { rng: seed, last: Vec::new(), last_val: None, + last_qs: Vec::new(), + last_visits: Vec::new(), saved: None, cache: Arc::new(EvalCache::new()), cache_net_ptr: 0, @@ -504,6 +511,8 @@ impl DecisionPolicy for Ismcts { fn decide(&mut self, d: &Decision) -> Option { self.last.clear(); self.last_val = None; + self.last_qs.clear(); + self.last_visits.clear(); if skipped(d.query) { return None; } @@ -529,7 +538,8 @@ impl DecisionPolicy for Ismcts { let tree_width = cfg.width.max(2); let weighted = sample_games_weighted(&mut self.rng, d, root, &net, &out.h, cfg.samples.max(1)); let (mut games, weights): (Vec, Vec) = weighted.into_iter().unzip(); - let stop = d.game.turn + 1 + cfg.extra_turns; + let root_turn = d.game.turn; + let stop = root_turn + 1 + cfg.extra_turns; let per = (cfg.budget / 16).clamp(50, cfg.playout_cap); let base = if pure_leaf { 0 } else { crate::eval::score_with(d.game, d.seat, cfg) }; let cpuct = cfg.cpuct as f32 / 1000.0; @@ -614,7 +624,7 @@ impl DecisionPolicy for Ismcts { match res { Ok(o) => { nodes += o.nodes.max(1); - let v = eval_iteration(&o.game, &walk, seat, base, cfg, &net); + let v = eval_iteration(&o.game, &walk, seat, root_turn, base, cfg, &net); walk.backup(v, seat); } Err(x) => nodes += x.max(1), @@ -668,7 +678,7 @@ impl DecisionPolicy for Ismcts { match res { Ok(o) => { local_nodes += o.nodes.max(1); - let v = eval_iteration(&o.game, &walk, seat, base, cfg, net_ref); + let v = eval_iteration(&o.game, &walk, seat, root_turn, base, cfg, net_ref); walk.backup(v, seat); } Err(x) => local_nodes += x.max(1), @@ -745,8 +755,19 @@ impl DecisionPolicy for Ismcts { logp[i] + sigma_gumbel(q, most, c_scale) }) .collect(); + if std::env::var_os("PLAYMAT_AI_TRACE_ROOT").is_some() { + eprintln!("ROOT turn={} {:?} seat={} v_prior={:.4} v_mix={:.4} most={}", d.game.turn, d.game.step, d.seat, v_prior, v_mix, most); + for i in 0..n { + let q = if agg_nw[i] > 0.0 { (agg_w[i] / agg_nw[i]) as f32 } else { f32::NAN }; + eprintln!(" cand[{i}] {:?} prior={:.4} logp={:.3} n={} q={:.4} key={:.3}", d.candidates[i], prior[i], logp[i], agg_n[i], q, key(i)); + } + } self.last = net::softmax(&improved, 1.0); self.last_val = Some((v_mix as f32).clamp(0.0, 1.0)); + self.last_qs = (0..n) + .map(|i| if agg_nw[i] > 0.0 { (agg_w[i] / agg_nw[i]) as f32 } else { f32::NAN }) + .collect(); + self.last_visits = agg_n; self.saved = None; return Some(Choice { answer: d.candidates[alive[0]].clone(), nodes }); } @@ -804,7 +825,7 @@ impl DecisionPolicy for Ismcts { match res { Ok(o) => { nodes += o.nodes.max(1); - let v = eval_iteration(&o.game, &walk, d.seat, base, cfg, &net); + let v = eval_iteration(&o.game, &walk, d.seat, root_turn, base, cfg, &net); walk.backup(v, d.seat); } Err(x) => nodes += x.max(1), @@ -855,8 +876,22 @@ impl DecisionPolicy for Ismcts { logp[i] + sigma_gumbel(q, most, c_scale) }) .collect(); + if std::env::var_os("PLAYMAT_AI_TRACE_ROOT").is_some() { + eprintln!("ROOT(1T) turn={} {:?} seat={} v_prior={:.4} v_mix={:.4} most={}", d.game.turn, d.game.step, d.seat, v_prior, v_mix, most); + for i in 0..n { + let k = &root_node.kids[i]; + let q = if k.n > 0 { (k.w / k.n as f64) as f32 } else { f32::NAN }; + eprintln!(" cand[{i}] {:?} prior={:.4} logp={:.3} n={} q={:.4} key={:.3}", d.candidates[i], prior[i], logp[i], k.n, q, key(i)); + } + } self.last = net::softmax(&improved, 1.0); self.last_val = Some((v_mix as f32).clamp(0.0, 1.0)); + self.last_qs = root_node + .kids + .iter() + .map(|k| if k.n > 0 { (k.w / k.n as f64) as f32 } else { f32::NAN }) + .collect(); + self.last_visits = root_node.kids.iter().map(|k| k.n).collect(); let pick_i = alive[0]; self.saved = tree.nodes[0].kids[pick_i].node.map(|c| tree.extract_subtree(c)); return Some(Choice { answer: d.candidates[pick_i].clone(), nodes }); @@ -902,7 +937,7 @@ impl DecisionPolicy for Ismcts { match res { Ok(o) => { nodes += o.nodes.max(1); - let v = eval_iteration(&o.game, &walk, d.seat, base, cfg, &net); + let v = eval_iteration(&o.game, &walk, d.seat, root_turn, base, cfg, &net); walk.backup(v, d.seat); } Err(x) => nodes += x.max(1), @@ -932,6 +967,14 @@ impl DecisionPolicy for Ismcts { fn last_value(&self) -> Option { self.last_val } + + fn last_action_qs(&self) -> Option<&[f32]> { + (!self.last_qs.is_empty()).then_some(&self.last_qs[..]) + } + + fn last_action_visits(&self) -> Option<&[u32]> { + (!self.last_visits.is_empty()).then_some(&self.last_visits[..]) + } } #[cfg(test)] diff --git a/rust/rl/anchor_gauntlet.py b/rust/rl/anchor_gauntlet.py new file mode 100644 index 0000000..81d66c0 --- /dev/null +++ b/rust/rl/anchor_gauntlet.py @@ -0,0 +1,234 @@ +"""Permanent Neural Anchor & Bradley-Terry Elo Gauntlet runner. + +Pins fixed neural and heuristic anchors (host@s6, host@s6-fair, obsv2-r6-1.3m-reg, wavec-final-1.3m-soup, +wavec-final-5m-soup) so Phase 3 models are measured against strong neural peers instead of saturating host@s6 alone. + +Computes exact Maximum-Likelihood Bradley-Terry Elo ratings with 95% confidence intervals via the observed +Fisher information matrix. +""" + +import argparse +import json +import math +import os +import re +import subprocess +import time + +import numpy as np +from scipy.optimize import minimize + +FAIR_HOST = "cfg:policy=playouts+budget=5000+width=12+threads=4+hide=1+samples=4+playout=2+eval=2+plans=1+mulligan_sim=1" + + +def default_anchors(runs_dir="runs"): + return { + "host@s6": "host@s6", + "host@s6-fair": FAIR_HOST, + "day1-r6@128": ( + f"cfg:policy=ismcts+net={runs_dir}/obsv2-r6-1.3m-reg/net.pmnet" + "+hide=1+samples=4+iters=128+cpuct=1000+leaf_blend=1000+multi_tree=1+mulligan_sim=1+extra_turns=0" + ), + "wavec-1.3m-soup@256": ( + f"cfg:policy=ismcts+net={runs_dir}/wavec-final-1.3m-soup/net.pmnet" + "+hide=1+iters=256+samples=8+cpuct=1000+leaf_blend=1000+gumbel_root=1+multi_tree=1+mulligan_net=1+width=16+consider=12+extra_turns=2" + ), + "wavec-5m-soup@256": ( + f"cfg:policy=ismcts+net={runs_dir}/wavec-final-5m-soup/net.pmnet" + "+hide=1+iters=256+samples=8+cpuct=1000+leaf_blend=1000+gumbel_root=1+multi_tree=1+mulligan_net=1+width=16+consider=12+extra_turns=2" + ), + } + + +def fit_bradley_terry_elo(names, records, anchor_name=None, prior_games=0.25): + """Fits MLE Bradley-Terry ratings (Elo scale: 400/ln(10) * theta) with 95% CI via Fisher Hessian. + + records: list of (i, j, wins_i, draws, losses_i) + anchor_name: entrant anchored to 1000.0 Elo (defaults to names[0]). + """ + m = len(names) + anchor = names.index(anchor_name) if (anchor_name in names) else 0 + free = [i for i in range(m) if i != anchor] + scale = 400.0 / math.log(10.0) + + def unpack(x): + th = np.zeros(m, dtype=np.float64) + for k, idx in enumerate(free): + th[idx] = x[k] + return th + + def nll(x): + th = unpack(x) + loss = 0.5 * prior_games * float(np.sum(th * th)) + for i, j, w, d, l in records: + s_i = w + 0.5 * d + s_j = l + 0.5 * d + diff = th[i] - th[j] + # log(1 + exp(-diff)) and log(1 + exp(diff)) stably + loss += s_i * np.logaddexp(0.0, -diff) + s_j * np.logaddexp(0.0, diff) + return loss + + def grad(x): + th = unpack(x) + g = prior_games * th.copy() + for i, j, w, d, l in records: + n_g = w + d + l + s_i = w + 0.5 * d + p = 1.0 / (1.0 + math.exp(max(-40.0, min(40.0, -(th[i] - th[j]))))) + diff_g = n_g * p - s_i + g[i] += diff_g + g[j] -= diff_g + return np.array([g[idx] for idx in free], dtype=np.float64) + + res = minimize(nll, np.zeros(len(free)), jac=grad, method="BFGS") + th = unpack(res.x) + + # Observed Fisher Information Hessian on free parameters + H = np.eye(len(free), dtype=np.float64) * prior_games + pos = {idx: k for k, idx in enumerate(free)} + for i, j, w, d, l in records: + n_g = w + d + l + p = 1.0 / (1.0 + math.exp(max(-40.0, min(40.0, -(th[i] - th[j]))))) + info = n_g * p * (1.0 - p) + if i in pos: + H[pos[i], pos[i]] += info + if j in pos: + H[pos[j], pos[j]] += info + if i in pos and j in pos: + H[pos[i], pos[j]] -= info + H[pos[j], pos[i]] -= info + cov = np.linalg.pinv(H) + se = np.zeros(m, dtype=np.float64) + for k, idx in enumerate(free): + se[idx] = math.sqrt(max(cov[k, k], 0.0)) + + out = [] + for i, name in enumerate(names): + w_tot = sum(w for a, b, w, d, l in records if a == i) + sum(l for a, b, w, d, l in records if b == i) + d_tot = sum(d for a, b, w, d, l in records if a == i or b == i) + l_tot = sum(l for a, b, w, d, l in records if a == i) + sum(w for a, b, w, d, l in records if b == i) + out.append({ + "name": name, + "elo": round(1000.0 + scale * th[i], 1), + "ci95": round(1.96 * scale * se[i], 1), + "w": int(w_tot), + "d": int(d_tot), + "l": int(l_tot), + "games": int(w_tot + d_tot + l_tot), + }) + out.sort(key=lambda r: r["elo"], reverse=True) + return out + + +def parse_archbench_h2h(text, spec_a, spec_b): + pat = re.compile(r"^ARCHBENCH\s+(.+?)\s+vs\s+(.+?):\s+(\d+)-(\d+)-(\d+)\s*$") + for line in text.splitlines(): + m = pat.match(line.strip()) + if not m: + continue + lhs, rhs = m.group(1).strip(), m.group(2).strip() + w, d, l = int(m.group(3)), int(m.group(4)), int(m.group(5)) + if lhs == spec_a and rhs == spec_b: + return w, d, l + if lhs == spec_b and rhs == spec_a: + return l, d, w + raise RuntimeError(f"Could not parse archbench W-D-L for ({spec_a} vs {spec_b}) from output:\n{text[-1000:]}") + + +def run_match(bin_path, suite, deals, jobs, spec_a, spec_b): + cmd = [ + bin_path, + "--suite", suite, + "--deals", str(deals), + "--jobs", str(jobs), + "--entrants", f"{spec_a},{spec_b}", + ] + t0 = time.time() + proc = subprocess.run(cmd, capture_output=True, text=True, check=True) + w, d, l = parse_archbench_h2h(proc.stdout, spec_a, spec_b) + return w, d, l, time.time() - t0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bin", default="../../rust/target/release/archbench") + ap.add_argument("--suite", default="../../archbench/constructed-2") + ap.add_argument("--runs-dir", default="runs") + ap.add_argument("--deals", type=int, default=100, help="duplicate deals per pairing (2*deals games)") + ap.add_argument("--jobs", type=int, default=32) + ap.add_argument("--anchors", default="host@s6,day1-r6@128,wavec-1.3m-soup@256,wavec-5m-soup@256") + ap.add_argument("--candidate", action="append", default=[], help="label=entrant_spec") + ap.add_argument("--round-robin", action="store_true", help="play all pairs instead of candidates vs anchors") + ap.add_argument("--anchor-elo", default="host@s6", help="entrant anchored at 1000.0 Elo") + ap.add_argument("--out-json", default=None) + ap.add_argument("--self-test", action="store_true", help="run unit test of MLE Bradley-Terry solver") + args = ap.parse_args() + + if args.self_test: + names = ["host@s6", "day1", "soup13", "phase3"] + recs = [ + (1, 0, 220, 16, 164), + (2, 0, 267, 13, 120), + (2, 1, 243, 18, 139), + (3, 2, 230, 14, 156), + (3, 0, 290, 10, 100), + ] + board = fit_bradley_terry_elo(names, recs, anchor_name="host@s6") + assert board[0]["name"] == "phase3" and board[-1]["name"] == "host@s6" + assert 1120 < [r for r in board if r["name"] == "soup13"][0]["elo"] < 1150 + print("BRADLEY_TERRY_SELF_TEST_OK", json.dumps(board, indent=2)) + return + + all_anchors = default_anchors(args.runs_dir) + selected_anchors = [a.strip() for a in args.anchors.split(",") if a.strip()] + entrants = {} + for a in selected_anchors: + if a not in all_anchors: + raise ValueError(f"Unknown anchor {a}; choices: {list(all_anchors)}") + entrants[a] = all_anchors[a] + cand_names = [] + for c in args.candidate: + k, v = c.split("=", 1) + entrants[k] = v + cand_names.append(k) + + names = list(entrants.keys()) + idx_of = {n: i for i, n in enumerate(names)} + pairs = [] + if args.round_robin or not cand_names: + for i in range(len(names)): + for j in range(i + 1, len(names)): + pairs.append((names[i], names[j])) + else: + for c in cand_names: + for a in selected_anchors: + if c != a: + pairs.append((c, a)) + for i in range(len(cand_names)): + for j in range(i + 1, len(cand_names)): + pairs.append((cand_names[i], cand_names[j])) + + records = [] + raw_matches = [] + for a, b in pairs: + w, d, l, dt = run_match(args.bin, args.suite, args.deals, args.jobs, entrants[a], entrants[b]) + pct = 100.0 * (w + 0.5 * d) / max(w + d + l, 1) + print(f"MATCH {a} vs {b}: {w}-{d}-{l} ({pct:.1f}%) in {dt:.1f}s", flush=True) + records.append((idx_of[a], idx_of[b], w, d, l)) + raw_matches.append({"a": a, "b": b, "w": w, "d": d, "l": l, "seconds": round(dt, 1)}) + + board = fit_bradley_terry_elo(names, records, anchor_name=args.anchor_elo) + print(f"\nBRADLEY-TERRY LEADERBOARD (anchor {args.anchor_elo} = 1000.0 Elo):") + print(f"{'Rank':>4} {'Entrant':<24} {'Elo':>7} {'95% CI':>8} {'W-D-L':>13}") + for rank, r in enumerate(board, 1): + wdl = f"{r['w']}-{r['d']}-{r['l']}" + print(f"{rank:>4} {r['name']:<24} {r['elo']:>7.1f} +/-{r['ci95']:>5.1f} {wdl:>13}") + + if args.out_json: + with open(args.out_json, "w") as f: + json.dump({"suite": args.suite, "deals": args.deals, "anchor": args.anchor_elo, "leaderboard": board, "matches": raw_matches}, f, indent=2) + print(f"Wrote {args.out_json}") + + +if __name__ == "__main__": + main() diff --git a/rust/rl/data.py b/rust/rl/data.py index 008746c..fc5e3c5 100644 --- a/rust/rl/data.py +++ b/rust/rl/data.py @@ -21,10 +21,10 @@ import time import numpy as np try: import torch - from model import ACT_F, ENT_F, GLOB_F, GLOB_F_V1, NO_ENT + from model import ACT_F, BELIEF_META_F, ENT_F, GLOB_F, GLOB_F_V1, GLOB_F_V2, NO_ENT except ImportError: torch = None - ENT_F, GLOB_F_V1, GLOB_F, ACT_F, NO_ENT = 49, 65, 81, 65, 255 + ENT_F, GLOB_F_V1, GLOB_F_V2, GLOB_F, ACT_F, NO_ENT, BELIEF_META_F = 49, 65, 81, 89, 65, 255, 8 META = 10 N_ENT, N_ACT, N_HID, N_POOL = 80, 24, 16, 64 @@ -32,6 +32,8 @@ N_ENT, N_ACT, N_HID, N_POOL = 80, 24, 16, 64 # GLOB_F layout in obs.rs: 17 fitted features, then [turn/10, me.life/20, them.life/20, ...] GLOB_LIFE_ME = 17 + 1 GLOB_LIFE_OPP = 17 + 2 +GLOB_HAND_ME = 17 + 3 +GLOB_HAND_OPP = 17 + 4 FIXED_COLS = [ ("meta.i32", np.int32), @@ -108,11 +110,22 @@ def compact_dir(d, delete_chunks=True, min_shards=4): tmp = os.path.join(d, "_compact_tmp") any_qval = any(os.path.exists(b + ".qval.f16") for b in bases) any_rel = any(os.path.exists(b + ".ent_rel_idx.u8") for b in bases) + any_v3 = any(os.path.exists(b + ".act_q.f16") for b in bases) col_names = [ext for ext, _ in FIXED_COLS] if any_qval: col_names.append("qval.f16") if any_rel: col_names += ["ent_rel_idx.u8", "ent_rel_type.u8", "act_ent_idx.u8"] + if any_v3: + col_names += ["act_q.f16", "act_n.u16", "belief_meta.f16"] + max_g_w = GLOB_F_V1 + for base in bases: + mp = base + ".meta.i32" + gp = base + ".glob.f16" + if os.path.exists(mp) and os.path.exists(gp): + cnt = os.path.getsize(mp) // (META * 4) + if cnt > 0: + max_g_w = max(max_g_w, os.path.getsize(gp) // (2 * cnt)) out_files = {ext: open(f"{tmp}.{ext}", "wb") for ext in col_names} all_games, all_res, all_turns = [], [], [] n_steps = 0 @@ -125,6 +138,16 @@ def compact_dir(d, delete_chunks=True, min_shards=4): n_steps += n for ext, _ in FIXED_COLS: p = f"{base}.{ext}" + if ext == "glob.f16" and os.path.exists(p): + g_w = os.path.getsize(p) // (2 * n) + if g_w != max_g_w: + ga = _read(p, np.float16, count=n * g_w).reshape(n, g_w) + if g_w < max_g_w: + ga = np.concatenate([ga, np.zeros((n, max_g_w - g_w), dtype=np.float16)], axis=1) + else: + ga = ga[:, :max_g_w] + ga.tofile(out_files[ext]) + continue if os.path.exists(p): with open(p, "rb") as src: while True: @@ -153,6 +176,19 @@ def compact_dir(d, delete_chunks=True, min_shards=4): out_files[ext].write(src.read()) else: np.full(cnt, fill, dtype=np.uint8).tofile(out_files[ext]) + if any_v3: + c_act = int(meta[:, 5].sum()) + for ext, cnt, dt, fill in [ + ("act_q.f16", c_act, np.float16, np.nan), + ("act_n.u16", c_act, np.uint16, 0), + ("belief_meta.f16", n * BELIEF_META_F, np.float16, 0.0), + ]: + vp = f"{base}.{ext}" + if os.path.exists(vp): + with open(vp, "rb") as src: + out_files[ext].write(src.read()) + else: + np.full(cnt, fill, dtype=dt).tofile(out_files[ext]) g, r, t = _read_games_meta(base) if len(g): all_games.append(g) @@ -232,6 +268,16 @@ def _read_one_shard(args): } qp = base + ".qval.f16" d["qval"] = _read(qp, np.float16, count=n) if os.path.exists(qp) else np.full(n, np.nan, dtype=np.float16) + aqp = base + ".act_q.f16" + d["act_q"] = _read(aqp, np.float16, count=c_act) if os.path.exists(aqp) else np.full(c_act, np.nan, dtype=np.float16) + anp = base + ".act_n.u16" + d["act_n"] = _read(anp, np.uint16, count=c_act) if os.path.exists(anp) else np.zeros(c_act, dtype=np.uint16) + bmp = base + ".belief_meta.f16" + d["belief_meta"] = ( + _read(bmp, np.float16, count=n * BELIEF_META_F).reshape(-1, BELIEF_META_F) + if os.path.exists(bmp) + else np.zeros((n, BELIEF_META_F), dtype=np.float16) + ) if load_critic: d["hid"] = _read(base + ".hid.f16", np.float16, count=c_hid * ENT_F).reshape(-1, ENT_F) d["hid_ids"] = _read(base + ".hid_ids.u16", np.uint16, count=c_hid) @@ -263,7 +309,7 @@ class Data: col_keys = [ "meta", "logp", "glob", "ents", "ent_ids", "ent_rel_idx", "ent_rel_type", - "acts", "act_ids", "act_ent_idx", "target", "pool", "pool_hand", "qval", + "acts", "act_ids", "act_ent_idx", "target", "act_q", "act_n", "pool", "pool_hand", "qval", "belief_meta", ] if load_critic: col_keys += ["hid", "hid_ids"] @@ -324,6 +370,23 @@ class Data: last_life = np.zeros(s_inv.max() + 1, dtype=np.float32) last_life[s_inv] = life_diff self.final_life_diff = np.clip(last_life[s_inv], -2.0, 2.0).astype(np.float32) + # Auxiliary targets 3 & 4 (KataGo-style short-horizon deltas): life swing & hand+board swing to next decision + board_adv = (self.glob[:, GLOB_HAND_ME].astype(np.float32) - self.glob[:, GLOB_HAND_OPP].astype(np.float32)) + 0.5 * self.glob[:, 0].astype(np.float32) + s_ord = np.argsort(seat_key, kind="mergesort") + sk_ord = seat_key[s_ord] + same_n = np.empty(len(sk_ord), dtype=bool) + same_n[:-1] = sk_ord[:-1] == sk_ord[1:] + same_n[-1] = False + ld_ord = life_diff[s_ord] + ba_ord = board_adv[s_ord] + nld = np.zeros(len(sk_ord), dtype=np.float32) + nbd = np.zeros(len(sk_ord), dtype=np.float32) + nld[:-1] = np.where(same_n[:-1], ld_ord[1:] - ld_ord[:-1], 0.0) + nbd[:-1] = np.where(same_n[:-1], ba_ord[1:] - ba_ord[:-1], 0.0) + self.next_life_delta = np.empty(len(sk_ord), dtype=np.float32) + self.next_board_delta = np.empty(len(sk_ord), dtype=np.float32) + self.next_life_delta[s_ord] = np.clip(nld, -1.0, 1.0) + self.next_board_delta[s_ord] = np.clip(nbd, -1.0, 1.0) # Forward-looking TD(lambda) value target across each (run, game, seat) trajectory via O(N log L) suffix scan. # G_t = (1 - lam) * q_{t+1} + lam * G_{t+1} when next step has finite search Q, else G_{t+1}; G_{T-1} = z. @@ -373,6 +436,8 @@ class Data: "act_ids": self.act_ids.astype(np.int16), "act_ent_idx": self.act_ent_idx, "target": self.target, + "act_q": self.act_q, + "act_n": self.act_n.astype(np.int32), "pool": self.pool.astype(np.int16), "pool_hand": self.pool_hand, "chosen": self.chosen.astype(np.int64), @@ -382,6 +447,9 @@ class Data: "qval": self.qval, "turns_left": self.turns_left, "final_life_diff": self.final_life_diff, + "next_life_delta": self.next_life_delta, + "next_board_delta": self.next_board_delta, + "belief_meta": self.belief_meta, "val_w": self.val_w, "run": self.run, } @@ -430,6 +498,8 @@ class Data: aids, _, _ = cat_var(self.act_ids, self.act_off, self.n_act) aent, _, _ = cat_var(self.act_ent_idx, self.act_off, self.n_act) tgt, _, _ = cat_var(self.target, self.act_off, self.n_act) + act_q, _, _ = cat_var(self.act_q, self.act_off, self.n_act) + act_n, _, _ = cat_var(self.act_n, self.act_off, self.n_act) pool, pool_off, n_pool = cat_var(self.pool, self.pool_off, self.n_pool) ph, _, _ = cat_var(self.pool_hand, self.pool_off, self.n_pool) @@ -445,6 +515,8 @@ class Data: "act_ids": aids.astype(np.int16), "act_ent_idx": aent, "target": tgt, + "act_q": act_q, + "act_n": act_n.astype(np.int32), "act_off": act_off, "n_act": n_act, "pool": pool.astype(np.int16), @@ -458,6 +530,9 @@ class Data: "qval": cat_fixed(self.qval), "turns_left": cat_fixed(self.turns_left), "final_life_diff": cat_fixed(self.final_life_diff), + "next_life_delta": cat_fixed(self.next_life_delta), + "next_board_delta": cat_fixed(self.next_board_delta), + "belief_meta": cat_fixed(self.belief_meta), "val_w": cat_fixed(self.val_w), "run": cat_fixed(self.run), "game": cat_fixed(self.game), @@ -507,6 +582,8 @@ class Data: aids, _ = self._gather(self.act_ids, self.act_off, self.n_act, idx, N_ACT) aent, _ = self._gather(self.act_ent_idx, self.act_off, self.n_act, idx, N_ACT) tgt, _ = self._gather(self.target, self.act_off, self.n_act, idx, N_ACT) + act_q, _ = self._gather(self.act_q, self.act_off, self.n_act, idx, N_ACT) + act_n, _ = self._gather(self.act_n, self.act_off, self.n_act, idx, N_ACT) hid, hm = self._gather(self.hid, self.hid_off, self.n_hid, idx, N_HID) hids, _ = self._gather(self.hid_ids, self.hid_off, self.n_hid, idx, N_HID) pool, pm = self._gather(self.pool, self.pool_off, self.n_pool, idx, N_POOL) @@ -525,6 +602,8 @@ class Data: "act_mask": t(am, torch.bool), "act_ent_idx": t(np.where(am, aent, NO_ENT), torch.long), "target": t(tgt), + "act_q": t(np.where(am, act_q.astype(np.float32), np.nan)), + "act_n": t(act_n * am, torch.long), "chosen": t(np.minimum(self.chosen[idx], N_ACT - 1), torch.long), "logp": t(self.logp[idx]), "hid": t(hid * hm[..., None]), @@ -538,6 +617,9 @@ class Data: "qval": t(self.qval[idx]), "turns_left": t(self.turns_left[idx]), "final_life_diff": t(self.final_life_diff[idx]), + "next_life_delta": t(self.next_life_delta[idx]), + "next_board_delta": t(self.next_board_delta[idx]), + "belief_meta": t(self.belief_meta[idx]), "val_w": t(self.val_w[idx]), "run": t(self.run[idx], torch.long), } @@ -573,7 +655,7 @@ def _tgather_store(st, col, k, idx, width): def _pad_raw(raw): widths = {"ents": N_ENT, "em": N_ENT, "eids": N_ENT, "eridx": N_ENT, "ertyp": N_ENT, - "acts": N_ACT, "am": N_ACT, "aids": N_ACT, "aent": N_ACT, "tgt": N_ACT, + "acts": N_ACT, "am": N_ACT, "aids": N_ACT, "aent": N_ACT, "tgt": N_ACT, "act_q": N_ACT, "act_n": N_ACT, "pool": N_POOL, "pm": N_POOL, "ph": N_POOL} if "hid" in raw: widths.update({"hid": N_HID, "hm": N_HID, "hids": N_HID}) @@ -582,7 +664,7 @@ def _pad_raw(raw): v = raw[k] pad = w - v.shape[1] if pad > 0: - fill = NO_ENT if k in ("eridx", "aent") else 0 + fill = NO_ENT if k in ("eridx", "aent") else (float("nan") if k == "act_q" else 0) z = torch.full((v.shape[0], pad) + tuple(v.shape[2:]), fill, dtype=v.dtype, device=v.device) out[k] = torch.cat([v, z], 1) return out @@ -601,15 +683,17 @@ def _batch_from_store(st, s, load_critic, idx, device, trim=True): aids, _ = _tgather_store(st, "act_ids", "act", i, N_ACT) aent, _ = _tgather_store(st, "act_ent_idx", "act", i, N_ACT) tgt, _ = _tgather_store(st, "target", "act", i, N_ACT) + act_q, _ = _tgather_store(st, "act_q", "act", i, N_ACT) + act_n, _ = _tgather_store(st, "act_n", "act", i, N_ACT) pool, pm = _tgather_store(st, "pool", "pool", i, N_POOL) ph, _ = _tgather_store(st, "pool_hand", "pool", i, N_POOL) raw = { "glob": st["glob"][i], "ents": ents, "em": em, "eids": eids, "eridx": eridx, "ertyp": ertyp, - "acts": acts, "am": am, "aids": aids, "aent": aent, "tgt": tgt, + "acts": acts, "am": am, "aids": aids, "aent": aent, "tgt": tgt, "act_q": act_q, "act_n": act_n, "pool": pool, "pm": pm, "ph": ph, "chosen": st["chosen"][i], "logp": st["logp"][i], "z": st["z"][i], "z_td": st["z_td"][i], "qval": st["qval"][i], "turns_left": st["turns_left"][i], - "final_life_diff": st["final_life_diff"][i], "val_w": st["val_w"][i], "run": st["run"][i], + "final_life_diff": st["final_life_diff"][i], "next_life_delta": st["next_life_delta"][i], "next_board_delta": st["next_board_delta"][i], "belief_meta": st["belief_meta"][i], "val_w": st["val_w"][i], "run": st["run"][i], } if load_critic: hid, hm = _tgather_store(st, "hid", "hid", i, N_HID) @@ -636,6 +720,8 @@ def _batch_from_store(st, s, load_critic, idx, device, trim=True): "act_mask": am, "act_ent_idx": torch.where(am, r["aent"].long(), NO_ENT), "target": tgt, + "act_q": torch.where(am, r["act_q"].to(f), torch.full_like(r["act_q"].to(f), float("nan"))), + "act_n": r["act_n"].long() * am, "chosen": r["chosen"].clamp(max=am.shape[1] - 1), "logp": r["logp"].to(f), "pool": r["pool"].long() * pm, @@ -646,6 +732,9 @@ def _batch_from_store(st, s, load_critic, idx, device, trim=True): "qval": r["qval"].to(f), "turns_left": r["turns_left"].to(f), "final_life_diff": r["final_life_diff"].to(f), + "next_life_delta": r["next_life_delta"].to(f), + "next_board_delta": r["next_board_delta"].to(f), + "belief_meta": r["belief_meta"].to(f), "val_w": r["val_w"].to(f), "run": r["run"].long(), } diff --git a/rust/rl/model.py b/rust/rl/model.py index 504a53d..9205125 100644 --- a/rust/rl/model.py +++ b/rust/rl/model.py @@ -1,417 +1,436 @@ -"""The policy, value and belief network: the same as playmat-ai's `net.rs`, in PyTorch, plus a critic that sees the -opponent's hand (training only, never exported). - -Shapes come from `obs.rs`: ENT_F entity features, GLOB_F global ones, ACT_F per action, BUCKETS card-name buckets. -""" - -import json -import math -import struct - -import torch -import torch.nn as nn -import torch.nn.functional as F - -ENT_F = 49 -GLOB_F_V1 = 65 -GLOB_F = 81 -ACT_F = 65 -BUCKETS = 4096 -NUM_REL_TYPES = 4 -NO_ENT = 255 - - -class Net(nn.Module): - def __init__(self, dim=16, ent=64, glob=64, trunk=128, act=64, belief=True): - super().__init__() - self.emb = nn.Embedding(BUCKETS, dim) - self.ent1 = nn.Linear(dim + ENT_F, ent) - self.ent2 = nn.Linear(ent, ent) - self.glob1 = nn.Linear(GLOB_F, glob) - self.trunk1 = nn.Linear(2 * ent + glob, trunk) - self.trunk2 = nn.Linear(trunk, trunk) - self.value = nn.Linear(trunk, 1) - self.act1 = nn.Linear(dim + ACT_F, act) - self.act2 = nn.Linear(act, act) - self.query = nn.Linear(trunk, act) - self.abias = nn.Linear(act, 1) - self.belief = nn.Linear(trunk, dim) if belief else None - - def pool(self, ids, feats, mask): - """Entities [B, N] ids, [B, N, ENT_F] feats, [B, N] mask -> [B, 2*ent] (mean, max; zeros when empty)""" - x = torch.cat([self.emb(ids), feats], -1) - z = F.relu(self.ent2(F.relu(self.ent1(x)))) - m = mask.unsqueeze(-1).float() - n = m.sum(1).clamp(min=1) - mean = (z * m).sum(1) / n - mx = torch.where(m > 0, z, torch.full_like(z, -1e9)).max(1).values - mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) - return torch.cat([mean, mx], -1) - - def state(self, b): - p = self.pool(b["ent_ids"], b["ents"], b["ent_mask"]) - g = F.relu(self.glob1(b["glob"])) - return F.relu(self.trunk2(F.relu(self.trunk1(torch.cat([p, g], -1))))) - - def forward(self, b, return_vfeat=False, detach_val=False): - """-> logits [B, K] (masked to -inf past each row's actions), value logit [B], state h [B, trunk]""" - h = self.state(b) - v = self.value(h.detach() if detach_val else h).squeeze(-1) - a = self.act2(F.relu(self.act1(torch.cat([self.emb(b["act_ids"]), b["acts"]], -1)))) - q = self.query(h).unsqueeze(1) - logits = (q * a).sum(-1) + self.abias(a).squeeze(-1) - logits = logits.masked_fill(~b["act_mask"], -1e9) - if return_vfeat: - return logits, v, h, h - return logits, v, h - - def belief_logits(self, h, pool_ids): - """[B, trunk], [B, P] -> [B, P]""" - q = self.belief(h).unsqueeze(1) - return (q * self.emb(pool_ids)).sum(-1) - - -class Critic(nn.Module): - """A value network that also sees the opponent's hand (PerfectDou's critic): training only""" - - def __init__(self, dim=16, ent=64, glob=64, trunk=128): - super().__init__() - self.emb = nn.Embedding(BUCKETS, dim) - self.ent1 = nn.Linear(dim + ENT_F, ent) - self.ent2 = nn.Linear(ent, ent) - self.hid1 = nn.Linear(dim + ENT_F, ent) - self.hid2 = nn.Linear(ent, ent) - self.glob1 = nn.Linear(GLOB_F, glob) - self.trunk1 = nn.Linear(4 * ent + glob, trunk) - self.trunk2 = nn.Linear(trunk, trunk) - self.value = nn.Linear(trunk, 1) - - def _pool(self, l1, l2, ids, feats, mask): - z = F.relu(l2(F.relu(l1(torch.cat([self.emb(ids), feats], -1))))) - m = mask.unsqueeze(-1).float() - mean = (z * m).sum(1) / m.sum(1).clamp(min=1) - mx = torch.where(m > 0, z, torch.full_like(z, -1e9)).max(1).values - mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) - return torch.cat([mean, mx], -1) - - def forward(self, b): - p = self._pool(self.ent1, self.ent2, b["ent_ids"], b["ents"], b["ent_mask"]) - q = self._pool(self.hid1, self.hid2, b["hid_ids"], b["hid"], b["hid_mask"]) - g = F.relu(self.glob1(b["glob"])) - h = F.relu(self.trunk2(F.relu(self.trunk1(torch.cat([p, q, g], -1))))) - return self.value(h).squeeze(-1) - - -class CardEmb(nn.Module): - """The name embedding, plus (with `text`) a learned projection of the fixed card-text rows (`cardtext.py`): - `weight[id] + text[id] @ proj`. `export` writes the sum as one table, so `net.rs` sees a plain embedding.""" - - def __init__(self, dim, text=0): - super().__init__() - self.weight = nn.Parameter(torch.randn(BUCKETS, dim)) - if text: - import numpy as np - import os - - fname = "cardtext_sem.npy" if int(text) == 2 else "cardtext.npy" - rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", fname)) - self.register_buffer("text", torch.from_numpy(rows.astype("float32"))) - self.proj = nn.Parameter(torch.zeros(rows.shape[1], dim)) - else: - self.text = None - - def table(self): - return self.weight if self.text is None else self.weight + self.text @ self.proj - - def forward(self, ids): - if self.text is None: - return F.embedding(ids, self.weight) - return F.embedding(ids, self.weight) + F.embedding(ids, self.text) @ self.proj - - -class AuxHead(nn.Module): - """Training-only auxiliary positional head (predicts turns remaining and final life diff); never exported.""" - - def __init__(self, in_dim, hidden=128): - super().__init__() - self.fc1 = nn.Linear(in_dim, hidden) - self.fc2 = nn.Linear(hidden, 2) - - def forward(self, x): - return self.fc2(F.gelu(self.fc1(x))) - - -def _gelu(x): - return F.gelu(x, approximate="tanh") - - -class Tx(nn.Module): - """The transformer network (#400 R2): a global token and one token per entity through `layers` pre-norm - self-attention blocks; each candidate attends to the tokens once. Same outputs as `Net`. `net.rs` (`Tx`) runs it - in plain Rust; everything here is written out by hand so the two match exactly. - - Optional extensions (all default off so older checkpoints load identically): - - `val_mlp=1`: dedicated 2-layer value MLP reading `[t[:, 0], mean_ent, max_ent, glob]` with LayerNorm & dropout - - `gelu=1`: tanh-approximated GELU instead of ReLU in FFN / trunk / value layers - - `drop`: training-only dropout rate in transformer blocks (0.0 at eval/export) - """ - - def __init__( - self, - d=128, - heads=4, - layers=3, - ff=256, - dim=32, - trunk=128, - text=0, - val_mlp=0, - gelu=0, - glob_f=GLOB_F_V1, - rel=0, - act_ent=0, - drop=0.0, - ): - super().__init__() - self.cfg = {"d": d, "heads": heads, "layers": layers, "ff": ff, "dim": dim, "trunk": trunk} - if text: - self.cfg["text"] = int(text) - if val_mlp: - self.cfg["val_mlp"] = 1 - if gelu: - self.cfg["gelu"] = 1 - if int(glob_f) != GLOB_F_V1: - self.cfg["glob_f"] = int(glob_f) - if rel: - self.cfg["rel"] = 1 - if act_ent: - self.cfg["act_ent"] = 1 - self.heads = heads - self.d = d - self.glob_f = int(glob_f) - self.val_mlp = bool(val_mlp) - self.use_gelu = bool(gelu) - self.use_rel = bool(rel) - self.act_ent = bool(act_ent) - self.drop = nn.Dropout(drop) if drop > 0 else nn.Identity() - self.emb = CardEmb(dim, int(text)) - self.ent_in = nn.Linear(dim + ENT_F, d) - self.glob_in = nn.Linear(self.glob_f, d) - self.rel_bias = nn.Parameter(torch.zeros(2 * NUM_REL_TYPES, heads)) if self.use_rel else None - self.blocks = nn.ModuleList() - for _ in range(layers): - b = nn.Module() - b.ln1, b.qkv, b.out = nn.LayerNorm(d), nn.Linear(d, 3 * d), nn.Linear(d, d) - b.ln2, b.ff1, b.ff2 = nn.LayerNorm(d), nn.Linear(d, ff), nn.Linear(ff, d) - self.blocks.append(b) - self.ln_f = nn.LayerNorm(d) - self.trunk1 = nn.Linear(2 * d, trunk) - if self.val_mlp: - v_in = 3 * d + self.glob_f - self.val_ln = nn.LayerNorm(v_in) - self.val_fc1 = nn.Linear(v_in, trunk) - self.val_drop = nn.Dropout(0.3) - self.val_fc2 = nn.Linear(trunk, 1) - self.value = None - else: - self.value = nn.Linear(trunk, 1) - self.belief = nn.Linear(trunk, dim) - self.act_in = nn.Linear(dim + ACT_F + (d if self.act_ent else 0), d) - self.act_ln = nn.LayerNorm(d) - self.act_q, self.act_kv, self.act_o = nn.Linear(d, d), nn.Linear(d, 2 * d), nn.Linear(d, d) - self.act_ff = nn.Linear(d, d) - self.query = nn.Linear(trunk, d) - self.abias = nn.Linear(d, 1) - - def _act(self, x): - return _gelu(x) if self.use_gelu else F.relu(x) - - def _glob(self, g): - if g.shape[-1] == self.glob_f: - return g - if g.shape[-1] > self.glob_f: - return g[..., : self.glob_f] - return F.pad(g, (0, self.glob_f - g.shape[-1])) - - def _build_attn_bias(self, b, mask, dtype): - if self.rel_bias is None or "ent_rel_idx" not in b or "ent_rel_type" not in b: - return mask[:, None, None, :] - B, T = mask.shape - ne = T - 1 - if ne <= 0: - return mask[:, None, None, :] - ri = b["ent_rel_idx"].long() - rt = b["ent_rel_type"].long() - em = b["ent_mask"] - ri_safe = ri.clamp(0, ne - 1) - valid = em & (rt >= 1) & (rt <= NUM_REL_TYPES) & (ri < ne) & em.gather(1, ri_safe) - bi, ei = torch.nonzero(valid, as_tuple=True) - if bi.numel() == 0: - return mask[:, None, None, :] - bias = torch.zeros((B, T, T, self.heads), device=mask.device, dtype=dtype) - bias.masked_fill_(~mask[:, None, :, None], float("-inf")) - ti = ri[bi, ei] - r = rt[bi, ei] - 1 - rb = self.rel_bias.to(dtype) - bias.index_put_((bi, 1 + ei, 1 + ti), rb[r], accumulate=True) - bias.index_put_((bi, 1 + ti, 1 + ei), rb[r + NUM_REL_TYPES], accumulate=True) - return bias.permute(0, 3, 1, 2).contiguous() - - def _attend(self, q, k, v, attn_mask): - """q [B, Q, d], k/v [B, T, d], attn_mask [B, 1/H, 1/Q, T] -> [B, Q, d], `heads` heads""" - B, Q, D = q.shape - T = k.shape[1] - h, hd = self.heads, D // self.heads - q = q.view(B, Q, h, hd).transpose(1, 2) - k = k.view(B, T, h, hd).transpose(1, 2) - v = v.view(B, T, h, hd).transpose(1, 2) - out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) - return out.transpose(1, 2).reshape(B, Q, D) - - def tokens(self, b): - """-> tokens [B, 1+N, d] after the blocks (normed), mask [B, 1+N]""" - g = self.glob_in(self._glob(b["glob"])).unsqueeze(1) - e = self.ent_in(torch.cat([self.emb(b["ent_ids"]), b["ents"]], -1)) - x = torch.cat([g, e], 1) - mask = torch.cat([torch.ones_like(b["ent_mask"][:, :1]), b["ent_mask"]], 1) - attn_mask = self._build_attn_bias(b, mask, x.dtype) - for blk in self.blocks: - y = blk.ln1(x) - q, k, v = blk.qkv(y).chunk(3, -1) - x = x + self.drop(blk.out(self._attend(q, k, v, attn_mask))) - x = x + self.drop(blk.ff2(self._act(blk.ff1(blk.ln2(x))))) - return self.ln_f(x), mask - - def _pool_val_features(self, t, mask, glob): - m = mask[:, 1:].unsqueeze(-1).float() - ent_t = t[:, 1:] - mean = (ent_t * m).sum(1) / m.sum(1).clamp(min=1) - mx = torch.where(m > 0, ent_t, torch.full_like(ent_t, -1e9)).max(1).values - mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) - return torch.cat([t[:, 0], mean, mx, self._glob(glob)], -1), mean - - def state_tokens(self, b): - t, mask = self.tokens(b) - m = mask[:, 1:].unsqueeze(-1).float() - mean = (t[:, 1:] * m).sum(1) / m.sum(1).clamp(min=1) - h = self._act(self.trunk1(torch.cat([t[:, 0], mean], -1))) - return h, t, mask - - def state(self, b): - return self.state_tokens(b)[0] - - def forward(self, b, return_vfeat=False, detach_val=False): - t, mask = self.tokens(b) - vfeat, mean = self._pool_val_features(t, mask, b["glob"]) - h = self._act(self.trunk1(torch.cat([t[:, 0], mean], -1))) - if self.val_mlp: - vf = vfeat.detach() if detach_val else vfeat - vh = self.val_drop(self._act(self.val_fc1(self.val_ln(vf)))) - v = self.val_fc2(vh).squeeze(-1) - else: - v = self.value(h.detach() if detach_val else h).squeeze(-1) - if self.act_ent: - B, na = b["act_ids"].shape - ne = t.shape[1] - 1 - if ne > 0 and "act_ent_idx" in b: - ae = b["act_ent_idx"].long() - ae_valid = (ae < ne) & b["act_mask"] - ae_safe = ae.clamp(0, ne - 1) - ctx = t[:, 1:].gather(1, ae_safe.unsqueeze(-1).expand(-1, -1, self.d)) - ctx = ctx * ae_valid.unsqueeze(-1).to(ctx.dtype) - else: - ctx = torch.zeros((B, na, self.d), device=t.device, dtype=t.dtype) - a_feat = torch.cat([self.emb(b["act_ids"]), b["acts"], ctx], -1) - else: - a_feat = torch.cat([self.emb(b["act_ids"]), b["acts"]], -1) - a = self.act_in(a_feat) - k, vv = self.act_kv(t).chunk(2, -1) - a = a + self.act_o(self._attend(self.act_q(self.act_ln(a)), k, vv, mask[:, None, None, :])) - a = a + self._act(self.act_ff(a)) - logits = (self.query(h).unsqueeze(1) * a).sum(-1) + self.abias(a).squeeze(-1) - logits = logits.masked_fill(~b["act_mask"], -1e9) - if return_vfeat: - return logits, v, h, vfeat - return logits, v, h - - def belief_logits(self, h, pool_ids): - return (self.belief(h).unsqueeze(1) * self.emb(pool_ids)).sum(-1) - - -def make(arch, **kw): - return Tx(**kw) if arch == "tx" else Net(**kw) - - -def arch_of(net): - return {"arch": "tx", **net.cfg} if isinstance(net, Tx) else {"arch": "mlp"} - - -def build(spec): - spec = dict(spec) - return make(spec.pop("arch", "mlp"), **spec) - - -def save_dir(net, d): - """Writes net.pt and arch.json into run folder `d`""" - torch.save(net.state_dict(), f"{d}/net.pt") - json.dump(arch_of(net), open(f"{d}/arch.json", "w")) - - -def load_dir(d, dev, upgrade_val_mlp=False, drop=0.0): - """The network in run folder `d` (arch.json says which; the first network without one)""" - import os - spec = json.load(open(f"{d}/arch.json")) if os.path.exists(f"{d}/arch.json") else {"arch": "mlp"} - upgraded = False - if upgrade_val_mlp and spec.get("arch") == "tx" and not spec.get("val_mlp"): - spec["val_mlp"] = 1 - upgraded = True - if spec.get("arch") == "tx" and drop > 0: - spec["drop"] = drop - net = build(spec).to(dev) - sd = torch.load(f"{d}/net.pt", map_location=dev) - if upgraded: - sd = {k: v for k, v in sd.items() if not k.startswith("value.")} - net.load_state_dict(sd, strict=False) - else: - net.load_state_dict(sd) - return net - - -TENSORS = ["emb", "ent1", "ent2", "glob1", "trunk1", "trunk2", "value", "act1", "act2", "query", "abias", "belief"] - - -def export(net, path, meta=None): - """Writes the `.pmnet` file `net.rs` reads: a JSON header line, then little-endian f32 tensors""" - sd = {k: v.detach().float().cpu() for k, v in net.state_dict().items()} - if isinstance(net, Tx): - # the card-text projection folded into the name embedding - sd["emb.weight"] = net.emb.table().detach().float().cpu() - names = [k for k in sd if k not in ("emb.text", "emb.proj")] - cfg = {k: v for k, v in net.cfg.items() if k != "text"} - header = {"arch": "tx", "config": cfg, "tensors": [[k, list(sd[k].shape)] for k in names], "meta": meta or {}} - else: - names = [] - for t in TENSORS: - for part in ("weight", "bias"): - k = f"{t}.{part}" - if k in sd: - names.append(k) - header = {"tensors": [[k, list(sd[k].shape)] for k in names], "meta": meta or {}} - with open(path, "wb") as f: - f.write(json.dumps(header).encode() + b"\n") - for k in names: - a = sd[k].contiguous().view(-1).tolist() - f.write(struct.pack(f"<{len(a)}f", *a)) - - -def params(net): - return sum(p.numel() for p in net.parameters()) - - -if __name__ == "__main__": - import sys - - torch.manual_seed(0) - n = Net() - export(n, sys.argv[1] if len(sys.argv) > 1 else "net.pmnet", {"kind": "random init"}) - print("params", params(n)) +"""The policy, value and belief network: the same as playmat-ai's `net.rs`, in PyTorch, plus a critic that sees the +opponent's hand (training only, never exported). + +Shapes come from `obs.rs`: ENT_F entity features, GLOB_F global ones, ACT_F per action, BUCKETS card-name buckets. +""" + +import json +import math +import struct + +import torch +import torch.nn as nn +import torch.nn.functional as F + +ENT_F = 49 +GLOB_F_V1 = 65 +GLOB_F_V2 = 81 +GLOB_F = 89 +BELIEF_META_F = 8 +ACT_F = 65 +BUCKETS = 4096 +NUM_REL_TYPES = 4 +NO_ENT = 255 + + +class Net(nn.Module): + def __init__(self, dim=16, ent=64, glob=64, trunk=128, act=64, belief=True): + super().__init__() + self.emb = nn.Embedding(BUCKETS, dim) + self.ent1 = nn.Linear(dim + ENT_F, ent) + self.ent2 = nn.Linear(ent, ent) + self.glob1 = nn.Linear(GLOB_F, glob) + self.trunk1 = nn.Linear(2 * ent + glob, trunk) + self.trunk2 = nn.Linear(trunk, trunk) + self.value = nn.Linear(trunk, 1) + self.act1 = nn.Linear(dim + ACT_F, act) + self.act2 = nn.Linear(act, act) + self.query = nn.Linear(trunk, act) + self.abias = nn.Linear(act, 1) + self.belief = nn.Linear(trunk, dim) if belief else None + + def pool(self, ids, feats, mask): + """Entities [B, N] ids, [B, N, ENT_F] feats, [B, N] mask -> [B, 2*ent] (mean, max; zeros when empty)""" + x = torch.cat([self.emb(ids), feats], -1) + z = F.relu(self.ent2(F.relu(self.ent1(x)))) + m = mask.unsqueeze(-1).float() + n = m.sum(1).clamp(min=1) + mean = (z * m).sum(1) / n + mx = torch.where(m > 0, z, torch.full_like(z, -1e9)).max(1).values + mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) + return torch.cat([mean, mx], -1) + + def state(self, b): + p = self.pool(b["ent_ids"], b["ents"], b["ent_mask"]) + g = F.relu(self.glob1(b["glob"])) + return F.relu(self.trunk2(F.relu(self.trunk1(torch.cat([p, g], -1))))) + + def forward(self, b, return_vfeat=False, return_act_emb=False, detach_val=False): + """-> logits [B, K] (masked to -inf past each row's actions), value logit [B], state h [B, trunk]""" + h = self.state(b) + v = self.value(h.detach() if detach_val else h).squeeze(-1) + a = self.act2(F.relu(self.act1(torch.cat([self.emb(b["act_ids"]), b["acts"]], -1)))) + q = self.query(h).unsqueeze(1) + logits = (q * a).sum(-1) + self.abias(a).squeeze(-1) + logits = logits.masked_fill(~b["act_mask"], -1e9) + if return_act_emb: + return logits, v, h, h, a + if return_vfeat: + return logits, v, h, h + return logits, v, h + + def belief_logits(self, h, pool_ids): + """[B, trunk], [B, P] -> [B, P]""" + q = self.belief(h).unsqueeze(1) + return (q * self.emb(pool_ids)).sum(-1) + + +class Critic(nn.Module): + """A value network that also sees the opponent's hand (PerfectDou's critic): training only""" + + def __init__(self, dim=16, ent=64, glob=64, trunk=128): + super().__init__() + self.emb = nn.Embedding(BUCKETS, dim) + self.ent1 = nn.Linear(dim + ENT_F, ent) + self.ent2 = nn.Linear(ent, ent) + self.hid1 = nn.Linear(dim + ENT_F, ent) + self.hid2 = nn.Linear(ent, ent) + self.glob1 = nn.Linear(GLOB_F, glob) + self.trunk1 = nn.Linear(4 * ent + glob, trunk) + self.trunk2 = nn.Linear(trunk, trunk) + self.value = nn.Linear(trunk, 1) + + def _pool(self, l1, l2, ids, feats, mask): + z = F.relu(l2(F.relu(l1(torch.cat([self.emb(ids), feats], -1))))) + m = mask.unsqueeze(-1).float() + mean = (z * m).sum(1) / m.sum(1).clamp(min=1) + mx = torch.where(m > 0, z, torch.full_like(z, -1e9)).max(1).values + mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) + return torch.cat([mean, mx], -1) + + def forward(self, b): + p = self._pool(self.ent1, self.ent2, b["ent_ids"], b["ents"], b["ent_mask"]) + q = self._pool(self.hid1, self.hid2, b["hid_ids"], b["hid"], b["hid_mask"]) + g = F.relu(self.glob1(b["glob"])) + h = F.relu(self.trunk2(F.relu(self.trunk1(torch.cat([p, q, g], -1))))) + return self.value(h).squeeze(-1) + + +class CardEmb(nn.Module): + """The name embedding, plus (with `text`) a learned projection of the fixed card-text rows (`cardtext.py`): + `weight[id] + text[id] @ proj`. `export` writes the sum as one table, so `net.rs` sees a plain embedding.""" + + def __init__(self, dim, text=0): + super().__init__() + self.weight = nn.Parameter(torch.randn(BUCKETS, dim)) + if text: + import numpy as np + import os + + fname = "cardtext_sem.npy" if int(text) == 2 else "cardtext.npy" + rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", fname)) + self.register_buffer("text", torch.from_numpy(rows.astype("float32"))) + self.proj = nn.Parameter(torch.zeros(rows.shape[1], dim)) + else: + self.text = None + + def table(self): + return self.weight if self.text is None else self.weight + self.text @ self.proj + + def forward(self, ids): + if self.text is None: + return F.embedding(ids, self.weight) + return F.embedding(ids, self.weight) + F.embedding(ids, self.text) @ self.proj + + +class AuxHead(nn.Module): + """Training-only KataGo-style auxiliary positional head; never exported. + Predicts 4 dense targets: [turns_left, final_life_diff, next_life_delta, next_board_delta].""" + + def __init__(self, in_dim, hidden=128, out_dim=4): + super().__init__() + self.fc1 = nn.Linear(in_dim, hidden) + self.fc2 = nn.Linear(hidden, out_dim) + + def forward(self, x): + return self.fc2(F.gelu(self.fc1(x))) + + +class ActQHead(nn.Module): + """Training-only per-action Q-value head for v3 shards (`act_q.f16`); never exported.""" + + def __init__(self, in_dim, hidden=128): + super().__init__() + self.fc1 = nn.Linear(in_dim, hidden) + self.fc2 = nn.Linear(hidden, 1) + + def forward(self, a): + return self.fc2(F.gelu(self.fc1(a))).squeeze(-1) + + +def _gelu(x): + return F.gelu(x, approximate="tanh") + + +class Tx(nn.Module): + """The transformer network (#400 R2): a global token and one token per entity through `layers` pre-norm + self-attention blocks; each candidate attends to the tokens once. Same outputs as `Net`. `net.rs` (`Tx`) runs it + in plain Rust; everything here is written out by hand so the two match exactly. + + Optional extensions (all default off so older checkpoints load identically): + - `val_mlp=1`: dedicated 2-layer value MLP reading `[t[:, 0], mean_ent, max_ent, glob]` with LayerNorm & dropout + - `gelu=1`: tanh-approximated GELU instead of ReLU in FFN / trunk / value layers + - `drop`: training-only dropout rate in transformer blocks (0.0 at eval/export) + """ + + def __init__( + self, + d=128, + heads=4, + layers=3, + ff=256, + dim=32, + trunk=128, + text=0, + val_mlp=0, + gelu=0, + glob_f=GLOB_F_V1, + rel=0, + act_ent=0, + drop=0.0, + ): + super().__init__() + self.cfg = {"d": d, "heads": heads, "layers": layers, "ff": ff, "dim": dim, "trunk": trunk} + if text: + self.cfg["text"] = int(text) + if val_mlp: + self.cfg["val_mlp"] = 1 + if gelu: + self.cfg["gelu"] = 1 + if int(glob_f) != GLOB_F_V1: + self.cfg["glob_f"] = int(glob_f) + if rel: + self.cfg["rel"] = 1 + if act_ent: + self.cfg["act_ent"] = 1 + self.heads = heads + self.d = d + self.glob_f = int(glob_f) + self.val_mlp = bool(val_mlp) + self.use_gelu = bool(gelu) + self.use_rel = bool(rel) + self.act_ent = bool(act_ent) + self.drop = nn.Dropout(drop) if drop > 0 else nn.Identity() + self.emb = CardEmb(dim, int(text)) + self.ent_in = nn.Linear(dim + ENT_F, d) + self.glob_in = nn.Linear(self.glob_f, d) + self.rel_bias = nn.Parameter(torch.zeros(2 * NUM_REL_TYPES, heads)) if self.use_rel else None + self.blocks = nn.ModuleList() + for _ in range(layers): + b = nn.Module() + b.ln1, b.qkv, b.out = nn.LayerNorm(d), nn.Linear(d, 3 * d), nn.Linear(d, d) + b.ln2, b.ff1, b.ff2 = nn.LayerNorm(d), nn.Linear(d, ff), nn.Linear(ff, d) + self.blocks.append(b) + self.ln_f = nn.LayerNorm(d) + self.trunk1 = nn.Linear(2 * d, trunk) + if self.val_mlp: + v_in = 3 * d + self.glob_f + self.val_ln = nn.LayerNorm(v_in) + self.val_fc1 = nn.Linear(v_in, trunk) + self.val_drop = nn.Dropout(0.3) + self.val_fc2 = nn.Linear(trunk, 1) + self.value = None + else: + self.value = nn.Linear(trunk, 1) + self.belief = nn.Linear(trunk, dim) + self.act_in = nn.Linear(dim + ACT_F + (d if self.act_ent else 0), d) + self.act_ln = nn.LayerNorm(d) + self.act_q, self.act_kv, self.act_o = nn.Linear(d, d), nn.Linear(d, 2 * d), nn.Linear(d, d) + self.act_ff = nn.Linear(d, d) + self.query = nn.Linear(trunk, d) + self.abias = nn.Linear(d, 1) + + def _act(self, x): + return _gelu(x) if self.use_gelu else F.relu(x) + + def _glob(self, g): + if g.shape[-1] == self.glob_f: + return g + if g.shape[-1] > self.glob_f: + return g[..., : self.glob_f] + return F.pad(g, (0, self.glob_f - g.shape[-1])) + + def _build_attn_bias(self, b, mask, dtype): + if self.rel_bias is None or "ent_rel_idx" not in b or "ent_rel_type" not in b: + return mask[:, None, None, :] + B, T = mask.shape + ne = T - 1 + if ne <= 0: + return mask[:, None, None, :] + ri = b["ent_rel_idx"].long() + rt = b["ent_rel_type"].long() + em = b["ent_mask"] + ri_safe = ri.clamp(0, ne - 1) + valid = em & (rt >= 1) & (rt <= NUM_REL_TYPES) & (ri < ne) & em.gather(1, ri_safe) + bi, ei = torch.nonzero(valid, as_tuple=True) + if bi.numel() == 0: + return mask[:, None, None, :] + bias = torch.zeros((B, T, T, self.heads), device=mask.device, dtype=dtype) + bias.masked_fill_(~mask[:, None, :, None], float("-inf")) + ti = ri[bi, ei] + r = rt[bi, ei] - 1 + rb = self.rel_bias.to(dtype) + bias.index_put_((bi, 1 + ei, 1 + ti), rb[r], accumulate=True) + bias.index_put_((bi, 1 + ti, 1 + ei), rb[r + NUM_REL_TYPES], accumulate=True) + return bias.permute(0, 3, 1, 2).contiguous() + + def _attend(self, q, k, v, attn_mask): + """q [B, Q, d], k/v [B, T, d], attn_mask [B, 1/H, 1/Q, T] -> [B, Q, d], `heads` heads""" + B, Q, D = q.shape + T = k.shape[1] + h, hd = self.heads, D // self.heads + q = q.view(B, Q, h, hd).transpose(1, 2) + k = k.view(B, T, h, hd).transpose(1, 2) + v = v.view(B, T, h, hd).transpose(1, 2) + out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + return out.transpose(1, 2).reshape(B, Q, D) + + def tokens(self, b): + """-> tokens [B, 1+N, d] after the blocks (normed), mask [B, 1+N]""" + g = self.glob_in(self._glob(b["glob"])).unsqueeze(1) + e = self.ent_in(torch.cat([self.emb(b["ent_ids"]), b["ents"]], -1)) + x = torch.cat([g, e], 1) + mask = torch.cat([torch.ones_like(b["ent_mask"][:, :1]), b["ent_mask"]], 1) + attn_mask = self._build_attn_bias(b, mask, x.dtype) + for blk in self.blocks: + y = blk.ln1(x) + q, k, v = blk.qkv(y).chunk(3, -1) + x = x + self.drop(blk.out(self._attend(q, k, v, attn_mask))) + x = x + self.drop(blk.ff2(self._act(blk.ff1(blk.ln2(x))))) + return self.ln_f(x), mask + + def _pool_val_features(self, t, mask, glob): + m = mask[:, 1:].unsqueeze(-1).float() + ent_t = t[:, 1:] + mean = (ent_t * m).sum(1) / m.sum(1).clamp(min=1) + mx = torch.where(m > 0, ent_t, torch.full_like(ent_t, -1e9)).max(1).values + mx = torch.where(m.sum(1) > 0, mx, torch.zeros_like(mx)) + return torch.cat([t[:, 0], mean, mx, self._glob(glob)], -1), mean + + def state_tokens(self, b): + t, mask = self.tokens(b) + m = mask[:, 1:].unsqueeze(-1).float() + mean = (t[:, 1:] * m).sum(1) / m.sum(1).clamp(min=1) + h = self._act(self.trunk1(torch.cat([t[:, 0], mean], -1))) + return h, t, mask + + def state(self, b): + return self.state_tokens(b)[0] + + def forward(self, b, return_vfeat=False, return_act_emb=False, detach_val=False): + t, mask = self.tokens(b) + vfeat, mean = self._pool_val_features(t, mask, b["glob"]) + h = self._act(self.trunk1(torch.cat([t[:, 0], mean], -1))) + if self.val_mlp: + vf = vfeat.detach() if detach_val else vfeat + vh = self.val_drop(self._act(self.val_fc1(self.val_ln(vf)))) + v = self.val_fc2(vh).squeeze(-1) + else: + v = self.value(h.detach() if detach_val else h).squeeze(-1) + if self.act_ent: + B, na = b["act_ids"].shape + ne = t.shape[1] - 1 + if ne > 0 and "act_ent_idx" in b: + ae = b["act_ent_idx"].long() + ae_valid = (ae < ne) & b["act_mask"] + ae_safe = ae.clamp(0, ne - 1) + ctx = t[:, 1:].gather(1, ae_safe.unsqueeze(-1).expand(-1, -1, self.d)) + ctx = ctx * ae_valid.unsqueeze(-1).to(ctx.dtype) + else: + ctx = torch.zeros((B, na, self.d), device=t.device, dtype=t.dtype) + a_feat = torch.cat([self.emb(b["act_ids"]), b["acts"], ctx], -1) + else: + a_feat = torch.cat([self.emb(b["act_ids"]), b["acts"]], -1) + a = self.act_in(a_feat) + k, vv = self.act_kv(t).chunk(2, -1) + a = a + self.act_o(self._attend(self.act_q(self.act_ln(a)), k, vv, mask[:, None, None, :])) + a = a + self._act(self.act_ff(a)) + logits = (self.query(h).unsqueeze(1) * a).sum(-1) + self.abias(a).squeeze(-1) + logits = logits.masked_fill(~b["act_mask"], -1e9) + if return_act_emb: + return logits, v, h, vfeat, a + if return_vfeat: + return logits, v, h, vfeat + return logits, v, h + + def belief_logits(self, h, pool_ids): + return (self.belief(h).unsqueeze(1) * self.emb(pool_ids)).sum(-1) + + +def make(arch, **kw): + return Tx(**kw) if arch == "tx" else Net(**kw) + + +def arch_of(net): + return {"arch": "tx", **net.cfg} if isinstance(net, Tx) else {"arch": "mlp"} + + +def build(spec): + spec = dict(spec) + return make(spec.pop("arch", "mlp"), **spec) + + +def save_dir(net, d): + """Writes net.pt and arch.json into run folder `d`""" + torch.save(net.state_dict(), f"{d}/net.pt") + json.dump(arch_of(net), open(f"{d}/arch.json", "w")) + + +def load_dir(d, dev, upgrade_val_mlp=False, drop=0.0): + """The network in run folder `d` (arch.json says which; the first network without one)""" + import os + spec = json.load(open(f"{d}/arch.json")) if os.path.exists(f"{d}/arch.json") else {"arch": "mlp"} + upgraded = False + if upgrade_val_mlp and spec.get("arch") == "tx" and not spec.get("val_mlp"): + spec["val_mlp"] = 1 + upgraded = True + if spec.get("arch") == "tx" and drop > 0: + spec["drop"] = drop + net = build(spec).to(dev) + sd = torch.load(f"{d}/net.pt", map_location=dev) + if upgraded: + sd = {k: v for k, v in sd.items() if not k.startswith("value.")} + net.load_state_dict(sd, strict=False) + else: + net.load_state_dict(sd) + return net + + +TENSORS = ["emb", "ent1", "ent2", "glob1", "trunk1", "trunk2", "value", "act1", "act2", "query", "abias", "belief"] + + +def export(net, path, meta=None): + """Writes the `.pmnet` file `net.rs` reads: a JSON header line, then little-endian f32 tensors""" + sd = {k: v.detach().float().cpu() for k, v in net.state_dict().items()} + if isinstance(net, Tx): + # the card-text projection folded into the name embedding + sd["emb.weight"] = net.emb.table().detach().float().cpu() + names = [k for k in sd if k not in ("emb.text", "emb.proj")] + cfg = {k: v for k, v in net.cfg.items() if k != "text"} + header = {"arch": "tx", "config": cfg, "tensors": [[k, list(sd[k].shape)] for k in names], "meta": meta or {}} + else: + names = [] + for t in TENSORS: + for part in ("weight", "bias"): + k = f"{t}.{part}" + if k in sd: + names.append(k) + header = {"tensors": [[k, list(sd[k].shape)] for k in names], "meta": meta or {}} + with open(path, "wb") as f: + f.write(json.dumps(header).encode() + b"\n") + for k in names: + a = sd[k].contiguous().view(-1).tolist() + f.write(struct.pack(f"<{len(a)}f", *a)) + + +def params(net): + return sum(p.numel() for p in net.parameters()) + + +if __name__ == "__main__": + import sys + + torch.manual_seed(0) + n = Net() + export(n, sys.argv[1] if len(sys.argv) > 1 else "net.pmnet", {"kind": "random init"}) + print("params", params(n)) diff --git a/rust/rl/pfsp_league.py b/rust/rl/pfsp_league.py new file mode 100644 index 0000000..04a70be --- /dev/null +++ b/rust/rl/pfsp_league.py @@ -0,0 +1,214 @@ +"""Prioritized Fictitious Self-Play (PFSP) League Manager for Phase 3 anti-echo-chamber self-play. + +Tracks a heterogeneous opponent pool (1.3M soup, 5M soup, 10M, historical anchors, host@s6) in a persistent +`league_state.json`, computes PFSP sampling probabilities (`hard`: (1 - winrate)^p, `variance`: w*(1 - w), +or `uniform`), mixes Constructed + OOD deck suites, randomizes opening temperature/turn schedules, and +executes or plans `selfplay` rounds writing v3 shards. +""" + +import argparse +import json +import math +import os +import re +import subprocess +import time + +import numpy as np + + +def default_league(runs_dir="runs"): + return { + "version": 1, + "agents": { + "wavec-1.3m-soup": { + "arch": "2.05m", + "spec": f"cfg:policy=ismcts+net={runs_dir}/wavec-final-1.3m-soup/net.pmnet+hide=1+iters=256+samples=8+cpuct=1000+leaf_blend=1000+gumbel_root=1+multi_tree=1+mulligan_net=1+width=16+consider=12+extra_turns=2", + "elo": 1110.0, + }, + "wavec-5m-soup": { + "arch": "5.07m", + "spec": f"cfg:policy=ismcts+net={runs_dir}/wavec-final-5m-soup/net.pmnet+hide=1+iters=256+samples=8+cpuct=1000+leaf_blend=1000+gumbel_root=1+multi_tree=1+mulligan_net=1+width=16+consider=12+extra_turns=2", + "elo": 1114.0, + }, + "wavec-r12-5m": { + "arch": "5.07m", + "spec": f"cfg:policy=ismcts+net={runs_dir}/wavec-r12-5m-sem-oracle/net.pmnet+hide=1+iters=256+samples=8+cpuct=1000+leaf_blend=1000+gumbel_root=1+multi_tree=1+mulligan_net=1+width=16+consider=12+extra_turns=2", + "elo": 1102.0, + }, + "day1-r6-1.3m": { + "arch": "1.3m", + "spec": f"cfg:policy=ismcts+net={runs_dir}/obsv2-r6-1.3m-reg/net.pmnet+hide=1+iters=128+cpuct=1000+leaf_blend=1000+multi_tree=1+mulligan_sim=1+extra_turns=0", + "elo": 1020.0, + }, + "host@s6": { + "arch": "heuristic", + "spec": "host@s6", + "elo": 1000.0, + }, + }, + "history": {}, + } + + +def load_league(path, runs_dir="runs"): + if path and os.path.exists(path): + return json.load(open(path)) + return default_league(runs_dir) + + +def save_league(state, path): + os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) + with open(path, "w") as f: + json.dump(state, f, indent=2) + + +def winrate_against(state, learner, opp): + key = f"{learner}__vs__{opp}" + rec = state["history"].get(key) + if not rec or rec["games"] == 0: + # Prior from Elo difference if unplayed + e_l = state["agents"].get(learner, {}).get("elo", 1100.0) + e_o = state["agents"].get(opp, {}).get("elo", 1000.0) + return 1.0 / (1.0 + 10.0 ** ((e_o - e_l) / 400.0)) + return (rec["w"] + 0.5 * rec["d"] + 1.0) / (rec["games"] + 2.0) + + +def pfsp_weights(state, learner, opponents, mode="hard", p=2.0, self_play_frac=0.35): + """Returns normalized opponent sampling probabilities combining self-play + PFSP over diverse opponents.""" + weights = {} + others = [o for o in opponents if o != learner] + if not others: + return {learner: 1.0} + raw = [] + for o in others: + wr = winrate_against(state, learner, o) + if mode == "hard": + f = (1.0 - wr) ** p + elif mode == "variance": + f = wr * (1.0 - wr) + else: + f = 1.0 + raw.append(max(f, 1e-3)) + s = sum(raw) + other_share = 1.0 - (self_play_frac if learner in opponents else 0.0) + if learner in opponents: + weights[learner] = self_play_frac + for o, r in zip(others, raw): + weights[o] = other_share * (r / s) + return weights + + +def plan_round(state, learner, total_games, suites, suite_weights, mode="hard", p=2.0, self_play_frac=0.35, seed=0): + rng = np.random.default_rng(seed) + opps = list(state["agents"].keys()) + if learner not in opps: + opps.append(learner) + probs = pfsp_weights(state, learner, opps, mode=mode, p=p, self_play_frac=self_play_frac) + sw = np.array(suite_weights, dtype=np.float64) + sw = sw / sw.sum() + # Allocate games into chunks of >= 20 games across (opponent, suite, temp) + plan = [] + for opp, prob in sorted(probs.items(), key=lambda kv: -kv[1]): + opp_games = int(round(total_games * prob)) + if opp_games < 2: + continue + for si, suite in enumerate(suites): + g = int(round(opp_games * sw[si])) + if g < 2: + continue + temp = int(rng.choice([750, 1000, 1200])) + temp_turn = int(rng.choice([6, 8, 10])) + plan.append({ + "opponent": opp, + "opponent_spec": state["agents"][opp]["spec"] if opp in state["agents"] else state["agents"][learner]["spec"], + "suite": suite, + "games": g, + "temp": temp, + "temp_turn": temp_turn, + "pfsp_prob": round(prob, 4), + "est_winrate": round(winrate_against(state, learner, opp), 4), + }) + return plan + + +def with_temp(spec, temp, temp_turn): + if not spec.startswith("cfg:"): + return spec + spec = re.sub(r"\+temp=\d+", "", spec) + spec = re.sub(r"\+temp_turn=\d+", "", spec) + return f"{spec}+temp={temp}+temp_turn={temp_turn}" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--state", default="league_state.json") + ap.add_argument("--runs-dir", default="runs") + ap.add_argument("--learner", default="wavec-1.3m-soup") + ap.add_argument("--learner-spec", default=None) + ap.add_argument("--games", type=int, default=2000) + ap.add_argument("--jobs", type=int, default=32) + ap.add_argument("--keep", type=int, default=160) + ap.add_argument("--fast", default="ismcts:12") + ap.add_argument("--suites", default="../../archbench/constructed-2,../../archbench/constructed-ood-1") + ap.add_argument("--suite-weights", default="0.65,0.35") + ap.add_argument("--mode", choices=["hard", "variance", "uniform"], default="hard") + ap.add_argument("--power", type=float, default=2.0) + ap.add_argument("--self-play-frac", type=float, default=0.35) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--bin", default="../../rust/target/release/selfplay") + ap.add_argument("--out", default=None, help="output shard directory when --run-round is set") + ap.add_argument("--run-round", action="store_true") + args = ap.parse_args() + + state = load_league(args.state, args.runs_dir) + if args.learner_spec: + state["agents"][args.learner] = {"arch": "custom", "spec": args.learner_spec, "elo": 1120.0} + suites = [s.strip() for s in args.suites.split(",") if s.strip()] + sw = [float(x) for x in args.suite_weights.split(",")] + plan = plan_round(state, args.learner, args.games, suites, sw, mode=args.mode, p=args.power, self_play_frac=args.self_play_frac, seed=args.seed) + + print(f"PFSP PLAN learner={args.learner} total~{sum(p['games'] for p in plan)} games mode={args.mode} (p={args.power})") + for i, item in enumerate(plan): + print(f" [{i:02d}] vs {item['opponent']:<18} suite={os.path.basename(item['suite']):<18} games={item['games']:>4} temp={item['temp']}@{item['temp_turn']} pfsp={item['pfsp_prob']:.3f} wr={item['est_winrate']:.3f}") + + if not args.run_round: + return + + if not args.out: + raise ValueError("--out is required with --run-round") + os.makedirs(args.out, exist_ok=True) + learner_base = state["agents"][args.learner]["spec"] + pat = re.compile(r"SELFPLAY against .*?: (\d+)-(\d+)-(\d+)") + for i, item in enumerate(plan): + sub_out = os.path.join(args.out, f"slot_{i:02d}_{item['opponent'].replace('@', '_')}") + os.makedirs(sub_out, exist_ok=True) + cmd = [ + args.bin, + "--suite", item["suite"], + "--games", str(item["games"]), + "--jobs", str(args.jobs), + "--keep", str(args.keep), + "--fast", args.fast, + "--out", sub_out, + "--learner", with_temp(learner_base, item["temp"], item["temp_turn"]), + "--opponent", item["opponent_spec"], + ] + print(f"RUN slot {i:02d}: {' '.join(cmd)}", flush=True) + proc = subprocess.run(cmd, capture_output=True, text=True, check=True) + print(proc.stdout.strip(), flush=True) + m = pat.search(proc.stdout) + if m: + w, d, l = int(m.group(1)), int(m.group(2)), int(m.group(3)) + key = f"{args.learner}__vs__{item['opponent']}" + rec = state["history"].setdefault(key, {"w": 0, "d": 0, "l": 0, "games": 0}) + rec["w"] += w + rec["d"] += d + rec["l"] += l + rec["games"] += w + d + l + save_league(state, args.state) + print(f"Updated league state -> {args.state}") + + +if __name__ == "__main__": + main() diff --git a/rust/rl/pro_eval.py b/rust/rl/pro_eval.py new file mode 100644 index 0000000..a56933e --- /dev/null +++ b/rust/rl/pro_eval.py @@ -0,0 +1,103 @@ +"""Evaluates one or more entrants on categorized competitive MTG decision suites (e.g. archbench/pro-decisions-1). + +Example: + python pro_eval.py --suite ../../archbench/pro-decisions-1 --seeds 4 \ + --entrant host=host@s6 \ + --entrant soup13=cfg:policy=ismcts+net=runs/wavec-final-1.3m-soup/net.pmnet+iters=256+extra_turns=3+gumbel_root=1+leaf_blend=1000+multi_tree=1+samples=8+width=24+consider=16 +""" + +import argparse +import collections +import json +import os +import re +import subprocess +import sys + + +def parse_tactics_output(text, labels): + rows = {} + pat = re.compile(r"^TACTICS\s+(\S+)\s+((?:\d+/\d+\s*)+)$") + for line in text.splitlines(): + m = pat.match(line.strip()) + if not m: + continue + name = m.group(1) + scores = m.group(2).split() + if len(scores) != len(labels): + continue + parsed = [] + for s in scores: + a, b = s.split("/") + parsed.append((int(a), int(b))) + rows[name] = parsed + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bin", default="../../rust/target/release/tactics") + ap.add_argument("--suite", default="../../archbench/pro-decisions-1") + ap.add_argument("--seeds", type=int, default=4) + ap.add_argument("--entrant", action="append", required=True, help="label=entrant_spec") + ap.add_argument("--out-json", default=None) + args = ap.parse_args() + + labels, specs = [], [] + for item in args.entrant: + if "=" in item and not item.startswith("cfg:"): + k, v = item.split("=", 1) + else: + k, v = item, item + labels.append(k) + specs.append(v) + + suite_data = json.load(open(os.path.join(args.suite, "puzzles.json"))) + cat_of = {p["name"]: p.get("category", "uncategorized") for p in suite_data["puzzles"]} + categories = sorted(set(cat_of.values())) + + cmd = [args.bin, "--suite", args.suite, "--seeds", str(args.seeds), "--entrants", ",".join(specs)] + proc = subprocess.run(cmd, capture_output=True, text=True, check=True) + rows = parse_tactics_output(proc.stdout, labels) + + cat_totals = {c: [[0, 0] for _ in labels] for c in categories} + overall = [[0, 0] for _ in labels] + for pname, scores in rows.items(): + c = cat_of.get(pname, "uncategorized") + for i, (s, n) in enumerate(scores): + cat_totals[c][i][0] += s + cat_totals[c][i][1] += n + overall[i][0] += s + overall[i][1] += n + + print(f"PRO-EVAL suite={suite_data.get('suite')} puzzles={len(rows)} seeds={args.seeds}") + hdr = f"{'Category':<20}" + "".join(f" {lb:>16}" for lb in labels) + print(hdr) + print("-" * len(hdr)) + summary = {"suite": suite_data.get("suite"), "seeds": args.seeds, "entrants": labels, "categories": {}, "overall": {}} + for c in categories: + parts = [] + summary["categories"][c] = {} + for i, lb in enumerate(labels): + s, n = cat_totals[c][i] + pct = 100.0 * s / max(n, 1) + parts.append(f" {s:>3}/{n:<3} ({pct:5.1f}%)") + summary["categories"][c][lb] = {"solved": s, "total": n, "pct": round(pct, 2)} + print(f"{c:<20}" + "".join(parts)) + print("-" * len(hdr)) + parts = [] + for i, lb in enumerate(labels): + s, n = overall[i] + pct = 100.0 * s / max(n, 1) + parts.append(f" {s:>3}/{n:<3} ({pct:5.1f}%)") + summary["overall"][lb] = {"solved": s, "total": n, "pct": round(pct, 2)} + print(f"{'OVERALL':<20}" + "".join(parts)) + + if args.out_json: + with open(args.out_json, "w") as f: + json.dump(summary, f, indent=2) + print(f"Wrote {args.out_json}") + + +if __name__ == "__main__": + main() diff --git a/rust/rl/train.py b/rust/rl/train.py index d5f3f79..ec4ae95 100644 --- a/rust/rl/train.py +++ b/rust/rl/train.py @@ -19,7 +19,7 @@ import torch import torch.nn.functional as F from data import Data, compact_dir -from model import AuxHead, Critic, GLOB_F, NO_ENT, Tx, build, export, load_dir, params, save_dir +from model import ActQHead, AuxHead, Critic, GLOB_F, NO_ENT, Tx, build, export, load_dir, params, save_dir def oracle_batch(b): @@ -116,13 +116,20 @@ def losses( oracle_net=None, oracle_mix=0.0, oracle_mode=False, + act_q_head=None, + act_q_weight=0.0, ): want_aux = aux_head is not None + want_aq = act_q_head is not None and act_q_weight > 0.0 nb_in = oracle_batch(b) if oracle_mode else b - if want_aux: + if want_aq: + logits, v, h, vfeat, act_emb = net(nb_in, return_vfeat=True, return_act_emb=True, detach_val=detach_val) + elif want_aux: logits, v, h, vfeat = net(nb_in, return_vfeat=True, detach_val=detach_val) + act_emb = None else: logits, v, h = net(nb_in, detach_val=detach_val) + vfeat, act_emb = None, None logp = F.log_softmax(logits, -1) pol_per = -(b["target"] * logp).sum(-1) if pol_min_run > 0: @@ -162,11 +169,23 @@ def losses( crit = F.binary_cross_entropy_with_logits(critic(b), b["z"]) if critic is not None else torch.zeros((), device=v.device) if want_aux: aux_pred = aux_head(vfeat.detach() if detach_val else vfeat) - aux_tgt = torch.stack([b["turns_left"], b["final_life_diff"]], -1) + aux_tgt = torch.stack( + [b["turns_left"], b["final_life_diff"], b["next_life_delta"], b["next_board_delta"]], -1 + ) aux_per = F.smooth_l1_loss(aux_pred, aux_tgt, reduction="none").mean(-1) aux = (aux_per * vw).sum() / vw.sum().clamp(min=1) else: aux = torch.zeros((), device=v.device) + if want_aq and "act_q" in b: + aq = b["act_q"] + aq_mask = torch.isfinite(aq) & b["act_mask"] + if aq_mask.any(): + aq_pred = act_q_head(act_emb) + aq_safe = torch.nan_to_num(aq, nan=0.5).clamp(0.0, 1.0) + aq_loss = ( + F.binary_cross_entropy_with_logits(aq_pred, aq_safe, reduction="none") * aq_mask.float() + ).sum() / aq_mask.float().sum().clamp(min=1) + aux = aux + float(act_q_weight) * aq_loss right = (logits.argmax(-1) == b["target"].argmax(-1)).float() off = (b["target"].argmax(-1) != 0).float() @@ -228,30 +247,24 @@ def evaluate(net, critic, data, idx, dev, bs=1024, q_mix=0.0, pol_min_run=0, ora return res -def _select_epoch_blocks(data, samples_target, pol_min_run, rng, block_len=512): - """Picks block start indices totaling ~`samples_target` decisions, ensuring recent policy dirs get >= 50% share.""" +def _select_epoch_blocks(data, samples_target, pol_min_run, rng, block_len=512, recency_decay=0.92): + """Picks block start indices totaling ~`samples_target` decisions strictly WITHOUT replacement (hard <= 1.0x/epoch + pass cap per block) using smooth exponential recency weighting over runs. Eliminates narrow-window oversampling.""" n_blocks = max(1, (len(data) + block_len - 1) // block_len) want_blocks = max(1, min(n_blocks, (samples_target + block_len - 1) // block_len)) starts = np.arange(0, len(data), block_len) - if pol_min_run <= 0: - chosen = rng.choice(starts, size=want_blocks, replace=False) - chosen.sort() - return chosen - block_runs = data.run[starts] - recent = starts[block_runs >= pol_min_run] - older = starts[block_runs < pol_min_run] - if len(older) == 0 or len(recent) == 0: - chosen = rng.choice(starts, size=want_blocks, replace=False) - chosen.sort() - return chosen - # Allocate 60% of epoch blocks to recent policy rounds, 40% to older value replay buffer - n_rec = min(len(recent), max(1, int(want_blocks * 0.6))) - n_old = min(len(older), want_blocks - n_rec) - if n_rec + n_old < want_blocks: - n_rec = min(len(recent), want_blocks - n_old) - c_rec = rng.choice(recent, size=n_rec, replace=False) - c_old = rng.choice(older, size=n_old, replace=False) if n_old > 0 else np.zeros(0, dtype=starts.dtype) - chosen = np.concatenate([c_rec, c_old]) + if want_blocks >= len(starts): + return starts + block_runs = data.run[starts].astype(np.float64) + max_run = float(block_runs.max()) if len(block_runs) else 0.0 + if 0.0 < recency_decay < 1.0 and max_run > 0.0: + w = np.power(recency_decay, max_run - block_runs) + else: + w = np.ones(len(starts), dtype=np.float64) + if pol_min_run > 0: + w = np.where(block_runs >= pol_min_run, w * 1.5, w) + w = w / w.sum() + chosen = rng.choice(starts, size=want_blocks, replace=False, p=w) chosen.sort() return chosen @@ -270,6 +283,8 @@ def build_parser(): ap.add_argument("--value-weight", type=float, default=0.5) ap.add_argument("--belief-weight", type=float, default=0.2) ap.add_argument("--aux-weight", type=float, default=0.15, help="training-only auxiliary positional loss weight (0 disables)") + ap.add_argument("--act-q-weight", type=float, default=0.2, help="training-only v3 per-action Q head loss weight (0 disables)") + ap.add_argument("--recency-decay", type=float, default=0.92, help="exponential recency decay per run in block sampling (1.0 = uniform; always <= 1x/epoch)") ap.add_argument("--q-mix", type=float, default=0.4, help="weight on root search Q-value in value target when present") ap.add_argument("--td-lambda", type=float, default=0.0, help="forward-looking TD(lambda) value target across future search Q-values (0 = plain z)") ap.add_argument("--policy-recent", type=int, default=0, help="only train policy on the last N --data dirs (0 = all)") @@ -348,7 +363,11 @@ def train_main(argv=None, shared_data=None): aux_head = None if args.aux_weight > 0: aux_in = (3 * net.d + net.glob_f) if isinstance(net, Tx) else net.trunk2.out_features - aux_head = AuxHead(aux_in).to(dev) + aux_head = AuxHead(aux_in, out_dim=4).to(dev) + act_q_head = None + if args.act_q_weight > 0: + aq_in = net.d if isinstance(net, Tx) else net.act2.out_features + act_q_head = ActQHead(aq_in).to(dev) print( f"TRAIN net {params(net)} params" @@ -374,6 +393,8 @@ def train_main(argv=None, shared_data=None): extra_params += list(critic.parameters()) if aux_head is not None: extra_params += list(aux_head.parameters()) + if act_q_head is not None: + extra_params += list(act_q_head.parameters()) param_groups = [ {"params": base_params + extra_params, "weight_decay": 1e-4}, {"params": vh_params, "weight_decay": args.val_wd}, @@ -401,7 +422,7 @@ def train_main(argv=None, shared_data=None): tl = torch.zeros(5, device=dev) nb = 0 if use_staging or (args.samples_per_epoch > 0 and args.samples_per_epoch < len(train_idx)): - blocks = _select_epoch_blocks(data, epoch_samples, pol_min_run, rng) + blocks = _select_epoch_blocks(data, epoch_samples, pol_min_run, rng, recency_decay=args.recency_decay) rng.shuffle(blocks) chunk_blks = max(1, args.stage_chunk // 512) if args.stage_chunk > 0 else len(blocks) for ci in range(0, len(blocks), chunk_blks): @@ -417,6 +438,7 @@ def train_main(argv=None, shared_data=None): q_mix=args.q_mix, pol_min_run=pol_min_run, pol_old_weight=args.pol_old_weight, val_prob=args.val_prob, detach_val=(args.detach_val or not value_on), oracle_net=oracle_net, oracle_mix=args.oracle_mix, oracle_mode=args.oracle_mode, + act_q_head=act_q_head, act_q_weight=args.act_q_weight, )[:5] loss = ( pol @@ -457,6 +479,7 @@ def train_main(argv=None, shared_data=None): q_mix=args.q_mix, pol_min_run=pol_min_run, pol_old_weight=args.pol_old_weight, val_prob=args.val_prob, detach_val=(args.detach_val or not value_on), oracle_net=oracle_net, oracle_mix=args.oracle_mix, oracle_mode=args.oracle_mode, + act_q_head=act_q_head, act_q_weight=args.act_q_weight, )[:5] loss = ( pol @@ -497,6 +520,7 @@ def train_main(argv=None, shared_data=None): q_mix=args.q_mix, pol_min_run=pol_min_run, pol_old_weight=args.pol_old_weight, val_prob=args.val_prob, detach_val=(args.detach_val or not value_on), oracle_net=oracle_net, oracle_mix=args.oracle_mix, oracle_mode=args.oracle_mode, + act_q_head=act_q_head, act_q_weight=args.act_q_weight, )[:5] loss = ( pol