Files
pokerfreak/sharingan-1/search/tests/exploit.rs
T

386 lines
19 KiB
Rust

//! 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, rake: nlhe::Rake::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 mc_solution_is_nearly_unexploitable_after_millions_of_iterations_heads_up() {
// Measured (explore_mc_river_curve): 5.5% pot after 3M iterations, 3.0% after 6M.
let (long, _, _) = river_subgame_pct(3_000_000, false);
assert!(long < 10.0, "3M iterations: {long}% pot");
}
#[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, threads: 2, rake: None };
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());
}
}
#[test]
fn vector_candidate_is_measured_through_the_same_gate() {
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 (none, frozen) = (Extras::new(), HashMap::new());
let run = |passes: u64| {
let prm = SearchParams { vector: true, vec_keep_all: true, vec_iters: [passes; 3], vec_min_street: Street::Flop, parallel: false, ..Default::default() };
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);
assert!(sol.vector().is_some());
let rep = measure(&sg, &sol, &Opts { gadget: false, ..Default::default() }).expect("report");
assert_eq!(rep.mode, "exact_hu");
rep.pct_pot(rep.sum_gain)
};
let (short, long) = (run(10), run(600));
assert!(long < 0.5 * short && long < 2.0, "10 passes: {short}% pot, 600 passes: {long}% pot");
}
// ---- rake in the measurement ------------------------------------------------------------------------------------------
/// A strategy that plays a fixed script: at every node it picks the first action satisfying `pick`.
struct Script<'a> {
sz: &'a BetSizing,
pick: fn(&State, nlhe::Action) -> bool,
}
impl Strat for Script<'_> {
fn probs(&self, q: &Query, n: usize, out: &mut [f64]) {
let m = q.hands.len();
let mut list = nlhe::abstraction::ActionList::new();
search::tree::search_actions(q.st, self.sz, &[], &mut list);
assert_eq!(list.len(), n);
let k = (0..n).find(|&i| (self.pick)(q.st, list.get(i))).expect("a scripted action exists");
for a in 0..n {
for h in 0..m {
out[a * m + h] = if a == k { 1.0 } else { 0.0 };
}
}
}
}
fn single(board: &[Card], hole: &str) -> Vec<f64> {
let h = cs(hole);
let bm = cards::mask_of(board);
cards::all_holes().iter().map(|x| if (x[0] == h[0] && x[1] == h[1]) || (x[0] == h[1] && x[1] == h[0]) { assert_eq!((cards::bit(x[0]) | cards::bit(x[1])) & bm, 0); 1.0 } else { 0.0 }).collect()
}
/// 5 % of the pot, rounded to the chip, cap 50 chips, at a 100-chip big blind (1 cent = 1 chip), so a 200-chip pot pays 10.
fn test_rule() -> nlhe::RakeRule {
nlhe::RakeRule { limit: "t", big_blind_cents: 100, basis_points: 500, step_cents: 1, cap_cents: [0, 0, 50, 50, 50, 50, 50], no_flop_no_drop: false, free_preflop_cents: 0 }
}
/// River, both put in 100 chips before (pot 200): player 0 (seat 1) holds trips, player 1 air; `rake` of the measurement.
fn river_values(pick: fn(&State, nlhe::Action) -> bool, rake: nlhe::Rake) -> (f64, f64) {
let root = check_down(2, Street::River);
assert_eq!((root.contributed(0), root.contributed(1), root.pot()), (100, 100, 200));
let board = cs("2c7d9hJsKc");
let (sz, later) = (search::tree::small_sizing(), later_sizing());
let (none, frozen) = (Extras::new(), HashMap::new());
let mut g = river_game(root, &board, &sz, &later, &none, &frozen);
g.ranges = [single(&board, "KdKh"), single(&board, "3d4s")];
g.rake = rake;
let rep = evaluate_profile(&g, &Script { sz: &sz, pick });
// the rake is no function of a card: the sum of values is the pot minus the rake
(rep.value[0], rep.value[1])
}
fn passive(_: &State, a: nlhe::Action) -> bool {
matches!(a, nlhe::Action::Check | nlhe::Action::Call)
}
/// Bet the smallest size when allowed, else fold to a bet.
fn bet_or_fold(st: &State, a: nlhe::Action) -> bool {
if st.legal().can_check {
matches!(a, nlhe::Action::RaiseTo(_))
} else {
a == nlhe::Action::Fold
}
}
#[test]
fn rake_comes_out_of_the_showdown_pot_hand_computed() {
let rake = test_rule().in_chips(2, 100).unwrap();
assert_eq!(rake.of_pot(200, true), 10);
let (v0, v1) = river_values(passive, rake);
assert!((v0 - 90.0).abs() < 1e-9 && (v1 + 100.0).abs() < 1e-9, "check-down with rake: {v0} {v1}");
let (v0, v1) = river_values(passive, nlhe::Rake::NONE);
assert!((v0 - 100.0).abs() < 1e-9 && (v1 + 100.0).abs() < 1e-9, "check-down without rake: {v0} {v1}");
}
#[test]
fn rake_comes_out_of_the_pot_when_the_bettor_wins_by_a_fold_and_the_uncalled_bet_is_not_raked() {
let rake = test_rule().in_chips(2, 100).unwrap();
// player 0 bets, player 1 folds: matched pot 200 (the bet is returned), rake 10
let (v0, v1) = river_values(bet_or_fold, rake);
assert!((v0 - 90.0).abs() < 1e-9 && (v1 + 100.0).abs() < 1e-9, "bet-fold with rake: {v0} {v1}");
}
#[test]
fn the_rake_is_capped() {
// cap 5 chips: a 200-chip pot pays 5, not 10
let mut rule = test_rule();
rule.cap_cents = [0, 0, 5, 5, 5, 5, 5];
let (v0, _) = river_values(passive, rule.in_chips(2, 100).unwrap());
assert!((v0 - 95.0).abs() < 1e-9, "{v0}");
}
#[test]
fn with_a_rake_the_gain_sum_is_still_nonnegative_and_matches_the_profile_values() {
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 mut g = river_game(root, &board, &sz, &later, &none, &frozen);
g.rake = test_rule().in_chips(2, 100).unwrap();
let sol = solve_vec(&g, &VecParams { iters: 300, plus: true, keep_all: true, ..Default::default() });
let rep = evaluate_profile(&g, &sol.strategy(true, None));
let gain: f64 = (0..2).map(|p| rep.br[p] - rep.value[p]).sum();
assert!(gain >= -1e-6, "negative sum of gains {gain}");
// the established evaluator agrees (it replaces `dead` by the strategy's own values under a rake)
let (expl, _) = exploitability(&g, &sol.strategy(true, None));
assert!((2.0 * expl - gain).abs() < 1e-6 * root.pot() as f64, "{} vs {}", 2.0 * expl, gain);
// values add up to the pot minus the expected rake, strictly less than without
assert!(rep.value[0] + rep.value[1] < rep.dead - 1e-9);
}
// ---- value against the perfect opponent (root best response) ----------------------------------------------------------------
#[test]
fn perfect_opponent_value_of_the_reference_mixture_and_of_a_shifted_mixture() {
use search::vector::{node_values, perfect_values};
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 mut g = river_game(root, &board, &sz, &later, &none, &frozen);
g.rake = test_rule().in_chips(2, 100).unwrap();
let sol = solve_vec(&g, &VecParams { iters: 1500, plus: true, keep_all: true, floor: 1e-3, ..Default::default() });
let strat = sol.strategy(true, None);
let nv = node_values(&g, &strat, &[], 0).expect("root node of player 0");
let (n, m) = (nv.actions.len(), nv.w.len());
let value = |q: &Vec<Vec<f64>>, pi: &Vec<Vec<f64>>| -> f64 { (0..m).map(|h| nv.w[h] * (0..n).map(|a| pi[a][h] * q[a][h]).sum::<f64>()).sum() };
let pot = root.pot() as f64;
// the reference mixture: its value against the perfect opponent equals its value against the reference continuation (it is an equilibrium)
let val_gg = value(&nv.q, &nv.sigma);
let qbr_sigma: Vec<Vec<f64>> = perfect_values(&g, &strat, &[], 0, &nv.sigma, usize::MAX).unwrap().into_iter().map(|x| x.unwrap()).collect();
let pv_sigma = value(&qbr_sigma, &nv.sigma);
assert!((val_gg - pv_sigma).abs() < 0.03 * pot, "reference mixture: {val_gg} vs perfect {pv_sigma}");
// a shifted mixture (always the first action) loses at least its regret against the reference continuation
let shifted: Vec<Vec<f64>> = (0..n).map(|a| vec![(a == 0) as u8 as f64; m]).collect();
let qbr_shift: Vec<Vec<f64>> = perfect_values(&g, &strat, &[], 0, &shifted, usize::MAX).unwrap().into_iter().map(|x| x.unwrap()).collect();
let loss_perfect = val_gg - value(&qbr_shift, &shifted);
let regret: f64 = (0..m).map(|h| nv.w[h] * ((0..n).map(|a| nv.q[a][h]).fold(f64::NEG_INFINITY, f64::max) - nv.q[0][h])).sum();
assert!(regret > 0.0, "the shifted mixture must have a regret");
assert!(loss_perfect >= regret - 0.03 * pot, "perfect-opponent loss {loss_perfect} below regret {regret}");
// a policy cap that is too small yields None for the action, never a wrong number
let capped = perfect_values(&g, &strat, &[], 0, &nv.sigma, 1).unwrap();
assert!(capped.iter().any(|x| x.is_none()));
}
#[test]
fn solve_until_stops_at_the_target_or_reports_the_rest() {
use search::referenz::{reference_sizing, solve_until, RefParams};
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 mut g = river_game(root, &board, &sz, &later, &none, &frozen);
g.rake = test_rule().in_chips(2, 100).unwrap();
let (rs, rl) = reference_sizing("mittel").unwrap();
let mut p = RefParams { iters: 50, max_iters: 6400, target_pct: 0.03, floor: 2e-4, rake: None, big_blind: 100, sizing: rs, later: rl, max_bytes: 1 << 30, max_millis: None, measure: true, seed: 1 };
let pot = root.pot() as f64;
let (_, e, rounds, met) = solve_until(&g, &p, None);
assert!(met && e.unwrap() <= 0.03 * pot, "expl {e:?} rounds {rounds}");
assert!(rounds > 1, "the first 50 iterations should not be enough");
// an unreachable target within a small cap: the rest is reported, not hidden
p.target_pct = 1e-9;
p.max_iters = 100;
let (_, e, _, met) = solve_until(&g, &p, None);
assert!(!met && e.unwrap() > 1e-9 * pot);
// without measuring: one solve, no number
p.measure = false;
let (_, e, rounds, _) = solve_until(&g, &p, None);
assert!(e.is_none() && rounds == 1);
}