diff --git a/sharingan-1/search/src/exploit.rs b/sharingan-1/search/src/exploit.rs new file mode 100644 index 00000000..6ff424a1 --- /dev/null +++ b/sharingan-1/search/src/exploit.rs @@ -0,0 +1,358 @@ +//! Exploitability of the search strategy inside its own subgame (a fast gate for changes to the +//! search: averaging, iterations, menu). +//! +//! After `solver::solve` has produced a [`Solution`], this module computes how much each player +//! could win by best-responding to the strategy the search outputs (weighted average, or the +//! final iterate when `SearchParams::play_final`), in the SAME subgame: same root state, board, +//! beliefs (ranges), action menu (`sizing`, `later_sizing`, off-tree `extras`) and, for +//! multiway flops, the same depth-limit leaves. +//! +//! # What is measured +//! +//! * **Heads-up, solved to the end of the hand (no leaves): exact.** Vector-form best response +//! (`vector::evaluate`): both players' exact best response over all hole pairs and all +//! turn/river cards (chance enumerated, not sampled). The best-responding player sees its exact +//! hand and the exact board (no card abstraction); the strategy it responds to is what the +//! solver stores: lossless on the root street, blueprint-bucket pooled on later streets (or the +//! search buckets), so the number includes the card-abstraction error of the later streets. +//! Infosets the solution never visited use the blueprint prior translated to the menu +//! (uniform when the blueprint has none); the share of such lookups is reported. +//! * **Three or more players, or leaf subgames: a sampled LOWER bound.** For each player that can +//! still act, a best response is learned by CFR for that player alone against the frozen +//! strategies of all others (external sampling, `br_iters` iterations) and evaluated against the +//! frozen profile on common random deals (`eval_samples`). The learned strategy is an average +//! over a finite run, so it is at most the true best response: the reported gain is a lower +//! bound with a standard error, never an upper bound. The leaves are the same fixed +//! continuation rollouts the solver itself uses; the best response cannot deviate below them, +//! so whatever the leaf values hide is not seen (`leaf_share` says how many playouts end in a +//! leaf). +//! * **Sum over players.** With three or more players the sum of one-sided best-response gains +//! is NOT a Nash distance: a profile can have all one-sided gains near zero without being an +//! equilibrium (and the game is not zero-sum); it measures how far each player's strategy is +//! from unilaterally exploitable by one deviator, nothing more. With two players the sum is +//! the classic NashConv (exploitability = sum / 2). +//! * **Heads-up re-solve gadget** (Burch, Johanson, Bowling 2014; Moravcik et al. 2017): the +//! opponent may leave the subgame at entry and take the value it would get against the +//! BLUEPRINT strategy (its counterfactual best-response value per hand, computed here with the +//! same evaluator against the blueprint prior mapped to the menu). `gadget` is +//! `sum_h reach(h) * max(0, BR_cfv_search(h) - BR_cfv_blueprint(h))`, in chips: how much more +//! the opponent can win by entering than the blueprint would have allowed. A locally +//! unexploitable strategy can still be exploitable in the whole game; this number catches +//! that. The blueprint values are the translated prior, not the blueprint's own abstract game. +//! * `gain` and `gadget` are in chips; the report also gives % of the pot at the subgame root +//! and big blinds. + +use crate::beliefs::{hole_mask, holes}; +use crate::bp::Blueprint; +use crate::solver::{best_response_sampled, BrEstimate, SearchParams, Solution, Subgame}; +use crate::tree::{search_actions, Limit}; +use crate::vector::{evaluate_profile as evaluate, BrReport, Query, Strat, VecGame}; +use abstraction::search_buckets::FlopView; +use cards::bit; +use nlhe::abstraction::{ActionList, Shadow, MAX_ACTIONS}; +use nlhe::{State, Street}; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::time::Instant; + +#[derive(Clone, Debug)] +pub struct Opts { + /// Best-response learning iterations per player (sampled mode). + pub br_iters: u64, + /// Common deals for the sampled evaluation. + pub eval_samples: u64, + /// Heads-up: also compute the gadget value (one more exact pass per player). + pub gadget: bool, + pub big_blind: i32, +} + +impl Default for Opts { + fn default() -> Self { + Opts { br_iters: 200_000, eval_samples: 200_000, gadget: true, big_blind: 100 } + } +} + +#[derive(Clone, Debug)] +pub struct PlayerGain { + pub seat: usize, + /// Mean chips of the player following the profile / best-responding, and the gain (chips). + pub value: f64, + pub br: f64, + pub gain: f64, + /// Standard error of `gain` (sampled mode only). + pub gain_se: Option, + /// Heads-up gadget value (chips), see module docs. + pub gadget: Option, +} + +#[derive(Clone, Debug)] +pub struct Report { + /// `"exact_hu"` or `"sampled_lower_bound"`. + pub mode: &'static str, + pub players: Vec, + pub sum_gain: f64, + pub pot: f64, + pub big_blind: f64, + pub final_iterate: bool, + /// Share of strategy lookups that hit an infoset the solution never visited. + pub miss_share: f64, + pub leaf_share: Option, + pub millis: f64, +} + +impl Report { + pub fn pct_pot(&self, chips: f64) -> f64 { + 100.0 * chips / self.pot.max(1.0) + } + pub fn bb(&self, chips: f64) -> f64 { + chips / self.big_blind + } +} + +/// A complete strategy profile over the subgame for the exact evaluator: either the strategies +/// stored in a `Solution` (tables) or the blueprint prior translated onto the search menu. +pub struct ProfileStrat<'a> { + sol: Option<&'a Solution>, + final_it: bool, + bp: &'a Blueprint, + root: State, + root_sh: Shadow, + me: usize, + params: &'a SearchParams, + extras: &'a crate::tree::Extras, + view: Option, + /// `(board mask, street)` -> per compact hand: (blueprint bucket, search bucket). + buckets: RefCell>>, + lookups: Cell, + misses: Cell, +} + +impl<'a> ProfileStrat<'a> { + pub fn new(sg: &'a Subgame<'a>, sol: Option<&'a Solution>, final_it: bool) -> Self { + let view = match &sg.params.search_buckets { + Some(sb) if sg.root.street() != Street::Preflop && sg.board.len() >= 3 => Some(sb.for_flop([sg.board[0], sg.board[1], sg.board[2]])), + _ => None, + }; + ProfileStrat { + sol, + final_it, + bp: sg.bp, + root: sg.root, + root_sh: sg.bp_hist, + me: sg.me, + params: sg.params, + extras: sg.extras, + view, + buckets: RefCell::new(HashMap::new()), + lookups: Cell::new(0), + misses: Cell::new(0), + } + } + pub fn miss_share(&self) -> f64 { + self.misses.get() as f64 / self.lookups.get().max(1) as f64 + } + + fn shadow_at(&self, q: &Query) -> Shadow { + let mut st = self.root; + let mut sh = self.root_sh; + for &a in q.path { + self.bp.observe(&mut sh, &st, a, st.to_act() == Some(self.me)); + st.apply(a); + } + sh + } + + fn bucket_table(&self, q: &Query) -> std::cell::Ref<'_, Vec<(u32, u32)>> { + let mask = q.board.iter().fold(0u64, |m, &c| m | bit(c)); + let key = (mask, q.street.idx() as u8); + if !self.buckets.borrow().contains_key(&key) { + let hl = holes(); + let v: Vec<(u32, u32)> = q + .hands + .idx + .iter() + .map(|&i| { + let h = hl[i as usize]; + if (bit(h[0]) | bit(h[1])) & mask != 0 { + return (0, 0); + } + let b = self.bp.bucket(q.street, h, q.board); + let sb = self.view.as_ref().and_then(|v| v.bucket(h, q.board)).unwrap_or(b); + (b, sb) + }) + .collect(); + self.buckets.borrow_mut().insert(key, v); + } + std::cell::Ref::map(self.buckets.borrow(), |m| &m[&key]) + } +} + +impl Strat for ProfileStrat<'_> { + fn probs(&self, q: &Query, n: usize, out: &mut [f64]) { + let m = q.hands.len(); + let mut list = ActionList::new(); + let on_root = q.street == self.root.street(); + let ex: &[i32] = if on_root { self.extras.get(&q.akey).map_or(&[], |v| v.as_slice()) } else { &[] }; + let sz = if on_root { &self.params.sizing } else { &self.params.later_sizing }; + search_actions(q.st, sz, ex, &mut list); + debug_assert_eq!(list.len(), n); + let sh = self.shadow_at(q); + let need_buckets = !on_root || self.sol.is_none() || self.sol.is_some_and(|s| s.opp_pool); + let bk: Option>> = need_buckets.then(|| self.bucket_table(q)); + let mut buf = [0f32; MAX_ACTIONS]; + for h in 0..m { + let (bpb, sbb) = bk.as_ref().map_or((0, 0), |b| b[h]); + let hole = q.hands.idx[h] as usize; + let hit = match self.sol { + Some(s) if on_root && s.opp_pool && q.seat != self.me => s.probs_opp(q.akey, bpb, n, self.final_it, &mut buf), + Some(s) if on_root => s.probs(q.akey, hole, n, self.final_it, &mut buf), + Some(s) => s.probs_later(q.akey, q.street, sbb, n, self.final_it, &mut buf), + None => false, + }; + self.lookups.set(self.lookups.get() + 1); + if !hit { + if self.sol.is_some() { + self.misses.set(self.misses.get() + 1); + } + // The blueprint's bucket is needed for the prior even when the table key is a hole pair. + let bpb = if bk.is_some() { bpb } else { self.bp.bucket(q.street, holes()[hole], q.board) }; + match self.bp.prior(&sh, q.st, &list, bpb) { + Some(pr) => buf[..n].copy_from_slice(&pr[..n]), + None => buf[..n].iter_mut().for_each(|x| *x = 1.0 / n as f32), + } + } + for a in 0..n { + out[a * m + h] = buf[a] as f64; + } + } + } +} + +static EMPTY: std::sync::OnceLock> = std::sync::OnceLock::new(); + +fn vec_game<'a>(sg: &'a Subgame<'a>, seats: [usize; 2]) -> VecGame<'a> { + let bm = cards::mask_of(sg.board); + let ranges = seats.map(|s| sg.beliefs.w[s].iter().enumerate().map(|(i, &x)| if hole_mask(i) & bm == 0 { x as f64 } else { 0.0 }).collect::>()); + VecGame { + root: sg.root, + board: sg.board, + seats, + ranges, + sizing: &sg.params.sizing, + later: &sg.params.later_sizing, + extras: sg.extras, + me: seats.iter().position(|&s| s == sg.me), + my_hole: None, + frozen: EMPTY.get_or_init(HashMap::new), + pooled: None, + } +} + +fn gain_pair(r: &BrReport, seats: [usize; 2], alt: Option<&BrReport>) -> Vec { + (0..2) + .map(|p| { + let gadget = alt.map(|a| { + let m = r.hands.len(); + (0..m).map(|h| r.reach[p][h] * (r.br_cfv[p][h] - a.br_cfv[p][h]).max(0.0)).sum::() / r.z + }); + PlayerGain { seat: seats[p], value: r.value[p], br: r.br[p], gain: r.br[p] - r.value[p], gain_se: None, gadget } + }) + .collect() +} + +/// Exact heads-up evaluation of an arbitrary profile (`sol = None`: the blueprint prior). +pub fn exact_hu(sg: &Subgame, sol: Option<&Solution>, opts: &Opts) -> Option { + let t0 = Instant::now(); + let seats = VecGame::live_seats(&sg.root)?; + let final_it = sg.params.play_final; + let g = vec_game(sg, seats); + let strat = ProfileStrat::new(sg, sol, final_it); + let rep = evaluate(&g, &strat); + let alt = if opts.gadget && sol.is_some() { + let bps = ProfileStrat::new(sg, None, false); + Some(evaluate(&g, &bps)) + } else { + None + }; + let players = gain_pair(&rep, seats, alt.as_ref()); + let sum_gain = players.iter().map(|p| p.gain).sum(); + Some(Report { + mode: "exact_hu", + players, + sum_gain, + pot: sg.root.pot() as f64, + big_blind: opts.big_blind as f64, + final_iterate: final_it, + miss_share: strat.miss_share(), + leaf_share: None, + millis: t0.elapsed().as_secs_f64() * 1e3, + }) +} + +/// Exploitability report for a solved subgame (see module docs for what each mode means). +pub fn measure(sg: &Subgame, sol: &Solution, opts: &Opts) -> Option { + if sol.limit == Limit::EndOfGame && sg.root.live_count() == 2 { + if let Some(v) = sol.vector() { + return exact_hu_vector(sg, sol, v, opts); + } + return exact_hu(sg, Some(sol), opts); + } + sampled(sg, sol, opts) +} + +fn exact_hu_vector(sg: &Subgame, _sol: &Solution, v: &crate::vector::VecSolution, opts: &Opts) -> Option { + let t0 = Instant::now(); + let seats = VecGame::live_seats(&sg.root)?; + let g = vec_game(sg, seats); + let pooled: Option<&dyn crate::vector::Bucketing> = if sg.params.vec_pooled { Some(sg.bp as &dyn crate::vector::Bucketing) } else { None }; + let strat = v.strategy(!sg.params.play_final, pooled); + let rep = evaluate(&g, &strat); + let alt = opts.gadget.then(|| evaluate(&g, &ProfileStrat::new(sg, None, false))); + let players = gain_pair(&rep, seats, alt.as_ref()); + let sum_gain = players.iter().map(|p| p.gain).sum(); + Some(Report { + mode: "exact_hu", + players, + sum_gain, + pot: sg.root.pot() as f64, + big_blind: opts.big_blind as f64, + final_iterate: sg.params.play_final, + miss_share: 0.0, + leaf_share: None, + millis: t0.elapsed().as_secs_f64() * 1e3, + }) +} + +fn sampled(sg: &Subgame, sol: &Solution, opts: &Opts) -> Option { + let t0 = Instant::now(); + let root = &sg.root; + if root.is_terminal() { + return None; + } + let mut players = vec![]; + let mut leaf = 0.0f64; + let mut miss = 0.0f64; + let mut k = 0.0f64; + for seat in 0..root.num_players() { + if root.is_folded(seat) || root.is_all_in(seat) { + continue; + } + let e: BrEstimate = best_response_sampled(sg, sol, seat, opts.br_iters, opts.eval_samples); + leaf += e.leaf_share; + miss += e.miss_share; + k += 1.0; + players.push(PlayerGain { seat, value: e.value_profile, br: e.value_br, gain: e.gain, gain_se: Some(e.gain_se), gadget: None }); + } + let sum_gain = players.iter().map(|p| p.gain).sum(); + Some(Report { + mode: "sampled_lower_bound", + players, + sum_gain, + pot: root.pot() as f64, + big_blind: opts.big_blind as f64, + final_iterate: sg.params.play_final, + miss_share: miss / k.max(1.0), + leaf_share: Some(leaf / k.max(1.0)), + millis: t0.elapsed().as_secs_f64() * 1e3, + }) +} diff --git a/sharingan-1/search/src/lib.rs b/sharingan-1/search/src/lib.rs index 2d78f112..a9c60109 100644 --- a/sharingan-1/search/src/lib.rs +++ b/sharingan-1/search/src/lib.rs @@ -1,11 +1,12 @@ -//! Pluribus real-time search (Brown & Sandholm 2019, supplementary "Further details of the -//! real-time search algorithm", Algorithm 2) as a `bench` policy. -pub mod beliefs; -pub mod bp; -pub mod policy; -pub mod rundenspeicher; -pub mod solver; -pub mod table; -pub mod testkit; -pub mod tree; -pub mod vector; +//! Pluribus real-time search (Brown & Sandholm 2019, supplementary "Further details of the +//! real-time search algorithm", Algorithm 2) as a `bench` policy. +pub mod beliefs; +pub mod bp; +pub mod exploit; +pub mod policy; +pub mod rundenspeicher; +pub mod solver; +pub mod table; +pub mod testkit; +pub mod tree; +pub mod vector; diff --git a/sharingan-1/search/src/policy.rs b/sharingan-1/search/src/policy.rs index f32fa407..f47a3e02 100644 --- a/sharingan-1/search/src/policy.rs +++ b/sharingan-1/search/src/policy.rs @@ -1,591 +1,626 @@ -//! `SearchPolicy`: the Pluribus real-time search agent as a `bench` [`PolicyFactory`], -//! implementing supplementary Algorithm 2 (nested search). -//! -//! Per hand each [`Player`] tracks, from the stream of `observe` / `observe_board` calls, -//! -//! * the **blueprint history** (real raises translated to the nearest blueprint size), -//! * the **beliefs** over every seat's 1326 hole pairs at the root of the current betting -//! round, Bayes-updated at each round end with the *average* strategy of the round's search -//! (blueprint where the round was not searched), -//! * the **subgame**: root = start of the current betting round, `extras` = off-tree opponent -//! raises added as legal actions, `frozen` = our own actions this round (kept only for our -//! actual hand). -//! -//! Algorithm 2 mapping: `OpponentTurn` = `observe` of another seat (an off-tree raise adds the -//! action and marks the solution stale, re-searched from the same root at the next decision); -//! `OurTurn` = `dist` (sample from the final iterate, action frozen in `observe`); -//! `CheckNewRound` = `observe_board` (new root, beliefs updated, search at the next decision). -//! Searching is lazy: it runs the first time `dist` is called with the round's state because -//! the actual hole cards are only revealed to the player through `dist`. -//! -//! `dist(view, hole)` answers for *any* hole cards from the same solution (the range -//! strategy), so AIVAT and LBR can query it; only our actual hand has its earlier actions of -//! the round frozen. `fork()` yields a copy that shares the round's solution, may run the -//! round's first search if none exists, and never re-searches (an off-tree action in a fork -//! degrades it to blueprint play for the rest of the hand). - -use crate::beliefs::{holes, Beliefs}; -use crate::bp::Blueprint; -use crate::solver::{solve, SearchParams, Solution, Subgame}; -use crate::rundenspeicher::RoundCache; -use crate::tree::{search_actions, step_path, Extras}; -use bench::mix; -use bench::policy::{Dist, Player, PolicyFactory, View}; -use cards::{hole_index, mask_of, Card}; -use nlhe::abstraction::{ActionList, Shadow, MAX_ACTIONS}; -use nlhe::{Action, GameConfig, State, Street}; -use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; -use std::sync::{Arc, Mutex}; -use std::time::Instant; - -#[derive(Default)] -struct StatsInner { - searches: AtomicU64, - micros: AtomicU64, - max_micros: AtomicU64, - iters: AtomicU64, - infosets: AtomicU64, - resolves: AtomicU64, - preflop: AtomicU64, - max_vec_bytes: AtomicU64, - max_infosets: AtomicU64, -} - -#[derive(Clone, Copy, Debug)] -pub struct Stats { - pub searches: u64, - pub mean_ms: f64, - pub max_ms: f64, - pub mean_iters: f64, - pub mean_infosets: f64, - /// Searches caused by an off-tree action (re-search from the same root). - pub resolves: u64, - /// Searches on the first betting round. - pub preflop: u64, - /// Largest vector-solver node storage of any search, MB. - pub max_vec_mb: f64, - pub max_infosets: u64, -} - -struct Shared { - bp: Blueprint, - params: SearchParams, - stats: StatsInner, - /// pokerfreak (03.12.): Rundenspeicher und die eigenen Lochkarten fuer das Nachspielen (`with_rounds`); ohne: wie vorher. - rounds: Option>, - hole: Option<[Card; 2]>, -} - -pub struct SearchPolicy { - name: String, - sh: Arc, -} - -impl SearchPolicy { - pub fn new(name: &str, bp: Blueprint, params: SearchParams) -> Self { - SearchPolicy { - name: name.to_string(), - sh: Arc::new(Shared { bp, params, stats: StatsInner::default(), rounds: None, hole: None }), - } - } - /// pokerfreak (03.12.): Rundenspeicher fuer das Nachspielen (siehe `rundenspeicher`) und die eigenen Lochkarten, die der Spieler - /// sonst erst mit `dist` erfaehrt. Nur direkt nach `new` aufrufen. - pub fn with_rounds(mut self, rounds: Arc, hole: Option<[Card; 2]>) -> Self { - let sh = Arc::get_mut(&mut self.sh).expect("with_rounds direkt nach new"); - sh.rounds = Some(rounds); - sh.hole = hole; - self - } - pub fn params(&self) -> &SearchParams { - &self.sh.params - } - pub fn blueprint(&self) -> &Blueprint { - &self.sh.bp - } - pub fn stats(&self) -> Stats { - let s = &self.sh.stats; - let n = s.searches.load(Relaxed).max(1) as f64; - Stats { - searches: s.searches.load(Relaxed), - mean_ms: s.micros.load(Relaxed) as f64 / n / 1e3, - max_ms: s.max_micros.load(Relaxed) as f64 / 1e3, - mean_iters: s.iters.load(Relaxed) as f64 / n, - mean_infosets: s.infosets.load(Relaxed) as f64 / n, - resolves: s.resolves.load(Relaxed), - preflop: s.preflop.load(Relaxed), - max_vec_mb: s.max_vec_bytes.load(Relaxed) as f64 / 1e6, - max_infosets: s.max_infosets.load(Relaxed), - } - } - /// A fresh player (also usable directly in tests). - pub fn player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> SearchPlayer { - SearchPlayer::new(self.sh.clone(), seat, cfg, seed) - } -} - -impl PolicyFactory for SearchPolicy { - fn name(&self) -> String { - self.name.clone() - } - fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { - Box::new(self.player(seat, cfg, seed)) - } -} - -#[derive(Clone)] -struct Ev { - seat: usize, - pre: State, - action: Action, - path: u64, - /// Blueprint shadow game before `action`. - sh: Shadow, -} - -type Cell = Arc>>>; - -#[derive(Clone)] -pub struct SearchPlayer { - sh: Arc, - cfg: GameConfig, - seat: usize, - seed: u64, - state: State, - board: Vec, - hole: Option<[Card; 2]>, - out: bool, - bp_sh: Shadow, - root: State, - root_sh: Shadow, - root_beliefs: Arc, - events: Vec, - path: u64, - extras: Extras, - frozen: HashMap, - search_active: bool, - cell: Cell, - can_resolve: bool, - degraded: bool, - n_searches: u64, - /// pokerfreak (03.12.): laufender Schluessel des oeffentlichen Verlaufs (nur mit Rundenspeicher), Schluessel der Rundenwurzel, - /// und ob in dieser Runde schon `dist` lief (dann ist es kein Nachspielen). - hkey: u64, - round_key: u64, - dist_runde: bool, - /// Extras und eingefrorene Zuege beim letzten eigenen Zug der Runde (Nachspielen): Stand, an dem die damalige Anfrage suchte. - letzte_eigene: Option<(Extras, HashMap)>, -} - -fn n_extras(e: &Extras) -> usize { - e.values().map(|v| v.len()).sum() -} - -impl SearchPlayer { - fn new(sh: Arc, seat: usize, cfg: &GameConfig, seed: u64) -> Self { - let state = State::new(cfg); - let sh_bp_new = sh.bp.shadow(&state); - SearchPlayer { - sh, - cfg: *cfg, - seat, - seed, - state, - board: vec![], - hole: None, - out: false, - bp_sh: sh_bp_new, - root: state, - root_sh: sh_bp_new, - root_beliefs: Arc::new(Beliefs::uniform(cfg.players)), - events: vec![], - path: 0, - extras: Extras::new(), - frozen: HashMap::new(), - search_active: false, - cell: Arc::new(Mutex::new(None)), - can_resolve: true, - degraded: false, - n_searches: 0, - hkey: mix(seed, seat as u64 + 1), - round_key: mix(seed, seat as u64 + 1), - dist_runde: false, - letzte_eigene: None, - } - .mit_hole() - } - - fn mit_hole(mut self) -> Self { - if self.sh.rounds.is_some() { - self.hole = self.sh.hole; - } - self - } - - /// The current round's solution, if any. - pub fn solution(&self) -> Option> { - self.cell.lock().unwrap().clone() - } - /// Off-tree raise amounts added to the current round's subgame (per public node). - pub fn extras(&self) -> &Extras { - &self.extras - } - pub fn search_active(&self) -> bool { - self.search_active - } - pub fn beliefs(&self) -> &Beliefs { - &self.root_beliefs - } - pub fn searches_run(&self) -> u64 { - self.n_searches - } - /// Root state and blueprint history of the current betting round, and the board so far. - pub fn round_root(&self) -> (State, Shadow, &[Card]) { - (self.root, self.root_sh, &self.board) - } - - /// Would `dist` at `v` run a (blocking, possibly long) search right now? - pub fn needs_search(&self, v: &View) -> bool { - self.need_search() && !v.state.is_terminal() - } - - /// Plain blueprint answer (translated history), ignoring any search state. - pub fn blueprint_dist(&self, v: &View, hole: [Card; 2]) -> Dist { - self.sh.bp.dist(v.state, &self.bp_sh, hole, v.board) - } - - /// Abandon the current round's search: this player plays the blueprint for the rest of the - /// betting round (until the next `observe_board`) and no longer shares the old solution - /// cell, so a search still running on a clone of this player (whose lock it holds) can - /// neither block nor corrupt this one. - pub fn detach_search(&mut self) { - self.cell = Arc::new(Mutex::new(None)); - self.degraded = true; - } - - fn need_search(&self) -> bool { - if !self.search_active || self.degraded { - return false; - } - match &*self.cell.lock().unwrap() { - None => true, - Some(s) => self.can_resolve && n_extras(&s.extras) != n_extras(&self.extras), - } - } - - fn run_search(&mut self) { - self.suche(None) - } - - /// pokerfreak (03.12.): Nachspielen: beim eigenen Zug den Stand merken, an dem die damalige Anfrage suchte (Extras, eingefrorene - /// fruehere Zuege der Runde). Nur ohne `dist` in dieser Runde, also nie im durchgehend gehaltenen Spiel. - fn merke_eigenen_stand(&mut self) { - if self.sh.rounds.is_some() && !self.dist_runde && self.search_active { - self.letzte_eigene = Some((self.extras.clone(), self.frozen.clone())); - } - } - - /// pokerfreak (03.12.): Abschluss einer nachgespielten Runde ohne gemerkte Loesung (verdraengt, Dienst neu gestartet): die Suche so - /// rechnen, wie die damalige Anfrage sie beim letzten eigenen Zug rechnete (frischer Spieler: Saatzaehler 0, dieselben Extras und - /// eingefrorenen Zuege). Nur fuer abgeschlossene Runden - die laufende Runde sucht die Anfrage ohnehin selbst. Einfaedig bitgleich; - /// mit geteiltem Faden-Pool gleichwertig, nicht bitgleich. - fn nachrechnen(&mut self) -> Option> { - let c = self.sh.rounds.clone()?; - if !self.search_active || self.degraded || self.out || !self.can_resolve || self.hole.is_none() { - return None; - } - // Vorflop: unser Zug kam aus der Tabelle (der act-Dienst sucht nicht) - die Tabelle ist dort die gespielte Strategie - if self.root.street() == Street::Preflop { - return None; - } - let (ex, fr) = self.letzte_eigene.take()?; - let iters = if self.root.street() == Street::Flop { c.flop_iters } else { None }; - let (alt_ex, alt_fr) = (std::mem::replace(&mut self.extras, ex), std::mem::replace(&mut self.frozen, fr)); - let n = self.n_searches; - self.n_searches = 0; - self.cell = Arc::new(Mutex::new(None)); - self.suche(iters); - self.n_searches = n + 1; - self.extras = alt_ex; - self.frozen = alt_fr; - c.neu_gerechnet(); - self.solution() - } - - /// `iters`: andere Iterationszahl (Neurechnen einer frueheren Runde beim Nachspielen); sonst wie `run_search`. - fn suche(&mut self, iters: Option) { - let sh = self.sh.clone(); - let p_neu; - let params = match iters { - Some(n) => { - p_neu = SearchParams { iters: n, ..sh.params.clone() }; - &p_neu - } - None => &sh.params, - }; - let mut g = self.cell.lock().unwrap(); - let resolve = g.is_some(); - // A fork may find the first solution already done by a sibling. - if let Some(s) = &*g { - if !self.can_resolve || n_extras(&s.extras) == n_extras(&self.extras) { - return; - } - } - let t0 = Instant::now(); - let sg = Subgame { - bp: &sh.bp, - root: self.root, - board: &self.board, - beliefs: &self.root_beliefs, - bp_hist: self.root_sh, - extras: &self.extras, - me: self.seat, - my_hole: if self.can_resolve { self.hole } else { None }, - frozen: &self.frozen, - params, - seed: mix(self.seed, self.n_searches + 1), - }; - let sol = solve(&sg); - let us = t0.elapsed().as_micros() as u64; - let st = &sh.stats; - st.searches.fetch_add(1, Relaxed); - st.micros.fetch_add(us, Relaxed); - st.max_micros.fetch_max(us, Relaxed); - st.iters.fetch_add(sol.iters, Relaxed); - st.max_vec_bytes.fetch_max(sol.peak_bytes() as u64, Relaxed); - st.infosets.fetch_add(sol.infosets() as u64, Relaxed); - st.max_infosets.fetch_max(sol.infosets() as u64, Relaxed); - if resolve { - st.resolves.fetch_add(1, Relaxed); - } - if self.root.street() == Street::Preflop { - st.preflop.fetch_add(1, Relaxed); - } - let sol = Arc::new(sol); - if let Some(c) = &sh.rounds { - c.put(self.round_key, sol.clone()); - } - *g = Some(sol); - drop(g); - self.n_searches += 1; - } - - /// Range strategy of the current solution at the current node, as real actions. - fn search_dist(&self, sol: &Solution, st: &State, hole: [Card; 2]) -> Option { - if sol.root_street != st.street() { - return None; - } - let mut list = ActionList::new(); - let ex: &[i32] = sol.extras.get(&self.path).map_or(&[], |v| v.as_slice()); - search_actions(st, &sol.sizing, ex, &mut list); - let n = list.len(); - let mut p = [0f32; MAX_ACTIONS]; - if !sol.probs(self.path, hole_index(hole[0], hole[1]), n, self.sh.params.play_final, &mut p) { - return None; - } - let mut d = Dist::new(); - for i in 0..n { - d.push(list.get(i), p[i]); - } - Some(d) - } - - fn consider_off_tree(&mut self, pre: &State, a: Action, path: u64) { - let Action::RaiseTo(t) = a else { return }; - let prm = &self.sh.params; - if self.search_active { - let mut list = ActionList::new(); - let ex: &[i32] = self.extras.get(&path).map_or(&[], |v| v.as_slice()); - search_actions(pre, &prm.sizing, ex, &mut list); - if !list.as_slice().contains(&a) { - if self.can_resolve { - self.extras.entry(path).or_default().push(t); - } else { - self.degraded = true; - } - } - } else if self.can_resolve && prm.preflop_search && pre.street() == Street::Preflop { - // Off-tree by more than one big blind-sized margin ($100 in the paper) vs every - // blueprint raise size, with at most 4 players left. - let thr = prm.preflop_trigger_chips.unwrap_or(self.cfg.big_blind); - // Blueprint raise sizes at the shadow node, expressed as real chip amounts. - let mut list = ActionList::new(); - let bp = &self.sh.bp; - let sizes: Vec = if bp.node_list(&self.bp_sh, pre, &mut list) { - (0..list.len()) - .filter_map(|i| match self.bp_sh.real_action(pre, &list, i) { - Action::RaiseTo(r) => Some(r), - _ => None, - }) - .collect() - } else { - vec![] - }; - let far = sizes.iter().all(|&r| (r - t).abs() > thr); - let mut after = *pre; - after.apply(a); - if far && after.live_count() as usize <= prm.preflop_max_players { - self.search_active = true; - self.extras.entry(path).or_default().push(t); - } - } - } - - /// Bayes-update the round-root beliefs with every action of the finished round. - fn finish_round(&mut self, new_board: &[Card]) { - let mut b = (*self.root_beliefs).clone(); - // pokerfreak (03.12.): beim Nachspielen die damals gespielte Loesung aus dem Rundenspeicher - let sol = if self.search_active { self.solution().or_else(|| self.sh.rounds.as_ref().and_then(|c| c.get(self.round_key))) } else { None }; - let sol = if sol.is_none() && self.search_active { self.nachrechnen() } else { sol }; - let prm = &self.sh.params; - for ev in &self.events { - // `blueprint_beliefs`: Bayes with the blueprint instead of the search average, except - // (`own_search_beliefs`) for our own seat, whose real strategy IS the search's. - let off_tree = prm.offtree_search_beliefs - && matches!(ev.action, Action::RaiseTo(t) if sol.as_deref().is_some_and(|s| s.extras.get(&ev.path).is_some_and(|v| v.contains(&t)))); - let use_search = !prm.blueprint_beliefs || (prm.own_search_beliefs && ev.seat == self.seat) || off_tree; - self.update_event(&mut b, ev, if use_search { sol.as_deref() } else { None }); - } - b.remove_cards(mask_of(new_board)); - if let Some(h) = self.hole { - b.floor(self.seat, hole_index(h[0], h[1]), 1e-6); - } - self.root_beliefs = Arc::new(b); - } - - fn update_event(&self, b: &mut Beliefs, ev: &Ev, sol: Option<&Solution>) { - let bp = &self.sh.bp; - let street = ev.pre.street(); - let blen = street.board_len().min(self.board.len()); - let board = &self.board[..blen]; - let hl = holes(); - let mut list_b = ActionList::new(); - let synced = bp.node_list(&ev.sh, &ev.pre, &mut list_b); - let nb = list_b.len().max(1); - let ab = if synced { bp.translate_in(&ev.sh, &ev.pre, &list_b, ev.action, ev.seat == self.seat) } else { 0 }; - // Opponent tremble (our own seat's likelihood is exact: we know our strategy). - let eps = if ev.seat == self.seat { 0.0 } else { self.sh.params.belief_tremble.clamp(0.0, 1.0) }; - let mut buf = [0f32; MAX_ACTIONS]; - let bp_lik = |i: usize, buf: &mut [f32; MAX_ACTIONS]| -> f32 { - let bucket = bp.bucket(street, hl[i], board); - if bp.sigma(&ev.sh, &ev.pre, &list_b, bucket, buf) { - buf[ab] - } else { - 1.0 / nb as f32 - } - }; - if let Some(sol) = sol.filter(|s| s.root_street == street) { - let mut list = ActionList::new(); - let ex: &[i32] = sol.extras.get(&ev.path).map_or(&[], |v| v.as_slice()); - search_actions(&ev.pre, &sol.sizing, ex, &mut list); - if let Some(ai) = list.as_slice().iter().position(|x| *x == ev.action) { - let n = list.len(); - let pooled = sol.opp_pool && ev.seat != sol.me; - b.bayes(ev.seat, |i| { - let hit = if pooled { - sol.probs_opp(ev.path, bp.bucket(street, hl[i], board), n, false, &mut buf) - } else { - sol.probs(ev.path, i, n, false, &mut buf) - }; - let l = if hit { buf[ai] } else { bp_lik(i, &mut buf) }; - (1.0 - eps) * l + eps / n as f32 - }); - return; - } - } - // Shadow lost the game (unrepresentable action): no usable blueprint likelihood. - if synced { - b.bayes(ev.seat, |i| (1.0 - eps) * bp_lik(i, &mut buf) + eps / nb as f32); - } - } -} - -impl Player for SearchPlayer { - fn observe(&mut self, pre: &State, seat: usize, a: Action) { - if seat == self.seat { - self.merke_eigenen_stand(); - } - if self.sh.rounds.is_some() { - let code = match a { - Action::Fold => 1, - Action::Check => 2, - Action::Call => 3, - Action::RaiseTo(t) => 4 + t as u64, - }; - self.hkey = mix(self.hkey ^ (seat as u64) << 56, code); - } - let path = self.path; - self.events.push(Ev { seat, pre: *pre, action: a, path, sh: self.bp_sh }); - if seat == self.seat { - self.frozen.insert(path, a); - if a == Action::Fold { - self.out = true; - } - } else if !self.out { - self.consider_off_tree(pre, a, path); - } - // After the off-tree check (which reads the pre-action shadow node). - self.sh.bp.observe(&mut self.bp_sh, pre, a, seat == self.seat); - self.path = step_path(path, a); - self.state = *pre; - self.state.apply(a); - } - - fn observe_board(&mut self, board: &[Card]) { - if board.len() <= self.board.len() { - return; - } - if !self.out { - self.finish_round(board); - } - if self.sh.rounds.is_some() { - self.hkey = board.iter().fold(mix(self.hkey, 0xB0A7D), |k, &c| mix(k, c as u64 + 1)); - self.round_key = self.hkey; - } - self.dist_runde = false; - self.letzte_eigene = None; - self.board = board.to_vec(); - self.root = self.state; - self.root_sh = self.bp_sh; - self.events.clear(); - self.path = 0; - self.extras.clear(); - self.frozen.clear(); - self.cell = Arc::new(Mutex::new(None)); - self.degraded = false; - let prm = &self.sh.params; - let live = self.state.live_count() as usize; - let street_ok = (board.len() == 5 && prm.search_river && live <= prm.max_players[2]) - || (board.len() == 4 && prm.search_turn && live <= prm.max_players[1]) - || (board.len() == 3 && prm.search_flop && live <= prm.max_players[0] && live >= prm.min_flop_players); - self.search_active = prm.postflop_search && !self.out && street_ok; - } - - fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { - self.dist_runde = true; - if self.can_resolve && self.hole.is_none() { - self.hole = Some(hole); - } - if self.need_search() && !v.state.is_terminal() { - self.run_search(); - } - if self.search_active && !self.degraded { - if let Some(sol) = self.solution() { - if let Some(d) = self.search_dist(&sol, v.state, hole) { - return d; - } - } - } - self.sh.bp.dist(v.state, &self.bp_sh, hole, v.board) - } - - fn exposes_probs(&self) -> bool { - true - } - - fn fork(&self) -> Option> { - let mut f = self.clone(); - f.can_resolve = false; - Some(Box::new(f)) - } -} +//! `SearchPolicy`: the Pluribus real-time search agent as a `bench` [`PolicyFactory`], +//! implementing supplementary Algorithm 2 (nested search). +//! +//! Per hand each [`Player`] tracks, from the stream of `observe` / `observe_board` calls, +//! +//! * the **blueprint history** (real raises translated to the nearest blueprint size), +//! * the **beliefs** over every seat's 1326 hole pairs at the root of the current betting +//! round, Bayes-updated at each round end with the *average* strategy of the round's search +//! (blueprint where the round was not searched), +//! * the **subgame**: root = start of the current betting round, `extras` = off-tree opponent +//! raises added as legal actions, `frozen` = our own actions this round (kept only for our +//! actual hand). +//! +//! Algorithm 2 mapping: `OpponentTurn` = `observe` of another seat (an off-tree raise adds the +//! action and marks the solution stale, re-searched from the same root at the next decision); +//! `OurTurn` = `dist` (sample from the final iterate, action frozen in `observe`); +//! `CheckNewRound` = `observe_board` (new root, beliefs updated, search at the next decision). +//! Searching is lazy: it runs the first time `dist` is called with the round's state because +//! the actual hole cards are only revealed to the player through `dist`. +//! +//! `dist(view, hole)` answers for *any* hole cards from the same solution (the range +//! strategy), so AIVAT and LBR can query it; only our actual hand has its earlier actions of +//! the round frozen. `fork()` yields a copy that shares the round's solution, may run the +//! round's first search if none exists, and never re-searches (an off-tree action in a fork +//! degrades it to blueprint play for the rest of the hand). + +use crate::beliefs::{holes, Beliefs}; +use crate::bp::Blueprint; +use crate::solver::{solve, SearchParams, Solution, Subgame}; +use crate::rundenspeicher::RoundCache; +use crate::tree::{search_actions, step_path, Extras}; +use bench::mix; +use bench::policy::{Dist, Player, PolicyFactory, View}; +use cards::{hole_index, mask_of, Card}; +use nlhe::abstraction::{ActionList, Shadow, MAX_ACTIONS}; +use nlhe::{Action, GameConfig, State, Street}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +#[derive(Default)] +struct StatsInner { + searches: AtomicU64, + micros: AtomicU64, + max_micros: AtomicU64, + iters: AtomicU64, + infosets: AtomicU64, + resolves: AtomicU64, + preflop: AtomicU64, + max_vec_bytes: AtomicU64, + max_infosets: AtomicU64, +} + +#[derive(Clone, Copy, Debug)] +pub struct Stats { + pub searches: u64, + pub mean_ms: f64, + pub max_ms: f64, + pub mean_iters: f64, + pub mean_infosets: f64, + /// Searches caused by an off-tree action (re-search from the same root). + pub resolves: u64, + /// Searches on the first betting round. + pub preflop: u64, + /// Largest vector-solver node storage of any search, MB. + pub max_vec_mb: f64, + pub max_infosets: u64, +} + +struct Shared { + bp: Blueprint, + params: SearchParams, + stats: StatsInner, + /// pokerfreak (03.12.): Rundenspeicher und die eigenen Lochkarten fuer das Nachspielen (`with_rounds`); ohne: wie vorher. + rounds: Option>, + hole: Option<[Card; 2]>, +} + +pub struct SearchPolicy { + name: String, + sh: Arc, +} + +impl SearchPolicy { + pub fn new(name: &str, bp: Blueprint, params: SearchParams) -> Self { + SearchPolicy { + name: name.to_string(), + sh: Arc::new(Shared { bp, params, stats: StatsInner::default(), rounds: None, hole: None }), + } + } + /// pokerfreak (03.12.): Rundenspeicher fuer das Nachspielen (siehe `rundenspeicher`) und die eigenen Lochkarten, die der Spieler + /// sonst erst mit `dist` erfaehrt. Nur direkt nach `new` aufrufen. + pub fn with_rounds(mut self, rounds: Arc, hole: Option<[Card; 2]>) -> Self { + let sh = Arc::get_mut(&mut self.sh).expect("with_rounds direkt nach new"); + sh.rounds = Some(rounds); + sh.hole = hole; + self + } + pub fn params(&self) -> &SearchParams { + &self.sh.params + } + pub fn blueprint(&self) -> &Blueprint { + &self.sh.bp + } + pub fn stats(&self) -> Stats { + let s = &self.sh.stats; + let n = s.searches.load(Relaxed).max(1) as f64; + Stats { + searches: s.searches.load(Relaxed), + mean_ms: s.micros.load(Relaxed) as f64 / n / 1e3, + max_ms: s.max_micros.load(Relaxed) as f64 / 1e3, + mean_iters: s.iters.load(Relaxed) as f64 / n, + mean_infosets: s.infosets.load(Relaxed) as f64 / n, + resolves: s.resolves.load(Relaxed), + preflop: s.preflop.load(Relaxed), + max_vec_mb: s.max_vec_bytes.load(Relaxed) as f64 / 1e6, + max_infosets: s.max_infosets.load(Relaxed), + } + } + /// A fresh player (also usable directly in tests). + pub fn player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> SearchPlayer { + SearchPlayer::new(self.sh.clone(), seat, cfg, seed) + } +} + +impl PolicyFactory for SearchPolicy { + fn name(&self) -> String { + self.name.clone() + } + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { + Box::new(self.player(seat, cfg, seed)) + } +} + +#[derive(Clone)] +struct Ev { + seat: usize, + pre: State, + action: Action, + path: u64, + /// Blueprint shadow game before `action`. + sh: Shadow, +} + +type Cell = Arc>>>; + +#[derive(Clone)] +pub struct SearchPlayer { + sh: Arc, + cfg: GameConfig, + seat: usize, + seed: u64, + state: State, + board: Vec, + hole: Option<[Card; 2]>, + out: bool, + bp_sh: Shadow, + root: State, + root_sh: Shadow, + root_beliefs: Arc, + events: Vec, + path: u64, + extras: Extras, + frozen: HashMap, + search_active: bool, + cell: Cell, + can_resolve: bool, + degraded: bool, + n_searches: u64, + /// pokerfreak (03.12.): laufender Schluessel des oeffentlichen Verlaufs (nur mit Rundenspeicher), Schluessel der Rundenwurzel, + /// und ob in dieser Runde schon `dist` lief (dann ist es kein Nachspielen). + hkey: u64, + round_key: u64, + dist_runde: bool, + /// Extras und eingefrorene Zuege beim letzten eigenen Zug der Runde (Nachspielen): Stand, an dem die damalige Anfrage suchte. + letzte_eigene: Option<(Extras, HashMap)>, +} + +fn n_extras(e: &Extras) -> usize { + e.values().map(|v| v.len()).sum() +} + +impl SearchPlayer { + fn new(sh: Arc, seat: usize, cfg: &GameConfig, seed: u64) -> Self { + let state = State::new(cfg); + let sh_bp_new = sh.bp.shadow(&state); + SearchPlayer { + sh, + cfg: *cfg, + seat, + seed, + state, + board: vec![], + hole: None, + out: false, + bp_sh: sh_bp_new, + root: state, + root_sh: sh_bp_new, + root_beliefs: Arc::new(Beliefs::uniform(cfg.players)), + events: vec![], + path: 0, + extras: Extras::new(), + frozen: HashMap::new(), + search_active: false, + cell: Arc::new(Mutex::new(None)), + can_resolve: true, + degraded: false, + n_searches: 0, + hkey: mix(seed, seat as u64 + 1), + round_key: mix(seed, seat as u64 + 1), + dist_runde: false, + letzte_eigene: None, + } + .mit_hole() + } + + fn mit_hole(mut self) -> Self { + if self.sh.rounds.is_some() { + self.hole = self.sh.hole; + } + self + } + + /// The current round's solution, if any. + pub fn solution(&self) -> Option> { + self.cell.lock().unwrap().clone() + } + /// Off-tree raise amounts added to the current round's subgame (per public node). + pub fn extras(&self) -> &Extras { + &self.extras + } + pub fn search_active(&self) -> bool { + self.search_active + } + pub fn beliefs(&self) -> &Beliefs { + &self.root_beliefs + } + pub fn searches_run(&self) -> u64 { + self.n_searches + } + /// Root state and blueprint history of the current betting round, and the board so far. + pub fn round_root(&self) -> (State, Shadow, &[Card]) { + (self.root, self.root_sh, &self.board) + } + + /// Would `dist` at `v` run a (blocking, possibly long) search right now? + pub fn needs_search(&self, v: &View) -> bool { + self.need_search() && !v.state.is_terminal() + } + + /// Plain blueprint answer (translated history), ignoring any search state. + pub fn blueprint_dist(&self, v: &View, hole: [Card; 2]) -> Dist { + self.sh.bp.dist(v.state, &self.bp_sh, hole, v.board) + } + + /// Abandon the current round's search: this player plays the blueprint for the rest of the + /// betting round (until the next `observe_board`) and no longer shares the old solution + /// cell, so a search still running on a clone of this player (whose lock it holds) can + /// neither block nor corrupt this one. + pub fn detach_search(&mut self) { + self.cell = Arc::new(Mutex::new(None)); + self.degraded = true; + } + + fn need_search(&self) -> bool { + if !self.search_active || self.degraded { + return false; + } + match &*self.cell.lock().unwrap() { + None => true, + Some(s) => self.can_resolve && n_extras(&s.extras) != n_extras(&self.extras), + } + } + + fn run_search(&mut self) { + self.suche(None) + } + + /// pokerfreak (03.12.): Nachspielen: beim eigenen Zug den Stand merken, an dem die damalige Anfrage suchte (Extras, eingefrorene + /// fruehere Zuege der Runde). Nur ohne `dist` in dieser Runde, also nie im durchgehend gehaltenen Spiel. + fn merke_eigenen_stand(&mut self) { + if self.sh.rounds.is_some() && !self.dist_runde && self.search_active { + self.letzte_eigene = Some((self.extras.clone(), self.frozen.clone())); + } + } + + /// pokerfreak (03.12.): Abschluss einer nachgespielten Runde ohne gemerkte Loesung (verdraengt, Dienst neu gestartet): die Suche so + /// rechnen, wie die damalige Anfrage sie beim letzten eigenen Zug rechnete (frischer Spieler: Saatzaehler 0, dieselben Extras und + /// eingefrorenen Zuege). Nur fuer abgeschlossene Runden - die laufende Runde sucht die Anfrage ohnehin selbst. Einfaedig bitgleich; + /// mit geteiltem Faden-Pool gleichwertig, nicht bitgleich. + fn nachrechnen(&mut self) -> Option> { + let c = self.sh.rounds.clone()?; + if !self.search_active || self.degraded || self.out || !self.can_resolve || self.hole.is_none() { + return None; + } + // Vorflop: unser Zug kam aus der Tabelle (der act-Dienst sucht nicht) - die Tabelle ist dort die gespielte Strategie + if self.root.street() == Street::Preflop { + return None; + } + let (ex, fr) = self.letzte_eigene.take()?; + let iters = if self.root.street() == Street::Flop { c.flop_iters } else { None }; + let (alt_ex, alt_fr) = (std::mem::replace(&mut self.extras, ex), std::mem::replace(&mut self.frozen, fr)); + let n = self.n_searches; + self.n_searches = 0; + self.cell = Arc::new(Mutex::new(None)); + self.suche(iters); + self.n_searches = n + 1; + self.extras = alt_ex; + self.frozen = alt_fr; + c.neu_gerechnet(); + self.solution() + } + + /// `iters`: andere Iterationszahl (Neurechnen einer frueheren Runde beim Nachspielen); sonst wie `run_search`. + fn suche(&mut self, iters: Option) { + let sh = self.sh.clone(); + let p_neu; + let params = match iters { + Some(n) => { + p_neu = SearchParams { iters: n, ..sh.params.clone() }; + &p_neu + } + None => &sh.params, + }; + let mut g = self.cell.lock().unwrap(); + let resolve = g.is_some(); + // A fork may find the first solution already done by a sibling. + if let Some(s) = &*g { + if !self.can_resolve || n_extras(&s.extras) == n_extras(&self.extras) { + return; + } + } + let t0 = Instant::now(); + let sg = Subgame { + bp: &sh.bp, + root: self.root, + board: &self.board, + beliefs: &self.root_beliefs, + bp_hist: self.root_sh, + extras: &self.extras, + me: self.seat, + my_hole: if self.can_resolve { self.hole } else { None }, + frozen: &self.frozen, + params, + seed: mix(self.seed, self.n_searches + 1), + }; + let sol = solve(&sg); + let us = t0.elapsed().as_micros() as u64; + let st = &sh.stats; + st.searches.fetch_add(1, Relaxed); + st.micros.fetch_add(us, Relaxed); + st.max_micros.fetch_max(us, Relaxed); + st.iters.fetch_add(sol.iters, Relaxed); + st.max_vec_bytes.fetch_max(sol.peak_bytes() as u64, Relaxed); + st.infosets.fetch_add(sol.infosets() as u64, Relaxed); + st.max_infosets.fetch_max(sol.infosets() as u64, Relaxed); + if resolve { + st.resolves.fetch_add(1, Relaxed); + } + if self.root.street() == Street::Preflop { + st.preflop.fetch_add(1, Relaxed); + } + let sol = Arc::new(sol); + if let Some(c) = &sh.rounds { + c.put(self.round_key, sol.clone()); + } + *g = Some(sol); + drop(g); + self.n_searches += 1; + } + + + /// Exploitability gate: exploitability of the current round's solution (or, with + /// `blueprint_only`, of the translated blueprint) inside the current round's subgame. + /// Returns `(report, iterations, solve millis)`; `None` when there is no subgame / solution. + pub fn exploit_report(&self, opts: &crate::exploit::Opts, blueprint_only: bool) -> Option<(crate::exploit::Report, u64, f64)> { + if !self.search_active || self.root.is_terminal() { + return None; + } + let sol = self.solution(); + if sol.is_none() && !blueprint_only { + return None; + } + let sh = &self.sh; + let sg = Subgame { + bp: &sh.bp, + root: self.root, + board: &self.board, + beliefs: &self.root_beliefs, + bp_hist: self.root_sh, + extras: &self.extras, + me: self.seat, + my_hole: if self.can_resolve { self.hole } else { None }, + frozen: &self.frozen, + params: &sh.params, + seed: mix(self.seed, self.n_searches + 1), + }; + if blueprint_only { + let r = crate::exploit::exact_hu(&sg, None, opts)?; + return Some((r, 0, 0.0)); + } + let sol = sol?; + let r = crate::exploit::measure(&sg, &sol, opts)?; + Some((r, sol.iters, sol.millis)) + } + + /// Range strategy of the current solution at the current node, as real actions. + fn search_dist(&self, sol: &Solution, st: &State, hole: [Card; 2]) -> Option { + if sol.root_street != st.street() { + return None; + } + let mut list = ActionList::new(); + let ex: &[i32] = sol.extras.get(&self.path).map_or(&[], |v| v.as_slice()); + search_actions(st, &sol.sizing, ex, &mut list); + let n = list.len(); + let mut p = [0f32; MAX_ACTIONS]; + if !sol.probs(self.path, hole_index(hole[0], hole[1]), n, self.sh.params.play_final, &mut p) { + return None; + } + let mut d = Dist::new(); + for i in 0..n { + d.push(list.get(i), p[i]); + } + Some(d) + } + + fn consider_off_tree(&mut self, pre: &State, a: Action, path: u64) { + let Action::RaiseTo(t) = a else { return }; + let prm = &self.sh.params; + if self.search_active { + let mut list = ActionList::new(); + let ex: &[i32] = self.extras.get(&path).map_or(&[], |v| v.as_slice()); + search_actions(pre, &prm.sizing, ex, &mut list); + if !list.as_slice().contains(&a) { + if self.can_resolve { + self.extras.entry(path).or_default().push(t); + } else { + self.degraded = true; + } + } + } else if self.can_resolve && prm.preflop_search && pre.street() == Street::Preflop { + // Off-tree by more than one big blind-sized margin ($100 in the paper) vs every + // blueprint raise size, with at most 4 players left. + let thr = prm.preflop_trigger_chips.unwrap_or(self.cfg.big_blind); + // Blueprint raise sizes at the shadow node, expressed as real chip amounts. + let mut list = ActionList::new(); + let bp = &self.sh.bp; + let sizes: Vec = if bp.node_list(&self.bp_sh, pre, &mut list) { + (0..list.len()) + .filter_map(|i| match self.bp_sh.real_action(pre, &list, i) { + Action::RaiseTo(r) => Some(r), + _ => None, + }) + .collect() + } else { + vec![] + }; + let far = sizes.iter().all(|&r| (r - t).abs() > thr); + let mut after = *pre; + after.apply(a); + if far && after.live_count() as usize <= prm.preflop_max_players { + self.search_active = true; + self.extras.entry(path).or_default().push(t); + } + } + } + + /// Bayes-update the round-root beliefs with every action of the finished round. + fn finish_round(&mut self, new_board: &[Card]) { + let mut b = (*self.root_beliefs).clone(); + // pokerfreak (03.12.): beim Nachspielen die damals gespielte Loesung aus dem Rundenspeicher + let sol = if self.search_active { self.solution().or_else(|| self.sh.rounds.as_ref().and_then(|c| c.get(self.round_key))) } else { None }; + let sol = if sol.is_none() && self.search_active { self.nachrechnen() } else { sol }; + let prm = &self.sh.params; + for ev in &self.events { + // `blueprint_beliefs`: Bayes with the blueprint instead of the search average, except + // (`own_search_beliefs`) for our own seat, whose real strategy IS the search's. + let off_tree = prm.offtree_search_beliefs + && matches!(ev.action, Action::RaiseTo(t) if sol.as_deref().is_some_and(|s| s.extras.get(&ev.path).is_some_and(|v| v.contains(&t)))); + let use_search = !prm.blueprint_beliefs || (prm.own_search_beliefs && ev.seat == self.seat) || off_tree; + self.update_event(&mut b, ev, if use_search { sol.as_deref() } else { None }); + } + b.remove_cards(mask_of(new_board)); + if let Some(h) = self.hole { + b.floor(self.seat, hole_index(h[0], h[1]), 1e-6); + } + self.root_beliefs = Arc::new(b); + } + + fn update_event(&self, b: &mut Beliefs, ev: &Ev, sol: Option<&Solution>) { + let bp = &self.sh.bp; + let street = ev.pre.street(); + let blen = street.board_len().min(self.board.len()); + let board = &self.board[..blen]; + let hl = holes(); + let mut list_b = ActionList::new(); + let synced = bp.node_list(&ev.sh, &ev.pre, &mut list_b); + let nb = list_b.len().max(1); + let ab = if synced { bp.translate_in(&ev.sh, &ev.pre, &list_b, ev.action, ev.seat == self.seat) } else { 0 }; + // Opponent tremble (our own seat's likelihood is exact: we know our strategy). + let eps = if ev.seat == self.seat { 0.0 } else { self.sh.params.belief_tremble.clamp(0.0, 1.0) }; + let mut buf = [0f32; MAX_ACTIONS]; + let bp_lik = |i: usize, buf: &mut [f32; MAX_ACTIONS]| -> f32 { + let bucket = bp.bucket(street, hl[i], board); + if bp.sigma(&ev.sh, &ev.pre, &list_b, bucket, buf) { + buf[ab] + } else { + 1.0 / nb as f32 + } + }; + if let Some(sol) = sol.filter(|s| s.root_street == street) { + let mut list = ActionList::new(); + let ex: &[i32] = sol.extras.get(&ev.path).map_or(&[], |v| v.as_slice()); + search_actions(&ev.pre, &sol.sizing, ex, &mut list); + if let Some(ai) = list.as_slice().iter().position(|x| *x == ev.action) { + let n = list.len(); + let pooled = sol.opp_pool && ev.seat != sol.me; + b.bayes(ev.seat, |i| { + let hit = if pooled { + sol.probs_opp(ev.path, bp.bucket(street, hl[i], board), n, false, &mut buf) + } else { + sol.probs(ev.path, i, n, false, &mut buf) + }; + let l = if hit { buf[ai] } else { bp_lik(i, &mut buf) }; + (1.0 - eps) * l + eps / n as f32 + }); + return; + } + } + // Shadow lost the game (unrepresentable action): no usable blueprint likelihood. + if synced { + b.bayes(ev.seat, |i| (1.0 - eps) * bp_lik(i, &mut buf) + eps / nb as f32); + } + } +} + +impl Player for SearchPlayer { + fn observe(&mut self, pre: &State, seat: usize, a: Action) { + if seat == self.seat { + self.merke_eigenen_stand(); + } + if self.sh.rounds.is_some() { + let code = match a { + Action::Fold => 1, + Action::Check => 2, + Action::Call => 3, + Action::RaiseTo(t) => 4 + t as u64, + }; + self.hkey = mix(self.hkey ^ (seat as u64) << 56, code); + } + let path = self.path; + self.events.push(Ev { seat, pre: *pre, action: a, path, sh: self.bp_sh }); + if seat == self.seat { + self.frozen.insert(path, a); + if a == Action::Fold { + self.out = true; + } + } else if !self.out { + self.consider_off_tree(pre, a, path); + } + // After the off-tree check (which reads the pre-action shadow node). + self.sh.bp.observe(&mut self.bp_sh, pre, a, seat == self.seat); + self.path = step_path(path, a); + self.state = *pre; + self.state.apply(a); + } + + fn observe_board(&mut self, board: &[Card]) { + if board.len() <= self.board.len() { + return; + } + if !self.out { + self.finish_round(board); + } + if self.sh.rounds.is_some() { + self.hkey = board.iter().fold(mix(self.hkey, 0xB0A7D), |k, &c| mix(k, c as u64 + 1)); + self.round_key = self.hkey; + } + self.dist_runde = false; + self.letzte_eigene = None; + self.board = board.to_vec(); + self.root = self.state; + self.root_sh = self.bp_sh; + self.events.clear(); + self.path = 0; + self.extras.clear(); + self.frozen.clear(); + self.cell = Arc::new(Mutex::new(None)); + self.degraded = false; + let prm = &self.sh.params; + let live = self.state.live_count() as usize; + let street_ok = (board.len() == 5 && prm.search_river && live <= prm.max_players[2]) + || (board.len() == 4 && prm.search_turn && live <= prm.max_players[1]) + || (board.len() == 3 && prm.search_flop && live <= prm.max_players[0] && live >= prm.min_flop_players); + self.search_active = prm.postflop_search && !self.out && street_ok; + } + + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + self.dist_runde = true; + if self.can_resolve && self.hole.is_none() { + self.hole = Some(hole); + } + if self.need_search() && !v.state.is_terminal() { + self.run_search(); + } + if self.search_active && !self.degraded { + if let Some(sol) = self.solution() { + if let Some(d) = self.search_dist(&sol, v.state, hole) { + return d; + } + } + } + self.sh.bp.dist(v.state, &self.bp_sh, hole, v.board) + } + + fn exposes_probs(&self) -> bool { + true + } + + fn fork(&self) -> Option> { + let mut f = self.clone(); + f.can_resolve = false; + Some(Box::new(f)) + } +} diff --git a/sharingan-1/search/src/solver.rs b/sharingan-1/search/src/solver.rs index def4a174..d6e252d0 100644 --- a/sharingan-1/search/src/solver.rs +++ b/sharingan-1/search/src/solver.rs @@ -1,823 +1,1070 @@ -//! Monte-Carlo Linear CFR over a depth-limited imperfect-information subgame -//! (supplementary "Further details of the real-time search algorithm", "Abstraction and -//! off-tree actions in subgames", "Leaf node values"). -//! -//! One iteration `t` runs an external-sampling traversal per player that can still act: -//! -//! * the deal is sampled from the joint belief at the subgame root (rejection sampling gives -//! exact card removal between players), the unseen board cards uniformly; -//! * the traverser enumerates its actions, everyone else samples from the current -//! regret-matching strategy; regret and average-strategy updates are weighted by `t` -//! (Linear CFR), with hogwild atomics (`Table`); -//! * the current betting round is solved with lossless (exact hole card) infosets, later -//! rounds inside the subgame with the blueprint's bucketing by default, or with the paper's -//! per-flop 500-bucket search abstraction when `SearchParams::search_buckets` is set; -//! * leaves (depth limit, see `tree::Limit`) are an extra decision: every player still able to -//! act chooses one of the 4 continuation strategies, infoset = (public leaf, own bucket); the -//! value of a joint choice is a rollout of the rest of the hand on the sampled deal with each -//! player following its chosen continuation strategy (blueprint biased x5 toward fold / call / -//! raise), each compressed to one deterministic action per abstract infoset. -//! -//! Randomness is seeded per iteration (`mix(seed, t)`), never per thread. With -//! `parallel = false` the whole solve is bit-reproducible. - -use crate::beliefs::{hole_mask, holes, Beliefs, N}; -use crate::bp::{cont_pick, real_passive, Blueprint, K_BLUEPRINT, NUM_CONT}; -use crate::table::{Slot, Table}; -use crate::tree::{limit_for, search_actions, step_path, Extras, Limit}; -use crate::vector::{solve_vec, VecGame, VecParams, VecSolution}; -use abstraction::search_buckets::{FlopView, SearchBuckets}; -use bench::mix; -use cards::{bit, hole_index, Card, Rng}; -use nlhe::abstraction::{ActionList, BetSizing, Shadow, MAX_ACTIONS}; -use nlhe::{Action, Deal, State, Step, Street, MAX_PLAYERS}; -use rayon::prelude::*; -use std::collections::HashMap; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; -use std::sync::Arc; -use std::time::Instant; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LeafMode { - /// Paper: each player picks one of 4 continuation strategies. - Cont4, - /// Ablation: every player plays the plain blueprint after the leaf. - Blueprint, -} - -#[derive(Clone, Debug)] -pub struct SearchParams { - /// MCCFR iterations per search (each iteration = one traversal per acting player). Default 200k - /// (measured: 6-max vs 5 x B, 20k it -42, 100k +58, 200k +87, 500k +58 mbb/game; see RESULTS.md). - pub iters: u64, - /// Optional wall-clock cap, checked between batches. - pub max_millis: Option, - /// Search action abstraction for the root round (1-6 raise sizes per node in the paper). - pub sizing: BetSizing, - /// Coarser abstraction for rounds after the root round inside the subgame (keeps solving - /// to the end of the game affordable on one machine). - pub later_sizing: BetSizing, - /// Negative-regret pruning (Algorithm 1 MCCFR-P, applied to the subgame): after the first - /// fifth of the iterations, in this fraction of them the traverser skips actions whose - /// regret is below `-t^2/2 * prune_frac * stack` (a consistent per-iteration gap of - /// `prune_frac * stack` chips). 0 disables. - pub prune_prob: f32, - pub prune_frac: f32, - /// Warm start (deviation, compensates for far fewer iterations than the paper): a new - /// infoset's regrets are initialised to `warm_start * t * pot * sigma_blueprint`, i.e. the - /// blueprint's (translated) action probabilities, worth about `warm_start` iterations of - /// evidence. 0 = start uniform. - pub warm_start: f32, - /// Infoset table capacity per search. - pub max_infosets: usize, - /// Fraction of our own traversals that fix our actual hole cards (importance of the infosets - /// we actually play; unbiased per infoset, see crate docs). - pub focus_own: f32, - pub leaf: LeafMode, - /// Multiplier of the biased continuation strategies (paper: 5). - pub cont_bias: f32, - /// Compress each continuation strategy to one sampled action per abstract infoset (paper). - pub compress: bool, - pub parallel: bool, - pub seed: u64, - /// Play the final iterate (paper) instead of the weighted average. - pub play_final: bool, - /// Search the first betting round when an opponent raise is far off-tree (paper). - pub preflop_search: bool, - /// "More than $100 off": chips; `None` = one big blind of the game. - pub preflop_trigger_chips: Option, - /// Preflop search only with at most this many players remaining (paper: 4). - pub preflop_max_players: usize, - /// Search flop/turn/river (paper: always). `false` = pure blueprint (ablation). - pub postflop_search: bool, - /// Paper's search abstraction: per-flop potential-aware 500-bucket tables for the turn and - /// river inside the subgame (keys of later-round search infosets and of depth-limit leaves). - /// `None` (default) = reuse the blueprint's bucketing. Blueprint lookups (warm-start prior, - /// continuation-strategy rollouts, belief updates) always use the blueprint's own buckets. - pub search_buckets: Option>, - /// Heads-up subgames from `vec_min_street` on are solved with vector-form Linear CFR - /// (`vector.rs`: exact hole pairs and board cards, public chance sampling) instead of MC LCFR. - pub vector: bool, - pub vec_min_street: Street, - /// Vector passes by root street `[flop, turn, river]`. - pub vec_iters: [u64; 3], - /// CFR+ style regret flooring in the vector solver (default; `false` = plain Linear CFR, worse here). - pub vec_plus: bool, - /// Pool the infosets of rounds after the root round by the blueprint's card buckets (shared - /// across board runouts; far fewer passes needed, at the price of the abstraction). - pub vec_pooled: bool, - /// Search the flop (ablation: `false` = blueprint on the flop, search from the turn on). - pub search_flop: bool, - /// Search the turn (ablation). - pub search_turn: bool, - /// Search the river (ablation). - pub search_river: bool, - /// Update OPPONENT beliefs with the blueprint's likelihood instead of the search's average strategy - /// (default: opponents are modelled as the blueprint; a measured +100 mbb/game at 20k iterations). - pub blueprint_beliefs: bool, - /// With `blueprint_beliefs`: still update OUR OWN seat's belief with the search average. - pub own_search_beliefs: bool, - /// With `blueprint_beliefs`: opponent actions that were off the search tree (added as extras) are - /// still scored with the search's average strategy (the blueprint has no likelihood for them). - pub offtree_search_beliefs: bool, - /// Tremble ε on OPPONENT action likelihoods in the Bayes belief update: lik' = (1-ε)·lik + ε/n. - /// Keeps hands an off-model opponent (e.g. a rule bot) really holds from being zeroed out when - /// the model (blueprint/search) says "never". 0 = plain Bayes. - pub belief_tremble: f32, - /// Root-round infosets of the OTHER seats are keyed by the blueprint card bucket instead of the exact - /// hole pair (we keep lossless infosets for our own seat). Opponents then share samples across the - /// ~1326/200 hands of a bucket, like the blueprint they are modelled on. - pub opp_pool: bool, - /// Search a street only when at most this many players are still live at its start `[flop, turn, river]` - /// (diagnostic / robustness knob; 6 = always). - pub max_players: [usize; 3], - /// Minimum live players for the flop search (diagnostic: isolate multiway vs HU flops; 2 = always). - pub min_flop_players: usize, - /// Dedicated thread pool for `parallel` solves (default: rayon's global pool). - pub pool: Option>, -} - -impl Default for SearchParams { - fn default() -> Self { - SearchParams { - iters: 200_000, - max_millis: None, - sizing: crate::tree::default_sizing(), - later_sizing: crate::tree::later_sizing(), - prune_prob: 0.95, - prune_frac: 0.01, - warm_start: 8.0, - max_infosets: 1 << 20, - focus_own: 0.5, - leaf: LeafMode::Cont4, - cont_bias: 5.0, - compress: true, - parallel: true, - seed: 1, - play_final: false, - preflop_search: true, - preflop_trigger_chips: None, - preflop_max_players: 4, - postflop_search: true, - search_buckets: None, - vector: false, - vec_min_street: Street::Turn, - vec_iters: [300, 300, 150], - vec_plus: true, - vec_pooled: false, - search_flop: true, - search_turn: true, - search_river: true, - blueprint_beliefs: true, - own_search_beliefs: true, - offtree_search_beliefs: true, - belief_tremble: 0.0, - opp_pool: false, - max_players: [6, 6, 6], - min_flop_players: 2, - pool: None, - } - } -} - -/// Everything that defines one subgame solve. -pub struct Subgame<'a> { - pub bp: &'a Blueprint, - /// State at the start of the betting round (the subgame root). - pub root: State, - /// Board cards visible at the root. - pub board: &'a [Card], - /// Beliefs at the root (card removal vs `board` already applied). - pub beliefs: &'a Beliefs, - /// Shadow game at `root` (blueprint history of everything before the root, with off-menu - /// raises replaced by their translations); see [`Blueprint::shadow`]. - pub bp_hist: Shadow, - pub extras: &'a Extras, - /// Our seat, our actual hole cards, and the actions we already took this round. - pub me: usize, - pub my_hole: Option<[Card; 2]>, - pub frozen: &'a HashMap, - pub params: &'a SearchParams, - pub seed: u64, -} - -pub struct Solution { - table: Table, - vec: Option, - pub extras: Extras, - pub sizing: BetSizing, - pub root_street: Street, - pub limit: Limit, - pub iters: u64, - pub millis: f64, - pub nodes: u64, - /// Depth-limit leaves evaluated (0 when solving to the end of the game). - pub leaves: u64, - /// Most raises seen so far this street at any root-round decision node. - pub max_raises: u32, - pub opp_pool: bool, - pub me: usize, - /// Per-flop search-bucket lookups performed (0 unless `SearchParams::search_buckets`). - pub search_bucket_lookups: u64, - /// Mean sampled value (chips) of each seat's own traversals at the subgame root under the - /// strategies being learned, and the sample counts (MC solver only; zeros for vector). - pub root_value: [(f64, u64); MAX_PLAYERS], -} - -const TAG_LATER: u64 = 1 << 32; -const TAG_LEAF: u64 = 2 << 32; -const TAG_OPP: u64 = 3 << 32; -const VAL_STRIPES: usize = 256; - -impl Solution { - /// Strategy of the root-round infoset `(path, hole)` over `n` actions: the final iterate - /// or the weighted average. `false` if the infoset was never reached. - pub fn probs(&self, path: u64, hole: usize, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { - if let Some(v) = &self.vec { - return v.probs(path, hole, n, final_iterate, out); - } - let Some(slot) = self.table.find(Table::key(path, hole as u64)).filter(|s| s.n == n) else { - return false; - }; - if final_iterate { - self.table.strategy(slot, &mut out[..n]); - true - } else { - self.table.average(slot, &mut out[..n]) - } - } - /// Strategy of another seat's pooled root-round infoset `(path, blueprint bucket)` (`opp_pool` solves). - pub fn probs_opp(&self, path: u64, bucket: u32, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { - let Some(slot) = self.table.find(Table::key(path, TAG_OPP | bucket as u64)).filter(|s| s.n == n) else { - return false; - }; - if final_iterate { - self.table.strategy(slot, &mut out[..n]); - true - } else { - self.table.average(slot, &mut out[..n]) - } - } - pub fn infosets(&self) -> usize { - self.vec.as_ref().map_or_else(|| self.table.infosets(), |v| v.nodes()) - } - /// The vector-form solution, if the subgame was solved that way. - /// Peak node storage (bytes) of a vector solve, 0 for MC. - pub fn peak_bytes(&self) -> usize { - self.vec.as_ref().map_or(0, |v| v.peak_bytes) - } - pub fn vector(&self) -> Option<&VecSolution> { - self.vec.as_ref() - } - /// Later-round strategy of the MC solver: `(path, street, bucket)` (board-agnostic keys). - pub fn probs_later(&self, path: u64, street: Street, bucket: u32, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { - let key = Table::key(path, TAG_LATER | (street.idx() as u64) << 24 | bucket as u64); - let Some(slot) = self.table.find(key).filter(|s| s.n == n) else { return false }; - if final_iterate { - self.table.strategy(slot, &mut out[..n]); - true - } else { - self.table.average(slot, &mut out[..n]) - } - } -} - -struct Cx { - deal: Deal, - hole: [u16; MAX_PLAYERS], - /// Blueprint buckets (blueprint lookups: warm-start prior, rollouts). - bucket: [[u32; 4]; MAX_PLAYERS], - /// Buckets used as search infoset keys: per-flop search buckets when enabled, else `bucket`. - sbucket: [[u32; 4]; MAX_PLAYERS], - rng: Rng, - t: f32, - /// Regret threshold below which the traverser skips an action this iteration (or -inf). - prune_at: f32, - /// Per-traversal counters, flushed once (shared atomics per node made parallel solves ~10x slower). - nodes: u64, - leaves: u64, - sb: u64, -} - -struct Solver<'a> { - sg: &'a Subgame<'a>, - table: Table, - limit: Limit, - root_street: Street, - n: usize, - live: u8, - cdf: Vec>, - board_mask: u64, - my_idx: Option, - salt: u64, - nodes: AtomicU64, - leaves: AtomicU64, - max_raises: AtomicU32, - stack: f32, - view: Option, - sb_lookups: AtomicU64, - /// Sum and count of the traverser's sampled root values per seat (diagnostics). - val: Vec>, -} - -fn hash01(a: u64, b: u64, c: u64, d: u64) -> f64 { - (mix(mix(mix(a, b), c), d) >> 11) as f64 / (1u64 << 53) as f64 -} - -/// Solve the subgame and return the strategies. -pub fn solve(sg: &Subgame) -> Solution { - let start = Instant::now(); - let root = sg.root; - let n = root.num_players(); - let p = sg.params; - if p.vector && root.street() >= p.vec_min_street && root.street() != Street::Preflop { - if let Some(seats) = VecGame::live_seats(&root) { - return solve_vector(sg, seats, start); - } - } - let live = (0..n).filter(|&i| !root.is_folded(i)).fold(0u8, |m, i| m | 1 << i); - let solver = Solver { - sg, - table: Table::new(p.max_infosets, p.max_infosets * 8), - limit: limit_for(&root), - root_street: root.street(), - n, - live, - cdf: (0..n).map(|i| sg.beliefs.cdf(i)).collect(), - board_mask: cards::mask_of(sg.board), - my_idx: sg.my_hole.map(|h| hole_index(h[0], h[1]) as u16), - salt: mix(sg.seed, 0xC0FFEE), - nodes: AtomicU64::new(0), - leaves: AtomicU64::new(0), - max_raises: AtomicU32::new(0), - stack: (0..n).map(|i| root.stack(i) + root.contributed(i)).max().unwrap_or(0) as f32, - view: match &p.search_buckets { - Some(sb) if root.street() != Street::Preflop && sg.board.len() >= 3 => Some(sb.for_flop([sg.board[0], sg.board[1], sg.board[2]])), - _ => None, - }, - sb_lookups: AtomicU64::new(0), - val: (0..VAL_STRIPES).map(|_| std::sync::Mutex::new([(0.0, 0); MAX_PLAYERS])).collect(), - }; - let players: Vec = if root.is_terminal() { - vec![] - } else { - (0..n).filter(|&i| live >> i & 1 != 0 && !root.is_all_in(i)).collect() - }; - let batch = if p.parallel { 256u64 } else { 1 << 20 }; - let mut done = 0u64; - let drive = |done: &mut u64| { - let mut t0 = 1u64; - while t0 <= p.iters && !players.is_empty() { - let end = (t0 + batch - 1).min(p.iters); - let run = |t: u64| solver.iteration(t, &players); - if p.parallel { - (t0..=end).into_par_iter().for_each(run); - } else { - (t0..=end).for_each(run); - } - *done = end; - t0 = end + 1; - if p.max_millis.is_some_and(|ms| start.elapsed().as_millis() as u64 >= ms) { - break; - } - } - }; - match (&p.pool, p.parallel) { - // A dedicated pool is driven from a plain OS thread: blocking a rayon worker of another - // pool in `install` would let it steal unrelated jobs (nested searches) meanwhile. - (Some(pl), true) => std::thread::scope(|sc| { - sc.spawn(|| pl.install(|| drive(&mut done))).join().unwrap(); - }), - _ => drive(&mut done), - } - Solution { - table: solver.table, - vec: None, - extras: sg.extras.clone(), - sizing: p.sizing, - root_street: solver.root_street, - limit: solver.limit, - iters: done, - millis: start.elapsed().as_secs_f64() * 1e3, - nodes: solver.nodes.load(Relaxed), - leaves: solver.leaves.load(Relaxed), - max_raises: solver.max_raises.load(Relaxed), - opp_pool: p.opp_pool && solver.root_street != Street::Preflop, - me: sg.me, - search_bucket_lookups: solver.sb_lookups.load(Relaxed), - root_value: { - let mut tot = [(0.0f64, 0u64); MAX_PLAYERS]; - for m in &solver.val { - let g = m.lock().unwrap(); - for i in 0..MAX_PLAYERS { - tot[i].0 += g[i].0; - tot[i].1 += g[i].1; - } - } - let mut o = [(0.0, 0u64); MAX_PLAYERS]; - for i in 0..MAX_PLAYERS { - o[i] = (if tot[i].1 > 0 { tot[i].0 / tot[i].1 as f64 } else { 0.0 }, tot[i].1); - } - o - }, - } -} - -fn solve_vector(sg: &Subgame, seats: [usize; 2], start: Instant) -> Solution { - let p = sg.params; - let root = sg.root; - let bm = cards::mask_of(sg.board); - let ranges = seats.map(|s| { - sg.beliefs.w[s].iter().enumerate().map(|(i, &x)| if hole_mask(i) & bm == 0 { x as f64 } else { 0.0 }).collect::>() - }); - let g = VecGame { - root, - board: sg.board, - seats, - ranges, - sizing: &p.sizing, - later: &p.later_sizing, - extras: sg.extras, - me: seats.iter().position(|&s| s == sg.me), - my_hole: sg.my_hole.map(|h| hole_index(h[0], h[1])), - frozen: sg.frozen, - pooled: if p.vec_pooled { Some(sg.bp as &dyn crate::vector::Bucketing) } else { None }, - }; - let iters = p.vec_iters[(root.street().idx() - 1).min(2)]; - let vp = VecParams { iters, max_millis: p.max_millis, plus: p.vec_plus, stratify: true, seed: sg.seed, keep_all: false, max_bytes: 2 << 30 }; - let vs = solve_vec(&g, &vp); - Solution { - table: Table::new(1, 8), - extras: sg.extras.clone(), - sizing: p.sizing, - root_street: root.street(), - limit: Limit::EndOfGame, - iters: vs.iters, - millis: start.elapsed().as_secs_f64() * 1e3, - nodes: 0, - leaves: 0, - max_raises: 0, - opp_pool: false, - me: sg.me, - search_bucket_lookups: 0, - root_value: [(0.0, 0); MAX_PLAYERS], - vec: Some(vs), - } -} - -impl<'a> Solver<'a> { - fn iteration(&self, t: u64, players: &[usize]) { - let mut rng = Rng::new(mix(self.sg.seed, t)); - for &p in players { - let force = p == self.sg.me && self.my_idx.is_some() && rng.f32() < self.sg.params.focus_own; - if let Some(mut cx) = self.sample(&mut rng, force, t) { - let prm = self.sg.params; - if prm.prune_prob > 0.0 && t * 5 > prm.iters && rng.f32() < prm.prune_prob { - // Cumulative Linear-CFR regret of a consistently bad action grows like - // t^2/2 x its per-iteration gap. - let t = t as f32; - cx.prune_at = -0.5 * t * t * prm.prune_frac * self.stack; - } - let bph = self.sg.bp_hist; - let v = self.walk(&mut cx, &self.sg.root, 0, &bph, p); - self.nodes.fetch_add(cx.nodes, Relaxed); - self.leaves.fetch_add(cx.leaves, Relaxed); - if cx.sb > 0 { - self.sb_lookups.fetch_add(cx.sb, Relaxed); - } - // Diagnostic root values: per-thread stripes (a single mutex serialised all threads). - { - let mut g = self.val[rayon::current_thread_index().unwrap_or(0) % VAL_STRIPES].lock().unwrap(); - g[p].0 += v as f64; - g[p].1 += 1; - } - } - } - } - - /// Sample a deal: holes from the joint belief (rejection => exact card removal), then the - /// unseen board uniformly from the remaining deck. - fn sample(&self, rng: &mut Rng, force_me: bool, t: u64) -> Option { - let hl = holes(); - let mut idx = [0u16; MAX_PLAYERS]; - let mut ok = false; - for _ in 0..64 { - let mut dead = self.board_mask; - let mut good = true; - for s in 0..self.n { - if self.live >> s & 1 == 0 { - continue; - } - let i = if force_me && s == self.sg.me { - self.my_idx.unwrap() as usize - } else { - let c = &self.cdf[s]; - let tot = *c.last().unwrap(); - if tot <= 0.0 { - good = false; - break; - } - let x = rng.f64() * tot; - c.partition_point(|&v| v <= x).min(N - 1) - }; - let m = hole_mask(i); - if m & dead != 0 { - good = false; - break; - } - dead |= m; - idx[s] = i as u16; - } - if good { - ok = true; - break; - } - } - if !ok { - return None; - } - let mut dead = self.board_mask; - let mut deal = Deal { holes: [[0, 1]; MAX_PLAYERS], board: [0; 5] }; - for s in 0..self.n { - if self.live >> s & 1 != 0 { - deal.holes[s] = hl[idx[s] as usize]; - dead |= hole_mask(idx[s] as usize); - } - } - for (i, c) in self.sg.board.iter().enumerate() { - deal.board[i] = *c; - } - for i in self.sg.board.len()..5 { - let c = rng.draw(dead); - dead |= bit(c); - deal.board[i] = c; - } - let mut bucket = [[0u32; 4]; MAX_PLAYERS]; - for s in 0..self.n { - if self.live >> s & 1 == 0 { - continue; - } - for st in Street::ALL { - if st >= self.root_street { - bucket[s][st.idx()] = self.sg.bp.bucket(st, deal.holes[s], &deal.board[..st.board_len()]); - } - } - } - let mut sbucket = bucket; - let mut sb_n = 0u64; - if let Some(v) = &self.view { - for s in 0..self.n { - if self.live >> s & 1 == 0 { - continue; - } - for st in [Street::Turn, Street::River] { - if st >= self.root_street { - if let Some(b) = v.bucket(deal.holes[s], &deal.board[..st.board_len()]) { - sbucket[s][st.idx()] = b; - sb_n += 1; - } - } - } - } - } - Some(Cx { deal, hole: idx, bucket, sbucket, rng: Rng::new(mix(rng.next_u64(), t)), t: t as f32, prune_at: f32::NEG_INFINITY, nodes: 0, leaves: 0, sb: sb_n }) - } - - #[inline] - fn key(&self, cx: &Cx, st: &State, path: u64, seat: usize) -> u64 { - if st.street() == self.root_street { - if self.sg.params.opp_pool && seat != self.sg.me && self.root_street != Street::Preflop { - Table::key(path, TAG_OPP | cx.bucket[seat][st.street().idx()] as u64) - } else { - Table::key(path, cx.hole[seat] as u64) - } - } else { - Table::key(path, TAG_LATER | (st.street().idx() as u64) << 24 | cx.sbucket[seat][st.street().idx()] as u64) - } - } - - fn walk(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, p: usize) -> f32 { - cx.nodes += 1; - if st.street() == self.root_street && st.raises_this_street() > self.max_raises.load(Relaxed) { - self.max_raises.fetch_max(st.raises_this_street(), Relaxed); - } - let seat = st.to_act().unwrap(); - let mut list = ActionList::new(); - let ex: &[i32] = self.sg.extras.get(&path).map_or(&[], |v| v.as_slice()); - let sz = if st.street() == self.root_street { &self.sg.params.sizing } else { &self.sg.params.later_sizing }; - search_actions(st, sz, ex, &mut list); - let n = list.len(); - let key = self.key(cx, st, path, seat); - let slot = if self.sg.params.warm_start > 0.0 { - let lam = self.sg.params.warm_start * cx.t * st.pot() as f32; - let bucket = cx.bucket[seat][st.street().idx()]; - self.table.get_or_insert_with(key, n, |r| { - if let Some(pr) = self.sg.bp.prior(bph, st, &list, bucket) { - for (x, &q) in r.iter_mut().zip(&pr[..n]) { - *x = lam * q; - } - } - }) - } else { - self.table.get_or_insert(key, n) - }; - let mut sigma = [0f32; MAX_ACTIONS]; - match slot { - Some(s) => self.table.strategy(s, &mut sigma[..n]), - None => sigma[..n].iter_mut().for_each(|x| *x = 1.0 / n as f32), - } - // Frozen: our own earlier action this round, for our actual hand only. - let mut frozen = None; - if seat == self.sg.me && Some(cx.hole[seat]) == self.my_idx { - if let Some(fa) = self.sg.frozen.get(&path) { - frozen = list.as_slice().iter().position(|a| a == fa); - } - } - if let Some(f) = frozen { - sigma[..n].iter_mut().for_each(|x| *x = 0.0); - sigma[f] = 1.0; - if let Some(s) = slot { - // Readers (dist, belief updates) see the pinned pure strategy. - self.table.set_pure(s, f); - self.table.add_avg(s, f, 1.0); - } - } - if seat == p { - let mut va = [0f32; MAX_ACTIONS]; - let mut v = 0f32; - let mut explored = [true; MAX_ACTIONS]; - let mut mass = 0f32; - for a in 0..n { - if frozen.is_some_and(|f| f != a) { - explored[a] = false; - continue; - } - if cx.prune_at.is_finite() && !matches!(list.get(a), Action::Fold) { - if let Some(s) = slot { - if self.table.regret(s, a) < cx.prune_at && !self.ends_hand(st, list.get(a)) { - explored[a] = false; - continue; - } - } - } - va[a] = self.child(cx, st, path, bph, &list, a, p); - v += sigma[a] * va[a]; - mass += sigma[a]; - } - if mass < 1.0 { - // Pruned actions left out of the expectation: renormalise over explored ones. - if mass > 0.0 { - v /= mass; - } else { - let k = (0..n).filter(|&a| explored[a]).count().max(1); - v = (0..n).filter(|&a| explored[a]).map(|a| va[a]).sum::() / k as f32; - } - } - if frozen.is_none() { - if let Some(s) = slot { - for a in 0..n { - if explored[a] { - self.table.add_regret(s, a, cx.t * (va[a] - v)); - } - } - } - } - v - } else { - let a = cx.rng.sample_weighted(&sigma[..n]); - if frozen.is_none() { - if let Some(s) = slot { - for (i, &x) in sigma[..n].iter().enumerate() { - self.table.add_avg(s, i, cx.t * x); - } - } - } - self.child(cx, st, path, bph, &list, a, p) - } - } - - /// Does `a` end the hand immediately (never pruned, as in Algorithm 1)? - fn ends_hand(&self, st: &State, a: Action) -> bool { - let mut s2 = *st; - s2.apply(a) == Step::Terminal - } - - #[allow(clippy::too_many_arguments)] - fn child(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, list: &ActionList, a: usize, p: usize) -> f32 { - let act = list.get(a); - let mut s2 = *st; - let step = s2.apply(act); - if s2.is_folded(p) { - return -(s2.contributed(p) as f32); - } - let path2 = step_path(path, act); - if step == Step::Terminal { - return s2.payoffs(&cx.deal)[p] as f32; - } - let mut b2 = *bph; - self.sg.bp.observe(&mut b2, st, act, st.to_act() == Some(self.sg.me)); - match step { - Step::NewStreet(s) if self.limit != Limit::EndOfGame => { - let known = Street::ALL[s.idx() - 1]; - self.leaf(cx, &s2, path2, &b2, known, p) - } - Step::Continue - if self.limit == Limit::SecondRaise - && s2.street() == self.root_street - && s2.raises_this_street() >= 2 => - { - self.leaf(cx, &s2, path2, &b2, s2.street(), p) - } - _ => self.walk(cx, &s2, path2, &b2, p), - } - } - - /// Depth-limit leaf: continuation-strategy choice (supplement, "Leaf node values"). - fn leaf(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, known: Street, p: usize) -> f32 { - cx.leaves += 1; - let mut ks = [K_BLUEPRINT; MAX_PLAYERS]; - if self.sg.params.leaf == LeafMode::Blueprint { - return self.rollout(cx, st, bph, &ks, p); - } - let lpath = path.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x1EAF; - let mut mine: Option = None; - let mut p_chooses = false; - for i in 0..self.n { - if st.is_folded(i) || st.is_all_in(i) { - continue; - } - let key = Table::key(lpath, TAG_LEAF | cx.sbucket[i][known.idx()] as u64); - let slot = self.table.get_or_insert(key, NUM_CONT); - if i == p { - p_chooses = true; - mine = slot; - continue; - } - let mut sg = [0.25f32; NUM_CONT]; - if let Some(s) = slot { - self.table.strategy(s, &mut sg); - } - ks[i] = cx.rng.sample_weighted(&sg) as u8; - if let Some(s) = slot { - for (k, &x) in sg.iter().enumerate() { - self.table.add_avg(s, k, cx.t * x); - } - } - } - if !p_chooses { - return self.rollout(cx, st, bph, &ks, p); - } - let mut sg = [0.25f32; NUM_CONT]; - if let Some(s) = mine { - self.table.strategy(s, &mut sg); - } - let mut va = [0f32; NUM_CONT]; - let mut v = 0.0; - for k in 0..NUM_CONT { - ks[p] = k as u8; - va[k] = self.rollout(cx, st, bph, &ks, p); - v += sg[k] * va[k]; - } - if let Some(s) = mine { - for k in 0..NUM_CONT { - self.table.add_regret(s, k, cx.t * (va[k] - v)); - } - } - v - } - - /// Play the hand out on the sampled deal; seat `i` follows continuation strategy `ks[i]` - /// of the blueprint, compressed to one action per abstract infoset. - fn rollout(&self, cx: &mut Cx, st: &State, bph: &Shadow, ks: &[u8; MAX_PLAYERS], p: usize) -> f32 { - let bp = self.sg.bp; - let prm = self.sg.params; - let mut s = *st; - let mut h = *bph; - let mut list = ActionList::new(); - let mut sig = [0f32; MAX_ACTIONS]; - while !s.is_terminal() { - let seat = s.to_act().unwrap(); - let bucket = cx.bucket[seat][s.street().idx()]; - let a = if bp.node_list(&h, &s, &mut list) && bp.sigma(&h, &s, &list, bucket, &mut sig) { - let n = list.len(); - let u = if prm.compress { - hash01(self.salt, ks[seat] as u64, h.key(), bucket as u64) - } else { - cx.rng.f64() - }; - let idx = cont_pick(ks[seat], prm.cont_bias, &list, &mut sig[..n], u); - h.real_action(&s, &list, idx) - } else { - real_passive(&s) - }; - bp.observe(&mut h, &s, a, true); - s.apply(a); - } - s.payoffs(&cx.deal)[p] as f32 - } -} - -/// Number of hole pairs with positive mass in `b` for `seat` (diagnostics). -pub fn support(b: &Beliefs, seat: usize) -> usize { - b.w[seat].iter().filter(|&&x| x > 0.0).count() -} +//! Monte-Carlo Linear CFR over a depth-limited imperfect-information subgame +//! (supplementary "Further details of the real-time search algorithm", "Abstraction and +//! off-tree actions in subgames", "Leaf node values"). +//! +//! One iteration `t` runs an external-sampling traversal per player that can still act: +//! +//! * the deal is sampled from the joint belief at the subgame root (rejection sampling gives +//! exact card removal between players), the unseen board cards uniformly; +//! * the traverser enumerates its actions, everyone else samples from the current +//! regret-matching strategy; regret and average-strategy updates are weighted by `t` +//! (Linear CFR), with hogwild atomics (`Table`); +//! * the current betting round is solved with lossless (exact hole card) infosets, later +//! rounds inside the subgame with the blueprint's bucketing by default, or with the paper's +//! per-flop 500-bucket search abstraction when `SearchParams::search_buckets` is set; +//! * leaves (depth limit, see `tree::Limit`) are an extra decision: every player still able to +//! act chooses one of the 4 continuation strategies, infoset = (public leaf, own bucket); the +//! value of a joint choice is a rollout of the rest of the hand on the sampled deal with each +//! player following its chosen continuation strategy (blueprint biased x5 toward fold / call / +//! raise), each compressed to one deterministic action per abstract infoset. +//! +//! Randomness is seeded per iteration (`mix(seed, t)`), never per thread. With +//! `parallel = false` the whole solve is bit-reproducible. + +use crate::beliefs::{hole_mask, holes, Beliefs, N}; +use crate::bp::{cont_pick, real_passive, Blueprint, K_BLUEPRINT, NUM_CONT}; +use crate::table::{Slot, Table}; +use crate::tree::{limit_for, search_actions, step_path, Extras, Limit}; +use crate::vector::{solve_vec, VecGame, VecParams, VecSolution}; +use abstraction::search_buckets::{FlopView, SearchBuckets}; +use bench::mix; +use cards::{bit, hole_index, Card, Rng}; +use nlhe::abstraction::{ActionList, BetSizing, Shadow, MAX_ACTIONS}; +use nlhe::{Action, Deal, State, Step, Street, MAX_PLAYERS}; +use rayon::prelude::*; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::sync::Arc; +use std::time::Instant; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LeafMode { + /// Paper: each player picks one of 4 continuation strategies. + Cont4, + /// Ablation: every player plays the plain blueprint after the leaf. + Blueprint, +} + +#[derive(Clone, Debug)] +pub struct SearchParams { + /// MCCFR iterations per search (each iteration = one traversal per acting player). Default 200k + /// (measured: 6-max vs 5 x B, 20k it -42, 100k +58, 200k +87, 500k +58 mbb/game; see RESULTS.md). + pub iters: u64, + /// Optional wall-clock cap, checked between batches. + pub max_millis: Option, + /// Search action abstraction for the root round (1-6 raise sizes per node in the paper). + pub sizing: BetSizing, + /// Coarser abstraction for rounds after the root round inside the subgame (keeps solving + /// to the end of the game affordable on one machine). + pub later_sizing: BetSizing, + /// Negative-regret pruning (Algorithm 1 MCCFR-P, applied to the subgame): after the first + /// fifth of the iterations, in this fraction of them the traverser skips actions whose + /// regret is below `-t^2/2 * prune_frac * stack` (a consistent per-iteration gap of + /// `prune_frac * stack` chips). 0 disables. + pub prune_prob: f32, + pub prune_frac: f32, + /// Warm start (deviation, compensates for far fewer iterations than the paper): a new + /// infoset's regrets are initialised to `warm_start * t * pot * sigma_blueprint`, i.e. the + /// blueprint's (translated) action probabilities, worth about `warm_start` iterations of + /// evidence. 0 = start uniform. + pub warm_start: f32, + /// Infoset table capacity per search. + pub max_infosets: usize, + /// Fraction of our own traversals that fix our actual hole cards (importance of the infosets + /// we actually play; unbiased per infoset, see crate docs). + pub focus_own: f32, + pub leaf: LeafMode, + /// Multiplier of the biased continuation strategies (paper: 5). + pub cont_bias: f32, + /// Compress each continuation strategy to one sampled action per abstract infoset (paper). + pub compress: bool, + pub parallel: bool, + pub seed: u64, + /// Play the final iterate (paper) instead of the weighted average. + pub play_final: bool, + /// Search the first betting round when an opponent raise is far off-tree (paper). + pub preflop_search: bool, + /// "More than $100 off": chips; `None` = one big blind of the game. + pub preflop_trigger_chips: Option, + /// Preflop search only with at most this many players remaining (paper: 4). + pub preflop_max_players: usize, + /// Search flop/turn/river (paper: always). `false` = pure blueprint (ablation). + pub postflop_search: bool, + /// Paper's search abstraction: per-flop potential-aware 500-bucket tables for the turn and + /// river inside the subgame (keys of later-round search infosets and of depth-limit leaves). + /// `None` (default) = reuse the blueprint's bucketing. Blueprint lookups (warm-start prior, + /// continuation-strategy rollouts, belief updates) always use the blueprint's own buckets. + pub search_buckets: Option>, + /// Heads-up subgames from `vec_min_street` on are solved with vector-form Linear CFR + /// (`vector.rs`: exact hole pairs and board cards, public chance sampling) instead of MC LCFR. + pub vector: bool, + pub vec_min_street: Street, + /// Vector passes by root street `[flop, turn, river]`. + pub vec_iters: [u64; 3], + /// CFR+ style regret flooring in the vector solver (default; `false` = plain Linear CFR, worse here). + pub vec_plus: bool, + /// Pool the infosets of rounds after the root round by the blueprint's card buckets (shared + /// across board runouts; far fewer passes needed, at the price of the abstraction). + pub vec_pooled: bool, + /// Keep every street's vector-solver strategies (needed by `exploit` for the vector candidate; memory). + pub vec_keep_all: bool, + /// Search the flop (ablation: `false` = blueprint on the flop, search from the turn on). + pub search_flop: bool, + /// Search the turn (ablation). + pub search_turn: bool, + /// Search the river (ablation). + pub search_river: bool, + /// Update OPPONENT beliefs with the blueprint's likelihood instead of the search's average strategy + /// (default: opponents are modelled as the blueprint; a measured +100 mbb/game at 20k iterations). + pub blueprint_beliefs: bool, + /// With `blueprint_beliefs`: still update OUR OWN seat's belief with the search average. + pub own_search_beliefs: bool, + /// With `blueprint_beliefs`: opponent actions that were off the search tree (added as extras) are + /// still scored with the search's average strategy (the blueprint has no likelihood for them). + pub offtree_search_beliefs: bool, + /// Tremble ε on OPPONENT action likelihoods in the Bayes belief update: lik' = (1-ε)·lik + ε/n. + /// Keeps hands an off-model opponent (e.g. a rule bot) really holds from being zeroed out when + /// the model (blueprint/search) says "never". 0 = plain Bayes. + pub belief_tremble: f32, + /// Root-round infosets of the OTHER seats are keyed by the blueprint card bucket instead of the exact + /// hole pair (we keep lossless infosets for our own seat). Opponents then share samples across the + /// ~1326/200 hands of a bucket, like the blueprint they are modelled on. + pub opp_pool: bool, + /// Search a street only when at most this many players are still live at its start `[flop, turn, river]` + /// (diagnostic / robustness knob; 6 = always). + pub max_players: [usize; 3], + /// Minimum live players for the flop search (diagnostic: isolate multiway vs HU flops; 2 = always). + pub min_flop_players: usize, + /// Dedicated thread pool for `parallel` solves (default: rayon's global pool). + pub pool: Option>, +} + +impl Default for SearchParams { + fn default() -> Self { + SearchParams { + iters: 200_000, + max_millis: None, + sizing: crate::tree::default_sizing(), + later_sizing: crate::tree::later_sizing(), + prune_prob: 0.95, + prune_frac: 0.01, + warm_start: 8.0, + max_infosets: 1 << 20, + focus_own: 0.5, + leaf: LeafMode::Cont4, + cont_bias: 5.0, + compress: true, + parallel: true, + seed: 1, + play_final: false, + preflop_search: true, + preflop_trigger_chips: None, + preflop_max_players: 4, + postflop_search: true, + search_buckets: None, + vector: false, + vec_min_street: Street::Turn, + vec_iters: [300, 300, 150], + vec_plus: true, + vec_pooled: false, + vec_keep_all: false, + search_flop: true, + search_turn: true, + search_river: true, + blueprint_beliefs: true, + own_search_beliefs: true, + offtree_search_beliefs: true, + belief_tremble: 0.0, + opp_pool: false, + max_players: [6, 6, 6], + min_flop_players: 2, + pool: None, + } + } +} + +/// Everything that defines one subgame solve. +pub struct Subgame<'a> { + pub bp: &'a Blueprint, + /// State at the start of the betting round (the subgame root). + pub root: State, + /// Board cards visible at the root. + pub board: &'a [Card], + /// Beliefs at the root (card removal vs `board` already applied). + pub beliefs: &'a Beliefs, + /// Shadow game at `root` (blueprint history of everything before the root, with off-menu + /// raises replaced by their translations); see [`Blueprint::shadow`]. + pub bp_hist: Shadow, + pub extras: &'a Extras, + /// Our seat, our actual hole cards, and the actions we already took this round. + pub me: usize, + pub my_hole: Option<[Card; 2]>, + pub frozen: &'a HashMap, + pub params: &'a SearchParams, + pub seed: u64, +} + +pub struct Solution { + table: Table, + vec: Option, + pub extras: Extras, + pub sizing: BetSizing, + pub root_street: Street, + pub limit: Limit, + pub iters: u64, + pub millis: f64, + pub nodes: u64, + /// Depth-limit leaves evaluated (0 when solving to the end of the game). + pub leaves: u64, + /// Most raises seen so far this street at any root-round decision node. + pub max_raises: u32, + pub opp_pool: bool, + pub me: usize, + /// Per-flop search-bucket lookups performed (0 unless `SearchParams::search_buckets`). + pub search_bucket_lookups: u64, + /// Mean sampled value (chips) of each seat's own traversals at the subgame root under the + /// strategies being learned, and the sample counts (MC solver only; zeros for vector). + pub root_value: [(f64, u64); MAX_PLAYERS], +} + +const TAG_LATER: u64 = 1 << 32; +const TAG_LEAF: u64 = 2 << 32; +const TAG_OPP: u64 = 3 << 32; +const VAL_STRIPES: usize = 256; + +impl Solution { + /// Strategy of the root-round infoset `(path, hole)` over `n` actions: the final iterate + /// or the weighted average. `false` if the infoset was never reached. + pub fn probs(&self, path: u64, hole: usize, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { + if let Some(v) = &self.vec { + return v.probs(path, hole, n, final_iterate, out); + } + let Some(slot) = self.table.find(Table::key(path, hole as u64)).filter(|s| s.n == n) else { + return false; + }; + if final_iterate { + self.table.strategy(slot, &mut out[..n]); + true + } else { + self.table.average(slot, &mut out[..n]) + } + } + /// Strategy of another seat's pooled root-round infoset `(path, blueprint bucket)` (`opp_pool` solves). + pub fn probs_opp(&self, path: u64, bucket: u32, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { + let Some(slot) = self.table.find(Table::key(path, TAG_OPP | bucket as u64)).filter(|s| s.n == n) else { + return false; + }; + if final_iterate { + self.table.strategy(slot, &mut out[..n]); + true + } else { + self.table.average(slot, &mut out[..n]) + } + } + pub fn infosets(&self) -> usize { + self.vec.as_ref().map_or_else(|| self.table.infosets(), |v| v.nodes()) + } + /// The vector-form solution, if the subgame was solved that way. + /// Peak node storage (bytes) of a vector solve, 0 for MC. + pub fn peak_bytes(&self) -> usize { + self.vec.as_ref().map_or(0, |v| v.peak_bytes) + } + pub fn vector(&self) -> Option<&VecSolution> { + self.vec.as_ref() + } + /// Later-round strategy of the MC solver: `(path, street, bucket)` (board-agnostic keys). + pub fn probs_later(&self, path: u64, street: Street, bucket: u32, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { + let key = Table::key(path, TAG_LATER | (street.idx() as u64) << 24 | bucket as u64); + let Some(slot) = self.table.find(key).filter(|s| s.n == n) else { return false }; + if final_iterate { + self.table.strategy(slot, &mut out[..n]); + true + } else { + self.table.average(slot, &mut out[..n]) + } + } +} + +struct Cx { + deal: Deal, + hole: [u16; MAX_PLAYERS], + /// Blueprint buckets (blueprint lookups: warm-start prior, rollouts). + bucket: [[u32; 4]; MAX_PLAYERS], + /// Buckets used as search infoset keys: per-flop search buckets when enabled, else `bucket`. + sbucket: [[u32; 4]; MAX_PLAYERS], + rng: Rng, + t: f32, + /// Regret threshold below which the traverser skips an action this iteration (or -inf). + prune_at: f32, + /// Per-traversal counters, flushed once (shared atomics per node made parallel solves ~10x slower). + nodes: u64, + leaves: u64, + sb: u64, +} + +struct Solver<'a> { + sg: &'a Subgame<'a>, + table: Table, + limit: Limit, + root_street: Street, + n: usize, + live: u8, + cdf: Vec>, + board_mask: u64, + my_idx: Option, + salt: u64, + nodes: AtomicU64, + leaves: AtomicU64, + max_raises: AtomicU32, + stack: f32, + view: Option, + sb_lookups: AtomicU64, + /// Sum and count of the traverser's sampled root values per seat (diagnostics). + val: Vec>, + /// Best-response mode (`exploit`): every seat except `br_p` plays the frozen strategy of this + /// solution (read-only, average or final iterate) instead of learning. + fixed: Option<(&'a Solution, bool)>, + br_p: usize, + lookups: AtomicU64, + misses: AtomicU64, +} + +fn hash01(a: u64, b: u64, c: u64, d: u64) -> f64 { + (mix(mix(mix(a, b), c), d) >> 11) as f64 / (1u64 << 53) as f64 +} + +/// Solve the subgame and return the strategies. +pub fn solve(sg: &Subgame) -> Solution { + let start = Instant::now(); + let root = sg.root; + let n = root.num_players(); + let p = sg.params; + if p.vector && root.street() >= p.vec_min_street && root.street() != Street::Preflop { + if let Some(seats) = VecGame::live_seats(&root) { + return solve_vector(sg, seats, start); + } + } + let live = (0..n).filter(|&i| !root.is_folded(i)).fold(0u8, |m, i| m | 1 << i); + let solver = Solver::new(sg, None, usize::MAX); + let players: Vec = if root.is_terminal() { + vec![] + } else { + (0..n).filter(|&i| live >> i & 1 != 0 && !root.is_all_in(i)).collect() + }; + let batch = if p.parallel { 256u64 } else { 1 << 20 }; + let mut done = 0u64; + let drive = |done: &mut u64| { + let mut t0 = 1u64; + while t0 <= p.iters && !players.is_empty() { + let end = (t0 + batch - 1).min(p.iters); + let run = |t: u64| solver.iteration(t, &players); + if p.parallel { + (t0..=end).into_par_iter().for_each(run); + } else { + (t0..=end).for_each(run); + } + *done = end; + t0 = end + 1; + if p.max_millis.is_some_and(|ms| start.elapsed().as_millis() as u64 >= ms) { + break; + } + } + }; + match (&p.pool, p.parallel) { + // A dedicated pool is driven from a plain OS thread: blocking a rayon worker of another + // pool in `install` would let it steal unrelated jobs (nested searches) meanwhile. + (Some(pl), true) => std::thread::scope(|sc| { + sc.spawn(|| pl.install(|| drive(&mut done))).join().unwrap(); + }), + _ => drive(&mut done), + } + Solution { + table: solver.table, + vec: None, + extras: sg.extras.clone(), + sizing: p.sizing, + root_street: solver.root_street, + limit: solver.limit, + iters: done, + millis: start.elapsed().as_secs_f64() * 1e3, + nodes: solver.nodes.load(Relaxed), + leaves: solver.leaves.load(Relaxed), + max_raises: solver.max_raises.load(Relaxed), + opp_pool: p.opp_pool && solver.root_street != Street::Preflop, + me: sg.me, + search_bucket_lookups: solver.sb_lookups.load(Relaxed), + root_value: { + let mut tot = [(0.0f64, 0u64); MAX_PLAYERS]; + for m in &solver.val { + let g = m.lock().unwrap(); + for i in 0..MAX_PLAYERS { + tot[i].0 += g[i].0; + tot[i].1 += g[i].1; + } + } + let mut o = [(0.0, 0u64); MAX_PLAYERS]; + for i in 0..MAX_PLAYERS { + o[i] = (if tot[i].1 > 0 { tot[i].0 / tot[i].1 as f64 } else { 0.0 }, tot[i].1); + } + o + }, + } +} + +fn solve_vector(sg: &Subgame, seats: [usize; 2], start: Instant) -> Solution { + let p = sg.params; + let root = sg.root; + let bm = cards::mask_of(sg.board); + let ranges = seats.map(|s| { + sg.beliefs.w[s].iter().enumerate().map(|(i, &x)| if hole_mask(i) & bm == 0 { x as f64 } else { 0.0 }).collect::>() + }); + let g = VecGame { + root, + board: sg.board, + seats, + ranges, + sizing: &p.sizing, + later: &p.later_sizing, + extras: sg.extras, + me: seats.iter().position(|&s| s == sg.me), + my_hole: sg.my_hole.map(|h| hole_index(h[0], h[1])), + frozen: sg.frozen, + pooled: if p.vec_pooled { Some(sg.bp as &dyn crate::vector::Bucketing) } else { None }, + }; + let iters = p.vec_iters[(root.street().idx() - 1).min(2)]; + let vp = VecParams { iters, max_millis: p.max_millis, plus: p.vec_plus, stratify: true, seed: sg.seed, keep_all: p.vec_keep_all, max_bytes: 2 << 30 }; + let vs = solve_vec(&g, &vp); + Solution { + table: Table::new(1, 8), + extras: sg.extras.clone(), + sizing: p.sizing, + root_street: root.street(), + limit: Limit::EndOfGame, + iters: vs.iters, + millis: start.elapsed().as_secs_f64() * 1e3, + nodes: 0, + leaves: 0, + max_raises: 0, + opp_pool: false, + me: sg.me, + search_bucket_lookups: 0, + root_value: [(0.0, 0); MAX_PLAYERS], + vec: Some(vs), + } +} + +impl<'a> Solver<'a> { + fn new(sg: &'a Subgame<'a>, fixed: Option<&'a Solution>, br_p: usize) -> Solver<'a> { + let root = sg.root; + let n = root.num_players(); + let p = sg.params; + let live = (0..n).filter(|&i| !root.is_folded(i)).fold(0u8, |m, i| m | 1 << i); + Solver { + sg, + table: Table::new(p.max_infosets, p.max_infosets * 8), + limit: limit_for(&root), + root_street: root.street(), + n, + live, + cdf: (0..n).map(|i| sg.beliefs.cdf(i)).collect(), + board_mask: cards::mask_of(sg.board), + my_idx: sg.my_hole.map(|h| hole_index(h[0], h[1]) as u16), + salt: mix(sg.seed, 0xC0FFEE), + nodes: AtomicU64::new(0), + leaves: AtomicU64::new(0), + max_raises: AtomicU32::new(0), + stack: (0..n).map(|i| root.stack(i) + root.contributed(i)).max().unwrap_or(0) as f32, + view: match &p.search_buckets { + Some(sb) if root.street() != Street::Preflop && sg.board.len() >= 3 => Some(sb.for_flop([sg.board[0], sg.board[1], sg.board[2]])), + _ => None, + }, + sb_lookups: AtomicU64::new(0), + val: (0..VAL_STRIPES).map(|_| std::sync::Mutex::new([(0.0, 0); MAX_PLAYERS])).collect(), + fixed: fixed.map(|f| (f, sg.params.play_final)), + br_p, + lookups: AtomicU64::new(0), + misses: AtomicU64::new(0), + } + } + + fn iteration(&self, t: u64, players: &[usize]) { + let mut rng = Rng::new(mix(self.sg.seed, t)); + for &p in players { + let force = p == self.sg.me && self.my_idx.is_some() && rng.f32() < self.sg.params.focus_own; + if let Some(mut cx) = self.sample(&mut rng, force, t) { + let prm = self.sg.params; + if prm.prune_prob > 0.0 && t * 5 > prm.iters && rng.f32() < prm.prune_prob { + // Cumulative Linear-CFR regret of a consistently bad action grows like + // t^2/2 x its per-iteration gap. + let t = t as f32; + cx.prune_at = -0.5 * t * t * prm.prune_frac * self.stack; + } + let bph = self.sg.bp_hist; + let v = self.walk(&mut cx, &self.sg.root, 0, &bph, p); + self.nodes.fetch_add(cx.nodes, Relaxed); + self.leaves.fetch_add(cx.leaves, Relaxed); + if cx.sb > 0 { + self.sb_lookups.fetch_add(cx.sb, Relaxed); + } + // Diagnostic root values: per-thread stripes (a single mutex serialised all threads). + { + let mut g = self.val[rayon::current_thread_index().unwrap_or(0) % VAL_STRIPES].lock().unwrap(); + g[p].0 += v as f64; + g[p].1 += 1; + } + } + } + } + + /// Sample a deal: holes from the joint belief (rejection => exact card removal), then the + /// unseen board uniformly from the remaining deck. + fn sample(&self, rng: &mut Rng, force_me: bool, t: u64) -> Option { + let hl = holes(); + let mut idx = [0u16; MAX_PLAYERS]; + let mut ok = false; + for _ in 0..64 { + let mut dead = self.board_mask; + let mut good = true; + for s in 0..self.n { + if self.live >> s & 1 == 0 { + continue; + } + let i = if force_me && s == self.sg.me { + self.my_idx.unwrap() as usize + } else { + let c = &self.cdf[s]; + let tot = *c.last().unwrap(); + if tot <= 0.0 { + good = false; + break; + } + let x = rng.f64() * tot; + c.partition_point(|&v| v <= x).min(N - 1) + }; + let m = hole_mask(i); + if m & dead != 0 { + good = false; + break; + } + dead |= m; + idx[s] = i as u16; + } + if good { + ok = true; + break; + } + } + if !ok { + return None; + } + let mut dead = self.board_mask; + let mut deal = Deal { holes: [[0, 1]; MAX_PLAYERS], board: [0; 5] }; + for s in 0..self.n { + if self.live >> s & 1 != 0 { + deal.holes[s] = hl[idx[s] as usize]; + dead |= hole_mask(idx[s] as usize); + } + } + for (i, c) in self.sg.board.iter().enumerate() { + deal.board[i] = *c; + } + for i in self.sg.board.len()..5 { + let c = rng.draw(dead); + dead |= bit(c); + deal.board[i] = c; + } + let mut bucket = [[0u32; 4]; MAX_PLAYERS]; + for s in 0..self.n { + if self.live >> s & 1 == 0 { + continue; + } + for st in Street::ALL { + if st >= self.root_street { + bucket[s][st.idx()] = self.sg.bp.bucket(st, deal.holes[s], &deal.board[..st.board_len()]); + } + } + } + let mut sbucket = bucket; + let mut sb_n = 0u64; + if let Some(v) = &self.view { + for s in 0..self.n { + if self.live >> s & 1 == 0 { + continue; + } + for st in [Street::Turn, Street::River] { + if st >= self.root_street { + if let Some(b) = v.bucket(deal.holes[s], &deal.board[..st.board_len()]) { + sbucket[s][st.idx()] = b; + sb_n += 1; + } + } + } + } + } + Some(Cx { deal, hole: idx, bucket, sbucket, rng: Rng::new(mix(rng.next_u64(), t)), t: t as f32, prune_at: f32::NEG_INFINITY, nodes: 0, leaves: 0, sb: sb_n }) + } + + #[inline] + fn key(&self, cx: &Cx, st: &State, path: u64, seat: usize) -> u64 { + if st.street() == self.root_street { + if self.sg.params.opp_pool && seat != self.sg.me && self.root_street != Street::Preflop { + Table::key(path, TAG_OPP | cx.bucket[seat][st.street().idx()] as u64) + } else { + Table::key(path, cx.hole[seat] as u64) + } + } else { + Table::key(path, TAG_LATER | (st.street().idx() as u64) << 24 | cx.sbucket[seat][st.street().idx()] as u64) + } + } + + fn walk(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, p: usize) -> f32 { + cx.nodes += 1; + if st.street() == self.root_street && st.raises_this_street() > self.max_raises.load(Relaxed) { + self.max_raises.fetch_max(st.raises_this_street(), Relaxed); + } + let seat = st.to_act().unwrap(); + let mut list = ActionList::new(); + let ex: &[i32] = self.sg.extras.get(&path).map_or(&[], |v| v.as_slice()); + let sz = if st.street() == self.root_street { &self.sg.params.sizing } else { &self.sg.params.later_sizing }; + search_actions(st, sz, ex, &mut list); + let n = list.len(); + let key = self.key(cx, st, path, seat); + if let Some((fx, fin)) = self.fixed { + if seat != self.br_p { + let mut sigma = [0f32; MAX_ACTIONS]; + self.fixed_sigma(fx, fin, key, &list, st, bph, cx.bucket[seat][st.street().idx()], &mut sigma[..n]); + let a = cx.rng.sample_weighted(&sigma[..n]); + return self.child(cx, st, path, bph, &list, a, p); + } + } + let slot = if self.sg.params.warm_start > 0.0 { + let lam = self.sg.params.warm_start * cx.t * st.pot() as f32; + let bucket = cx.bucket[seat][st.street().idx()]; + self.table.get_or_insert_with(key, n, |r| { + if let Some(pr) = self.sg.bp.prior(bph, st, &list, bucket) { + for (x, &q) in r.iter_mut().zip(&pr[..n]) { + *x = lam * q; + } + } + }) + } else { + self.table.get_or_insert(key, n) + }; + let mut sigma = [0f32; MAX_ACTIONS]; + match slot { + Some(s) => self.table.strategy(s, &mut sigma[..n]), + None => sigma[..n].iter_mut().for_each(|x| *x = 1.0 / n as f32), + } + // Frozen: our own earlier action this round, for our actual hand only. + let mut frozen = None; + if seat == self.sg.me && Some(cx.hole[seat]) == self.my_idx { + if let Some(fa) = self.sg.frozen.get(&path) { + frozen = list.as_slice().iter().position(|a| a == fa); + } + } + if let Some(f) = frozen { + sigma[..n].iter_mut().for_each(|x| *x = 0.0); + sigma[f] = 1.0; + if let Some(s) = slot { + // Readers (dist, belief updates) see the pinned pure strategy. + self.table.set_pure(s, f); + self.table.add_avg(s, f, 1.0); + } + } + if seat == p { + let mut va = [0f32; MAX_ACTIONS]; + let mut v = 0f32; + let mut explored = [true; MAX_ACTIONS]; + let mut mass = 0f32; + for a in 0..n { + if frozen.is_some_and(|f| f != a) { + explored[a] = false; + continue; + } + if cx.prune_at.is_finite() && !matches!(list.get(a), Action::Fold) { + if let Some(s) = slot { + if self.table.regret(s, a) < cx.prune_at && !self.ends_hand(st, list.get(a)) { + explored[a] = false; + continue; + } + } + } + va[a] = self.child(cx, st, path, bph, &list, a, p); + v += sigma[a] * va[a]; + mass += sigma[a]; + } + if mass < 1.0 { + // Pruned actions left out of the expectation: renormalise over explored ones. + if mass > 0.0 { + v /= mass; + } else { + let k = (0..n).filter(|&a| explored[a]).count().max(1); + v = (0..n).filter(|&a| explored[a]).map(|a| va[a]).sum::() / k as f32; + } + } + if frozen.is_none() { + if let Some(s) = slot { + for a in 0..n { + if explored[a] { + self.table.add_regret(s, a, cx.t * (va[a] - v)); + } + } + } + } + v + } else { + let a = cx.rng.sample_weighted(&sigma[..n]); + if frozen.is_none() { + if let Some(s) = slot { + for (i, &x) in sigma[..n].iter().enumerate() { + self.table.add_avg(s, i, cx.t * x); + } + } + } + self.child(cx, st, path, bph, &list, a, p) + } + } + + /// Read-only strategy of the frozen solution `fx` at `key` (best-response mode); infosets it + /// never visited fall back to the blueprint prior, else uniform (counted in `misses`). + #[allow(clippy::too_many_arguments)] + fn fixed_sigma(&self, fx: &Solution, fin: bool, key: u64, list: &ActionList, st: &State, bph: &Shadow, bucket: u32, out: &mut [f32]) { + let n = out.len(); + self.lookups.fetch_add(1, Relaxed); + let hit = fx.table.find(key).filter(|s| s.n == n).is_some_and(|s| { + if fin { + fx.table.strategy(s, out); + true + } else { + fx.table.average(s, out) + } + }); + if !hit { + self.misses.fetch_add(1, Relaxed); + match self.sg.bp.prior(bph, st, list, bucket) { + Some(pr) => out.copy_from_slice(&pr[..n]), + None => out.iter_mut().for_each(|x| *x = 1.0 / n as f32), + } + } + } + + fn fixed_leaf_sigma(&self, fx: &Solution, fin: bool, key: u64, out: &mut [f32; NUM_CONT]) { + if let Some(s) = fx.table.find(key).filter(|s| s.n == NUM_CONT) { + if fin { + fx.table.strategy(s, out); + } else if !fx.table.average(s, out) { + *out = [0.25; NUM_CONT]; + } + } + } + + /// Does `a` end the hand immediately (never pruned, as in Algorithm 1)? + fn ends_hand(&self, st: &State, a: Action) -> bool { + let mut s2 = *st; + s2.apply(a) == Step::Terminal + } + + #[allow(clippy::too_many_arguments)] + fn child(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, list: &ActionList, a: usize, p: usize) -> f32 { + let act = list.get(a); + let mut s2 = *st; + let step = s2.apply(act); + if s2.is_folded(p) { + return -(s2.contributed(p) as f32); + } + let path2 = step_path(path, act); + if step == Step::Terminal { + return s2.payoffs(&cx.deal)[p] as f32; + } + let mut b2 = *bph; + self.sg.bp.observe(&mut b2, st, act, st.to_act() == Some(self.sg.me)); + match step { + Step::NewStreet(s) if self.limit != Limit::EndOfGame => { + let known = Street::ALL[s.idx() - 1]; + self.leaf(cx, &s2, path2, &b2, known, p) + } + Step::Continue + if self.limit == Limit::SecondRaise + && s2.street() == self.root_street + && s2.raises_this_street() >= 2 => + { + self.leaf(cx, &s2, path2, &b2, s2.street(), p) + } + _ => self.walk(cx, &s2, path2, &b2, p), + } + } + + /// Depth-limit leaf: continuation-strategy choice (supplement, "Leaf node values"). + fn leaf(&self, cx: &mut Cx, st: &State, path: u64, bph: &Shadow, known: Street, p: usize) -> f32 { + cx.leaves += 1; + let mut ks = [K_BLUEPRINT; MAX_PLAYERS]; + if self.sg.params.leaf == LeafMode::Blueprint { + return self.rollout(cx, st, bph, &ks, p); + } + let lpath = path.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x1EAF; + let mut mine: Option = None; + let mut p_chooses = false; + for i in 0..self.n { + if st.is_folded(i) || st.is_all_in(i) { + continue; + } + let key = Table::key(lpath, TAG_LEAF | cx.sbucket[i][known.idx()] as u64); + if let Some((fx, fin)) = self.fixed { + if i != self.br_p { + let mut sg = [0.25f32; NUM_CONT]; + self.fixed_leaf_sigma(fx, fin, key, &mut sg); + ks[i] = cx.rng.sample_weighted(&sg) as u8; + continue; + } + } + let slot = self.table.get_or_insert(key, NUM_CONT); + if i == p { + p_chooses = true; + mine = slot; + continue; + } + let mut sg = [0.25f32; NUM_CONT]; + if let Some(s) = slot { + self.table.strategy(s, &mut sg); + } + ks[i] = cx.rng.sample_weighted(&sg) as u8; + if let Some(s) = slot { + for (k, &x) in sg.iter().enumerate() { + self.table.add_avg(s, k, cx.t * x); + } + } + } + if !p_chooses { + return self.rollout(cx, st, bph, &ks, p); + } + let mut sg = [0.25f32; NUM_CONT]; + if let Some(s) = mine { + self.table.strategy(s, &mut sg); + } + let mut va = [0f32; NUM_CONT]; + let mut v = 0.0; + for k in 0..NUM_CONT { + ks[p] = k as u8; + va[k] = self.rollout(cx, st, bph, &ks, p); + v += sg[k] * va[k]; + } + if let Some(s) = mine { + for k in 0..NUM_CONT { + self.table.add_regret(s, k, cx.t * (va[k] - v)); + } + } + v + } + + /// Play the hand out on the sampled deal; seat `i` follows continuation strategy `ks[i]` + /// of the blueprint, compressed to one action per abstract infoset. + fn rollout(&self, cx: &mut Cx, st: &State, bph: &Shadow, ks: &[u8; MAX_PLAYERS], p: usize) -> f32 { + let bp = self.sg.bp; + let prm = self.sg.params; + let mut s = *st; + let mut h = *bph; + let mut list = ActionList::new(); + let mut sig = [0f32; MAX_ACTIONS]; + while !s.is_terminal() { + let seat = s.to_act().unwrap(); + let bucket = cx.bucket[seat][s.street().idx()]; + let a = if bp.node_list(&h, &s, &mut list) && bp.sigma(&h, &s, &list, bucket, &mut sig) { + let n = list.len(); + let u = if prm.compress { + hash01(self.salt, ks[seat] as u64, h.key(), bucket as u64) + } else { + cx.rng.f64() + }; + let idx = cont_pick(ks[seat], prm.cont_bias, &list, &mut sig[..n], u); + h.real_action(&s, &list, idx) + } else { + real_passive(&s) + }; + bp.observe(&mut h, &s, a, true); + s.apply(a); + } + s.payoffs(&cx.deal)[p] as f32 + } +} + +/// Number of hole pairs with positive mass in `b` for `seat` (diagnostics). +pub fn support(b: &Beliefs, seat: usize) -> usize { + b.w[seat].iter().filter(|&&x| x > 0.0).count() +} + +// --------------------------------------------------------------------------------------------- +// Sampled best response (3+ players, or when the exact vector evaluator does not apply) +// --------------------------------------------------------------------------------------------- + +/// Estimate of one player's best-response gain against a frozen solution of the same subgame. +#[derive(Clone, Debug, Default)] +pub struct BrEstimate { + /// Mean chips (relative to the start of the hand) of the player following the frozen strategy / its learned best response. + pub value_profile: f64, + pub value_br: f64, + /// Paired gain `value_br - value_profile` and its standard error over `samples` common deals. + pub gain: f64, + pub gain_se: f64, + pub samples: u64, + /// Share of the best-response playouts that end in a depth-limit leaf (their value is a fixed rollout, not searched). + pub leaf_share: f64, + /// Share of frozen-strategy lookups that hit an infoset the solution never visited (blueprint prior used instead). + pub miss_share: f64, + pub br_iters: u64, + pub br_infosets: usize, +} + +impl<'a> Solver<'a> { + fn strat_of(&self, key: u64, n: usize, out: &mut [f32]) -> bool { + match self.table.find(key).filter(|s| s.n == n) { + Some(s) => self.table.average(s, out) || { + self.table.strategy(s, out); + true + }, + None => false, + } + } + + /// Play one hand from the subgame root on the deal in `cx`: every seat samples from the frozen + /// solution, except `p` which uses its learned best response when `use_br`. + /// Returns `(payoff of p, ended in a leaf)`. + fn play(&self, cx: &mut Cx, p: usize, use_br: bool) -> (f32, bool) { + let mut st = self.sg.root; + let mut path = 0u64; + let mut bph = self.sg.bp_hist; + let (fx, fin) = self.fixed.expect("play needs a frozen solution"); + loop { + let seat = st.to_act().unwrap(); + let mut list = ActionList::new(); + let ex: &[i32] = self.sg.extras.get(&path).map_or(&[], |v| v.as_slice()); + let sz = if st.street() == self.root_street { &self.sg.params.sizing } else { &self.sg.params.later_sizing }; + search_actions(&st, sz, ex, &mut list); + let n = list.len(); + let key = self.key(cx, &st, path, seat); + let mut sigma = [0f32; MAX_ACTIONS]; + if seat == p && use_br { + if !self.strat_of(key, n, &mut sigma[..n]) { + sigma[..n].iter_mut().for_each(|x| *x = 1.0 / n as f32); + } + } else { + self.fixed_sigma(fx, fin, key, &list, &st, &bph, cx.bucket[seat][st.street().idx()], &mut sigma[..n]); + } + let a = cx.rng.sample_weighted(&sigma[..n]); + let act = list.get(a); + let mut s2 = st; + let step = s2.apply(act); + if s2.is_folded(p) { + return (-(s2.contributed(p) as f32), false); + } + if step == Step::Terminal { + return (s2.payoffs(&cx.deal)[p] as f32, false); + } + let mut b2 = bph; + self.sg.bp.observe(&mut b2, &st, act, st.to_act() == Some(self.sg.me)); + path = step_path(path, act); + let known = match step { + Step::NewStreet(s) if self.limit != Limit::EndOfGame => Some(Street::ALL[s.idx() - 1]), + Step::Continue if self.limit == Limit::SecondRaise && s2.street() == self.root_street && s2.raises_this_street() >= 2 => Some(s2.street()), + _ => None, + }; + if let Some(known) = known { + let lpath = path.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x1EAF; + let mut ks = [K_BLUEPRINT; MAX_PLAYERS]; + for i in 0..self.n { + if s2.is_folded(i) || s2.is_all_in(i) { + continue; + } + let lkey = Table::key(lpath, TAG_LEAF | cx.sbucket[i][known.idx()] as u64); + let mut sg = [0.25f32; NUM_CONT]; + if i == p && use_br { + self.strat_of(lkey, NUM_CONT, &mut sg); + } else { + self.fixed_leaf_sigma(fx, fin, lkey, &mut sg); + } + ks[i] = cx.rng.sample_weighted(&sg) as u8; + } + return (self.rollout(cx, &s2, &b2, &ks, p), true); + } + st = s2; + bph = b2; + } + } +} + +/// Learn a best response of seat `p` against the frozen strategies of `sol` (CFR for `p` alone, +/// `br_iters` iterations, opponents fixed) and estimate its gain over `p` following `sol`, on +/// `eval_samples` common deals. The learned response is a LOWER bound of the true best response +/// (average of a finite run), so the gain is a lower bound of the exploitability. +pub fn best_response_sampled(sg: &Subgame, sol: &Solution, p: usize, br_iters: u64, eval_samples: u64) -> BrEstimate { + let params = SearchParams { iters: br_iters, warm_start: 0.0, prune_prob: 0.0, focus_own: 0.0, max_millis: None, ..sg.params.clone() }; + let empty = HashMap::new(); + let sg2 = Subgame { + bp: sg.bp, + root: sg.root, + board: sg.board, + beliefs: sg.beliefs, + bp_hist: sg.bp_hist, + extras: sg.extras, + me: sg.me, + my_hole: None, + frozen: &empty, + params: ¶ms, + seed: mix(sg.seed, 0xB357), + }; + let solver = Solver::new(&sg2, Some(sol), p); + let players = [p]; + let batch = 256u64; + let drive = || { + let mut t0 = 1u64; + while t0 <= br_iters { + let end = (t0 + batch - 1).min(br_iters); + (t0..=end).into_par_iter().for_each(|t| solver.iteration(t, &players)); + t0 = end + 1; + } + }; + match &sg.params.pool { + Some(pl) => std::thread::scope(|sc| { + sc.spawn(|| pl.install(drive)).join().unwrap(); + }), + None => drive(), + } + let eval_seed = mix(sg.seed, 0xE7A1); + let one = |i: u64| -> Option<(f32, f32, bool)> { + let mk = || { + let mut rng = Rng::new(mix(eval_seed, i)); + solver.sample(&mut rng, false, 1) + }; + let mut c0 = mk()?; + let mut c1 = mk()?; + let (v0, _) = solver.play(&mut c0, p, false); + let (v1, leaf) = solver.play(&mut c1, p, true); + Some((v0, v1, leaf)) + }; + let run = || (0..eval_samples).into_par_iter().filter_map(one).collect::>(); + let res = match &sg.params.pool { + Some(pl) => { + let mut out = vec![]; + std::thread::scope(|sc| { + out = sc.spawn(|| pl.install(run)).join().unwrap(); + }); + out + } + None => run(), + }; + let k = res.len().max(1) as f64; + let m0 = res.iter().map(|r| r.0 as f64).sum::() / k; + let m1 = res.iter().map(|r| r.1 as f64).sum::() / k; + let var = res.iter().map(|r| ((r.1 - r.0) as f64 - (m1 - m0)).powi(2)).sum::() / (k - 1.0).max(1.0); + let lk = solver.lookups.load(Relaxed).max(1) as f64; + BrEstimate { + value_profile: m0, + value_br: m1, + gain: m1 - m0, + gain_se: (var / k).sqrt(), + samples: res.len() as u64, + leaf_share: res.iter().filter(|r| r.2).count() as f64 / k, + miss_share: solver.misses.load(Relaxed) as f64 / lk, + br_iters, + br_infosets: solver.table.infosets(), + } +} diff --git a/sharingan-1/search/src/vector.rs b/sharingan-1/search/src/vector.rs index dc9e6e5c..430b35c7 100644 --- a/sharingan-1/search/src/vector.rs +++ b/sharingan-1/search/src/vector.rs @@ -1,832 +1,874 @@ -//! Vector-form Linear CFR for heads-up subgames (supplement: "an optimized vector-based form of -//! Linear CFR ... that samples one set of public board cards per thread"), plus an exact best -//! response / exploitability evaluator on the same tree. -//! -//! Instead of sampling one pair of hole hands per traversal (`solver.rs`, external sampling) a -//! pass walks the betting tree ONCE with a reach vector over all live hole pairs per player -//! and returns counterfactual-value vectors; card removal at terminals is O(M) by -//! inclusion-exclusion over the two hole cards. Public chance (the next board card) is sampled, -//! stratified by cycling a shuffled deck per chance node, so a node below chance node `c` is -//! visited every ~k-th pass. Infosets are `(public node incl. board cards, exact hole pair)`: -//! no card abstraction anywhere in the subgame. -//! -//! Utilities: dead money from players who folded before the root is respected (winner takes -//! the pot), so the game is constant-sum (`u0 + u1 = dead`), not zero-sum. -//! -//! Conventions: player index 0/1 = `seats[0]/seats[1]`. Values are chips relative to the start -//! of the hand. Chance weights: sampling one of `k` unseen cards with weight `k/(k-4)` and -//! enumerating with weight `1/(k-4)` both give the conditional expectation over the `k-4` -//! cards not blocked by the two holes. - -use crate::beliefs::holes; -use crate::tree::{search_actions, step_path, Extras}; -use bench::mix; -use cards::{bit, evaluate, mask_of, Card, Rng}; -use nlhe::abstraction::{ActionList, BetSizing, MAX_ACTIONS}; -use nlhe::{Action, State, Step, Street}; -use std::collections::HashMap; -use std::rc::Rc; -use std::time::Instant; - -pub const N: usize = 1326; - -/// Live hole pairs of the subgame (positive root reach for either player), compacted. -pub struct Hands { - pub idx: Vec, - pub cards: Vec<[u8; 2]>, - /// Hole index (0..1326) -> compact index, `u32::MAX` if absent. - pub of_hole: Vec, - /// Compact indices of the hands containing card `c`. - pub by_card: Vec>, -} - -impl Hands { - fn new(ranges: &[Vec; 2]) -> Hands { - let hl = holes(); - let mut idx = Vec::new(); - let mut cards = Vec::new(); - let mut of_hole = vec![u32::MAX; N]; - let mut by_card = vec![Vec::new(); 52]; - for i in 0..N { - if ranges[0][i] > 0.0 || ranges[1][i] > 0.0 { - of_hole[i] = idx.len() as u32; - for &c in &hl[i] { - by_card[c as usize].push(idx.len() as u32); - } - idx.push(i as u16); - cards.push(hl[i]); - } - } - Hands { idx, cards, of_hole, by_card } - } - pub fn len(&self) -> usize { - self.idx.len() - } - pub fn is_empty(&self) -> bool { - self.idx.is_empty() - } -} - -/// Card abstraction for the rounds after the root round (pooled infosets shared by every board -/// runout, exactly like the blueprint's keys). -pub trait Bucketing { - fn bucket(&self, street: Street, hole: [Card; 2], board: &[Card]) -> u32; - fn n_buckets(&self, street: Street) -> usize; -} - -/// A heads-up subgame instance. -pub struct VecGame<'a> { - pub root: State, - /// Board visible at the root (3, 4 or 5 cards). - pub board: &'a [Card], - /// Player index -> seat. - pub seats: [usize; 2], - /// Root reach per player over all 1326 holes (must already exclude board-blocked hands). - pub ranges: [Vec; 2], - pub sizing: &'a BetSizing, - pub later: &'a BetSizing, - pub extras: &'a Extras, - /// Our player index, our actual hole index and the actions we took already this round. - pub me: Option, - pub my_hole: Option, - pub frozen: &'a HashMap, - /// `Some`: rounds after the root round use bucket-pooled infosets (regrets aggregated over - /// the hands of a bucket weighted by the root belief); the root round stays lossless. - pub pooled: Option<&'a dyn Bucketing>, -} - -impl<'a> VecGame<'a> { - /// Both live seats of `root` (None unless exactly two are live and the state is a decision). - pub fn live_seats(root: &State) -> Option<[usize; 2]> { - if root.is_terminal() || root.live_count() != 2 { - return None; - } - let v: Vec = (0..root.num_players()).filter(|&s| !root.is_folded(s)).collect(); - Some([v[0], v[1]]) - } -} - -/// Per-board showdown data over the compact hand list. -struct Ctx { - valid: Vec, - order: Vec, - groups: Vec<(usize, usize)>, -} - -impl Ctx { - fn new(hands: &Hands, board: &[Card]) -> Ctx { - let bm = mask_of(board); - let m = hands.len(); - let mut valid = vec![false; m]; - let mut rank = vec![0u32; m]; - for i in 0..m { - let h = hands.cards[i]; - if bit(h[0]) & bm == 0 && bit(h[1]) & bm == 0 { - valid[i] = true; - rank[i] = evaluate(bit(h[0]) | bit(h[1]) | bm); - } - } - let mut order: Vec = (0..m as u32).filter(|&i| valid[i as usize]).collect(); - order.sort_by_key(|&i| rank[i as usize]); - let mut groups = Vec::new(); - let mut s = 0; - for i in 1..=order.len() { - if i == order.len() || rank[order[i] as usize] != rank[order[s] as usize] { - groups.push((s, i)); - s = i; - } - } - Ctx { valid, order, groups } - } -} - -fn card_sums(hands: &Hands, r: &[f64]) -> (f64, [f64; 52]) { - let mut t = 0.0; - let mut c = [0.0; 52]; - for i in 0..r.len() { - let x = r[i]; - if x != 0.0 { - t += x; - c[hands.cards[i][0] as usize] += x; - c[hands.cards[i][1] as usize] += x; - } - } - (t, c) -} - -/// `out[i]` = sum of `r[j]` over hands `j` sharing no card with hand `i`. -fn compat(hands: &Hands, r: &[f64]) -> Vec { - let (t, c) = card_sums(hands, r); - (0..r.len()) - .map(|i| { - let [a, b] = hands.cards[i]; - t - c[a as usize] - c[b as usize] + r[i] - }) - .collect() -} - -/// Showdown cfv of the holder: `win*P(>) - lose*P(<) + tie*P(=)` weighted by opponent reach. -fn showdown(hands: &Hands, ctx: &Ctx, r: &[f64], win: f64, lose: f64, tie: f64) -> Vec { - let (tot, tc) = card_sums(hands, r); - let mut less = 0.0; - let mut lc = [0.0f64; 52]; - let mut out = vec![0.0; r.len()]; - for &(s, e) in &ctx.groups { - if e - s == 1 { - // Singleton tie group: no equal-rank hands to account for. - let h = ctx.order[s] as usize; - let [a, b] = [hands.cards[h][0] as usize, hands.cards[h][1] as usize]; - let comp_less = less - lc[a] - lc[b]; - let comp_all = tot - tc[a] - tc[b] + r[h]; - out[h] = win * comp_less - lose * (comp_all - comp_less); - less += r[h]; - lc[a] += r[h]; - lc[b] += r[h]; - continue; - } - let mut gt = 0.0; - let mut gc = [0.0f64; 52]; - for &h in &ctx.order[s..e] { - let h = h as usize; - gt += r[h]; - gc[hands.cards[h][0] as usize] += r[h]; - gc[hands.cards[h][1] as usize] += r[h]; - } - for &h in &ctx.order[s..e] { - let h = h as usize; - let [a, b] = [hands.cards[h][0] as usize, hands.cards[h][1] as usize]; - let comp_less = less - lc[a] - lc[b]; - let comp_eq = gt - gc[a] - gc[b] + r[h]; - let comp_all = tot - tc[a] - tc[b] + r[h]; - let greater = comp_all - comp_less - comp_eq; - out[h] = win * comp_less - lose * greater + tie * comp_eq; - } - for &h in &ctx.order[s..e] { - let h = h as usize; - less += r[h]; - lc[hands.cards[h][0] as usize] += r[h]; - lc[hands.cards[h][1] as usize] += r[h]; - } - } - out -} - -struct Perm { - order: Vec, - pos: usize, -} - -/// State shared by the solver and the best-response evaluator. -struct Core<'a> { - g: &'a VecGame<'a>, - hands: Hands, - board: Vec, - ctxs: HashMap>, - perms: HashMap, - path: Vec, - rng: Rng, - enumerate: bool, - stratify: bool, - dead: f64, - root_street: Street, - bk_cache: HashMap<(u64, u8), Rc>>, - /// Root belief per player over the compact hands (regret weights of pooled infosets). - w: [Vec; 2], -} - -impl<'a> Core<'a> { - fn new(g: &'a VecGame<'a>, seed: u64, enumerate: bool, stratify: bool) -> Core<'a> { - let c0 = g.root.contributed(g.seats[0]) + g.root.contributed(g.seats[1]); - let hands = Hands::new(&g.ranges); - let w = [0, 1].map(|p| hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); - Core { - g, - w, - bk_cache: HashMap::new(), - hands, - board: g.board.to_vec(), - ctxs: HashMap::new(), - perms: HashMap::new(), - path: Vec::new(), - rng: Rng::new(seed), - enumerate, - stratify, - dead: (g.root.pot() - c0) as f64, - root_street: g.root.street(), - } - } - - /// Bucket of every compact hand on the current board and `street`. - fn buckets(&mut self, street: Street) -> Rc> { - let key = (mask_of(&self.board), street.idx() as u8); - if let Some(b) = self.bk_cache.get(&key) { - return b.clone(); - } - let pb = self.g.pooled.unwrap(); - let hl = holes(); - let bm = key.0; - // Hands blocked by the board are impossible (zero reach): any bucket will do. - let v: Vec = self - .hands - .idx - .iter() - .map(|&i| { - let h = hl[i as usize]; - if (bit(h[0]) | bit(h[1])) & bm != 0 { - 0 - } else { - pb.bucket(street, h, &self.board) - } - }) - .collect(); - let v = Rc::new(v); - self.bk_cache.insert(key, v.clone()); - v - } - - fn player_of(&self, seat: usize) -> usize { - (seat != self.g.seats[0]) as usize - } - - fn ctx(&mut self) -> Rc { - let key = mask_of(&self.board); - if let Some(c) = self.ctxs.get(&key) { - return c.clone(); - } - let c = Rc::new(Ctx::new(&self.hands, &self.board)); - self.ctxs.insert(key, c.clone()); - c - } - - /// Cards to branch on at a chance node with identity `key`, each with its weight. - fn deal(&mut self, key: u64) -> Vec<(Card, f64)> { - let used = mask_of(&self.board); - let free: Vec = (0..52u8).filter(|&c| used & bit(c) == 0).collect(); - let k = free.len() as f64; - if self.enumerate { - return free.iter().map(|&c| (c, 1.0 / (k - 4.0))).collect(); - } - let c = if self.stratify { - let p = self.perms.entry(key).or_insert(Perm { order: vec![], pos: 0 }); - if p.pos >= p.order.len() { - p.order = free.clone(); - self.rng.shuffle(&mut p.order); - p.pos = 0; - } - p.pos += 1; - p.order[p.pos - 1] - } else { - free[self.rng.below(free.len() as u32) as usize] - }; - vec![(c, k / (k - 4.0))] - } - - /// Terminal cfv vectors for both players: folds, or showdown (running out the board). - fn terminal(&mut self, st: &State, reach: [&[f64]; 2], key: u64) -> [Vec; 2] { - let g = self.g; - if !st.showdown() { - let [s0, s1] = g.seats; - let f = if st.is_folded(s0) { 0 } else { 1 }; - let w = 1 - f; - let cf = st.contributed(g.seats[f]) as f64; - let mut vf = compat(&self.hands, reach[w]); - let mut vw = compat(&self.hands, reach[f]); - vf.iter_mut().for_each(|x| *x *= -cf); - vw.iter_mut().for_each(|x| *x *= self.dead + cf); - let _ = (s0, s1); - let mut out = [Vec::new(), Vec::new()]; - out[f] = vf; - out[w] = vw; - return out; - } - if self.board.len() < 5 { - let m = self.hands.len(); - let mut out = [vec![0.0; m], vec![0.0; m]]; - for (c, w) in self.deal(mix(key, 0x7E4)) { - let r0 = self.masked(reach[0], c); - let r1 = self.masked(reach[1], c); - self.board.push(c); - let mut v = self.terminal(st, [&r0, &r1], mix(key, c as u64 + 1)); - self.board.pop(); - for p in 0..2 { - for &h in &self.hands.by_card[c as usize] { - v[p][h as usize] = 0.0; - } - for i in 0..m { - out[p][i] += w * v[p][i]; - } - } - } - return out; - } - let ctx = self.ctx(); - let c = st.contributed(g.seats[0]).min(st.contributed(g.seats[1])) as f64; - let (win, lose, tie) = (self.dead + c, c, self.dead / 2.0); - let mut v0 = showdown(&self.hands, &ctx, reach[1], win, lose, tie); - let mut v1 = showdown(&self.hands, &ctx, reach[0], win, lose, tie); - for i in 0..v0.len() { - if !ctx.valid[i] { - v0[i] = 0.0; - v1[i] = 0.0; - } - } - [v0, v1] - } - - fn masked(&self, r: &[f64], c: Card) -> Vec { - let mut v = r.to_vec(); - for &h in &self.hands.by_card[c as usize] { - v[h as usize] = 0.0; - } - v - } - - fn actions(&self, st: &State, akey: u64, list: &mut ActionList) { - if st.street() == self.root_street { - let ex: &[i32] = self.g.extras.get(&akey).map_or(&[], |v| v.as_slice()); - search_actions(st, self.g.sizing, ex, list); - } else { - search_actions(st, self.g.later, &[], list); - } - } -} - -struct VNode { - n: usize, - reg: Vec, - ssum: Vec, - root: bool, - player: u8, - /// Bucket count for pooled nodes (0 = per-hand node). - nb: usize, -} - -/// Solution of a vector solve: the root round's strategies per public node and hole pair. -pub struct VecSolution { - nodes: HashMap, - hands: Hands, - pub iters: u64, - pub millis: f64, - /// Bytes of regret / average storage allocated during the solve (peak, before dropping later rounds). - pub peak_bytes: usize, - /// Root reach per compact hand (belief) and `sum_t t`: the average strategy of a hand whose - /// accumulated own-path weight is a tiny fraction of the maximum is meaningless (the node is - /// practically never reached with it) and `probs` reports it as unavailable. - root_w: [Vec; 2], - total_t: f64, - root_street: Street, -} - -/// Minimum average own-path probability for the averaged strategy of a hand to be trusted. -const MIN_REACH: f64 = 1e-3; - -impl VecSolution { - /// Strategy of root-round node `path` for hole pair `hole` (index 0..1326): current regret - /// matching (`final_iterate`) or the weighted average. `false` if not available. - pub fn probs(&self, path: u64, hole: usize, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { - let Some(nd) = self.nodes.get(&path).filter(|nd| nd.n == n && nd.root) else { return false }; - let m = self.hands.of_hole[hole]; - if m == u32::MAX { - return false; - } - let (m, mm) = (m as usize, self.hands.len()); - if final_iterate { - let tot: f64 = (0..n).map(|a| nd.reg[a * mm + m].max(0.0)).sum(); - for a in 0..n { - out[a] = if tot > 0.0 { (nd.reg[a * mm + m].max(0.0) / tot) as f32 } else { 1.0 / n as f32 }; - } - true - } else { - let tot: f64 = (0..n).map(|a| nd.ssum[a * mm + m]).sum(); - if tot <= 0.0 || tot < MIN_REACH * self.root_w[nd.player as usize][m] * self.total_t { - return false; - } - for a in 0..n { - out[a] = (nd.ssum[a * mm + m] / tot) as f32; - } - true - } - } - pub fn nodes(&self) -> usize { - self.nodes.len() - } - pub fn hands(&self) -> &Hands { - &self.hands - } - /// Full-subgame strategy (needs `keep_all` at solve time) for exploitability evaluation. - pub fn strategy<'b>(&'b self, average: bool, pooled: Option<&'b dyn Bucketing>) -> impl Strat + 'b { - SolStrat { sol: self, average, pooled } - } -} - -#[derive(Clone, Copy, Debug)] -pub struct VecParams { - pub iters: u64, - pub max_millis: Option, - /// CFR+ style (regrets floored at 0, unweighted) instead of Linear CFR. - pub plus: bool, - pub stratify: bool, - pub seed: u64, - /// Keep every street's strategies (default: root round only, to save memory). - pub keep_all: bool, - /// Stop the solve (keeping the passes done) once node storage exceeds this many bytes. - pub max_bytes: usize, -} - -impl Default for VecParams { - fn default() -> Self { - VecParams { iters: 300, max_millis: None, plus: false, stratify: true, seed: 1, keep_all: false, max_bytes: 3 << 30 } - } -} - -struct Solver<'a> { - core: Core<'a>, - nodes: HashMap, - t: f64, - plus: bool, - frozen_m: Option, - bytes: usize, -} - -pub fn solve_vec(g: &VecGame, p: &VecParams) -> VecSolution { - let start = Instant::now(); - let core = Core::new(g, p.seed, false, p.stratify); - let frozen_m = g.my_hole.and_then(|h| match core.hands.of_hole[h] { - u32::MAX => None, - m => Some(m as usize), - }); - let mut sv = Solver { core, nodes: HashMap::new(), t: 0.0, plus: p.plus, frozen_m, bytes: 0 }; - let r0: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[0][i as usize]).collect(); - let r1: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[1][i as usize]).collect(); - let root = g.root; - let mut done = 0; - if !root.is_terminal() && !sv.core.hands.is_empty() { - for t in 1..=p.iters { - sv.t = t as f64; - sv.walk(&root, 0, 0, [&r0, &r1]); - done = t; - if sv.bytes > p.max_bytes { - break; - } - if p.max_millis.is_some_and(|ms| start.elapsed().as_millis() as u64 >= ms) { - break; - } - } - } - let sv_bytes = sv.bytes; - let mut nodes = sv.nodes; - if !p.keep_all { - nodes.retain(|_, v| v.root); - } - let root_w = [0, 1].map(|p| sv.core.hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); - let total_t = done as f64 * (done as f64 + 1.0) / 2.0; - VecSolution { nodes, hands: sv.core.hands, iters: done, millis: start.elapsed().as_secs_f64() * 1e3, peak_bytes: sv_bytes, root_w, total_t, root_street: g.root.street() } -} - -fn finish(p: usize, q: usize, vp: Vec, vq: Vec) -> [Vec; 2] { - let mut out = [Vec::new(), Vec::new()]; - out[p] = vp; - out[q] = vq; - out -} - -impl<'a> Solver<'a> { - fn walk(&mut self, st: &State, akey: u64, vkey: u64, reach: [&[f64]; 2]) -> [Vec; 2] { - let g = self.core.g; - let m = self.core.hands.len(); - let seat = st.to_act().unwrap(); - let p = self.core.player_of(seat); - let q = 1 - p; - let mut list = ActionList::new(); - self.core.actions(st, akey, &mut list); - let n = list.len(); - let is_root = st.street() == self.core.root_street; - let pooled = !is_root && g.pooled.is_some(); - let bk: Option>> = if pooled { Some(self.core.buckets(st.street())) } else { None }; - let nb = if pooled { g.pooled.unwrap().n_buckets(st.street()) } else { 0 }; - let nkey = if pooled { mix(akey, 0xB0C7) } else { vkey }; - let width = if pooled { nb } else { m }; - let mut fresh = 0usize; - let _node = self.nodes.entry(nkey).or_insert_with(|| { - fresh = 16 * n * width; - VNode { n, reg: vec![0.0; n * width], ssum: vec![0.0; n * width], root: is_root, player: p as u8, nb } - }); - self.bytes += fresh; - let node = self.nodes.get_mut(&nkey).unwrap(); - debug_assert_eq!(node.n, n); - // Regret matching (action-major loops over contiguous slices); pooled nodes first per - // bucket, then expanded to the hands. - let mut sigb = vec![0.0f64; n * width]; - let mut tot = vec![0.0f64; width]; - for a in 0..n { - for (t, &r) in tot.iter_mut().zip(&node.reg[a * width..(a + 1) * width]) { - *t += r.max(0.0); - } - } - let uni = 1.0 / n as f64; - for a in 0..n { - for ((s, &r), &t) in sigb[a * width..(a + 1) * width].iter_mut().zip(&node.reg[a * width..(a + 1) * width]).zip(&tot) { - *s = if t > 0.0 { r.max(0.0) / t } else { uni }; - } - } - let mut sig = if let Some(bk) = &bk { - let mut v = vec![0.0f64; n * m]; - for a in 0..n { - for (x, &b) in v[a * m..(a + 1) * m].iter_mut().zip(bk.iter()) { - *x = sigb[a * nb + b as usize]; - } - } - v - } else { - std::mem::take(&mut sigb) - }; - // Our own earlier action this round is fixed for our actual hand. - let mut frozen_h = None; - let mut frozen_f = 0usize; - if is_root && Some(p) == g.me { - if let (Some(h), Some(fa)) = (self.frozen_m, g.frozen.get(&akey)) { - if let Some(f) = list.as_slice().iter().position(|a| a == fa) { - for a in 0..n { - sig[a * m + h] = (a == f) as u8 as f64; - } - frozen_h = Some(h); - frozen_f = f; - } - } - } - let mut vp = vec![0.0; m]; - let mut vq = vec![0.0; m]; - let mut cps: Vec> = Vec::with_capacity(n); - for a in 0..n { - let act = list.get(a); - let mut s2 = *st; - let step = s2.apply(act); - let nr: Vec = reach[p].iter().zip(&sig[a * m..(a + 1) * m]).map(|(r, s)| r * s).collect(); - let mut r2 = reach; - r2[p] = &nr; - let akey2 = step_path(akey, act); - let vkey2 = step_path(vkey, act); - let mut c = match step { - Step::Terminal => self.core.terminal(&s2, r2, vkey2), - Step::NewStreet(_) => self.chance(&s2, akey2, vkey2, r2), - Step::Continue => self.walk(&s2, akey2, vkey2, r2), - }; - for ((v, &s), &x) in vp.iter_mut().zip(&sig[a * m..(a + 1) * m]).zip(&c[p]) { - *v += s * x; - } - for (v, &x) in vq.iter_mut().zip(&c[q]) { - *v += x; - } - cps.push(std::mem::take(&mut c[p])); - } - let t = self.t; - let plus = self.plus; - let node = self.nodes.get_mut(&nkey).unwrap(); - if let Some(bk) = &bk { - let w = &self.core.w[p]; - let mut rsum = vec![0.0f64; nb]; - for (&b, &r) in bk.iter().zip(reach[p]) { - rsum[b as usize] += r; - } - let mut delta = vec![0.0f64; nb]; - for a in 0..n { - delta.iter_mut().for_each(|x| *x = 0.0); - for (((&b, &c), &v), &wt) in bk.iter().zip(&cps[a]).zip(&vp).zip(w) { - delta[b as usize] += wt * (c - v); - } - let (reg, ss) = (&mut node.reg[a * nb..(a + 1) * nb], &mut node.ssum[a * nb..(a + 1) * nb]); - for b in 0..nb { - reg[b] = if plus { (reg[b] + delta[b]).max(0.0) } else { reg[b] + t * delta[b] }; - ss[b] += t * rsum[b] * sigb[a * nb + b]; - } - } - return finish(p, q, vp, vq); - } - for a in 0..n { - let (reg, ss) = (&mut node.reg[a * m..(a + 1) * m], &mut node.ssum[a * m..(a + 1) * m]); - let (cp, sg) = (&cps[a], &sig[a * m..(a + 1) * m]); - let keep = frozen_h.map(|h| (h, reg[h])); - if plus { - for (((r, &c), &v), (x, (&rp, &s))) in reg.iter_mut().zip(cp).zip(&vp).zip(ss.iter_mut().zip(reach[p].iter().zip(sg))) { - *r = (*r + c - v).max(0.0); - *x += t * rp * s; - } - } else { - for (((r, &c), &v), (x, (&rp, &s))) in reg.iter_mut().zip(cp).zip(&vp).zip(ss.iter_mut().zip(reach[p].iter().zip(sg))) { - *r += t * (c - v); - *x += t * rp * s; - } - } - if let Some((h, _)) = keep { - // Readers of the final iterate see the pinned pure action. - reg[h] = (a == frozen_f) as u8 as f64; - } - } - finish(p, q, vp, vq) - } - - /// A new street opens: branch on the next board card(s). - fn chance(&mut self, st: &State, akey: u64, vkey: u64, reach: [&[f64]; 2]) -> [Vec; 2] { - let m = self.core.hands.len(); - let mut out = [vec![0.0; m], vec![0.0; m]]; - for (c, w) in self.core.deal(vkey) { - let r0 = self.core.masked(reach[0], c); - let r1 = self.core.masked(reach[1], c); - self.core.board.push(c); - let mut v = self.walk(st, akey, mix(vkey, c as u64 + 1), [&r0, &r1]); - self.core.board.pop(); - for p in 0..2 { - for &h in &self.core.hands.by_card[c as usize] { - v[p][h as usize] = 0.0; - } - for i in 0..m { - out[p][i] += w * v[p][i]; - } - } - } - out - } -} - -// --------------------------------------------------------------------------------------------- -// Exact best response / exploitability -// --------------------------------------------------------------------------------------------- - -/// Where in the subgame a strategy is queried. -pub struct Query<'a> { - pub akey: u64, - pub vkey: u64, - pub street: Street, - pub board: &'a [Card], - pub seat: usize, - pub hands: &'a Hands, - /// Decision state and the actions taken since the subgame root. - pub st: &'a State, - pub path: &'a [Action], -} - -/// A complete strategy profile: fill `out[a*M + m]` (M = number of compact hands) for the -/// acting player at the queried node. -pub trait Strat { - fn probs(&self, q: &Query, n: usize, out: &mut [f64]); -} - -struct SolStrat<'a> { - sol: &'a VecSolution, - average: bool, - pooled: Option<&'a dyn Bucketing>, -} - -impl Strat for SolStrat<'_> { - fn probs(&self, q: &Query, n: usize, out: &mut [f64]) { - let m = q.hands.len(); - let uni = |out: &mut [f64]| out.iter_mut().for_each(|x| *x = 1.0 / n as f64); - let pooled = q.street != self.sol.root_street && self.pooled.is_some(); - let key = if pooled { mix(q.akey, 0xB0C7) } else { q.vkey }; - let Some(nd) = self.sol.nodes.get(&key).filter(|nd| nd.n == n) else { return uni(out) }; - let pick = |a: usize, w: usize| -> f64 { if self.average { nd.ssum[a * (if pooled { nd.nb } else { m }) + w] } else { nd.reg[a * (if pooled { nd.nb } else { m }) + w].max(0.0) } }; - let hl = holes(); - for h in 0..m { - let w = if pooled { self.pooled.unwrap().bucket(q.street, hl[q.hands.idx[h] as usize], q.board) as usize } else { h }; - let tot: f64 = (0..n).map(|a| pick(a, w)).sum(); - for a in 0..n { - out[a * m + h] = if tot > 0.0 { pick(a, w) / tot } else { 1.0 / n as f64 }; - } - } - } -} - -/// Exact best-response values. Returns `(exploitability, [br0, br1], z)` in chips: the mean of -/// both players' best-response gains over the equilibrium value, normalised by the compatible -/// range mass. -pub fn exploitability(g: &VecGame, s: &dyn Strat) -> (f64, [f64; 2]) { - let mut core = Core::new(g, 0, true, false); - let m = core.hands.len(); - let r: [Vec; 2] = [0, 1].map(|p| core.hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); - let comp = compat(&core.hands, &r[1]); - let z: f64 = (0..m).map(|h| r[0][h] * comp[h]).sum(); - let mut br = [0.0; 2]; - for p in 0..2 { - let v = core.br(g.root, 0, 0, p, &r[1 - p], s); - br[p] = (0..m).map(|h| r[p][h] * v[h]).sum::() / z; - } - let dead = core.dead; - (((br[0] + br[1]) - dead) / 2.0, br) -} - -impl<'a> Core<'a> { - /// Best-response cfv of player `p` against `s` for the other player, given the opponent's reach. - fn br(&mut self, st: State, akey: u64, vkey: u64, p: usize, opp: &[f64], s: &dyn Strat) -> Vec { - let m = self.hands.len(); - let q = 1 - p; - let seat = st.to_act().unwrap(); - let mut list = ActionList::new(); - self.actions(&st, akey, &mut list); - let n = list.len(); - let actor = self.player_of(seat); - let mut sig = vec![0.0f64; if actor == p { 0 } else { n * m }]; - if actor == q { - let hands = std::mem::replace(&mut self.hands, Hands { idx: vec![], cards: vec![], of_hole: vec![], by_card: vec![] }); - { - let board = self.board.clone(); - let qy = Query { akey, vkey, street: st.street(), board: &board, seat, hands: &hands, st: &st, path: &self.path }; - s.probs(&qy, n, &mut sig); - } - self.hands = hands; - } - let dummy = vec![0.0; m]; - let mut best = vec![f64::NEG_INFINITY; m]; - let mut sum = vec![0.0; m]; - for a in 0..n { - let act = list.get(a); - let mut s2 = st; - let step = s2.apply(act); - let nr: Vec = if actor == q { (0..m).map(|h| opp[h] * sig[a * m + h]).collect() } else { opp.to_vec() }; - let akey2 = step_path(akey, act); - let vkey2 = step_path(vkey, act); - self.path.push(act); - let c = match step { - Step::Terminal => { - let mut reach: [&[f64]; 2] = [&dummy, &dummy]; - reach[q] = &nr; - let mut v = self.terminal(&s2, reach, vkey2); - std::mem::take(&mut v[p]) - } - Step::NewStreet(_) => { - let mut acc = vec![0.0; m]; - for (cd, w) in self.deal(vkey2) { - let nrm = self.masked(&nr, cd); - self.board.push(cd); - let mut v = self.br(s2, akey2, mix(vkey2, cd as u64 + 1), p, &nrm, s); - self.board.pop(); - for &h in &self.hands.by_card[cd as usize] { - v[h as usize] = 0.0; - } - for i in 0..m { - acc[i] += w * v[i]; - } - } - acc - } - Step::Continue => self.br(s2, akey2, vkey2, p, &nr, s), - }; - self.path.pop(); - if actor == p { - for h in 0..m { - best[h] = best[h].max(c[h]); - } - } else { - for h in 0..m { - sum[h] += c[h]; - } - } - } - if actor == p { - best - } else { - sum - } - } -} - -pub const _MAX: usize = MAX_ACTIONS; +//! Vector-form Linear CFR for heads-up subgames (supplement: "an optimized vector-based form of +//! Linear CFR ... that samples one set of public board cards per thread"), plus an exact best +//! response / exploitability evaluator on the same tree. +//! +//! Instead of sampling one pair of hole hands per traversal (`solver.rs`, external sampling) a +//! pass walks the betting tree ONCE with a reach vector over all live hole pairs per player +//! and returns counterfactual-value vectors; card removal at terminals is O(M) by +//! inclusion-exclusion over the two hole cards. Public chance (the next board card) is sampled, +//! stratified by cycling a shuffled deck per chance node, so a node below chance node `c` is +//! visited every ~k-th pass. Infosets are `(public node incl. board cards, exact hole pair)`: +//! no card abstraction anywhere in the subgame. +//! +//! Utilities: dead money from players who folded before the root is respected (winner takes +//! the pot), so the game is constant-sum (`u0 + u1 = dead`), not zero-sum. +//! +//! Conventions: player index 0/1 = `seats[0]/seats[1]`. Values are chips relative to the start +//! of the hand. Chance weights: sampling one of `k` unseen cards with weight `k/(k-4)` and +//! enumerating with weight `1/(k-4)` both give the conditional expectation over the `k-4` +//! cards not blocked by the two holes. + +use crate::beliefs::holes; +use crate::tree::{search_actions, step_path, Extras}; +use bench::mix; +use cards::{bit, evaluate, mask_of, Card, Rng}; +use nlhe::abstraction::{ActionList, BetSizing, MAX_ACTIONS}; +use nlhe::{Action, State, Step, Street}; +use std::collections::HashMap; +use std::rc::Rc; +use std::time::Instant; + +pub const N: usize = 1326; + +/// Live hole pairs of the subgame (positive root reach for either player), compacted. +pub struct Hands { + pub idx: Vec, + pub cards: Vec<[u8; 2]>, + /// Hole index (0..1326) -> compact index, `u32::MAX` if absent. + pub of_hole: Vec, + /// Compact indices of the hands containing card `c`. + pub by_card: Vec>, +} + +impl Hands { + fn new(ranges: &[Vec; 2]) -> Hands { + let hl = holes(); + let mut idx = Vec::new(); + let mut cards = Vec::new(); + let mut of_hole = vec![u32::MAX; N]; + let mut by_card = vec![Vec::new(); 52]; + for i in 0..N { + if ranges[0][i] > 0.0 || ranges[1][i] > 0.0 { + of_hole[i] = idx.len() as u32; + for &c in &hl[i] { + by_card[c as usize].push(idx.len() as u32); + } + idx.push(i as u16); + cards.push(hl[i]); + } + } + Hands { idx, cards, of_hole, by_card } + } + pub fn len(&self) -> usize { + self.idx.len() + } + pub fn is_empty(&self) -> bool { + self.idx.is_empty() + } +} + +/// Card abstraction for the rounds after the root round (pooled infosets shared by every board +/// runout, exactly like the blueprint's keys). +pub trait Bucketing { + fn bucket(&self, street: Street, hole: [Card; 2], board: &[Card]) -> u32; + fn n_buckets(&self, street: Street) -> usize; +} + +/// A heads-up subgame instance. +pub struct VecGame<'a> { + pub root: State, + /// Board visible at the root (3, 4 or 5 cards). + pub board: &'a [Card], + /// Player index -> seat. + pub seats: [usize; 2], + /// Root reach per player over all 1326 holes (must already exclude board-blocked hands). + pub ranges: [Vec; 2], + pub sizing: &'a BetSizing, + pub later: &'a BetSizing, + pub extras: &'a Extras, + /// Our player index, our actual hole index and the actions we took already this round. + pub me: Option, + pub my_hole: Option, + pub frozen: &'a HashMap, + /// `Some`: rounds after the root round use bucket-pooled infosets (regrets aggregated over + /// the hands of a bucket weighted by the root belief); the root round stays lossless. + pub pooled: Option<&'a dyn Bucketing>, +} + +impl<'a> VecGame<'a> { + /// Both live seats of `root` (None unless exactly two are live and the state is a decision). + pub fn live_seats(root: &State) -> Option<[usize; 2]> { + if root.is_terminal() || root.live_count() != 2 { + return None; + } + let v: Vec = (0..root.num_players()).filter(|&s| !root.is_folded(s)).collect(); + Some([v[0], v[1]]) + } +} + +/// Per-board showdown data over the compact hand list. +struct Ctx { + valid: Vec, + order: Vec, + groups: Vec<(usize, usize)>, +} + +impl Ctx { + fn new(hands: &Hands, board: &[Card]) -> Ctx { + let bm = mask_of(board); + let m = hands.len(); + let mut valid = vec![false; m]; + let mut rank = vec![0u32; m]; + for i in 0..m { + let h = hands.cards[i]; + if bit(h[0]) & bm == 0 && bit(h[1]) & bm == 0 { + valid[i] = true; + rank[i] = evaluate(bit(h[0]) | bit(h[1]) | bm); + } + } + let mut order: Vec = (0..m as u32).filter(|&i| valid[i as usize]).collect(); + order.sort_by_key(|&i| rank[i as usize]); + let mut groups = Vec::new(); + let mut s = 0; + for i in 1..=order.len() { + if i == order.len() || rank[order[i] as usize] != rank[order[s] as usize] { + groups.push((s, i)); + s = i; + } + } + Ctx { valid, order, groups } + } +} + +fn card_sums(hands: &Hands, r: &[f64]) -> (f64, [f64; 52]) { + let mut t = 0.0; + let mut c = [0.0; 52]; + for i in 0..r.len() { + let x = r[i]; + if x != 0.0 { + t += x; + c[hands.cards[i][0] as usize] += x; + c[hands.cards[i][1] as usize] += x; + } + } + (t, c) +} + +/// `out[i]` = sum of `r[j]` over hands `j` sharing no card with hand `i`. +fn compat(hands: &Hands, r: &[f64]) -> Vec { + let (t, c) = card_sums(hands, r); + (0..r.len()) + .map(|i| { + let [a, b] = hands.cards[i]; + t - c[a as usize] - c[b as usize] + r[i] + }) + .collect() +} + +/// Showdown cfv of the holder: `win*P(>) - lose*P(<) + tie*P(=)` weighted by opponent reach. +fn showdown(hands: &Hands, ctx: &Ctx, r: &[f64], win: f64, lose: f64, tie: f64) -> Vec { + let (tot, tc) = card_sums(hands, r); + let mut less = 0.0; + let mut lc = [0.0f64; 52]; + let mut out = vec![0.0; r.len()]; + for &(s, e) in &ctx.groups { + if e - s == 1 { + // Singleton tie group: no equal-rank hands to account for. + let h = ctx.order[s] as usize; + let [a, b] = [hands.cards[h][0] as usize, hands.cards[h][1] as usize]; + let comp_less = less - lc[a] - lc[b]; + let comp_all = tot - tc[a] - tc[b] + r[h]; + out[h] = win * comp_less - lose * (comp_all - comp_less); + less += r[h]; + lc[a] += r[h]; + lc[b] += r[h]; + continue; + } + let mut gt = 0.0; + let mut gc = [0.0f64; 52]; + for &h in &ctx.order[s..e] { + let h = h as usize; + gt += r[h]; + gc[hands.cards[h][0] as usize] += r[h]; + gc[hands.cards[h][1] as usize] += r[h]; + } + for &h in &ctx.order[s..e] { + let h = h as usize; + let [a, b] = [hands.cards[h][0] as usize, hands.cards[h][1] as usize]; + let comp_less = less - lc[a] - lc[b]; + let comp_eq = gt - gc[a] - gc[b] + r[h]; + let comp_all = tot - tc[a] - tc[b] + r[h]; + let greater = comp_all - comp_less - comp_eq; + out[h] = win * comp_less - lose * greater + tie * comp_eq; + } + for &h in &ctx.order[s..e] { + let h = h as usize; + less += r[h]; + lc[hands.cards[h][0] as usize] += r[h]; + lc[hands.cards[h][1] as usize] += r[h]; + } + } + out +} + +struct Perm { + order: Vec, + pos: usize, +} + +/// State shared by the solver and the best-response evaluator. +struct Core<'a> { + g: &'a VecGame<'a>, + hands: Hands, + board: Vec, + ctxs: HashMap>, + perms: HashMap, + path: Vec, + rng: Rng, + enumerate: bool, + stratify: bool, + dead: f64, + root_street: Street, + bk_cache: HashMap<(u64, u8), Rc>>, + /// Root belief per player over the compact hands (regret weights of pooled infosets). + w: [Vec; 2], +} + +impl<'a> Core<'a> { + fn new(g: &'a VecGame<'a>, seed: u64, enumerate: bool, stratify: bool) -> Core<'a> { + let c0 = g.root.contributed(g.seats[0]) + g.root.contributed(g.seats[1]); + let hands = Hands::new(&g.ranges); + let w = [0, 1].map(|p| hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); + Core { + g, + w, + bk_cache: HashMap::new(), + hands, + board: g.board.to_vec(), + ctxs: HashMap::new(), + perms: HashMap::new(), + path: Vec::new(), + rng: Rng::new(seed), + enumerate, + stratify, + dead: (g.root.pot() - c0) as f64, + root_street: g.root.street(), + } + } + + /// Bucket of every compact hand on the current board and `street`. + fn buckets(&mut self, street: Street) -> Rc> { + let key = (mask_of(&self.board), street.idx() as u8); + if let Some(b) = self.bk_cache.get(&key) { + return b.clone(); + } + let pb = self.g.pooled.unwrap(); + let hl = holes(); + let bm = key.0; + // Hands blocked by the board are impossible (zero reach): any bucket will do. + let v: Vec = self + .hands + .idx + .iter() + .map(|&i| { + let h = hl[i as usize]; + if (bit(h[0]) | bit(h[1])) & bm != 0 { + 0 + } else { + pb.bucket(street, h, &self.board) + } + }) + .collect(); + let v = Rc::new(v); + self.bk_cache.insert(key, v.clone()); + v + } + + fn player_of(&self, seat: usize) -> usize { + (seat != self.g.seats[0]) as usize + } + + fn ctx(&mut self) -> Rc { + let key = mask_of(&self.board); + if let Some(c) = self.ctxs.get(&key) { + return c.clone(); + } + let c = Rc::new(Ctx::new(&self.hands, &self.board)); + self.ctxs.insert(key, c.clone()); + c + } + + /// Cards to branch on at a chance node with identity `key`, each with its weight. + fn deal(&mut self, key: u64) -> Vec<(Card, f64)> { + let used = mask_of(&self.board); + let free: Vec = (0..52u8).filter(|&c| used & bit(c) == 0).collect(); + let k = free.len() as f64; + if self.enumerate { + return free.iter().map(|&c| (c, 1.0 / (k - 4.0))).collect(); + } + let c = if self.stratify { + let p = self.perms.entry(key).or_insert(Perm { order: vec![], pos: 0 }); + if p.pos >= p.order.len() { + p.order = free.clone(); + self.rng.shuffle(&mut p.order); + p.pos = 0; + } + p.pos += 1; + p.order[p.pos - 1] + } else { + free[self.rng.below(free.len() as u32) as usize] + }; + vec![(c, k / (k - 4.0))] + } + + /// Terminal cfv vectors for both players: folds, or showdown (running out the board). + fn terminal(&mut self, st: &State, reach: [&[f64]; 2], key: u64) -> [Vec; 2] { + let g = self.g; + if !st.showdown() { + let [s0, s1] = g.seats; + let f = if st.is_folded(s0) { 0 } else { 1 }; + let w = 1 - f; + let cf = st.contributed(g.seats[f]) as f64; + let mut vf = compat(&self.hands, reach[w]); + let mut vw = compat(&self.hands, reach[f]); + vf.iter_mut().for_each(|x| *x *= -cf); + vw.iter_mut().for_each(|x| *x *= self.dead + cf); + let _ = (s0, s1); + let mut out = [Vec::new(), Vec::new()]; + out[f] = vf; + out[w] = vw; + return out; + } + if self.board.len() < 5 { + let m = self.hands.len(); + let mut out = [vec![0.0; m], vec![0.0; m]]; + for (c, w) in self.deal(mix(key, 0x7E4)) { + let r0 = self.masked(reach[0], c); + let r1 = self.masked(reach[1], c); + self.board.push(c); + let mut v = self.terminal(st, [&r0, &r1], mix(key, c as u64 + 1)); + self.board.pop(); + for p in 0..2 { + for &h in &self.hands.by_card[c as usize] { + v[p][h as usize] = 0.0; + } + for i in 0..m { + out[p][i] += w * v[p][i]; + } + } + } + return out; + } + let ctx = self.ctx(); + let c = st.contributed(g.seats[0]).min(st.contributed(g.seats[1])) as f64; + let (win, lose, tie) = (self.dead + c, c, self.dead / 2.0); + let mut v0 = showdown(&self.hands, &ctx, reach[1], win, lose, tie); + let mut v1 = showdown(&self.hands, &ctx, reach[0], win, lose, tie); + for i in 0..v0.len() { + if !ctx.valid[i] { + v0[i] = 0.0; + v1[i] = 0.0; + } + } + [v0, v1] + } + + fn masked(&self, r: &[f64], c: Card) -> Vec { + let mut v = r.to_vec(); + for &h in &self.hands.by_card[c as usize] { + v[h as usize] = 0.0; + } + v + } + + fn actions(&self, st: &State, akey: u64, list: &mut ActionList) { + if st.street() == self.root_street { + let ex: &[i32] = self.g.extras.get(&akey).map_or(&[], |v| v.as_slice()); + search_actions(st, self.g.sizing, ex, list); + } else { + search_actions(st, self.g.later, &[], list); + } + } +} + +struct VNode { + n: usize, + reg: Vec, + ssum: Vec, + root: bool, + player: u8, + /// Bucket count for pooled nodes (0 = per-hand node). + nb: usize, +} + +/// Solution of a vector solve: the root round's strategies per public node and hole pair. +pub struct VecSolution { + nodes: HashMap, + hands: Hands, + pub iters: u64, + pub millis: f64, + /// Bytes of regret / average storage allocated during the solve (peak, before dropping later rounds). + pub peak_bytes: usize, + /// Root reach per compact hand (belief) and `sum_t t`: the average strategy of a hand whose + /// accumulated own-path weight is a tiny fraction of the maximum is meaningless (the node is + /// practically never reached with it) and `probs` reports it as unavailable. + root_w: [Vec; 2], + total_t: f64, + root_street: Street, +} + +/// Minimum average own-path probability for the averaged strategy of a hand to be trusted. +const MIN_REACH: f64 = 1e-3; + +impl VecSolution { + /// Strategy of root-round node `path` for hole pair `hole` (index 0..1326): current regret + /// matching (`final_iterate`) or the weighted average. `false` if not available. + pub fn probs(&self, path: u64, hole: usize, n: usize, final_iterate: bool, out: &mut [f32]) -> bool { + let Some(nd) = self.nodes.get(&path).filter(|nd| nd.n == n && nd.root) else { return false }; + let m = self.hands.of_hole[hole]; + if m == u32::MAX { + return false; + } + let (m, mm) = (m as usize, self.hands.len()); + if final_iterate { + let tot: f64 = (0..n).map(|a| nd.reg[a * mm + m].max(0.0)).sum(); + for a in 0..n { + out[a] = if tot > 0.0 { (nd.reg[a * mm + m].max(0.0) / tot) as f32 } else { 1.0 / n as f32 }; + } + true + } else { + let tot: f64 = (0..n).map(|a| nd.ssum[a * mm + m]).sum(); + if tot <= 0.0 || tot < MIN_REACH * self.root_w[nd.player as usize][m] * self.total_t { + return false; + } + for a in 0..n { + out[a] = (nd.ssum[a * mm + m] / tot) as f32; + } + true + } + } + pub fn nodes(&self) -> usize { + self.nodes.len() + } + pub fn hands(&self) -> &Hands { + &self.hands + } + /// Full-subgame strategy (needs `keep_all` at solve time) for exploitability evaluation. + pub fn strategy<'b>(&'b self, average: bool, pooled: Option<&'b dyn Bucketing>) -> impl Strat + 'b { + SolStrat { sol: self, average, pooled } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct VecParams { + pub iters: u64, + pub max_millis: Option, + /// CFR+ style (regrets floored at 0, unweighted) instead of Linear CFR. + pub plus: bool, + pub stratify: bool, + pub seed: u64, + /// Keep every street's strategies (default: root round only, to save memory). + pub keep_all: bool, + /// Stop the solve (keeping the passes done) once node storage exceeds this many bytes. + pub max_bytes: usize, +} + +impl Default for VecParams { + fn default() -> Self { + VecParams { iters: 300, max_millis: None, plus: false, stratify: true, seed: 1, keep_all: false, max_bytes: 3 << 30 } + } +} + +struct Solver<'a> { + core: Core<'a>, + nodes: HashMap, + t: f64, + plus: bool, + frozen_m: Option, + bytes: usize, +} + +pub fn solve_vec(g: &VecGame, p: &VecParams) -> VecSolution { + let start = Instant::now(); + let core = Core::new(g, p.seed, false, p.stratify); + let frozen_m = g.my_hole.and_then(|h| match core.hands.of_hole[h] { + u32::MAX => None, + m => Some(m as usize), + }); + let mut sv = Solver { core, nodes: HashMap::new(), t: 0.0, plus: p.plus, frozen_m, bytes: 0 }; + let r0: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[0][i as usize]).collect(); + let r1: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[1][i as usize]).collect(); + let root = g.root; + let mut done = 0; + if !root.is_terminal() && !sv.core.hands.is_empty() { + for t in 1..=p.iters { + sv.t = t as f64; + sv.walk(&root, 0, 0, [&r0, &r1]); + done = t; + if sv.bytes > p.max_bytes { + break; + } + if p.max_millis.is_some_and(|ms| start.elapsed().as_millis() as u64 >= ms) { + break; + } + } + } + let sv_bytes = sv.bytes; + let mut nodes = sv.nodes; + if !p.keep_all { + nodes.retain(|_, v| v.root); + } + let root_w = [0, 1].map(|p| sv.core.hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); + let total_t = done as f64 * (done as f64 + 1.0) / 2.0; + VecSolution { nodes, hands: sv.core.hands, iters: done, millis: start.elapsed().as_secs_f64() * 1e3, peak_bytes: sv_bytes, root_w, total_t, root_street: g.root.street() } +} + +fn finish(p: usize, q: usize, vp: Vec, vq: Vec) -> [Vec; 2] { + let mut out = [Vec::new(), Vec::new()]; + out[p] = vp; + out[q] = vq; + out +} + +impl<'a> Solver<'a> { + fn walk(&mut self, st: &State, akey: u64, vkey: u64, reach: [&[f64]; 2]) -> [Vec; 2] { + let g = self.core.g; + let m = self.core.hands.len(); + let seat = st.to_act().unwrap(); + let p = self.core.player_of(seat); + let q = 1 - p; + let mut list = ActionList::new(); + self.core.actions(st, akey, &mut list); + let n = list.len(); + let is_root = st.street() == self.core.root_street; + let pooled = !is_root && g.pooled.is_some(); + let bk: Option>> = if pooled { Some(self.core.buckets(st.street())) } else { None }; + let nb = if pooled { g.pooled.unwrap().n_buckets(st.street()) } else { 0 }; + let nkey = if pooled { mix(akey, 0xB0C7) } else { vkey }; + let width = if pooled { nb } else { m }; + let mut fresh = 0usize; + let _node = self.nodes.entry(nkey).or_insert_with(|| { + fresh = 16 * n * width; + VNode { n, reg: vec![0.0; n * width], ssum: vec![0.0; n * width], root: is_root, player: p as u8, nb } + }); + self.bytes += fresh; + let node = self.nodes.get_mut(&nkey).unwrap(); + debug_assert_eq!(node.n, n); + // Regret matching (action-major loops over contiguous slices); pooled nodes first per + // bucket, then expanded to the hands. + let mut sigb = vec![0.0f64; n * width]; + let mut tot = vec![0.0f64; width]; + for a in 0..n { + for (t, &r) in tot.iter_mut().zip(&node.reg[a * width..(a + 1) * width]) { + *t += r.max(0.0); + } + } + let uni = 1.0 / n as f64; + for a in 0..n { + for ((s, &r), &t) in sigb[a * width..(a + 1) * width].iter_mut().zip(&node.reg[a * width..(a + 1) * width]).zip(&tot) { + *s = if t > 0.0 { r.max(0.0) / t } else { uni }; + } + } + let mut sig = if let Some(bk) = &bk { + let mut v = vec![0.0f64; n * m]; + for a in 0..n { + for (x, &b) in v[a * m..(a + 1) * m].iter_mut().zip(bk.iter()) { + *x = sigb[a * nb + b as usize]; + } + } + v + } else { + std::mem::take(&mut sigb) + }; + // Our own earlier action this round is fixed for our actual hand. + let mut frozen_h = None; + let mut frozen_f = 0usize; + if is_root && Some(p) == g.me { + if let (Some(h), Some(fa)) = (self.frozen_m, g.frozen.get(&akey)) { + if let Some(f) = list.as_slice().iter().position(|a| a == fa) { + for a in 0..n { + sig[a * m + h] = (a == f) as u8 as f64; + } + frozen_h = Some(h); + frozen_f = f; + } + } + } + let mut vp = vec![0.0; m]; + let mut vq = vec![0.0; m]; + let mut cps: Vec> = Vec::with_capacity(n); + for a in 0..n { + let act = list.get(a); + let mut s2 = *st; + let step = s2.apply(act); + let nr: Vec = reach[p].iter().zip(&sig[a * m..(a + 1) * m]).map(|(r, s)| r * s).collect(); + let mut r2 = reach; + r2[p] = &nr; + let akey2 = step_path(akey, act); + let vkey2 = step_path(vkey, act); + let mut c = match step { + Step::Terminal => self.core.terminal(&s2, r2, vkey2), + Step::NewStreet(_) => self.chance(&s2, akey2, vkey2, r2), + Step::Continue => self.walk(&s2, akey2, vkey2, r2), + }; + for ((v, &s), &x) in vp.iter_mut().zip(&sig[a * m..(a + 1) * m]).zip(&c[p]) { + *v += s * x; + } + for (v, &x) in vq.iter_mut().zip(&c[q]) { + *v += x; + } + cps.push(std::mem::take(&mut c[p])); + } + let t = self.t; + let plus = self.plus; + let node = self.nodes.get_mut(&nkey).unwrap(); + if let Some(bk) = &bk { + let w = &self.core.w[p]; + let mut rsum = vec![0.0f64; nb]; + for (&b, &r) in bk.iter().zip(reach[p]) { + rsum[b as usize] += r; + } + let mut delta = vec![0.0f64; nb]; + for a in 0..n { + delta.iter_mut().for_each(|x| *x = 0.0); + for (((&b, &c), &v), &wt) in bk.iter().zip(&cps[a]).zip(&vp).zip(w) { + delta[b as usize] += wt * (c - v); + } + let (reg, ss) = (&mut node.reg[a * nb..(a + 1) * nb], &mut node.ssum[a * nb..(a + 1) * nb]); + for b in 0..nb { + reg[b] = if plus { (reg[b] + delta[b]).max(0.0) } else { reg[b] + t * delta[b] }; + ss[b] += t * rsum[b] * sigb[a * nb + b]; + } + } + return finish(p, q, vp, vq); + } + for a in 0..n { + let (reg, ss) = (&mut node.reg[a * m..(a + 1) * m], &mut node.ssum[a * m..(a + 1) * m]); + let (cp, sg) = (&cps[a], &sig[a * m..(a + 1) * m]); + let keep = frozen_h.map(|h| (h, reg[h])); + if plus { + for (((r, &c), &v), (x, (&rp, &s))) in reg.iter_mut().zip(cp).zip(&vp).zip(ss.iter_mut().zip(reach[p].iter().zip(sg))) { + *r = (*r + c - v).max(0.0); + *x += t * rp * s; + } + } else { + for (((r, &c), &v), (x, (&rp, &s))) in reg.iter_mut().zip(cp).zip(&vp).zip(ss.iter_mut().zip(reach[p].iter().zip(sg))) { + *r += t * (c - v); + *x += t * rp * s; + } + } + if let Some((h, _)) = keep { + // Readers of the final iterate see the pinned pure action. + reg[h] = (a == frozen_f) as u8 as f64; + } + } + finish(p, q, vp, vq) + } + + /// A new street opens: branch on the next board card(s). + fn chance(&mut self, st: &State, akey: u64, vkey: u64, reach: [&[f64]; 2]) -> [Vec; 2] { + let m = self.core.hands.len(); + let mut out = [vec![0.0; m], vec![0.0; m]]; + for (c, w) in self.core.deal(vkey) { + let r0 = self.core.masked(reach[0], c); + let r1 = self.core.masked(reach[1], c); + self.core.board.push(c); + let mut v = self.walk(st, akey, mix(vkey, c as u64 + 1), [&r0, &r1]); + self.core.board.pop(); + for p in 0..2 { + for &h in &self.core.hands.by_card[c as usize] { + v[p][h as usize] = 0.0; + } + for i in 0..m { + out[p][i] += w * v[p][i]; + } + } + } + out + } +} + +// --------------------------------------------------------------------------------------------- +// Exact best response / exploitability +// --------------------------------------------------------------------------------------------- + +/// Where in the subgame a strategy is queried. +pub struct Query<'a> { + pub akey: u64, + pub vkey: u64, + pub street: Street, + pub board: &'a [Card], + pub seat: usize, + pub hands: &'a Hands, + /// Decision state and the actions taken since the subgame root. + pub st: &'a State, + pub path: &'a [Action], +} + +/// A complete strategy profile: fill `out[a*M + m]` (M = number of compact hands) for the +/// acting player at the queried node. +pub trait Strat { + fn probs(&self, q: &Query, n: usize, out: &mut [f64]); +} + +struct SolStrat<'a> { + sol: &'a VecSolution, + average: bool, + pooled: Option<&'a dyn Bucketing>, +} + +impl Strat for SolStrat<'_> { + fn probs(&self, q: &Query, n: usize, out: &mut [f64]) { + let m = q.hands.len(); + let uni = |out: &mut [f64]| out.iter_mut().for_each(|x| *x = 1.0 / n as f64); + let pooled = q.street != self.sol.root_street && self.pooled.is_some(); + let key = if pooled { mix(q.akey, 0xB0C7) } else { q.vkey }; + let Some(nd) = self.sol.nodes.get(&key).filter(|nd| nd.n == n) else { return uni(out) }; + let pick = |a: usize, w: usize| -> f64 { if self.average { nd.ssum[a * (if pooled { nd.nb } else { m }) + w] } else { nd.reg[a * (if pooled { nd.nb } else { m }) + w].max(0.0) } }; + let hl = holes(); + for h in 0..m { + let w = if pooled { self.pooled.unwrap().bucket(q.street, hl[q.hands.idx[h] as usize], q.board) as usize } else { h }; + let tot: f64 = (0..n).map(|a| pick(a, w)).sum(); + for a in 0..n { + out[a * m + h] = if tot > 0.0 { pick(a, w) / tot } else { 1.0 / n as f64 }; + } + } + } +} + +/// Result of [`evaluate`]: the strategy profile's value and each player's exact best response. +pub struct BrReport { + /// Chips, relative to the start of the hand, averaged over the compatible root ranges. + pub value: [f64; 2], + pub br: [f64; 2], + /// Best-response counterfactual value per compact hand (unnormalised: weighted by the opponent's root reach). + pub br_cfv: [Vec; 2], + /// Root reach per compact hand and player, the normaliser `z`, and the dead money. + pub reach: [Vec; 2], + pub z: f64, + pub dead: f64, + pub hands: Hands, +} + +/// Value of the profile `s` for both players and each player's exact best response against `s`. +pub fn evaluate_profile(g: &VecGame, s: &dyn Strat) -> BrReport { + let mut core = Core::new(g, 0, true, false); + let m = core.hands.len(); + let r: [Vec; 2] = [0, 1].map(|p| core.hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); + let comp = compat(&core.hands, &r[1]); + let z: f64 = (0..m).map(|h| r[0][h] * comp[h]).sum(); + let mut br = [0.0; 2]; + let mut value = [0.0; 2]; + let mut br_cfv: [Vec; 2] = [vec![], vec![]]; + for p in 0..2 { + let v = core.br(g.root, 0, 0, p, &r[1 - p], s, true); + br[p] = (0..m).map(|h| r[p][h] * v[h]).sum::() / z; + br_cfv[p] = v; + let w = core.br(g.root, 0, 0, p, &r[1 - p], s, false); + value[p] = (0..m).map(|h| r[p][h] * w[h]).sum::() / z; + } + let dead = core.dead; + BrReport { value, br, br_cfv, reach: r, z, dead, hands: core.hands } +} + +/// Exact best-response values. Returns `(exploitability, [br0, br1])` in chips: the mean of +/// both players' best-response gains over the equilibrium value, normalised by the compatible +/// range mass. +pub fn exploitability(g: &VecGame, s: &dyn Strat) -> (f64, [f64; 2]) { + let mut core = Core::new(g, 0, true, false); + let m = core.hands.len(); + let r: [Vec; 2] = [0, 1].map(|p| core.hands.idx.iter().map(|&i| g.ranges[p][i as usize]).collect()); + let comp = compat(&core.hands, &r[1]); + let z: f64 = (0..m).map(|h| r[0][h] * comp[h]).sum(); + let mut br = [0.0; 2]; + for p in 0..2 { + let v = core.br(g.root, 0, 0, p, &r[1 - p], s, true); + br[p] = (0..m).map(|h| r[p][h] * v[h]).sum::() / z; + } + let dead = core.dead; + (((br[0] + br[1]) - dead) / 2.0, br) +} + +impl<'a> Core<'a> { + /// Counterfactual value of player `p` against `s` for the other player, given the opponent's + /// reach. `play_br`: `p` best-responds; otherwise `p` also follows `s` (profile value). + #[allow(clippy::too_many_arguments)] + fn br(&mut self, st: State, akey: u64, vkey: u64, p: usize, opp: &[f64], s: &dyn Strat, play_br: bool) -> Vec { + let m = self.hands.len(); + let q = 1 - p; + let seat = st.to_act().unwrap(); + let mut list = ActionList::new(); + self.actions(&st, akey, &mut list); + let n = list.len(); + let actor = self.player_of(seat); + let need_sig = actor == q || !play_br; + let mut sig = vec![0.0f64; if need_sig { n * m } else { 0 }]; + if need_sig { + let hands = std::mem::replace(&mut self.hands, Hands { idx: vec![], cards: vec![], of_hole: vec![], by_card: vec![] }); + { + let board = self.board.clone(); + let qy = Query { akey, vkey, street: st.street(), board: &board, seat, hands: &hands, st: &st, path: &self.path }; + s.probs(&qy, n, &mut sig); + } + self.hands = hands; + } + let dummy = vec![0.0; m]; + let mut best = vec![f64::NEG_INFINITY; m]; + let mut sum = vec![0.0; m]; + for a in 0..n { + let act = list.get(a); + let mut s2 = st; + let step = s2.apply(act); + let nr: Vec = if actor == q { (0..m).map(|h| opp[h] * sig[a * m + h]).collect() } else { opp.to_vec() }; + let akey2 = step_path(akey, act); + let vkey2 = step_path(vkey, act); + self.path.push(act); + let c = match step { + Step::Terminal => { + let mut reach: [&[f64]; 2] = [&dummy, &dummy]; + reach[q] = &nr; + let mut v = self.terminal(&s2, reach, vkey2); + std::mem::take(&mut v[p]) + } + Step::NewStreet(_) => { + let mut acc = vec![0.0; m]; + for (cd, w) in self.deal(vkey2) { + let nrm = self.masked(&nr, cd); + self.board.push(cd); + let mut v = self.br(s2, akey2, mix(vkey2, cd as u64 + 1), p, &nrm, s, play_br); + self.board.pop(); + for &h in &self.hands.by_card[cd as usize] { + v[h as usize] = 0.0; + } + for i in 0..m { + acc[i] += w * v[i]; + } + } + acc + } + Step::Continue => self.br(s2, akey2, vkey2, p, &nr, s, play_br), + }; + self.path.pop(); + if actor == p && play_br { + for h in 0..m { + best[h] = best[h].max(c[h]); + } + } else if actor == p { + for h in 0..m { + sum[h] += sig[a * m + h] * c[h]; + } + } else { + for h in 0..m { + sum[h] += c[h]; + } + } + } + if actor == p && play_br { + best + } else { + sum + } + } +} + +pub const _MAX: usize = MAX_ACTIONS; diff --git a/sharingan-1/search/tests/exploit.rs b/sharingan-1/search/tests/exploit.rs new file mode 100644 index 00000000..e6df23a8 --- /dev/null +++ b/sharingan-1/search/tests/exploit.rs @@ -0,0 +1,191 @@ +//! Spec of the exploitability gate (`search::exploit`). +//! +//! * the exact evaluator: exploitability falls with iterations and is ~0 after a long run, an +//! exploitable profile has a large gain, per-player gains are >= 0, profile values add up to the +//! dead money, the sum equals twice the existing `vector::exploitability`; +//! * the same on the MC solver's tables (heads-up river, exact): falls with iterations; +//! * multiway (3 players, flop with depth-limit leaves): the sampled lower bound falls with +//! iterations and is not negative beyond noise; +//! * the gadget is 0 for the blueprint itself and never negative. +use cards::{parse_cards, Card}; +use nlhe::abstraction::BetSizing; +use nlhe::{Action, GameConfig, State, Step, Street}; +use search::beliefs::Beliefs; +use search::bp::Blueprint; +use search::exploit::{exact_hu, measure, Opts}; +use search::solver::{solve, SearchParams, Subgame}; +use search::testkit::train_blueprint; +use search::tree::{later_sizing, Extras}; +use search::vector::{evaluate_profile, exploitability, solve_vec, Query, Strat, VecGame, VecParams}; +use std::collections::HashMap; +use std::sync::{Arc, OnceLock}; + +fn cs(s: &str) -> Vec { + parse_cards(s).unwrap() +} + +fn hu_bp() -> &'static Blueprint { + static B: OnceLock = OnceLock::new(); + B.get_or_init(|| train_blueprint(2, BetSizing::tiny(), Arc::new(bench::bp::CoarseBucketer), 60_000, 3)) +} + +fn p3_bp() -> &'static Blueprint { + static B: OnceLock = OnceLock::new(); + B.get_or_init(|| train_blueprint(3, BetSizing::tiny(), Arc::new(bench::bp::CoarseBucketer), 60_000, 5)) +} + +/// Both players check down to `street`. +fn check_down(players: usize, street: Street) -> State { + let mut s = State::new(&GameConfig::new(players)); + loop { + let l = s.legal(); + if let Step::NewStreet(st) = s.apply(if l.can_check { Action::Check } else { Action::Call }) { + if st == street { + return s; + } + } + } +} + +struct Uniform; +impl Strat for Uniform { + fn probs(&self, q: &Query, n: usize, out: &mut [f64]) { + let m = q.hands.len(); + for a in 0..n { + for h in 0..m { + out[a * m + h] = 1.0 / n as f64; + } + } + } +} + +fn river_game<'a>(root: State, board: &'a [Card], sz: &'a BetSizing, later: &'a BetSizing, none: &'a Extras, frozen: &'a HashMap) -> VecGame<'a> { + let bm = cards::mask_of(board); + let ranges = [0, 1].map(|_| cards::all_holes().iter().map(|h| if (cards::bit(h[0]) | cards::bit(h[1])) & bm != 0 { 0.0 } else { 1.0 }).collect()); + VecGame { root, board, seats: [1, 0], ranges, sizing: sz, later, extras: none, me: None, my_hole: None, frozen, pooled: None } +} + +#[test] +fn exact_exploitability_falls_with_iterations_and_is_consistent() { + let root = check_down(2, Street::River); + let board = cs("2c7d9hJsKc"); + let (sz, later) = (search::tree::small_sizing(), later_sizing()); + let (none, frozen) = (Extras::new(), HashMap::new()); + let g = river_game(root, &board, &sz, &later, &none, &frozen); + let nashconv = |iters: u64| { + let sol = solve_vec(&g, &VecParams { iters, plus: true, keep_all: true, ..Default::default() }); + let rep = evaluate_profile(&g, &sol.strategy(true, None)); + // per-player gains are non-negative; values add up to the dead money (constant-sum) + for p in 0..2 { + assert!(rep.br[p] - rep.value[p] >= -1e-6, "negative gain {}", rep.br[p] - rep.value[p]); + } + assert!((rep.value[0] + rep.value[1] - rep.dead).abs() < 1e-6 * root.pot() as f64, "values {:?} dead {}", rep.value, rep.dead); + let sum = rep.br[0] + rep.br[1] - rep.dead; + // identical to the established evaluator + let (expl, _) = exploitability(&g, &sol.strategy(true, None)); + assert!((2.0 * expl - sum).abs() < 1e-6 * root.pot() as f64, "{} vs {}", 2.0 * expl, sum); + 100.0 * sum / root.pot() as f64 + }; + let (short, long) = (nashconv(10), nashconv(1000)); + assert!(long < 0.5 * short, "short {short} long {long}"); + assert!(long < 1.0, "after 1000 passes the river must be within 1% pot, got {long}"); +} + +#[test] +fn an_exploitable_profile_has_a_large_gain() { + let root = check_down(2, Street::River); + let board = cs("2c7d9hJsKc"); + let (sz, later) = (search::tree::small_sizing(), later_sizing()); + let (none, frozen) = (Extras::new(), HashMap::new()); + let g = river_game(root, &board, &sz, &later, &none, &frozen); + let rep = evaluate_profile(&g, &Uniform); + let pct = 100.0 * (rep.br[0] + rep.br[1] - rep.dead) / root.pot() as f64; + assert!(pct > 20.0, "uniform play should lose far more than 20% pot to best responses, got {pct}"); +} + +fn river_subgame_pct(iters: u64, gadget: bool) -> (f64, Option, f64) { + let bp = hu_bp(); + let root = check_down(2, Street::River); + let board = cs("2c7d9hJsKc"); + let mut b = Beliefs::uniform(2); + b.remove_cards(cards::mask_of(&board)); + let prm = SearchParams { iters, max_infosets: 1 << 18, parallel: false, warm_start: 0.0, prune_prob: 0.0, ..Default::default() }; + let (none, frozen) = (Extras::new(), HashMap::new()); + let sg = Subgame { bp, root, board: &board, beliefs: &b, bp_hist: bp.shadow(&root), extras: &none, me: 1, my_hole: None, frozen: &frozen, params: &prm, seed: 1 }; + let sol = solve(&sg); + let rep = measure(&sg, &sol, &Opts { gadget, ..Default::default() }).expect("exact report"); + assert_eq!(rep.mode, "exact_hu"); + let g = gadget.then(|| rep.players.iter().map(|p| p.gadget.unwrap()).sum::()); + (rep.pct_pot(rep.sum_gain), g.map(|x| rep.pct_pot(x)), rep.miss_share) +} + +#[test] +fn mc_solution_exploitability_falls_by_an_order_of_magnitude_heads_up() { + // Deep stacks vs a 2 bb pot: the numbers are large in % pot (measured: 1418% at 3k iterations, + // 65% at 300k, see `explore_mc_river_curve`), but they must keep falling. + let (short, _, _) = river_subgame_pct(3_000, false); + let (long, _, miss) = river_subgame_pct(300_000, false); + assert!(long < 0.1 * short, "3k it: {short}% pot, 300k it: {long}% pot"); + assert!(miss < 0.1, "most lookups must hit visited infosets after 300k iterations, miss share {miss}"); +} + +#[test] +fn gadget_is_never_negative_and_zero_for_the_blueprint_itself() { + // 0 iterations: the table is empty, every lookup falls back to the blueprint prior, so the + // "search" strategy IS the blueprint profile and the gadget (gain over the blueprint CBV) is 0. + let (_, g0, miss) = river_subgame_pct(0, true); + assert!(miss > 0.99, "all lookups must miss, got {miss}"); + assert!(g0.unwrap().abs() < 1e-9, "gadget {g0:?}"); + let (_, g, _) = river_subgame_pct(3000, true); + assert!(g.unwrap() >= 0.0); +} + +#[test] +fn blueprint_profile_is_measurable_without_a_search() { + let bp = hu_bp(); + let root = check_down(2, Street::River); + let board = cs("2c7d9hJsKc"); + let mut b = Beliefs::uniform(2); + b.remove_cards(cards::mask_of(&board)); + let prm = SearchParams { parallel: false, ..Default::default() }; + let (none, frozen) = (Extras::new(), HashMap::new()); + let sg = Subgame { bp, root, board: &board, beliefs: &b, bp_hist: bp.shadow(&root), extras: &none, me: 1, my_hole: None, frozen: &frozen, params: &prm, seed: 1 }; + let rep = exact_hu(&sg, None, &Opts::default()).unwrap(); + assert!(rep.sum_gain > 0.0 && rep.sum_gain.is_finite()); +} + +#[test] +fn multiway_sampled_lower_bound_falls_with_iterations() { + let bp = p3_bp(); + let root = check_down(3, Street::Flop); + let board = cs("2c7d9h"); + let mut b = Beliefs::uniform(3); + b.remove_cards(cards::mask_of(&board)); + let (none, frozen) = (Extras::new(), HashMap::new()); + let run = |iters: u64| { + let prm = SearchParams { iters, max_infosets: 1 << 18, parallel: false, warm_start: 0.0, prune_prob: 0.0, ..Default::default() }; + let sg = Subgame { bp, root, board: &board, beliefs: &b, bp_hist: bp.shadow(&root), extras: &none, me: 0, my_hole: None, frozen: &frozen, params: &prm, seed: 1 }; + let sol = solve(&sg); + let opts = Opts { br_iters: 20_000, eval_samples: 20_000, gadget: false, big_blind: 100 }; + let rep = measure(&sg, &sol, &opts).unwrap(); + assert_eq!(rep.mode, "sampled_lower_bound"); + assert_eq!(rep.players.len(), 3); + for p in &rep.players { + assert!(p.gain > -4.0 * p.gain_se.unwrap(), "gain {} se {:?}", p.gain, p.gain_se); + } + assert!(rep.leaf_share.unwrap() > 0.0); + rep.pct_pot(rep.sum_gain) + }; + let (short, long) = (run(200), run(30_000)); + assert!(long < 0.7 * short, "200 it: {short}% pot, 30000 it: {long}% pot"); +} + +#[test] +#[ignore] +fn explore_mc_river_curve() { + for it in [300u64, 3_000, 30_000, 300_000, 3_000_000, 6_000_000] { + let t = std::time::Instant::now(); + let (pct, _, miss) = river_subgame_pct(it, false); + eprintln!("iters {it}: nashconv {pct:.2}% pot, miss share {miss:.3}, {:.1}s", t.elapsed().as_secs_f64()); + } +} diff --git a/sharingan-1/serve/src/bin/sharingan-teilspiel.rs b/sharingan-1/serve/src/bin/sharingan-teilspiel.rs new file mode 100644 index 00000000..47f9b1ce --- /dev/null +++ b/sharingan-1/serve/src/bin/sharingan-teilspiel.rs @@ -0,0 +1,146 @@ +//! `sharingan-teilspiel`: exploitability gate for the SHARINGAN search (see `search::exploit`). +//! +//! Reads recorded search requests (one JSON per line in the Farm's MOTOR_SUCHE_SPUR format, +//! `{"frage": {"op":"suche", "req": , "iters"?: n, ...}, "r": ...}`), replays each hand +//! with the live service code (`Core`), runs the search with a given iteration budget and measures +//! how much each player could win by best-responding to the output strategy in the same subgame. +//! +//! Output: one JSON line per situation, appended to `--out` (already present keys are skipped, so +//! a run can be resumed): `{"schluessel": "[[hole], [board]]", "index": i, "": {...}}`. +//! +//! Candidates (`--cands`, comma separated): `mittel` (standard), `final` (`--set final=1`), +//! `warm64` (`--set warm=64`), `vektor` (`--set vector=1,vecmin=flop`), `tabelle` (blueprint, no search). +//! +//! Flags of its own: `--requests F --out F [--cands a,b] [--iters-other 24000] [--iters-flop N] +//! [--br-iters N] [--eval-samples N] [--only i,j] [--no-gadget] [--max-lines N]`; everything else +//! is `sharingan-serve`'s configuration (`--blueprint`, `--buckets`, `--sizing`, `--set`, ...). + +use serde_json::{json, Value}; +use sharingan_serve::api::ActRequest; +use sharingan_serve::config::Config; +use sharingan_serve::decide::Core; +use std::collections::{HashMap, HashSet}; +use std::io::Write; +use std::time::Instant; + +const OWN: &[&str] = &["requests", "out", "cands", "iters-other", "iters-flop", "br-iters", "eval-samples", "only", "no-gadget", "max-lines"]; + +fn candidate_sets(name: &str) -> Option<&'static str> { + Some(match name { + "mittel" => "", + "final" => "final=1", + "warm64" => "warm=64", + "vektor" => "vector=1,vecmin=flop", + "tabelle" => "", + _ => return None, + }) +} + +fn main() { + let raw: Vec = std::env::args().skip(1).collect(); + let mut own: HashMap = HashMap::new(); + let mut rest: Vec = vec!["--no-auth".into()]; + let mut i = 0; + while i < raw.len() { + let k = raw[i].trim_start_matches("--").to_string(); + if raw[i].starts_with("--") && OWN.contains(&k.as_str()) { + if k == "no-gadget" { + own.insert(k, "1".into()); + i += 1; + } else { + own.insert(k, raw.get(i + 1).cloned().unwrap_or_default()); + i += 2; + } + } else { + rest.push(raw[i].clone()); + i += 1; + } + } + let cfg = Config::parse(&|k| std::env::var(k).ok(), &rest).unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(2) + }); + let num = |k: &str, d: u64| own.get(k).and_then(|v| v.parse::().ok()).unwrap_or(d); + let (Some(req_path), Some(out_path)) = (own.get("requests"), own.get("out")) else { + eprintln!("--requests F and --out F are required"); + std::process::exit(2) + }; + let cands: Vec = own.get("cands").map_or("mittel".to_string(), |s| s.clone()).split(',').map(|s| s.trim().to_string()).collect(); + for c in &cands { + if candidate_sets(c).is_none() { + eprintln!("unknown candidate {c}"); + std::process::exit(2) + } + } + let only: Option> = own.get("only").map(|s| s.split(',').filter_map(|x| x.trim().parse().ok()).collect()); + let opts = search::exploit::Opts { + br_iters: num("br-iters", 200_000), + eval_samples: num("eval-samples", 200_000), + gadget: !own.contains_key("no-gadget"), + big_blind: 100, + }; + let iters_other = num("iters-other", 24_000); + let iters_flop = own.get("iters-flop").and_then(|v| v.parse::().ok()); + + let core = Core::new(&cfg).unwrap_or_else(|e| { + eprintln!("error: {e}"); + std::process::exit(1) + }); + let done: HashSet = std::fs::read_to_string(out_path) + .map(|t| t.lines().filter_map(|l| serde_json::from_str::(l).ok()).filter_map(|v| v["schluessel"].as_str().map(String::from)).collect()) + .unwrap_or_default(); + let text = std::fs::read_to_string(req_path).unwrap_or_else(|e| { + eprintln!("{req_path}: {e}"); + std::process::exit(1) + }); + let mut out = std::fs::OpenOptions::new().create(true).append(true).open(out_path).expect("open --out"); + let mut seen: HashSet = done; + let max_lines = num("max-lines", u64::MAX) as usize; + let mut ran = 0usize; + for (idx, line) in text.lines().enumerate() { + if ran >= max_lines { + break; + } + if only.as_ref().is_some_and(|o| !o.contains(&idx)) { + continue; + } + let Ok(v) = serde_json::from_str::(line) else { continue }; + let f = &v["frage"]; + if f["op"] != "suche" { + continue; + } + let Ok(req) = serde_json::from_value::(f["req"].clone()) else { + eprintln!("line {idx}: bad request"); + continue; + }; + // json.dumps([hole_cards, board]) with Python's default separators. + let q = |a: &[String]| format!("[{}]", a.iter().map(|c| format!("\"{c}\"")).collect::>().join(", ")); + let key = format!("[{}, {}]", q(&req.hole_cards), q(&req.board)); + if !seen.insert(key.clone()) { + continue; + } + let flop = req.board.len() == 3; + let iters = if flop { + iters_flop.or(f["iters"].as_u64()).unwrap_or(200_000) + } else if own.contains_key("iters-other") { + iters_other + } else { + f["iters"].as_u64().unwrap_or(iters_other) + }; + let mut rec = json!({"schluessel": key, "index": idx, "iters": iters, "street": req.board.len()}); + for c in &cands { + let t = Instant::now(); + let res = core.teilspiel(&req, candidate_sets(c).unwrap(), iters, &opts, c == "tabelle"); + let mut val = match res { + Ok(v) => v, + Err(e) => json!({"fehler": e.body()}), + }; + val["wall_ms"] = json!(t.elapsed().as_secs_f64() * 1e3); + rec[c.as_str()] = val; + } + writeln!(out, "{rec}").expect("write"); + out.flush().ok(); + ran += 1; + eprintln!("[{idx}] done in cands {:?}", cands); + } +} diff --git a/sharingan-1/serve/src/decide.rs b/sharingan-1/serve/src/decide.rs index e84bb796..84def4e5 100644 --- a/sharingan-1/serve/src/decide.rs +++ b/sharingan-1/serve/src/decide.rs @@ -1,536 +1,597 @@ -//! The bot: one [`Core`] per process, shared by every request. -//! -//! * The compact blueprint is mmapped once at startup (`Core::new`) and shared (lock-free reads). -//! * Each request builds a fresh [`search::policy::SearchPlayer`] by replaying the history -//! ([`crate::replay`]); the turn/river decision then runs a real-time search **on a worker thread -//! under a hard budget** (same two layers as `arena/openpoker/src/guard.rs`): the solver's -//! cooperative cap (70% of the budget) returns a truncated-but-valid solution; the hard -//! `recv_timeout` guarantees an answer, falling back to the blueprint action. -//! * A [`Gate`] bounds concurrent searches (they share one rayon pool). A timed-out search keeps -//! its slot until it really ends, so abandoned work can never pile up. - -use crate::api::*; -use crate::config::Config; -use crate::error::ApiError; -use crate::replay::{street_name, Hand}; -use bench::bp::{bucketer_by_name, sizing_by_name}; -use bench::mix; -use bench::policy::{Dist, Player, View}; -use blueprint::compact::Compact; -use cards::Card; -use nlhe::abstraction::{BetSizing, TrackOpts}; -use nlhe::Street; -use search::bp::Blueprint; -use search::policy::{SearchPlayer, SearchPolicy}; -use search::solver::SearchParams; -use serde_json::{json, Value}; -use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; -use std::sync::{mpsc, Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; - -// ---------------------------------------------------------------------------------------- gate - -/// Counting semaphore with a timed acquire (decisions run on blocking threads). -pub struct Gate { - used: Mutex, - cv: Condvar, - cap: usize, -} - -pub struct Permit(Arc); - -impl Drop for Permit { - fn drop(&mut self) { - *self.0.used.lock().unwrap() -= 1; - self.0.cv.notify_one(); - } -} - -impl Gate { - pub fn new(cap: usize) -> Arc { - Arc::new(Gate { used: Mutex::new(0), cv: Condvar::new(), cap }) - } - pub fn acquire(g: &Arc, wait: Duration) -> Option { - let deadline = Instant::now() + wait; - let mut used = g.used.lock().unwrap(); - loop { - if *used < g.cap { - *used += 1; - return Some(Permit(g.clone())); - } - let left = deadline.checked_duration_since(Instant::now())?; - let (u, to) = g.cv.wait_timeout(used, left).unwrap(); - used = u; - if to.timed_out() && *used >= g.cap { - return None; - } - } - } - pub fn in_use(&self) -> usize { - *self.used.lock().unwrap() - } - pub fn capacity(&self) -> usize { - self.cap - } -} - -// -------------------------------------------------------------------------------- search params - -/// Parse `k=v,...` overrides of `SearchParams` (same keys as `openpoker --set` / `vsbp --set`). -pub fn apply_sets(prm: &mut SearchParams, sets: &str) -> Result<(), String> { - fn p(k: &str, v: &str) -> Result { - v.parse().map_err(|_| format!("--set {k}={v}: bad value")) - } - for kv in sets.split(',').filter(|x| !x.is_empty()) { - let (k, v) = kv.split_once('=').unwrap_or((kv, "1")); - let b = v != "0" && v != "false"; - match k { - "iters" => prm.iters = p(k, v)?, - "warm" => prm.warm_start = p(k, v)?, - "focus" => prm.focus_own = p(k, v)?, - "leaf" => prm.leaf = if v == "bp" { search::solver::LeafMode::Blueprint } else { search::solver::LeafMode::Cont4 }, - "final" => prm.play_final = b, - "flop" => prm.search_flop = b, - "turn" => prm.search_turn = b, - "river" => prm.search_river = b, - "pre" => prm.preflop_search = b, - "post" => prm.postflop_search = b, - "bpbeliefs" => prm.blueprint_beliefs = b, - "offbel" => prm.offtree_search_beliefs = b, - "ownbel" => prm.own_search_beliefs = b, - "tremble" => prm.belief_tremble = p(k, v)?, - "prune" => prm.prune_prob = p(k, v)?, - "ms" => prm.max_millis = Some(p(k, v)?), - "minflop" => prm.min_flop_players = p(k, v)?, - "vecmin" => prm.vec_min_street = match v { "flop" => Street::Flop, "turn" => Street::Turn, _ => Street::River }, - "vector" => prm.vector = b, - "sizing" | "later" => { - let s: BetSizing = match v { - "small" => search::tree::small_sizing(), - o => sizing_by_name(o).ok_or(format!("--set {k}={o}: unknown sizing"))?, - }; - if k == "sizing" { - prm.sizing = s; - } else { - prm.later_sizing = s; - } - } - _ => return Err(format!("unknown --set key {k}")), - } - } - Ok(()) -} - -// ------------------------------------------------------------------------------ belief checks - -/// Hero belief below this (uniform is ~1/1176 = 8.5e-4; `finish_round` floors the hero's own hand -/// at 1e-6) means the hero's earlier actions were off-policy for this hand. -const OFF_POLICY_BELIEF: f32 = 1e-5; - -fn hero_belief(player: &SearchPlayer, seat: usize, hole: [Card; 2]) -> f32 { - let i = cards::hole_index(hole[0], hole[1]); - player.beliefs().w.get(seat).and_then(|r| r.get(i)).copied().unwrap_or(1.0) -} - -/// Bit-identical distributions (same actions, same probabilities). -fn same_dist(a: &Dist, b: &Dist) -> bool { - a.len() == b.len() && (0..a.len()).all(|i| a.action(i) == b.action(i) && a.prob(i) == b.prob(i)) -} - -/// pokerfreak-Zusatz (03.12.): HYBRID_RUNDEN=1 - Rundenspeicher fuer das Nachspielen (search::rundenspeicher): die Belief-Fortschreibung -/// nimmt die damals gespielte Suchloesung statt der Tabelle (sonst `off_policy_history` nach eigenen Suchzuegen). HYBRID_RUNDEN_PLAETZE -/// (Standard 4096 Runden), HYBRID_RUNDEN_FLOP_ITERS: Iterationen, wenn eine verdraengte Flop-Runde neu gerechnet wird. Ohne: wie vorher. -fn runden() -> Option<&'static Arc> { - static A: std::sync::OnceLock>> = std::sync::OnceLock::new(); - A.get_or_init(|| { - std::env::var("HYBRID_RUNDEN").is_ok_and(|x| x == "1").then(|| { - let zahl = |k: &str| std::env::var(k).ok().and_then(|x| x.parse::().ok()); - Arc::new(search::rundenspeicher::RoundCache::new(zahl("HYBRID_RUNDEN_PLAETZE").unwrap_or(4096) as usize, zahl("HYBRID_RUNDEN_FLOP_ITERS"))) - }) - }) - .as_ref() -} - -/// pokerfreak-Zusatz (30.11.): HYBRID_EIGENER_POOL=1, ein 1-Faden-Pool je Suche (siehe `Core::decide`). -fn eigener_pool() -> bool { - static A: std::sync::OnceLock = std::sync::OnceLock::new(); - *A.get_or_init(|| std::env::var("HYBRID_EIGENER_POOL").is_ok_and(|x| x == "1")) -} - -// ------------------------------------------------------------------------------------------ core - -#[derive(Default)] -struct Counters { - requests: AtomicU64, - searched: AtomicU64, - timeouts: AtomicU64, - panics: AtomicU64, - busy: AtomicU64, - fallbacks: AtomicU64, - off_policy: AtomicU64, - no_mass: AtomicU64, - search_micros: AtomicU64, - search_max_micros: AtomicU64, -} - -/// Blueprint facts reported by `/v1/info`. -pub struct Meta { - pub path: String, - pub infosets: u64, - pub file_bytes: u64, - pub src_infosets: u64, - pub used_snapshots: bool, -} - -pub struct Core { - pub cfg: Config, - blueprint: Blueprint, - prm: SearchParams, - gate: Arc, - meta: Meta, - started: Instant, - c: Counters, - seq: AtomicU64, -} - -impl Core { - /// Load the compact blueprint, the card abstraction and the search pool. - pub fn new(cfg: &Config) -> Result { - let buckets = if cfg.buckets == "coarse" || cfg.buckets.starts_with("tables:") { cfg.buckets.clone() } else { format!("tables:{}", cfg.buckets) }; - let bucketer = bucketer_by_name(&buckets).ok_or_else(|| format!("cannot load card abstraction {buckets}"))?; - let sizing = sizing_by_name(&cfg.sizing).ok_or_else(|| format!("unknown sizing {}", cfg.sizing))?; - let compact = Arc::new(Compact::open(&cfg.blueprint).map_err(|e| format!("blueprint {}: {e}", cfg.blueprint.display()))?); - if cfg.warm { - compact.warm(); - } else { - compact.random_access(); - } - let meta = Meta { - path: cfg.blueprint.display().to_string(), - infosets: compact.len() as u64, - file_bytes: compact.file_bytes(), - src_infosets: compact.info().src_infosets, - used_snapshots: compact.info().used_snapshots, - }; - // pokerfreak-Zusatz (29.11.): HYBRID_UEBERSETZUNG=phm -> zufaellige pseudo-harmonische Uebersetzung (Ganzfried/Sandholm), - // HYBRID_ALLIN_SNAP (Standard 0.1 bei phm): ein Fast-All-in gilt nur als All-in, wenn der Rest <= x * Topf danach ist. - let mut track = TrackOpts::default(); - if std::env::var("HYBRID_UEBERSETZUNG").is_ok_and(|x| x == "phm") { - track.translation = nlhe::abstraction::Translation::Random; - track.allin_snap = 0.1; - } - if let Some(x) = std::env::var("HYBRID_ALLIN_SNAP").ok().and_then(|x| x.parse::().ok()) { - track.allin_snap = x; - } - let bp = Blueprint::from_source(compact, bucketer, sizing).with_opts(track); - Self::with_blueprint(cfg, bp, meta) - } - - /// Same over an already-built blueprint (tests). - pub fn with_blueprint(cfg: &Config, bp: Blueprint, meta: Meta) -> Result { - let mut prm = SearchParams::default(); - apply_sets(&mut prm, &cfg.sets)?; - if let Some(dir) = &cfg.search_buckets { - let sb = abstraction::search_buckets::SearchBuckets::new(Some(dir.into()), abstraction::search_buckets::BuildParams::default(), 64) - .map_err(|e| format!("search buckets {dir}: {e}"))?; - prm.search_buckets = Some(Arc::new(sb)); - } - if !cfg.search { - prm.postflop_search = false; - prm.preflop_search = false; - } - prm.parallel = true; - prm.pool = Some(Arc::new( - rayon::ThreadPoolBuilder::new() - .num_threads(cfg.search_threads.max(1)) - .thread_name(|i| format!("search-pool-{i}")) - .build() - .map_err(|e| format!("thread pool: {e}"))?, - )); - Ok(Core { - cfg: cfg.clone(), - blueprint: bp, - prm, - gate: Gate::new(cfg.search_concurrency.max(1)), - meta, - started: Instant::now(), - c: Counters::default(), - seq: AtomicU64::new(0), - }) - } - - pub fn gate(&self) -> &Arc { - &self.gate - } - - pub fn next_request_id(&self) -> String { - format!("r-{:x}-{}", crate::log::now_ms(), self.seq.fetch_add(1, Relaxed)) - } - - /// `GET /v1/info`. - pub fn info(&self) -> Value { - let p = &self.prm; - let n = self.c.searched.load(Relaxed).max(1) as f64; - json!({ - "model_id": self.cfg.model_id, - "name": "SHARINGAN-1", - "version": env!("CARGO_PKG_VERSION"), - "blueprint": { - "path": self.meta.path, "infosets": self.meta.infosets, "file_bytes": self.meta.file_bytes, - "source_infosets": self.meta.src_infosets, "snapshot_averaged": self.meta.used_snapshots, - "format": "PLCP1 (compact, mmap)", - }, - "sizing": self.cfg.sizing, - "buckets": self.cfg.buckets, - "players": "2-6 (trained for 6-max, 100 bb; 3-5 players embedded in the 6-max tree)", - "search": { - "enabled": self.cfg.search, - "set": self.cfg.sets, - "iters": p.iters, - "flop": p.search_flop, "turn": p.search_turn, "river": p.search_river, - "preflop_off_tree": p.preflop_search, - "play_final": p.play_final, - "leaf": format!("{:?}", p.leaf), - "budget_ms": self.cfg.budget_ms, - "cooperative_cap_ms": (self.cfg.budget_ms * 7 / 10).max(1), - "threads": self.cfg.search_threads, - "concurrency": self.gate.capacity(), - "queue_ms": self.cfg.queue_ms, - }, - "max_stack_bb": self.cfg.max_stack_bb, - "limits": {"max_batch": self.cfg.max_batch, "rate_rps": self.cfg.rate_rps, "rate_burst": self.cfg.rate_burst, "max_inflight": self.cfg.max_inflight}, - "panic_strategy": if cfg!(panic = "unwind") { "unwind" } else { "abort" }, - "stats": { - "uptime_s": self.started.elapsed().as_secs(), - "requests": self.c.requests.load(Relaxed), - "searched": self.c.searched.load(Relaxed), - "search_timeouts": self.c.timeouts.load(Relaxed), - "search_panics": self.c.panics.load(Relaxed), - "search_busy": self.c.busy.load(Relaxed), - "fallbacks": self.c.fallbacks.load(Relaxed), - "off_policy_history": self.c.off_policy.load(Relaxed), - "no_search_mass": self.c.no_mass.load(Relaxed), - "runden": runden().map(|c| { let s = c.stats(); json!({"treffer": s.treffer, "neu_gerechnet": s.neu_gerechnet, "gemerkt": s.gemerkt, "plaetze": c.len()}) }), - "search_mean_ms": self.c.search_micros.load(Relaxed) as f64 / n / 1e3, - "search_max_ms": self.c.search_max_micros.load(Relaxed) as f64 / 1e3, - "searches_in_flight": self.gate.in_use(), - }, - }) - } - - pub fn health(&self) -> Value { - json!({"status": "ok", "model_id": self.cfg.model_id, "uptime_s": self.started.elapsed().as_secs(), "searches_in_flight": self.gate.in_use()}) - } - - /// Answer one request. Blocking: call from a blocking thread. - pub fn decide(&self, req: &ActRequest, request_id: String) -> Result { - let t0 = Instant::now(); - self.c.requests.fetch_add(1, Relaxed); - let opts = &req.options; - if opts.time_budget_ms == Some(0) { - return Err(ApiError::invalid("bad_budget", "options.time_budget_ms must be > 0")); - } - let budget_ms = opts.time_budget_ms.map_or(self.cfg.budget_ms, |b| b.min(self.cfg.budget_ms)); - let seed = opts.seed.unwrap_or_else(|| mix(crate::log::now_ms().wrapping_mul(1_000_003) ^ t0.elapsed().as_nanos() as u64, self.seq.fetch_add(1, Relaxed))); - let mut prm = self.prm.clone(); - let cap = (budget_ms * 7 / 10).max(1); - prm.max_millis = Some(prm.max_millis.map_or(cap, |m| m.min(cap))); - prm.seed = mix(seed, 7); - // pokerfreak-Zusatz (30.11., Mehrtisch): options.iters ersetzt die feste Iterationszahl fuer diese Anfrage; - // HYBRID_EIGENER_POOL=1: jede Suche auf einem eigenen Pool mit einem Faden (wie --search-threads 1, also bitgleich - // reproduzierbar), damit mehrere Suchen nebeneinander laufen statt sich einen Pool zu teilen. Ohne beides wie vorher. - if let Some(i) = opts.iters.filter(|&i| i > 0) { - prm.iters = i; - } - if opts.search && eigener_pool() { - let pl = rayon::ThreadPoolBuilder::new() - .num_threads(1) - .thread_name(|_| "search-slot".into()) - .build() - .map_err(|e| ApiError::internal(format!("pool: {e}")))?; - prm.pool = Some(Arc::new(pl)); - } - let mut policy = SearchPolicy::new("serve", self.blueprint.clone(), prm); - if let Some(c) = runden() { - let hole = crate::replay::parse_cards_field("hole_cards", &req.hole_cards).ok().filter(|v| v.len() == 2).map(|v| [v[0], v[1]]); - policy = policy.with_rounds(c.clone(), hole); - } - - let mut hand = Hand::replay(req, Some(&policy), opts.track_seed.map_or(mix(seed, 1), |t| mix(t, 1)))?; - let street = hand.real.street(); - - let mut source = "blueprint"; - let mut reason: Option = None; - let mut search_ms: Option = None; - let mut dist: Option = None; - if let Some(why) = hand.desync.clone() { - source = "fallback"; - reason = Some(format!("desync: {why}")); - } else if let Some(mut player) = hand.player.take() { - let hole = hand.hole; - let view = hand.view(); - let want_search = opts.search && self.cfg.search; - if !want_search { - dist = Some(player.blueprint_dist(&view, hole)); - } else if !player.needs_search(&view) { - dist = Some(Player::dist(&mut player, &view, hole)); - } else if hero_belief(&player, view.seat, hole) < OFF_POLICY_BELIEF { - // The hero's own earlier actions had ~zero likelihood under the hero's strategy - // (e.g. a replayed foreign hand): the subgame would have no mass for this hand and - // the search average would be empty. Skip the search, answer from the blueprint. - self.c.off_policy.fetch_add(1, Relaxed); - dist = Some(player.blueprint_dist(&view, hole)); - reason = Some("off_policy_history".into()); - } else { - let (d, src, why, ms) = self.guarded_search(&mut player, &view, hole, Duration::from_millis(budget_ms)); - dist = Some(d); - source = src; - reason = why; - search_ms = Some(ms); - } - } - if dist.as_ref().is_some_and(|d| d.is_empty()) { - dist = None; - source = "fallback"; - reason = Some("policy returned an empty distribution".into()); - } - - // ---- choose, map to real chips, guard - let mut notes = std::mem::take(&mut hand.notes); - let mut ra = match &dist { - Some(d) => { - let i = if opts.sample { - d.sample(cards::Rng::new(mix(seed, 3)).f64()) - } else { - (0..d.len()).max_by(|&a, &b| d.prob(a).total_cmp(&d.prob(b)).then(b.cmp(&a))).unwrap_or(0) - }; - hand.to_real(d.action(i)) - } - // This fallback uses real chips and cards; to_real would scale it twice. - None => bench::bp::fallback_action(&hand.real, &hand.board, hand.hole), - }; - if self.cfg.max_stack_bb > 0.0 { - let capc = (self.cfg.max_stack_bb * hand.big_blind as f64).round() as i64; - if let Some((na, note)) = hand.cap_guard(ra, capc) { - notes.push(note); - ra = na; - } - } - if !hand.is_legal(ra) { - notes.push(format!("internal: {ra:?} was not legal; replaced by the passive action")); - ra = hand.passive(); - source = "fallback"; - reason.get_or_insert_with(|| "illegal mapped action".into()); - } - if source == "fallback" { - self.c.fallbacks.fetch_add(1, Relaxed); - } - - let probs = opts.include_probs.then(|| { - let mut out: Vec = vec![]; - if let Some(d) = &dist { - for i in 0..d.len() { - // Report the same real-chip actions that selection can actually return. - // Several abstract entries may collapse onto one capped action. - let mut real = hand.to_real(d.action(i)); - if self.cfg.max_stack_bb > 0.0 { - let cap = (self.cfg.max_stack_bb * hand.big_blind as f64).round() as i64; - if let Some((guarded, _)) = hand.cap_guard(real, cap) { - real = guarded; - } - } - if !hand.is_legal(real) { - real = hand.passive(); - } - let a = hand.describe(real); - let p = d.prob(i); - match out.iter_mut().find(|o| o.kind == a.kind && o.to == a.to) { - Some(o) => o.p += p, - None => out.push(ProbOut { kind: a.kind, to: a.to, p }), - } - } - } else { - let a = hand.describe(ra); - out.push(ProbOut { kind: a.kind, to: a.to, p: 1.0 }); - } - for o in out.iter_mut() { - o.p = (o.p * 1e6).round() / 1e6; - } - out.sort_by(|a, b| b.p.total_cmp(&a.p)); - out - }); - - Ok(ActResponse { - request_id, - hand_id: req.hand_id.clone(), - model_id: self.cfg.model_id.clone(), - street: street_name(street), - action: hand.describe(ra), - source, - fallback_reason: reason, - probs, - legal: hand.legal_out(), - timing: Timing { total_ms: t0.elapsed().as_secs_f64() * 1e3, search_ms, budget_ms }, - notes, - }) - } - - /// Run the search on a worker thread; blueprint on timeout / panic / no free slot. - fn guarded_search(&self, player: &mut SearchPlayer, view: &View, hole: [Card; 2], budget: Duration) -> (Dist, &'static str, Option, f64) { - let t0 = Instant::now(); - let fallback = |player: &mut SearchPlayer, why: String| { - player.detach_search(); - (player.blueprint_dist(view, hole), "fallback", Some(why), t0.elapsed().as_secs_f64() * 1e3) - }; - let Some(permit) = Gate::acquire(&self.gate, Duration::from_millis(self.cfg.queue_ms)) else { - self.c.busy.fetch_add(1, Relaxed); - return fallback(player, format!("search_busy: all {} search slots in use for {}ms; blueprint", self.gate.capacity(), self.cfg.queue_ms)); - }; - let t_search = Instant::now(); - let mut worker = player.clone(); - let (cfg, state, seat) = (*view.cfg, *view.state, view.seat); - let (board, history) = (view.board.to_vec(), view.history.to_vec()); - let delay = self.cfg.debug_search_delay_ms; - let (tx, rx) = mpsc::channel(); - let spawned = std::thread::Builder::new().name("search-decision".into()).spawn(move || { - let _permit = permit; // held until the search really ends, even if abandoned - if delay > 0 { - std::thread::sleep(Duration::from_millis(delay)); - } - let v = View { cfg: &cfg, state: &state, board: &board, history: &history, seat }; - let d = Player::dist(&mut worker, &v, hole); - let _ = tx.send(d); - }); - if let Err(e) = spawned { - return fallback(player, format!("spawn_failed: {e}")); - } - let res = rx.recv_timeout(budget); - let us = t_search.elapsed().as_micros() as u64; - self.c.search_micros.fetch_add(us, Relaxed); - self.c.search_max_micros.fetch_max(us, Relaxed); - let ms = t_search.elapsed().as_secs_f64() * 1e3; - match res { - Ok(d) => { - self.c.searched.fetch_add(1, Relaxed); - // Player::dist silently falls back to the blueprint when the search has no average - // for this hand; only call it "search" when the answer really differs from it. - if same_dist(&d, &player.blueprint_dist(view, hole)) { - self.c.no_mass.fetch_add(1, Relaxed); - (d, "blueprint", Some("no_search_mass".into()), ms) - } else { - (d, "search", None, ms) - } - } - Err(mpsc::RecvTimeoutError::Timeout) => { - self.c.timeouts.fetch_add(1, Relaxed); - let (d, s, w, _) = fallback(player, format!("search_timeout>{}ms: blueprint", budget.as_millis())); - (d, s, w, ms) - } - Err(mpsc::RecvTimeoutError::Disconnected) => { - self.c.panics.fetch_add(1, Relaxed); - let (d, s, w, _) = fallback(player, "search_panic: blueprint".into()); - (d, s, w, ms) - } - } - } -} +//! The bot: one [`Core`] per process, shared by every request. +//! +//! * The compact blueprint is mmapped once at startup (`Core::new`) and shared (lock-free reads). +//! * Each request builds a fresh [`search::policy::SearchPlayer`] by replaying the history +//! ([`crate::replay`]); the turn/river decision then runs a real-time search **on a worker thread +//! under a hard budget** (same two layers as `arena/openpoker/src/guard.rs`): the solver's +//! cooperative cap (70% of the budget) returns a truncated-but-valid solution; the hard +//! `recv_timeout` guarantees an answer, falling back to the blueprint action. +//! * A [`Gate`] bounds concurrent searches (they share one rayon pool). A timed-out search keeps +//! its slot until it really ends, so abandoned work can never pile up. + +use crate::api::*; +use crate::config::Config; +use crate::error::ApiError; +use crate::replay::{street_name, Hand}; +use bench::bp::{bucketer_by_name, sizing_by_name}; +use bench::mix; +use bench::policy::{Dist, Player, View}; +use blueprint::compact::Compact; +use cards::Card; +use nlhe::abstraction::{BetSizing, TrackOpts}; +use nlhe::Street; +use search::bp::Blueprint; +use search::policy::{SearchPlayer, SearchPolicy}; +use search::solver::SearchParams; +use serde_json::{json, Value}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{mpsc, Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +// ---------------------------------------------------------------------------------------- gate + +/// Counting semaphore with a timed acquire (decisions run on blocking threads). +pub struct Gate { + used: Mutex, + cv: Condvar, + cap: usize, +} + +pub struct Permit(Arc); + +impl Drop for Permit { + fn drop(&mut self) { + *self.0.used.lock().unwrap() -= 1; + self.0.cv.notify_one(); + } +} + +impl Gate { + pub fn new(cap: usize) -> Arc { + Arc::new(Gate { used: Mutex::new(0), cv: Condvar::new(), cap }) + } + pub fn acquire(g: &Arc, wait: Duration) -> Option { + let deadline = Instant::now() + wait; + let mut used = g.used.lock().unwrap(); + loop { + if *used < g.cap { + *used += 1; + return Some(Permit(g.clone())); + } + let left = deadline.checked_duration_since(Instant::now())?; + let (u, to) = g.cv.wait_timeout(used, left).unwrap(); + used = u; + if to.timed_out() && *used >= g.cap { + return None; + } + } + } + pub fn in_use(&self) -> usize { + *self.used.lock().unwrap() + } + pub fn capacity(&self) -> usize { + self.cap + } +} + +// -------------------------------------------------------------------------------- search params + +/// Parse `k=v,...` overrides of `SearchParams` (same keys as `openpoker --set` / `vsbp --set`). +pub fn apply_sets(prm: &mut SearchParams, sets: &str) -> Result<(), String> { + fn p(k: &str, v: &str) -> Result { + v.parse().map_err(|_| format!("--set {k}={v}: bad value")) + } + for kv in sets.split(',').filter(|x| !x.is_empty()) { + let (k, v) = kv.split_once('=').unwrap_or((kv, "1")); + let b = v != "0" && v != "false"; + match k { + "iters" => prm.iters = p(k, v)?, + "warm" => prm.warm_start = p(k, v)?, + "focus" => prm.focus_own = p(k, v)?, + "leaf" => prm.leaf = if v == "bp" { search::solver::LeafMode::Blueprint } else { search::solver::LeafMode::Cont4 }, + "final" => prm.play_final = b, + "flop" => prm.search_flop = b, + "turn" => prm.search_turn = b, + "river" => prm.search_river = b, + "pre" => prm.preflop_search = b, + "post" => prm.postflop_search = b, + "bpbeliefs" => prm.blueprint_beliefs = b, + "offbel" => prm.offtree_search_beliefs = b, + "ownbel" => prm.own_search_beliefs = b, + "tremble" => prm.belief_tremble = p(k, v)?, + "prune" => prm.prune_prob = p(k, v)?, + "ms" => prm.max_millis = Some(p(k, v)?), + "minflop" => prm.min_flop_players = p(k, v)?, + "vecmin" => prm.vec_min_street = match v { "flop" => Street::Flop, "turn" => Street::Turn, _ => Street::River }, + "vector" => prm.vector = b, + "sizing" | "later" => { + let s: BetSizing = match v { + "small" => search::tree::small_sizing(), + o => sizing_by_name(o).ok_or(format!("--set {k}={o}: unknown sizing"))?, + }; + if k == "sizing" { + prm.sizing = s; + } else { + prm.later_sizing = s; + } + } + _ => return Err(format!("unknown --set key {k}")), + } + } + Ok(()) +} + +// ------------------------------------------------------------------------------ belief checks + +/// Hero belief below this (uniform is ~1/1176 = 8.5e-4; `finish_round` floors the hero's own hand +/// at 1e-6) means the hero's earlier actions were off-policy for this hand. +const OFF_POLICY_BELIEF: f32 = 1e-5; + +fn hero_belief(player: &SearchPlayer, seat: usize, hole: [Card; 2]) -> f32 { + let i = cards::hole_index(hole[0], hole[1]); + player.beliefs().w.get(seat).and_then(|r| r.get(i)).copied().unwrap_or(1.0) +} + +/// Bit-identical distributions (same actions, same probabilities). +fn same_dist(a: &Dist, b: &Dist) -> bool { + a.len() == b.len() && (0..a.len()).all(|i| a.action(i) == b.action(i) && a.prob(i) == b.prob(i)) +} + +/// pokerfreak-Zusatz (03.12.): HYBRID_RUNDEN=1 - Rundenspeicher fuer das Nachspielen (search::rundenspeicher): die Belief-Fortschreibung +/// nimmt die damals gespielte Suchloesung statt der Tabelle (sonst `off_policy_history` nach eigenen Suchzuegen). HYBRID_RUNDEN_PLAETZE +/// (Standard 4096 Runden), HYBRID_RUNDEN_FLOP_ITERS: Iterationen, wenn eine verdraengte Flop-Runde neu gerechnet wird. Ohne: wie vorher. +fn runden() -> Option<&'static Arc> { + static A: std::sync::OnceLock>> = std::sync::OnceLock::new(); + A.get_or_init(|| { + std::env::var("HYBRID_RUNDEN").is_ok_and(|x| x == "1").then(|| { + let zahl = |k: &str| std::env::var(k).ok().and_then(|x| x.parse::().ok()); + Arc::new(search::rundenspeicher::RoundCache::new(zahl("HYBRID_RUNDEN_PLAETZE").unwrap_or(4096) as usize, zahl("HYBRID_RUNDEN_FLOP_ITERS"))) + }) + }) + .as_ref() +} + +/// pokerfreak-Zusatz (30.11.): HYBRID_EIGENER_POOL=1, ein 1-Faden-Pool je Suche (siehe `Core::decide`). +fn eigener_pool() -> bool { + static A: std::sync::OnceLock = std::sync::OnceLock::new(); + *A.get_or_init(|| std::env::var("HYBRID_EIGENER_POOL").is_ok_and(|x| x == "1")) +} + +// ------------------------------------------------------------------------------------------ core + +#[derive(Default)] +struct Counters { + requests: AtomicU64, + searched: AtomicU64, + timeouts: AtomicU64, + panics: AtomicU64, + busy: AtomicU64, + fallbacks: AtomicU64, + off_policy: AtomicU64, + no_mass: AtomicU64, + search_micros: AtomicU64, + search_max_micros: AtomicU64, +} + +/// Blueprint facts reported by `/v1/info`. +pub struct Meta { + pub path: String, + pub infosets: u64, + pub file_bytes: u64, + pub src_infosets: u64, + pub used_snapshots: bool, +} + +pub struct Core { + pub cfg: Config, + blueprint: Blueprint, + prm: SearchParams, + gate: Arc, + meta: Meta, + started: Instant, + c: Counters, + seq: AtomicU64, +} + +impl Core { + /// Load the compact blueprint, the card abstraction and the search pool. + pub fn new(cfg: &Config) -> Result { + let buckets = if cfg.buckets == "coarse" || cfg.buckets.starts_with("tables:") { cfg.buckets.clone() } else { format!("tables:{}", cfg.buckets) }; + let bucketer = bucketer_by_name(&buckets).ok_or_else(|| format!("cannot load card abstraction {buckets}"))?; + let sizing = sizing_by_name(&cfg.sizing).ok_or_else(|| format!("unknown sizing {}", cfg.sizing))?; + let compact = Arc::new(Compact::open(&cfg.blueprint).map_err(|e| format!("blueprint {}: {e}", cfg.blueprint.display()))?); + if cfg.warm { + compact.warm(); + } else { + compact.random_access(); + } + let meta = Meta { + path: cfg.blueprint.display().to_string(), + infosets: compact.len() as u64, + file_bytes: compact.file_bytes(), + src_infosets: compact.info().src_infosets, + used_snapshots: compact.info().used_snapshots, + }; + // pokerfreak-Zusatz (29.11.): HYBRID_UEBERSETZUNG=phm -> zufaellige pseudo-harmonische Uebersetzung (Ganzfried/Sandholm), + // HYBRID_ALLIN_SNAP (Standard 0.1 bei phm): ein Fast-All-in gilt nur als All-in, wenn der Rest <= x * Topf danach ist. + let mut track = TrackOpts::default(); + if std::env::var("HYBRID_UEBERSETZUNG").is_ok_and(|x| x == "phm") { + track.translation = nlhe::abstraction::Translation::Random; + track.allin_snap = 0.1; + } + if let Some(x) = std::env::var("HYBRID_ALLIN_SNAP").ok().and_then(|x| x.parse::().ok()) { + track.allin_snap = x; + } + let bp = Blueprint::from_source(compact, bucketer, sizing).with_opts(track); + Self::with_blueprint(cfg, bp, meta) + } + + /// Same over an already-built blueprint (tests). + pub fn with_blueprint(cfg: &Config, bp: Blueprint, meta: Meta) -> Result { + let mut prm = SearchParams::default(); + apply_sets(&mut prm, &cfg.sets)?; + if let Some(dir) = &cfg.search_buckets { + let sb = abstraction::search_buckets::SearchBuckets::new(Some(dir.into()), abstraction::search_buckets::BuildParams::default(), 64) + .map_err(|e| format!("search buckets {dir}: {e}"))?; + prm.search_buckets = Some(Arc::new(sb)); + } + if !cfg.search { + prm.postflop_search = false; + prm.preflop_search = false; + } + prm.parallel = true; + prm.pool = Some(Arc::new( + rayon::ThreadPoolBuilder::new() + .num_threads(cfg.search_threads.max(1)) + .thread_name(|i| format!("search-pool-{i}")) + .build() + .map_err(|e| format!("thread pool: {e}"))?, + )); + Ok(Core { + cfg: cfg.clone(), + blueprint: bp, + prm, + gate: Gate::new(cfg.search_concurrency.max(1)), + meta, + started: Instant::now(), + c: Counters::default(), + seq: AtomicU64::new(0), + }) + } + + pub fn gate(&self) -> &Arc { + &self.gate + } + + pub fn next_request_id(&self) -> String { + format!("r-{:x}-{}", crate::log::now_ms(), self.seq.fetch_add(1, Relaxed)) + } + + /// `GET /v1/info`. + pub fn info(&self) -> Value { + let p = &self.prm; + let n = self.c.searched.load(Relaxed).max(1) as f64; + json!({ + "model_id": self.cfg.model_id, + "name": "SHARINGAN-1", + "version": env!("CARGO_PKG_VERSION"), + "blueprint": { + "path": self.meta.path, "infosets": self.meta.infosets, "file_bytes": self.meta.file_bytes, + "source_infosets": self.meta.src_infosets, "snapshot_averaged": self.meta.used_snapshots, + "format": "PLCP1 (compact, mmap)", + }, + "sizing": self.cfg.sizing, + "buckets": self.cfg.buckets, + "players": "2-6 (trained for 6-max, 100 bb; 3-5 players embedded in the 6-max tree)", + "search": { + "enabled": self.cfg.search, + "set": self.cfg.sets, + "iters": p.iters, + "flop": p.search_flop, "turn": p.search_turn, "river": p.search_river, + "preflop_off_tree": p.preflop_search, + "play_final": p.play_final, + "leaf": format!("{:?}", p.leaf), + "budget_ms": self.cfg.budget_ms, + "cooperative_cap_ms": (self.cfg.budget_ms * 7 / 10).max(1), + "threads": self.cfg.search_threads, + "concurrency": self.gate.capacity(), + "queue_ms": self.cfg.queue_ms, + }, + "max_stack_bb": self.cfg.max_stack_bb, + "limits": {"max_batch": self.cfg.max_batch, "rate_rps": self.cfg.rate_rps, "rate_burst": self.cfg.rate_burst, "max_inflight": self.cfg.max_inflight}, + "panic_strategy": if cfg!(panic = "unwind") { "unwind" } else { "abort" }, + "stats": { + "uptime_s": self.started.elapsed().as_secs(), + "requests": self.c.requests.load(Relaxed), + "searched": self.c.searched.load(Relaxed), + "search_timeouts": self.c.timeouts.load(Relaxed), + "search_panics": self.c.panics.load(Relaxed), + "search_busy": self.c.busy.load(Relaxed), + "fallbacks": self.c.fallbacks.load(Relaxed), + "off_policy_history": self.c.off_policy.load(Relaxed), + "no_search_mass": self.c.no_mass.load(Relaxed), + "runden": runden().map(|c| { let s = c.stats(); json!({"treffer": s.treffer, "neu_gerechnet": s.neu_gerechnet, "gemerkt": s.gemerkt, "plaetze": c.len()}) }), + "search_mean_ms": self.c.search_micros.load(Relaxed) as f64 / n / 1e3, + "search_max_ms": self.c.search_max_micros.load(Relaxed) as f64 / 1e3, + "searches_in_flight": self.gate.in_use(), + }, + }) + } + + pub fn health(&self) -> Value { + json!({"status": "ok", "model_id": self.cfg.model_id, "uptime_s": self.started.elapsed().as_secs(), "searches_in_flight": self.gate.in_use()}) + } + + /// Answer one request. Blocking: call from a blocking thread. + pub fn decide(&self, req: &ActRequest, request_id: String) -> Result { + let t0 = Instant::now(); + self.c.requests.fetch_add(1, Relaxed); + let opts = &req.options; + if opts.time_budget_ms == Some(0) { + return Err(ApiError::invalid("bad_budget", "options.time_budget_ms must be > 0")); + } + let budget_ms = opts.time_budget_ms.map_or(self.cfg.budget_ms, |b| b.min(self.cfg.budget_ms)); + let seed = opts.seed.unwrap_or_else(|| mix(crate::log::now_ms().wrapping_mul(1_000_003) ^ t0.elapsed().as_nanos() as u64, self.seq.fetch_add(1, Relaxed))); + let mut prm = self.prm.clone(); + let cap = (budget_ms * 7 / 10).max(1); + prm.max_millis = Some(prm.max_millis.map_or(cap, |m| m.min(cap))); + prm.seed = mix(seed, 7); + // pokerfreak-Zusatz (30.11., Mehrtisch): options.iters ersetzt die feste Iterationszahl fuer diese Anfrage; + // HYBRID_EIGENER_POOL=1: jede Suche auf einem eigenen Pool mit einem Faden (wie --search-threads 1, also bitgleich + // reproduzierbar), damit mehrere Suchen nebeneinander laufen statt sich einen Pool zu teilen. Ohne beides wie vorher. + if let Some(i) = opts.iters.filter(|&i| i > 0) { + prm.iters = i; + } + if opts.search && eigener_pool() { + let pl = rayon::ThreadPoolBuilder::new() + .num_threads(1) + .thread_name(|_| "search-slot".into()) + .build() + .map_err(|e| ApiError::internal(format!("pool: {e}")))?; + prm.pool = Some(Arc::new(pl)); + } + let mut policy = SearchPolicy::new("serve", self.blueprint.clone(), prm); + if let Some(c) = runden() { + let hole = crate::replay::parse_cards_field("hole_cards", &req.hole_cards).ok().filter(|v| v.len() == 2).map(|v| [v[0], v[1]]); + policy = policy.with_rounds(c.clone(), hole); + } + + let mut hand = Hand::replay(req, Some(&policy), opts.track_seed.map_or(mix(seed, 1), |t| mix(t, 1)))?; + let street = hand.real.street(); + + let mut source = "blueprint"; + let mut reason: Option = None; + let mut search_ms: Option = None; + let mut dist: Option = None; + if let Some(why) = hand.desync.clone() { + source = "fallback"; + reason = Some(format!("desync: {why}")); + } else if let Some(mut player) = hand.player.take() { + let hole = hand.hole; + let view = hand.view(); + let want_search = opts.search && self.cfg.search; + if !want_search { + dist = Some(player.blueprint_dist(&view, hole)); + } else if !player.needs_search(&view) { + dist = Some(Player::dist(&mut player, &view, hole)); + } else if hero_belief(&player, view.seat, hole) < OFF_POLICY_BELIEF { + // The hero's own earlier actions had ~zero likelihood under the hero's strategy + // (e.g. a replayed foreign hand): the subgame would have no mass for this hand and + // the search average would be empty. Skip the search, answer from the blueprint. + self.c.off_policy.fetch_add(1, Relaxed); + dist = Some(player.blueprint_dist(&view, hole)); + reason = Some("off_policy_history".into()); + } else { + let (d, src, why, ms) = self.guarded_search(&mut player, &view, hole, Duration::from_millis(budget_ms)); + dist = Some(d); + source = src; + reason = why; + search_ms = Some(ms); + } + } + if dist.as_ref().is_some_and(|d| d.is_empty()) { + dist = None; + source = "fallback"; + reason = Some("policy returned an empty distribution".into()); + } + + // ---- choose, map to real chips, guard + let mut notes = std::mem::take(&mut hand.notes); + let mut ra = match &dist { + Some(d) => { + let i = if opts.sample { + d.sample(cards::Rng::new(mix(seed, 3)).f64()) + } else { + (0..d.len()).max_by(|&a, &b| d.prob(a).total_cmp(&d.prob(b)).then(b.cmp(&a))).unwrap_or(0) + }; + hand.to_real(d.action(i)) + } + // This fallback uses real chips and cards; to_real would scale it twice. + None => bench::bp::fallback_action(&hand.real, &hand.board, hand.hole), + }; + if self.cfg.max_stack_bb > 0.0 { + let capc = (self.cfg.max_stack_bb * hand.big_blind as f64).round() as i64; + if let Some((na, note)) = hand.cap_guard(ra, capc) { + notes.push(note); + ra = na; + } + } + if !hand.is_legal(ra) { + notes.push(format!("internal: {ra:?} was not legal; replaced by the passive action")); + ra = hand.passive(); + source = "fallback"; + reason.get_or_insert_with(|| "illegal mapped action".into()); + } + if source == "fallback" { + self.c.fallbacks.fetch_add(1, Relaxed); + } + + let probs = opts.include_probs.then(|| { + let mut out: Vec = vec![]; + if let Some(d) = &dist { + for i in 0..d.len() { + // Report the same real-chip actions that selection can actually return. + // Several abstract entries may collapse onto one capped action. + let mut real = hand.to_real(d.action(i)); + if self.cfg.max_stack_bb > 0.0 { + let cap = (self.cfg.max_stack_bb * hand.big_blind as f64).round() as i64; + if let Some((guarded, _)) = hand.cap_guard(real, cap) { + real = guarded; + } + } + if !hand.is_legal(real) { + real = hand.passive(); + } + let a = hand.describe(real); + let p = d.prob(i); + match out.iter_mut().find(|o| o.kind == a.kind && o.to == a.to) { + Some(o) => o.p += p, + None => out.push(ProbOut { kind: a.kind, to: a.to, p }), + } + } + } else { + let a = hand.describe(ra); + out.push(ProbOut { kind: a.kind, to: a.to, p: 1.0 }); + } + for o in out.iter_mut() { + o.p = (o.p * 1e6).round() / 1e6; + } + out.sort_by(|a, b| b.p.total_cmp(&a.p)); + out + }); + + Ok(ActResponse { + request_id, + hand_id: req.hand_id.clone(), + model_id: self.cfg.model_id.clone(), + street: street_name(street), + action: hand.describe(ra), + source, + fallback_reason: reason, + probs, + legal: hand.legal_out(), + timing: Timing { total_ms: t0.elapsed().as_secs_f64() * 1e3, search_ms, budget_ms }, + notes, + }) + } + + + /// Exploitability gate (no budget guard, no sampling): replay `req`, run the search with `sets` + /// (`k=v,...` as `--set`) and `iters` iterations, then measure the exploitability of the + /// resulting subgame strategy (`search::exploit`). `blueprint_only`: measure the blueprint + /// profile instead (no search). Blocking; not for the serving path. + pub fn teilspiel(&self, req: &ActRequest, sets: &str, iters: u64, opts: &search::exploit::Opts, blueprint_only: bool) -> Result { + let mut prm = self.prm.clone(); + apply_sets(&mut prm, sets).map_err(|e| ApiError::invalid("bad_sets", e))?; + prm.iters = iters; + prm.max_millis = None; + prm.parallel = true; + let seed = req.options.seed.unwrap_or(1); + prm.seed = mix(seed, 7); + if prm.vector { + prm.vec_keep_all = true; + } + let policy = SearchPolicy::new("teilspiel", self.blueprint.clone(), prm); + let mut hand = Hand::replay(req, Some(&policy), req.options.track_seed.map_or(mix(seed, 1), |t| mix(t, 1)))?; + if let Some(why) = hand.desync.clone() { + return Err(ApiError::invalid("desync", why)); + } + let mut player = hand.player.take().ok_or_else(|| ApiError::invalid("no_player", "hero has no search player"))?; + let view = hand.view(); + // The bot's engine is scaled to a 100-chip big blind. + let mut opts = opts.clone(); + opts.big_blind = 100; + if blueprint_only { + let (r, _, _) = player.exploit_report(&opts, true).ok_or_else(|| ApiError::invalid("no_subgame", "no searchable subgame"))?; + return Ok(report_json(&r, 0, 0.0)); + } + if !player.needs_search(&view) { + return Err(ApiError::invalid("no_search", "this decision is not searched")); + } + let _ = Player::dist(&mut player, &view, hand.hole); + let (r, it, ms) = player.exploit_report(&opts, false).ok_or_else(|| ApiError::invalid("no_solution", "search produced no solution"))?; + Ok(report_json(&r, it, ms)) + } + + /// Run the search on a worker thread; blueprint on timeout / panic / no free slot. + fn guarded_search(&self, player: &mut SearchPlayer, view: &View, hole: [Card; 2], budget: Duration) -> (Dist, &'static str, Option, f64) { + let t0 = Instant::now(); + let fallback = |player: &mut SearchPlayer, why: String| { + player.detach_search(); + (player.blueprint_dist(view, hole), "fallback", Some(why), t0.elapsed().as_secs_f64() * 1e3) + }; + let Some(permit) = Gate::acquire(&self.gate, Duration::from_millis(self.cfg.queue_ms)) else { + self.c.busy.fetch_add(1, Relaxed); + return fallback(player, format!("search_busy: all {} search slots in use for {}ms; blueprint", self.gate.capacity(), self.cfg.queue_ms)); + }; + let t_search = Instant::now(); + let mut worker = player.clone(); + let (cfg, state, seat) = (*view.cfg, *view.state, view.seat); + let (board, history) = (view.board.to_vec(), view.history.to_vec()); + let delay = self.cfg.debug_search_delay_ms; + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("search-decision".into()).spawn(move || { + let _permit = permit; // held until the search really ends, even if abandoned + if delay > 0 { + std::thread::sleep(Duration::from_millis(delay)); + } + let v = View { cfg: &cfg, state: &state, board: &board, history: &history, seat }; + let d = Player::dist(&mut worker, &v, hole); + let _ = tx.send(d); + }); + if let Err(e) = spawned { + return fallback(player, format!("spawn_failed: {e}")); + } + let res = rx.recv_timeout(budget); + let us = t_search.elapsed().as_micros() as u64; + self.c.search_micros.fetch_add(us, Relaxed); + self.c.search_max_micros.fetch_max(us, Relaxed); + let ms = t_search.elapsed().as_secs_f64() * 1e3; + match res { + Ok(d) => { + self.c.searched.fetch_add(1, Relaxed); + // Player::dist silently falls back to the blueprint when the search has no average + // for this hand; only call it "search" when the answer really differs from it. + if same_dist(&d, &player.blueprint_dist(view, hole)) { + self.c.no_mass.fetch_add(1, Relaxed); + (d, "blueprint", Some("no_search_mass".into()), ms) + } else { + (d, "search", None, ms) + } + } + Err(mpsc::RecvTimeoutError::Timeout) => { + self.c.timeouts.fetch_add(1, Relaxed); + let (d, s, w, _) = fallback(player, format!("search_timeout>{}ms: blueprint", budget.as_millis())); + (d, s, w, ms) + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + self.c.panics.fetch_add(1, Relaxed); + let (d, s, w, _) = fallback(player, "search_panic: blueprint".into()); + (d, s, w, ms) + } + } + } +} + +fn report_json(r: &search::exploit::Report, iters: u64, solve_ms: f64) -> Value { + let conv = |x: f64| json!({"chips": x, "pct_pot": r.pct_pot(x), "bb": r.bb(x)}); + let pl: Vec = r + .players + .iter() + .map(|p| { + json!({ + "seat": p.seat, "value_chips": p.value, "br_chips": p.br, "gain": conv(p.gain), + "gain_se_pct_pot": p.gain_se.map(|s| r.pct_pot(s)), "gadget": p.gadget.map(conv), + }) + }) + .collect(); + json!({ + "mode": r.mode, "players": pl, "sum_gain": conv(r.sum_gain), + "ausnutzbarkeit_topf": r.pct_pot(r.sum_gain), + "ausnutzbarkeit_bb": r.bb(r.sum_gain), + "gadget_topf": r.players.iter().map(|p| p.gadget).collect::>>().map(|g| r.pct_pot(g.iter().sum::())), + "pot_chips": r.pot, "big_blind": r.big_blind, "final_iterate": r.final_iterate, + "miss_share": r.miss_share, "leaf_share": r.leaf_share, + "iters": iters, "solve_ms": solve_ms, "eval_ms": r.millis, + }) +}