Files
pokerfreak/src/sim/exploit_river.rs
T
mmintelandClaude Opus 4.8 1492fb6a38 Synthetik-Labor: Population, Zwillings-Tor, adaptive Liga, Optimizer, Sim-to-Real
Ersetzt die irrefuehrende Oracle-Leiter durch eine ehrliche Messmethodik
(Oracle aus, Read via Memory/Posterior gegen eine gezogene Gegner-Population).

Stufen:
- 0 Exploitation-Luecke: +18.98 bb/100 gegen die gezogene Population
- 1 Kalibrierung an echte HUD-Daten (lesen/kalibrierung.py)
- 2 Zwillings-Tor (EGTA + Exploitability-Waechter): Offense +43.95,
  Boden gto -36.25 (verliert gegen Balancierte - die Oracle-verdeckte Wurzel)
- 3 Adaptive Liga L0-L3 (reaktiv / modellierend / Liga)
- 4 Sim-to-Real: HUD-Gap (sim::simreal) + Outcome-Abgleich (lesen/liveabgleich.py):
  real -266.75 vs Sim +43.95 => Gap -311; A/B-Pipeline + Runbook fertig,
  nur der geldechte Live-Lauf unter beiden Armen bleibt offen
- 5 Optimizer (Diagonal-CMA-ES, parallel): Nemesis -414.81 bb/100

Befunde und Architektur in docs/notizen/. Lab-Tests gruen
(Rust lib 92/0, python liveabgleich/kalibrierung/gegnersignal gruen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-11 09:57:32 +01:00

325 lines
14 KiB
Rust

//! Postflop exploitability of the LIVE engine on a heads-up river subgame.
//!
//! The ladder (`sim::benchmark`) measures bb/100 against fixed card-blind bots; it cannot say how far
//! the engine is from a Nash equilibrium, and against near-GTO bots its signal is cooler-dominated
//! (BEFUND-conditioned-fold-barrel, BEFUND-gto-restleck-river-overcall). MODULES.md names the missing
//! measure outright: "Postflop-Exploitability gegen eine Best Response fehlt noch". This module builds
//! it for the river - the one street where the subgame is exact (board complete, showdown exact, no
//! future chance).
//!
//! # What is measured
//!
//! A heads-up river subgame over real cards: a board, hero's range and villain's range as combo lists.
//! Hands are bucketed by their EXACT showdown strength on the board (`hand::showdown::best`), card
//! removal between the two ranges is baked into the joint deal table, and the betting tree is
//! `cfr::river` (hero first, one bet size, no raises).
//!
//! Hero plays the ENGINE's real policy: at each hero node and bucket the engine is queried
//! (`engine::decide`) for a representative hand of that bucket, giving a pure action per bucket. The
//! villain then BEST-RESPONDS to that fixed policy over the true ranges. Hero's exploitability is
//!
//! ```text
//! exploitability = v* - value(hero | villain best-responds to the engine)
//! ```
//!
//! where `v*` is hero's value at the solved equilibrium of the same subgame. It is `>= 0` and `0`
//! exactly when the engine already plays the river unexploitably. Units: bb per 100 deals (the pot and
//! bet are given in big blinds, `big_blind = 1`).
//!
//! # Approximations (named)
//!
//! - One representative hand per bucket drives the engine query; hands of equal showdown strength but
//! different blockers can in principle play differently, which this collapses.
//! - The betting tree is the `cfr::river` v1 (one bet size, no raises). A richer action abstraction
//! only grows the villain's best-response power, so this is a LOWER bound on exploitability.
//! - The engine models the villain from the spot's profile, not from the tree's true range; that is
//! the point - the best response knows the engine's policy and the true range, the engine plays its
//! own beliefs.
use crate::card::Card;
use crate::cfr::exploitability::game_value;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::cfr::strategy::Strategy;
use crate::cfr::tree::Tree;
use crate::cfr::value_walk::{root_values, Responder};
use crate::engine::decide::decide;
use crate::engine::river_subgame;
use crate::exploit::profile::Profile;
use crate::game::{ActionKind, Choice, Spot, Street, Villain};
use crate::hand::showdown::best;
use crate::rng::Rng;
use crate::variant::{rules, Variant};
/// A heads-up river subgame over real cards. Pot and bet are in big blinds.
pub struct RiverSpec<'a> {
pub board: &'a [Card],
pub hero_range: &'a [Vec<Card>],
pub villain_range: &'a [Vec<Card>],
/// The profile the engine sees for the villain (its belief); the best response ignores it.
pub villain_profile: Option<Profile>,
pub pot: f64,
pub bet: f64,
}
/// The exploitability of the engine's river play on one subgame, all in bb/100.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ExploitReport {
pub buckets: usize,
/// Hero's value at the solved equilibrium of the subgame.
pub gto_value: f64,
/// Hero's value when the villain best-responds to the engine's fixed policy.
pub engine_value_vs_br: f64,
/// `gto_value - engine_value_vs_br`, `>= 0`.
pub exploitability: f64,
}
/// Strength bucket of each combo on the board, 0 = weakest, plus the shared bucket count. Both ranges
/// share one ascending set of distinct showdown strengths, so a higher bucket always wins the showdown.
struct Buckets {
count: usize,
hero_bucket: Vec<usize>,
villain_bucket: Vec<usize>,
}
fn bucketize(board: &[Card], hero: &[Vec<Card>], villain: &[Vec<Card>]) -> Option<Buckets> {
let usage = rules(Variant::Nlhe).hole_usage;
let strength = |combo: &[Card]| best(usage, combo, board).ok();
let hero_s: Vec<_> = hero.iter().map(|c| strength(c)).collect();
let villain_s: Vec<_> = villain.iter().map(|c| strength(c)).collect();
// One ascending ladder of distinct strengths across both ranges.
let mut distinct: Vec<_> = hero_s.iter().chain(&villain_s).filter_map(|s| *s).collect();
distinct.sort();
distinct.dedup();
if distinct.len() < 2 {
return None;
}
let rank = |s: Option<_>| s.and_then(|v| distinct.iter().position(|d| *d == v));
let hero_bucket: Vec<usize> = hero_s.iter().map(|s| rank(*s).unwrap_or(0)).collect();
let villain_bucket: Vec<usize> = villain_s.iter().map(|s| rank(*s).unwrap_or(0)).collect();
Some(Buckets { count: distinct.len(), hero_bucket, villain_bucket })
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// The joint deal table `chance[i * n + j] = P(hero bucket i, villain bucket j)`: uniform over every
/// disjoint (hero combo, villain combo) pair, so card removal between the two ranges is exact.
fn joint_chance(spec: &RiverSpec, b: &Buckets) -> Vec<f64> {
let n = b.count;
let mut chance = vec![0.0; n * n];
for (hi, hcombo) in spec.hero_range.iter().enumerate() {
for (vi, vcombo) in spec.villain_range.iter().enumerate() {
if disjoint(hcombo, vcombo) {
chance[b.hero_bucket[hi] * n + b.villain_bucket[vi]] += 1.0;
}
}
}
let total: f64 = chance.iter().sum();
if total > 0.0 {
chance.iter_mut().for_each(|x| *x /= total);
}
chance
}
/// First hero combo in each bucket, to drive the engine query. `None` for a bucket hero never holds.
fn hero_reps<'a>(spec: &'a RiverSpec, b: &Buckets) -> Vec<Option<&'a [Card]>> {
let mut reps: Vec<Option<&[Card]>> = vec![None; b.count];
for (i, combo) in spec.hero_range.iter().enumerate() {
let bucket = b.hero_bucket[i];
if reps[bucket].is_none() {
reps[bucket] = Some(combo);
}
}
reps
}
/// Build the river spot the engine faces at a hero node: at the root (`facing_bet = false`) hero is
/// first to act into `pot` with check or a bet to `bet`; facing a bet hero calls `bet` into the pot the
/// villain already grew.
fn hero_spot(spec: &RiverSpec, hand: &[Card], facing_bet: bool) -> Spot {
let (pot, to_call, legal, allowed, min_raise, max_raise) = if facing_bet {
(spec.pot + spec.bet, spec.bet, vec![ActionKind::Fold, ActionKind::Call], None, None, None)
} else {
(
spec.pot,
0.0,
vec![ActionKind::Check, ActionKind::Raise],
Some(vec![spec.bet]),
Some(spec.bet),
Some(spec.bet.max(spec.pot) * 4.0),
)
};
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: hand.to_vec(),
board: spec.board.to_vec(),
street: Street::River,
pot,
to_call,
hero_stack: spec.bet.max(spec.pot) * 4.0,
min_raise_to: min_raise,
max_raise_to: max_raise,
legal,
allowed_sizes: allowed,
villains: vec![Villain { seat: 2, stack: spec.pot * 4.0, folded: false, profile: spec.villain_profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// The engine's action row at a hero node for a bucket's representative hand, as a probability per
/// action: `[check, bet]` at node "hero", `[fold, call]` at "hero_vs_bet". Where the river solver
/// applies (`river_subgame::river_mix`) the engine MIXES, so the row is its equilibrium frequency —
/// the whole point of Stage A, and the only way a balanced strategy can show as unexploitable. Where
/// the solver declines, the heuristic (`decide`) gives a pure row. A bucket hero never holds maps to
/// the passive action, which its zero chance makes irrelevant.
fn engine_row(spec: &RiverSpec, reps: &[Option<&[Card]>], name: &str, bucket: usize) -> Vec<f64> {
let facing = match name {
"hero" => false,
"hero_vs_bet" => true,
_ => return vec![1.0, 0.0],
};
let Some(hand) = reps.get(bucket).copied().flatten() else { return vec![1.0, 0.0] };
let spot = hero_spot(spec, hand, facing);
if let Some(plan) = river_subgame::river_mix(&spot) {
if plan.facing == facing {
return vec![plan.mix[0], plan.mix[1]];
}
}
// Solver declined for this node: fall back to the heuristic's pure action.
let aggressive = match facing {
false => matches!(decide(&spot).choice, Choice::Raise { .. }),
true => matches!(decide(&spot).choice, Choice::Call),
};
if aggressive {
vec![0.0, 1.0]
} else {
vec![1.0, 0.0]
}
}
/// Hero's exploitability on the subgame: `v* - value(hero | villain best-responds)`, in bb/100.
/// `iterations` solves the equilibrium reference; `seed` seeds the solver (the engine query is
/// deterministic). Returns `None` for a degenerate subgame (fewer than two buckets, empty ranges).
pub fn exploitability_river(spec: &RiverSpec, iterations: u32, seed: u64) -> Option<ExploitReport> {
let b = bucketize(spec.board, spec.hero_range, spec.villain_range)?;
let chance = joint_chance(spec, &b);
if chance.iter().sum::<f64>() <= 0.0 {
return None;
}
let tree = tree_with_chance(b.count, chance, spec.pot, spec.bet);
let reps = hero_reps(spec, &b);
// The engine's real per-bucket river policy as a (possibly mixed) behaviour strategy at both hero
// nodes; every other node keeps the uniform base (villain nodes are best-responded, not read).
let engine = Strategy::uniform(&tree)
.with_rows(&tree, "hero", |bucket| engine_row(spec, &reps, "hero", bucket))
.and_then(|s| s.with_rows(&tree, "hero_vs_bet", |bucket| engine_row(spec, &reps, "hero_vs_bet", bucket)))
.unwrap_or_else(|_| Strategy::uniform(&tree));
Some(report(&tree, &engine, iterations, seed, b.count))
}
/// Assemble the report from a built tree and a fixed hero strategy (shared by the engine path and the
/// tests). `v*` is the equilibrium value; the villain best-responds to `hero` for the exploited value.
fn report(tree: &Tree, hero: &Strategy, iterations: u32, seed: u64, buckets: usize) -> ExploitReport {
let solved = solve(tree, iterations, Rng::seeded(seed));
let gto_value = game_value(tree, &solved.strategy);
// Player 1 best-responds while player 0 follows `hero`; the summed value is the villain's, so hero
// gets its negation (zero-sum). Counterfactual values are per deal; x100 for bb/100.
let villain_br: f64 = root_values(tree, hero, Responder::Best, 1, &mut |_| {}).iter().sum();
let engine_value_vs_br = -villain_br;
ExploitReport {
buckets,
gto_value: gto_value * 100.0,
engine_value_vs_br: engine_value_vs_br * 100.0,
exploitability: (gto_value - engine_value_vs_br) * 100.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
const ITERS: u32 = 20_000;
const SEED: u64 = 0x5EED_E0F1;
/// A polarised river over abstract buckets built by hand (hero: air + nuts, villain: bluff-catcher)
/// — the same shape `cfr::river` proves against textbook GTO. Feeding the SOLVED strategy as hero's
/// own play must report ~0 exploitability: a Nash strategy is unexploitable, so the harness math
/// (v* + villain best response) cancels. This validates the pipeline independent of the engine.
fn polarised_tree() -> Tree {
// buckets: 0 = air, 1 = bluff-catcher, 2 = nuts. chance = independent product of the ranges.
let hero = [0.5, 0.0, 0.5];
let villain = [0.0, 1.0, 0.0];
let n = 3;
let mut chance = vec![0.0; n * n];
let mut total = 0.0;
for i in 0..n {
for j in 0..n {
let w = hero[i] * villain[j];
chance[i * n + j] = w;
total += w;
}
}
chance.iter_mut().for_each(|x| *x /= total);
tree_with_chance(n, chance, 2.0, 1.0)
}
#[test]
fn a_nash_strategy_reports_zero_exploitability() {
let tree = polarised_tree();
let solved = solve(&tree, ITERS, Rng::seeded(SEED));
let r = report(&tree, &solved.strategy, ITERS, SEED, 3);
assert!(r.exploitability.abs() < 1.5, "GTO must be ~unexploitable, got {:.3} bb/100", r.exploitability);
}
#[test]
fn a_fold_everything_strategy_is_exploitable() {
// Hero folds to every bet and never bets: the villain best-responds by always betting, printing
// the pot with any hand. That is strictly worse than the equilibrium, so exploitability > 0.
let tree = polarised_tree();
let hero = Strategy::pure(&tree, |name, _| match name {
"hero_vs_bet" => 0, // fold
"hero" => 0, // check
_ => 0,
});
let r = report(&tree, &hero, ITERS, SEED, 3);
assert!(r.exploitability > 5.0, "folding everything must be exploitable, got {:.3}", r.exploitability);
assert!(r.exploitability >= -1e-9, "exploitability is non-negative, got {:.3}", r.exploitability);
}
#[test]
fn the_live_engine_runs_and_reports_a_finite_number() {
// A real board, a small two-hand range each: the harness must bucketize real cards, query the
// engine and return a finite, non-negative exploitability. (Correctness of the number is the
// math tests above; this guards the live wiring.)
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let hero = [
Card::parse_list("Ac Qc").unwrap(), // top pair
Card::parse_list("5d 4d").unwrap(), // air
];
let villain = [
Card::parse_list("Ad Jc").unwrap(), // top pair worse kicker
Card::parse_list("6h 6d").unwrap(), // underpair / bluff-catcher
];
let spec = RiverSpec {
board: &board,
hero_range: &hero,
villain_range: &villain,
villain_profile: None,
pot: 6.0,
bet: 4.0,
};
let r = exploitability_river(&spec, 4_000, SEED).expect("non-degenerate subgame");
assert!(r.exploitability.is_finite());
assert!(r.exploitability >= -1e-6, "exploitability non-negative, got {:.3}", r.exploitability);
assert!(r.buckets >= 2);
}
}