diff --git a/sharingan-1/search/src/exploit.rs b/sharingan-1/search/src/exploit.rs index 6ff424a1..d151bbcd 100644 --- a/sharingan-1/search/src/exploit.rs +++ b/sharingan-1/search/src/exploit.rs @@ -46,7 +46,7 @@ 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 crate::vector::{br_cfv, report_from, BrReport, Query, Strat, VecGame}; use abstraction::search_buckets::FlopView; use cards::bit; use nlhe::abstraction::{ActionList, Shadow, MAX_ACTIONS}; @@ -64,11 +64,13 @@ pub struct Opts { /// Heads-up: also compute the gadget value (one more exact pass per player). pub gadget: bool, pub big_blind: i32, + /// Threads for the independent exact best-response passes (heads-up). + pub threads: usize, } impl Default for Opts { fn default() -> Self { - Opts { br_iters: 200_000, eval_samples: 200_000, gadget: true, big_blind: 100 } + Opts { br_iters: 200_000, eval_samples: 200_000, gadget: true, big_blind: 100, threads: 2 } } } @@ -98,6 +100,8 @@ pub struct Report { pub miss_share: f64, pub leaf_share: Option, pub millis: f64, + /// Players still in the hand at the subgame root. + pub live: usize, } impl Report { @@ -125,6 +129,8 @@ pub struct ProfileStrat<'a> { buckets: RefCell>>, lookups: Cell, misses: Cell, + /// Blueprint prior per (public node, hand or bucket): avoids repeated cold-mmap lookups. + priors: RefCell>>, } impl<'a> ProfileStrat<'a> { @@ -146,6 +152,7 @@ impl<'a> ProfileStrat<'a> { buckets: RefCell::new(HashMap::new()), lookups: Cell::new(0), misses: Cell::new(0), + priors: RefCell::new(HashMap::new()), } } pub fn miss_share(&self) -> f64 { @@ -216,7 +223,17 @@ impl Strat for ProfileStrat<'_> { } // 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) { + let ck = (q.akey, if on_root { hole as u64 } else { bpb as u64 | (q.street.idx() as u64) << 32 }); + let cached = self.priors.borrow().get(&ck).copied(); + let pr = match cached { + Some(p) => p, + None => { + let p = self.bp.prior(&sh, q.st, &list, bpb); + self.priors.borrow_mut().insert(ck, p); + p + } + }; + match pr { Some(pr) => buf[..n].copy_from_slice(&pr[..n]), None => buf[..n].iter_mut().for_each(|x| *x = 1.0 / n as f32), } @@ -248,66 +265,89 @@ fn vec_game<'a>(sg: &'a Subgame<'a>, seats: [usize; 2]) -> VecGame<'a> { } } -fn gain_pair(r: &BrReport, seats: [usize; 2], alt: Option<&BrReport>) -> Vec { +fn gain_pair(r: &BrReport, seats: [usize; 2], alt: Option<&[Vec; 2]>) -> 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 + (0..m).map(|h| r.reach[p][h] * (r.br_cfv[p][h] - a[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). +/// Which strategy profile an exact pass evaluates. +#[derive(Clone, Copy)] +enum Prof<'a> { + Tables(&'a Solution), + Vector(&'a crate::vector::VecSolution), + Blueprint, +} + +/// `(cfv vector, strategy lookups, misses)` of one best-response / profile-value pass. +type Pass = (Vec, u64, u64); + +fn run_pass(sg: &Subgame, seats: [usize; 2], prof: Prof, p: usize, play_br: bool) -> Pass { + let g = vec_game(sg, seats); + let final_it = sg.params.play_final; + match prof { + Prof::Vector(v) => { + let pooled: Option<&dyn crate::vector::Bucketing> = if sg.params.vec_pooled { Some(sg.bp as &dyn crate::vector::Bucketing) } else { None }; + (br_cfv(&g, &v.strategy(!final_it, pooled), p, play_br), 0, 0) + } + Prof::Tables(s) => { + let st = ProfileStrat::new(sg, Some(s), final_it); + (br_cfv(&g, &st, p, play_br), st.lookups.get(), st.misses.get()) + } + Prof::Blueprint => { + let st = ProfileStrat::new(sg, None, false); + (br_cfv(&g, &st, p, play_br), 0, 0) + } + } +} + +/// Run `tasks` (prof, player, play_br) on at most `threads` threads. +fn run_passes(sg: &Subgame, seats: [usize; 2], tasks: &[(Prof, usize, bool)], threads: usize) -> Vec { + let next = std::sync::atomic::AtomicUsize::new(0); + let results: std::sync::Mutex>> = std::sync::Mutex::new(vec![None; tasks.len()]); + std::thread::scope(|sc| { + for _ in 0..threads.clamp(1, tasks.len().max(1)) { + sc.spawn(|| loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if i >= tasks.len() { + break; + } + let (prof, p, play_br) = tasks[i]; + let r = run_pass(sg, seats, prof, p, play_br); + results.lock().unwrap()[i] = Some(r); + }); + } + }); + results.into_inner().unwrap().into_iter().map(|r| r.expect("pass finished")).collect() +} + +/// Exact heads-up evaluation of a profile: the solution's tables / vector strategy, or (`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 prof = match sol { + Some(s) => s.vector().map_or(Prof::Tables(s), Prof::Vector), + None => Prof::Blueprint, }; - 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); + let mut tasks = vec![(prof, 0, true), (prof, 1, true), (prof, 0, false), (prof, 1, false)]; + let gadget = opts.gadget && sol.is_some(); + if gadget { + tasks.extend([(Prof::Blueprint, 0, true), (Prof::Blueprint, 1, true)]); } - 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 mut res = run_passes(sg, seats, &tasks, opts.threads); + let (lookups, misses) = res.iter().take(4).fold((0, 0), |a, r| (a.0 + r.1, a.1 + r.2)); + let mut take = |i: usize| std::mem::take(&mut res[i].0); + let (b0, b1, p0, p1) = (take(0), take(1), take(2), take(3)); + let alt = gadget.then(|| [take(4), take(5)]); 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 rep = report_from(&g, [b0, b1], [p0, p1]); let players = gain_pair(&rep, seats, alt.as_ref()); let sum_gain = players.iter().map(|p| p.gain).sum(); Some(Report { @@ -317,12 +357,21 @@ fn exact_hu_vector(sg: &Subgame, _sol: &Solution, v: &crate::vector::VecSolution pot: sg.root.pot() as f64, big_blind: opts.big_blind as f64, final_iterate: sg.params.play_final, - miss_share: 0.0, + miss_share: misses as f64 / lookups.max(1) as f64, leaf_share: None, millis: t0.elapsed().as_secs_f64() * 1e3, + live: sg.root.live_count() as usize, }) } +/// 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 { + return exact_hu(sg, Some(sol), opts); + } + sampled(sg, sol, opts) +} + fn sampled(sg: &Subgame, sol: &Solution, opts: &Opts) -> Option { let t0 = Instant::now(); let root = &sg.root; @@ -343,7 +392,9 @@ fn sampled(sg: &Subgame, sol: &Solution, opts: &Opts) -> Option { 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(); + // The true best response is never worse than the profile itself: a negative estimate only means the + // learned response is not yet as good as the profile, so it counts as 0 in the sum (per-player raw values stay in `players`). + let sum_gain = players.iter().map(|p| p.gain.max(0.0)).sum(); Some(Report { mode: "sampled_lower_bound", players, @@ -354,5 +405,6 @@ fn sampled(sg: &Subgame, sol: &Solution, opts: &Opts) -> Option { miss_share: miss / k.max(1.0), leaf_share: Some(leaf / k.max(1.0)), millis: t0.elapsed().as_secs_f64() * 1e3, + live: sg.root.live_count() as usize, }) } diff --git a/sharingan-1/search/src/solver.rs b/sharingan-1/search/src/solver.rs index d6e252d0..e99ebb33 100644 --- a/sharingan-1/search/src/solver.rs +++ b/sharingan-1/search/src/solver.rs @@ -327,6 +327,8 @@ struct Solver<'a> { br_p: usize, lookups: AtomicU64, misses: AtomicU64, + /// Best-response mode: blueprint prior per missed infoset (the blueprint is a cold mmap, a lookup costs microseconds to milliseconds). + prior_cache: Vec>>>, } fn hash01(a: u64, b: u64, c: u64, d: u64) -> f64 { @@ -484,6 +486,7 @@ impl<'a> Solver<'a> { br_p, lookups: AtomicU64::new(0), misses: AtomicU64::new(0), + prior_cache: (0..64).map(|_| std::sync::Mutex::new(HashMap::new())).collect(), } } @@ -641,6 +644,18 @@ impl<'a> Solver<'a> { 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| { + // Best-response mode: start from the strategy being evaluated (so the response is + // at least as good as it from the first iteration on), else from the blueprint. + if let Some((fx, fin)) = self.fixed { + let mut own = [0f32; MAX_ACTIONS]; + let hit = fx.table.find(key).filter(|s| s.n == n).is_some_and(|s| if fin { fx.table.strategy(s, &mut own[..n]); true } else { fx.table.average(s, &mut own[..n]) }); + if hit { + for (x, &q) in r.iter_mut().zip(&own[..n]) { + *x = lam * q; + } + return; + } + } 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; @@ -741,7 +756,18 @@ impl<'a> Solver<'a> { }); if !hit { self.misses.fetch_add(1, Relaxed); - match self.sg.bp.prior(bph, st, list, bucket) { + let ck = mix(key, bucket as u64 + 1); + let shard = &self.prior_cache[(ck >> 20) as usize % 64]; + let cached = shard.lock().unwrap().get(&ck).copied(); + let pr = match cached { + Some(p) => p, + None => { + let p = self.sg.bp.prior(bph, st, list, bucket); + shard.lock().unwrap().insert(ck, p); + p + } + }; + match pr { Some(pr) => out.copy_from_slice(&pr[..n]), None => out.iter_mut().for_each(|x| *x = 1.0 / n as f32), } @@ -996,7 +1022,8 @@ impl<'a> Solver<'a> { /// `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 t_start = Instant::now(); + let params = SearchParams { iters: br_iters, warm_start: 16.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, @@ -1028,6 +1055,7 @@ pub fn best_response_sampled(sg: &Subgame, sol: &Solution, p: usize, br_iters: u }), None => drive(), } + let learn_ms = t_start.elapsed().as_millis(); let eval_seed = mix(sg.seed, 0xE7A1); let one = |i: u64| -> Option<(f32, f32, bool)> { let mk = || { @@ -1051,6 +1079,9 @@ pub fn best_response_sampled(sg: &Subgame, sol: &Solution, p: usize, br_iters: u } None => run(), }; + if std::env::var_os("TEILSPIEL_LOG").is_some() { + eprintln!(" best response seat {p}: learn {learn_ms} ms, eval {} ms", t_start.elapsed().as_millis() - learn_ms); + } 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; diff --git a/sharingan-1/search/src/vector.rs b/sharingan-1/search/src/vector.rs index 430b35c7..a9112437 100644 --- a/sharingan-1/search/src/vector.rs +++ b/sharingan-1/search/src/vector.rs @@ -750,25 +750,40 @@ pub struct BrReport { 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 { +/// Counterfactual-value vector of player `p` (compact hands, weighted by the opponent's root +/// reach) against `s` for the other player: `play_br` = `p` best-responds, else `p` also follows +/// `s`. Independent of every other call, so the four to six vectors of a report can be computed +/// on separate threads (each call owns its `Core`). +pub fn br_cfv(g: &VecGame, s: &dyn Strat, p: usize, play_br: bool) -> Vec { let mut core = Core::new(g, 0, true, false); + let r: Vec = core.hands.idx.iter().map(|&i| g.ranges[1 - p][i as usize]).collect(); + core.br(g.root, 0, 0, p, &r, s, play_br) +} + +/// Assemble the report from `br_cfv` results: `br[p]` (best response) and `prof[p]` (profile value). +pub fn report_from(g: &VecGame, br: [Vec; 2], prof: [Vec; 2]) -> BrReport { + let 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 tot = |v: &Vec, p: usize| (0..m).map(|h| r[p][h] * v[h]).sum::() / z; + BrReport { + value: [tot(&prof[0], 0), tot(&prof[1], 1)], + br: [tot(&br[0], 0), tot(&br[1], 1)], + dead: core.dead, + br_cfv: br, + reach: r, + z, + hands: core.hands, } - let dead = core.dead; - BrReport { value, br, br_cfv, reach: r, z, dead, hands: core.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 br = [br_cfv(g, s, 0, true), br_cfv(g, s, 1, true)]; + let prof = [br_cfv(g, s, 0, false), br_cfv(g, s, 1, false)]; + report_from(g, br, prof) } /// Exact best-response values. Returns `(exploitability, [br0, br1])` in chips: the mean of diff --git a/sharingan-1/search/tests/exploit.rs b/sharingan-1/search/tests/exploit.rs index e6df23a8..ffcf4b46 100644 --- a/sharingan-1/search/tests/exploit.rs +++ b/sharingan-1/search/tests/exploit.rs @@ -166,7 +166,7 @@ fn multiway_sampled_lower_bound_falls_with_iterations() { 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 opts = Opts { br_iters: 20_000, eval_samples: 20_000, gadget: false, big_blind: 100, threads: 2 }; let rep = measure(&sg, &sol, &opts).unwrap(); assert_eq!(rep.mode, "sampled_lower_bound"); assert_eq!(rep.players.len(), 3); diff --git a/sharingan-1/serve/src/bin/sharingan-teilspiel.rs b/sharingan-1/serve/src/bin/sharingan-teilspiel.rs index 47f9b1ce..418ee0f4 100644 --- a/sharingan-1/serve/src/bin/sharingan-teilspiel.rs +++ b/sharingan-1/serve/src/bin/sharingan-teilspiel.rs @@ -12,7 +12,7 @@ //! `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 +//! [--br-iters N] [--eval-samples N] [--only i,j] [--no-gadget] [--max-lines N] [--threads N]`; everything else //! is `sharingan-serve`'s configuration (`--blueprint`, `--buckets`, `--sizing`, `--set`, ...). use serde_json::{json, Value}; @@ -23,7 +23,7 @@ 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"]; +const OWN: &[&str] = &["requests", "out", "cands", "iters-other", "iters-flop", "br-iters", "eval-samples", "only", "no-gadget", "max-lines", "threads"]; fn candidate_sets(name: &str) -> Option<&'static str> { Some(match name { @@ -78,6 +78,7 @@ fn main() { eval_samples: num("eval-samples", 200_000), gadget: !own.contains_key("no-gadget"), big_blind: 100, + threads: num("threads", 2) as usize, }; let iters_other = num("iters-other", 24_000); let iters_flop = own.get("iters-flop").and_then(|v| v.parse::().ok()); diff --git a/sharingan-1/serve/src/decide.rs b/sharingan-1/serve/src/decide.rs index 84def4e5..a7f96692 100644 --- a/sharingan-1/serve/src/decide.rs +++ b/sharingan-1/serve/src/decide.rs @@ -502,11 +502,11 @@ impl Core { 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"))?; + let (r, _, _) = player.exploit_report(&opts, true).ok_or_else(|| ApiError::invalid("no_subgame", format!("no searchable subgame (search_active={}, street {:?})", player.search_active(), view.state.street())))?; return Ok(report_json(&r, 0, 0.0)); } if !player.needs_search(&view) { - return Err(ApiError::invalid("no_search", "this decision is not searched")); + return Err(ApiError::invalid("no_search", format!("this decision is not searched (search_active={}, street {:?}, post={} flop={} live={} minflop={} board={})", player.search_active(), view.state.street(), policy.params().postflop_search, policy.params().search_flop, view.state.live_count(), policy.params().min_flop_players, view.board.len()))); } 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"))?; @@ -591,7 +591,7 @@ fn report_json(r: &search::exploit::Report, iters: u64, solve_ms: f64) -> Value "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, + "miss_share": r.miss_share, "leaf_share": r.leaf_share, "live": r.live, "iters": iters, "solve_ms": solve_ms, "eval_ms": r.millis, }) }