Files
pokerfreak/tests/cfr_multi.rs
T
mmintelandClaude Opus 5.5 3d65e856f6 Rake-aware CFR and charts: rake rule, ante situation, regenerated preflop charts
Secures the worktree's uncommitted state before merging into main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:36:11 +01:00

348 lines
17 KiB
Rust

//! The multi-defender preflop games (one to four defenders behind the first actor) and their
//! frozen charts (`preflop::generated_charts_multi`).
//!
//! What is pinned, and why it is evidence:
//!
//! - **Same abstraction.** The k-way pot share is `payoffs::share` for two hands and
//! `three_way_shares` for three; the tree with one defender has exactly the decisions of
//! `open_game`, with two exactly those of `open3_game`; every terminal pays out the chips put
//! in (the payoffs add up to the dead money). The sampled evaluation of a fixed strategy matches
//! the exact full-width value of the same strategy in those games.
//! - **Gegenprobe.** For one and two defenders the frozen strategy is mapped into the exact game
//! and its exploitability recomputed full width: equal to the header, below `BOUND`. For three
//! and four the sampled best responses of the header (chosen on one set of deals, re-measured on
//! an independent one) are below `BOUND`; the sampled check itself is validated against the exact
//! one where both exist, and one three-defender spot is re-checked here on fresh deals.
//! - **Deviation from the one-defender charts.** The header's evidence table is recomputed from
//! the frozen rows (the file re-renders byte for byte). The sampled solver reproduces the exact
//! charts where they exist: with one defender against the full-width baseline, with two against
//! `generated_charts::OPEN` (`SAME_GAME`). With more defenders the open ranges get narrower.
mod cfr_support;
use pokerfreak::cfr::defenders::{behind, max_defenders, Lineup, Place, MAX_DEFENDERS};
use pokerfreak::cfr::environment::Environment;
use pokerfreak::cfr::exploitability::{exploitability, game_value};
use pokerfreak::cfr::frozen_multi::{multi_strategy, open_row, permille_rows};
use pokerfreak::cfr::frozen_strategy::binary_row;
use pokerfreak::cfr::game::Game;
use pokerfreak::cfr::multi_shares::multi_shares;
use pokerfreak::cfr::multi_solve::{exact_exploitability, exact_name, mean_abs_difference, width, CHECK_SEED};
use pokerfreak::cfr::multi_tree::{multi_open_tree, MultiNode, MultiOutcome, MultiTree};
use pokerfreak::cfr::multi_walk::{sampled_exploitability, sampled_values, MultiStrategy};
use pokerfreak::cfr::open3_game::open3_tree;
use pokerfreak::cfr::open_game::open_tree;
use pokerfreak::cfr::payoffs::share;
use pokerfreak::cfr::render_multi::{baseline_records, evidence, multi_plan, records, render_multi};
use pokerfreak::cfr::run_plan::{CFR_SEED, OPEN_ITERATIONS};
use pokerfreak::cfr::seat::Seat;
use pokerfreak::cfr::solve::solve;
use pokerfreak::cfr::strategy::Strategy;
use pokerfreak::cfr::three_way::three_way_shares;
use pokerfreak::cfr::walk3::game_value3;
use pokerfreak::preflop::generated_charts::OPEN;
use pokerfreak::preflop::generated_charts_multi::{BASELINE, MULTI};
use pokerfreak::rng::Rng;
/// Exploitability bound of every frozen multi-defender spot (bb per deal), as for the exact
/// tables (`tests/cfr_nash.rs`).
const BOUND: f64 = 0.01;
/// Largest combo-weighted mean |open difference| between the sampled solver and the exact
/// solver in the same game (one defender: baseline; two: `generated_charts::OPEN`), permille.
const SAME_GAME: u32 = 25;
fn env() -> Environment {
Environment::frozen()
}
// ---------------------------------------------------------------------------------------------
// Lineup and abstraction
#[test]
fn every_seat_has_one_to_four_defenders_ending_with_the_big_blind() {
let expected = [(Seat::Early, 4), (Seat::Middle, 4), (Seat::Cutoff, 3), (Seat::Button, 2), (Seat::SmallBlind, 1)];
for (seat, most) in expected {
assert_eq!(max_defenders(seat), most, "{seat:?}");
assert_eq!(behind(seat).last(), Some(&Place::BigBlind));
for k in 1..=most {
let lineup = Lineup::new(seat, k).expect("lineup");
assert_eq!(lineup.defenders.len(), k);
assert_eq!(lineup.field.len() + k, behind(seat).len());
assert_eq!(lineup.defenders.last(), Some(&Place::BigBlind));
}
assert!(Lineup::new(seat, 0).is_err());
assert!(Lineup::new(seat, most + 1).is_err());
}
assert_eq!(MAX_DEFENDERS, 4);
// From EP the middle position stays in the field even with four defenders.
assert_eq!(Lineup::new(Seat::Early, 4).expect("lineup").field, vec![Place::Middle]);
}
#[test]
fn the_k_way_share_is_the_two_and_three_way_share_of_the_old_games() {
let mut rng = Rng::seeded(7);
for _ in 0..2000 {
let (e, next) = rng.unit();
rng = next;
let (r, next) = rng.unit();
rng = next;
let mut out = [0.0; 2];
multi_shares(&[0.5, e, 1.0 - e, 0.5], 2, &[1.0, r], 1.3, &mut out);
assert!((out[0] - share(e, true, r)).abs() < 1e-12);
multi_shares(&[0.5, e, 1.0 - e, 0.5], 2, &[r, 1.0], 1.3, &mut out);
assert!((out[0] - share(e, false, r)).abs() < 1e-12);
let mut eq = [[0.5; 3]; 3];
for (x, y) in [(0, 1), (0, 2), (1, 2)] {
let (v, next) = rng.unit();
rng = next;
eq[x][y] = v;
eq[y][x] = 1.0 - v;
}
let flat: Vec<f64> = eq.iter().flatten().copied().collect();
let mut three = [0.0; 3];
multi_shares(&flat, 3, &[1.0, r, r], 1.3, &mut three);
let old = three_way_shares(eq, [1.0, r, r], 1.3);
assert!(three.iter().zip(old).all(|(a, b)| (a - b).abs() < 1e-12));
}
}
fn names(tree: &MultiTree) -> Vec<String> {
let mut n: Vec<String> = tree.decision_names().iter().map(|s| s.to_string()).collect();
n.sort();
n
}
#[test]
fn one_and_two_defenders_are_the_old_games_node_for_node() {
let env = env();
for seat in Seat::ALL {
let tree = multi_open_tree(&env, seat, 1, 100.0).expect("tree");
let mut mapped: Vec<&str> = names(&tree).iter().map(|n| exact_name(n, 1).expect("mapped")).collect();
mapped.sort();
let old = open_tree(&env, seat, 100.0).expect("tree");
let mut old_names: Vec<&str> = (0..old.nodes.len()).filter_map(|n| old.decision_name(n)).collect();
old_names.sort();
assert_eq!(mapped, old_names, "{seat:?}");
if seat == Seat::SmallBlind {
continue;
}
let tree = multi_open_tree(&env, seat, 2, 100.0).expect("tree");
let mut mapped: Vec<&str> = names(&tree).iter().map(|n| exact_name(n, 2).expect("mapped")).collect();
mapped.sort();
let old = open3_tree(&env, seat, 100.0).expect("tree");
let mut old_names: Vec<&str> = (0..old.nodes.len()).filter_map(|n| old.decision_name(n)).collect();
old_names.sort();
assert_eq!(mapped, old_names, "{seat:?}");
}
}
#[test]
fn four_defenders_have_every_overcall_history_as_its_own_decision() {
let tree = multi_open_tree(&env(), Seat::Early, 4, 100.0).expect("tree");
let n = names(&tree);
// open + 4 defends + 11 overcall histories + 4 x (opener vs 3-bet, 3-bettor vs jam)
assert_eq!(n.len(), 1 + 4 + 11 + 8);
for name in ["CO_defend", "BB_overcall_CO+BTN+SB", "SB_overcall_CO", "vs_BTN_three_bet", "BTN_vs_jam"] {
assert!(n.iter().any(|x| x == name), "{name}");
}
assert!(Lineup::new(Seat::Early, 5).is_err());
assert!(multi_open_tree(&env(), Seat::Early, 4, 7.0).is_err(), "stack below the 3-bet sizes");
}
#[test]
fn every_terminal_pays_out_exactly_the_chips_put_in() {
let env = Environment::frozen_free_table();
let mut rng = Rng::seeded(11);
for (seat, k, _) in multi_plan() {
let tree = multi_open_tree(&env, seat, k, 40.0).expect("tree");
let dead = tree.lineup.dead_money();
let root_fold = match &tree.nodes[tree.root] {
MultiNode::Decision { children, .. } => children[0],
_ => usize::MAX,
};
for (index, node) in tree.nodes.iter().enumerate() {
let MultiNode::Terminal(outcome) = node else { continue };
if index == root_fold || matches!(outcome, MultiOutcome::Own { .. }) {
continue;
}
for _ in 0..20 {
let classes: Vec<usize> = (0..tree.players)
.map(|_| {
let (c, next) = rng.below(169);
rng = next;
c as usize
})
.collect();
let total: f64 = tree.payoff(outcome, &classes).iter().sum();
assert!((total - dead).abs() < 1e-9, "{seat:?} k={k} node {index}: {total} vs dead {dead}");
}
}
}
}
fn mapped_strategy<G: Game>(game: &G, tree: &MultiTree, strategy: &MultiStrategy, k: usize) -> Strategy {
let mut out = Strategy::uniform(game);
for (node, n) in tree.nodes.iter().enumerate() {
if let MultiNode::Decision { name, .. } = n {
out = out.with_rows(game, exact_name(name, k).expect("mapped"), |c| strategy.row(node, c).to_vec()).expect("rows");
}
}
out
}
#[test]
fn sampled_evaluation_matches_the_exact_games() {
let env = env();
// A fixed, non-equilibrium strategy: the frozen two-blind chart where it exists.
let tree = multi_open_tree(&env, Seat::Cutoff, 1, 40.0).expect("tree");
let strategy = MultiStrategy::uniform(&tree);
let exact = game_value(&open_tree(&env, Seat::Cutoff, 40.0).expect("tree"), &mapped_strategy(&open_tree(&env, Seat::Cutoff, 40.0).expect("tree"), &tree, &strategy, 1));
let sampled = sampled_values(&tree, &strategy, 40_000, 3)[0];
assert!((exact - sampled).abs() < 0.01, "one defender: exact {exact}, sampled {sampled}");
let tree = multi_open_tree(&env, Seat::Cutoff, 2, 40.0).expect("tree");
let strategy = MultiStrategy::uniform(&tree);
let game = open3_tree(&env, Seat::Cutoff, 40.0).expect("tree");
let mapped = mapped_strategy(&game, &tree, &strategy, 2);
let sampled = sampled_values(&tree, &strategy, 40_000, 5);
for (p, sampled) in sampled.iter().enumerate() {
let exact = game_value3(&game, &mapped, p);
assert!((exact - sampled).abs() < 0.015, "two defenders, player {p}: exact {exact}, sampled {sampled}");
}
}
#[test]
fn the_sampled_best_response_brackets_the_exact_one() {
let env = env();
let tree = multi_open_tree(&env, Seat::Button, 1, 20.0).expect("tree");
let strategy = MultiStrategy::uniform(&tree);
let game = open_tree(&env, Seat::Button, 20.0).expect("tree");
let exact = exploitability(&game, &mapped_strategy(&game, &tree, &strategy, 1));
let check = sampled_exploitability(&tree, &strategy, 20_000, 9);
let (high, low) = (check.in_sample_total(), check.holdout_total());
assert!(low - 0.02 <= exact && exact <= high + 0.02, "exact {exact}, sampled {low} .. {high}");
assert!((high - exact).abs() / exact < 0.05, "in-sample {high} vs exact {exact}");
}
// ---------------------------------------------------------------------------------------------
// Frozen charts
#[test]
fn the_tables_cover_the_plan_and_every_decision() {
let env = env();
let plan = multi_plan();
assert_eq!(MULTI.len(), plan.len());
for ((seat, k, depth), spot) in plan.iter().zip(MULTI.iter()) {
assert_eq!((spot.seat, spot.defenders as usize, spot.depth_bb), (*seat, *k, *depth));
let tree = multi_open_tree(&env, *seat, *k, *depth as f64).expect("tree");
multi_strategy(&tree, spot.rows).expect("every decision has a well-formed row");
for row in spot.rows {
let rows = permille_rows(row).expect("row");
assert!(rows.iter().all(|r| r.iter().map(|v| *v as u32).sum::<u32>() == 1000));
}
let open = open_row(spot.rows).expect("open");
assert_eq!(open[cfr_support::id("AA")], 1000, "{seat:?} k={k} {depth}: AA opens");
// The sampled average keeps a trace of the early, near-uniform iterations: up to 2
// permille instead of the full-width solver's clean 0.
assert!(open[cfr_support::id("72o")] <= 2, "{seat:?} k={k} {depth}: 72o folds");
}
assert_eq!(BASELINE.len(), Seat::ALL.len() * 3);
}
#[test]
fn the_frozen_file_is_exactly_what_the_generator_prints() {
let env = env();
let reference: Vec<(Seat, u8, Vec<u16>)> = OPEN.iter().map(|s| (s.seat, s.depth_bb, s.open.to_vec())).collect();
let text = render_multi(&env, &records(&MULTI).expect("records"), &baseline_records(&BASELINE).expect("baseline"), &reference);
let frozen = include_str!("../src/preflop/generated_charts_multi.rs").replace("\r\n", "\n");
assert!(text == frozen, "re-rendered table differs from the file");
}
#[test]
fn the_baseline_is_the_one_defender_game_solved_full_width() {
let env = env();
let sb = BASELINE.iter().find(|b| b.seat == Seat::SmallBlind && b.depth_bb == 100).expect("spot");
let table = OPEN.iter().find(|s| s.seat == Seat::SmallBlind && s.depth_bb == 100).expect("spot");
let frozen = pokerfreak::cfr::frozen_multi::decode(sb.open).expect("decode");
assert_eq!(frozen, table.open.to_vec(), "the small blind's one-defender game is the shipped table");
let tree = open_tree(&env, Seat::Button, 100.0).expect("tree");
let solved = solve(&tree, OPEN_ITERATIONS, Rng::seeded(CFR_SEED));
let btn = BASELINE.iter().find(|b| b.seat == Seat::Button && b.depth_bb == 100).expect("spot");
let rebuilt = binary_row(&tree, &solved.strategy, "open").expect("row").to_vec();
assert_eq!(pokerfreak::cfr::frozen_multi::decode(btn.open).expect("decode"), rebuilt);
}
#[test]
fn gegenprobe_exact_for_one_and_two_defenders() {
let env = env();
for spot in MULTI.iter().filter(|s| s.defenders <= 2) {
let tree = multi_open_tree(&env, spot.seat, spot.defenders as usize, spot.depth_bb as f64).expect("tree");
let strategy = multi_strategy(&tree, spot.rows).expect("strategy");
let exact = exact_exploitability(&env, &tree, &strategy).expect("exact").expect("k <= 2");
let recorded = spot.exact_micro_bb.expect("recorded") as f64 * 1e-6;
let label = format!("{:?} k={} {}", spot.seat, spot.defenders, spot.depth_bb);
assert!((exact - recorded).abs() < 2e-6, "{label}: header {recorded}, recomputed {exact}");
assert!(exact < BOUND, "{label}: exploitability {exact}");
// The sampled check of the same strategy agrees with the exact one.
let (high, low) = (spot.in_sample_micro_bb as f64 * 1e-6, spot.holdout_micro_bb as f64 * 1e-6);
assert!(low - 0.002 <= exact && exact <= high + 0.002, "{label}: exact {exact}, sampled {low} .. {high}");
}
}
#[test]
fn gegenprobe_sampled_for_three_and_four_defenders() {
for spot in MULTI.iter().filter(|s| s.defenders >= 3) {
let label = format!("{:?} k={} {}", spot.seat, spot.defenders, spot.depth_bb);
assert!(spot.exact_micro_bb.is_none());
assert!((spot.in_sample_micro_bb as f64) * 1e-6 < BOUND, "{label}: in-sample {}", spot.in_sample_micro_bb);
assert!(spot.holdout_micro_bb <= spot.in_sample_micro_bb + 1000, "{label}");
}
// One spot re-checked on fresh deals (a tenth of the recorded sample).
let env = env();
let spot = MULTI.iter().find(|s| s.seat == Seat::Cutoff && s.defenders == 3 && s.depth_bb == 20).expect("spot");
let tree = multi_open_tree(&env, spot.seat, 3, 20.0).expect("tree");
let strategy = multi_strategy(&tree, spot.rows).expect("strategy");
let fresh = sampled_exploitability(&tree, &strategy, spot.check_samples / 10, CHECK_SEED ^ 0xF4E5);
assert!(fresh.holdout_total() < BOUND, "fresh holdout {}", fresh.holdout_total());
assert!(fresh.in_sample_total() < BOUND + 0.005, "fresh in-sample {}", fresh.in_sample_total());
}
#[test]
fn the_sampled_solver_reproduces_the_exact_charts_of_the_same_game() {
let env = env();
let reference: Vec<(Seat, u8, Vec<u16>)> = OPEN.iter().map(|s| (s.seat, s.depth_bb, s.open.to_vec())).collect();
let evidence = evidence(&env, &records(&MULTI).expect("records"), &baseline_records(&BASELINE).expect("baseline"), &reference);
for e in &evidence {
let label = format!("{:?} k={} {}", e.seat, e.defenders, e.depth_bb);
if e.defenders == 1 {
assert!(e.vs_one_defender <= SAME_GAME, "{label}: {} permille from the exact one-defender chart", e.vs_one_defender);
}
if let Some(two) = e.vs_two_defender_table {
assert!(two <= SAME_GAME, "{label}: {two} permille from generated_charts::OPEN");
}
}
}
#[test]
fn more_defenders_narrow_the_open() {
let env = env();
for seat in Seat::ALL {
for depth in [20u8, 40, 100] {
let widths: Vec<f64> = (1..=max_defenders(seat))
.map(|k| {
let spot = MULTI.iter().find(|s| s.seat == seat && s.defenders as usize == k && s.depth_bb == depth).expect("spot");
width(&env, &open_row(spot.rows).expect("open"))
})
.collect();
assert!(widths.windows(2).all(|w| w[1] <= w[0] + 0.005), "{seat:?} {depth}: {widths:?}");
let base = BASELINE.iter().find(|b| b.seat == seat && b.depth_bb == depth).expect("baseline");
let base = pokerfreak::cfr::frozen_multi::decode(base.open).expect("decode");
let last = MULTI.iter().rev().find(|s| s.seat == seat && s.depth_bb == depth).expect("spot");
let diff = mean_abs_difference(&env, &open_row(last.rows).expect("open"), &base);
if max_defenders(seat) >= 2 {
assert!(diff > 0.02, "{seat:?} {depth}: the full lineup changes the chart ({diff})");
}
}
}
}