search::exploit: exact HU / sampled multiway exploitability gate of the search strategy in its subgame

Exact vector best response over the MC solver's tables (HU, solved to the end),
sampled best-response lower bound for 3+ players and leaf subgames, HU re-solve
gadget against the blueprint CBV, sharingan-teilspiel bin (Farm spur format).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 18:59:19 +01:00
co-authored by Claude Opus 5.5
parent 5cf9863500
commit 554fd93188
8 changed files with 3874 additions and 2793 deletions
+358
View File
@@ -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<f64>,
/// Heads-up gadget value (chips), see module docs.
pub gadget: Option<f64>,
}
#[derive(Clone, Debug)]
pub struct Report {
/// `"exact_hu"` or `"sampled_lower_bound"`.
pub mode: &'static str,
pub players: Vec<PlayerGain>,
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<f64>,
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<FlopView>,
/// `(board mask, street)` -> per compact hand: (blueprint bucket, search bucket).
buckets: RefCell<HashMap<(u64, u8), Vec<(u32, u32)>>>,
lookups: Cell<u64>,
misses: Cell<u64>,
}
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<std::cell::Ref<'_, Vec<(u32, u32)>>> = 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<HashMap<u64, nlhe::Action>> = 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::<Vec<f64>>());
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<PlayerGain> {
(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::<f64>() / 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<Report> {
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<Report> {
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<Report> {
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<Report> {
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,
})
}
+12 -11
View File
@@ -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;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+191
View File
@@ -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<Card> {
parse_cards(s).unwrap()
}
fn hu_bp() -> &'static Blueprint {
static B: OnceLock<Blueprint> = 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<Blueprint> = 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<u64, Action>) -> 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>, 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::<f64>());
(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());
}
}
@@ -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": <ActRequest>, "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, "<candidate>": {...}}`.
//!
//! 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<String> = std::env::args().skip(1).collect();
let mut own: HashMap<String, String> = HashMap::new();
let mut rest: Vec<String> = 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::<u64>().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<String> = 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<HashSet<usize>> = 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::<u64>().ok());
let core = Core::new(&cfg).unwrap_or_else(|e| {
eprintln!("error: {e}");
std::process::exit(1)
});
let done: HashSet<String> = std::fs::read_to_string(out_path)
.map(|t| t.lines().filter_map(|l| serde_json::from_str::<Value>(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<String> = 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::<Value>(line) else { continue };
let f = &v["frage"];
if f["op"] != "suche" {
continue;
}
let Ok(req) = serde_json::from_value::<ActRequest>(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::<Vec<_>>().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);
}
}
File diff suppressed because it is too large Load Diff