Files
pokerfreak/src/engine/turn_game.rs
T
mmintelandClaude Opus 5.5 3311f874b5 Merge claude/engine-lecks-angreifen-de7b88 (62e51bb, Perf-Merge ab48024) in die 6-max-Messung
Konflikte geloest, Perf und Multiway-Solver beide erhalten:
- cfr/turn_river_game.rs: Konstruktor mit eq/eqm/lock (Solver) UND spare (Perf); show_into
  (Perf-Puffer) faellt bei gesetzter River-Equity auf show_eq zurueck, show ruft show_into.
- engine/turn_game.rs: street_line (Solver) behalten. decide.rs, mod.rs: nur Zeilenenden.
- STAND-weltklasse.md: beide Nachtraege behalten (Solver als 11a).

Bit-Identitaet gegen 62e51bb, alle 815 Spots aus tests/live_fixture (inkl. audit_heuristik, vorschlag):
Schalter aus 815/815 byte-gleich; Live-Satz (MDF_UNREAD=0, OPEN_JAM=1, TURN_SPIEL=grund) 815/815 gleich
bis auf die Rechenzeit in 23 Gruenden (dieselben 23 schwanken zwischen zwei Laeufen von 62e51bb).
live_lecks_spec 8 OK, audit_lauf_spec 12 OK, turnier_anfrage_spec OK.
cargo test --release: 1296 gruen, 11 rot = die bekannten 10 Chart-Tests + WTA-Test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:48:24 +01:00

431 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The turn re-solved at the table over real hands (plan E3, layer 2): both ranges from the
//! blueprint (`blueprint::ranges`, carried along the line actually played), the turn betting and
//! the river inside one game (`cfr::turn_river_game`), hero's equilibrium action at the real node.
//!
//! Switch: `TurnPlayer::Grund` (default `Off`; `ab_zelle` / `engine_lbr`: `TURN_SPIEL=grund`). Off,
//! `turn_game_decision` returns `None` before it looks at anything, so the engine's output is
//! unchanged. On, it plays only where the blueprint recognises the spot (S1: button open, big blind
//! call, about 100 bb, heads-up on the turn, hero at a decision); everywhere else the heuristic plays.
//!
//! The solve depends on the public state only (board, line, pot, stacks): the villain's range is NOT
//! conditioned on hero's real cards (`gewichtete_listen_offen`; the game deals card removal itself),
//! so one solve serves every hero hand at the same node. Solves are cached by public state (a
//! measurement that asks the engine for every hand of a range, as LBR does, pays one solve per node).
//!
//! Approximations (named, each a knob of `TurnConfig`): ranges are pruned to the `max_combos`
//! heaviest combos per player; the river is enumerated over `river_cards` evenly strided cards, each
//! standing for its share (`cfr::turn_river_game`); the bet menu is `TrBets::standard` plus the
//! observed size; the solve is a fixed `iterations` of CFR+. Hero's real hand, if pruned away or
//! outside the blueprint range, is put back with its weight (or a token weight) in an uncached solve.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Exploit, Hands, TNode, TrBets, TrSolver};
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
static MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Who plays the heads-up turn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnPlayer {
/// The heuristic (default).
Off,
/// The turn+river game with both ranges from the blueprint; only where the spot is a blueprint
/// scenario, else the heuristic plays.
Grund,
}
pub fn set_turn_player(mode: TurnPlayer) {
MODE.store(u8::from(mode == TurnPlayer::Grund), std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_player() -> TurnPlayer {
if MODE.load(std::sync::atomic::Ordering::Relaxed) == 1 {
TurnPlayer::Grund
} else {
TurnPlayer::Off
}
}
/// Size and budget of the solve.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TurnConfig {
/// Most combos per player (heaviest by weight).
pub max_combos: usize,
/// Stop adding combos once this share of the range mass is in (before `max_combos`).
pub cover: f64,
/// River cards enumerated (of 48).
pub river_cards: usize,
/// CFR+ iterations.
pub iterations: u32,
/// Also compute the best-response exploitability of the result (about two more iterations).
pub measure: bool,
/// Raises allowed after a river bet (0 or 1).
pub river_raises: usize,
/// Wall-time budget in ms (0 = none, run all `iterations`); a budgeted solve that stops under
/// `MIN_ITERS` returns `None` and the heuristic decides.
pub budget_ms: f64,
}
/// Fewest iterations a budgeted solve may decide with.
pub const MIN_ITERS: u32 = 60;
/// Stage B's own cap on one solve; the decision total is `frist::TURN_MS`.
pub const STAGE_B_BUDGET_MS: f64 = 1700.0;
/// Stage B's game size: 120 combos per player, 8 river cards (measured: same exploitability inside the
/// game as 160 × 10 at 200 iterations, 1.34 % of the pot, in 62 % of the time).
pub const STAGE_B_COMBOS: usize = 120;
pub const STAGE_B_RIVER_CARDS: usize = 8;
impl TurnConfig {
pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0, budget_ms: 0.0 };
/// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment.
pub fn from_env() -> TurnConfig {
let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d);
TurnConfig {
max_combos: num("TURN_COMBOS", Self::STANDARD.max_combos),
cover: num("TURN_COVER", 95) as f64 / 100.0,
river_cards: num("TURN_CARDS", Self::STANDARD.river_cards),
iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32,
measure: std::env::var("TURN_EXPLOIT").as_deref() == Ok("1"),
river_raises: std::env::var("TURN_RIVER_RAISES").ok().and_then(|s| s.parse().ok()).map_or(Self::STANDARD.river_raises, |n: usize| n.min(1)),
budget_ms: Self::STANDARD.budget_ms,
}
}
}
/// One solved node of the game: what every hero hand at this public state shares.
pub struct Solved {
/// Hero's turn-node action probabilities, `hero_masks.len()` rows of `acts.len()`.
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub combos: [usize; 2],
pub nodes: usize,
/// Best-response exploitability of the solved game, chips per deal (when `measure`).
pub exploit: Option<Exploit>,
pub big_blind: f64,
pub pot: f64,
}
impl Solved {
/// Exploitability in bb per 100 decisions of this kind (what the plan's gate counts).
pub fn exploit_bb_per_100(&self) -> Option<f64> {
self.exploit.map(|e| e.total / self.big_blind * 100.0)
}
}
/// The result of deciding one hand from a `Solved`.
pub struct TurnSolved {
pub decision: Decision,
/// Hero's action probabilities for the real hand at the real node, and the actions they stand for.
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub solved: Arc<Solved>,
}
/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the
/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
pub(crate) fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
street_line(spot, villain, Street::Turn)
}
/// The line of `street` so far (as `turn_line`).
pub(crate) fn street_line(spot: &Spot, villain: &Villain, street: Street) -> (usize, Vec<Act>, [f64; 2]) {
let mut first = None;
let mut acts = Vec::new();
let mut c = [0.0f64, 0.0];
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == street) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
1
} else {
continue;
};
first.get_or_insert(who);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => acts.push(Act::Check),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => {
acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) });
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
acts.push(Act::Call);
c[who] = c[1 - who];
}
_ => {}
}
}
let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0);
match first {
Some(f) if consistent => (f, acts, c),
_ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]),
_ => (0, Vec::new(), [0.0, 0.0]),
}
}
/// Masks and weights of a combo list: off the board, the `max` heaviest, `keep` (hero's hand) always in.
pub(crate) fn prune(list: &[(Vec<Card>, f64)], board: u64, cfg: &TurnConfig, keep: Option<u64>) -> Hands {
let mut v: Vec<(u64, f64)> = list
.iter()
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
.map(|(c, w)| (fast7::mask(c), *w))
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
.collect();
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
v.dedup_by_key(|x| x.0);
let top = v.first().map_or(1.0, |x| x.1);
let kept = keep.and_then(|k| v.iter().position(|x| x.0 == k).map(|i| v[i].1));
let total: f64 = v.iter().map(|x| x.1).sum();
let mut acc = 0.0;
let enough = v
.iter()
.position(|x| {
acc += x.1;
acc >= cfg.cover * total
})
.map_or(v.len(), |i| i + 1);
v.truncate(enough.min(cfg.max_combos).max(1));
if let Some(k) = keep {
if !v.iter().any(|x| x.0 == k) {
// Pruned away, or not in the blueprint range at all: stays in with the weight it had, else
// a token weight, so the game has a strategy for it without moving the equilibrium.
v.push((k, kept.unwrap_or(top * 1e-6)));
}
}
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Solve the game of `spot`'s public state with these weighted ranges. `keep`: a hero hand that must
/// be in the game whatever the pruning. `None` outside a heads-up turn decision or when the line
/// leaves the tree.
fn solve_core(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig, keep: Option<u64>) -> Option<Solved> {
if spot.street != Street::Turn || spot.board.len() != 4 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = turn_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= c[0].max(c[1]) {
return None;
}
let started = std::time::Instant::now();
let board = fast7::mask(&spot.board);
let hands = [prune(hero, board, cfg, keep), prune(villain_list, board, cfg, None)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let mut bets = TrBets::standard(pot, stack, first);
bets.river.max_raises = cfg.river_raises;
let game = build(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let mut solver = TrSolver::new(game, hands, board, Some(cfg.river_cards));
if cfg.budget_ms > 0.0 {
let mut done = 0;
while done < cfg.iterations {
solver.iterate();
done += 1;
if started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms {
break;
}
}
if done < MIN_ITERS {
return None;
}
} else {
solver.run(cfg.iterations);
}
let strategy = solver.strategy();
let exploit = cfg.measure.then(|| solver.exploitability(&strategy));
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, combos, nodes, exploit, big_blind: spot.big_blind, pot })
}
/// Hero's decision for the real hand from a solved node.
fn decide_from(spot: &Spot, solved: Arc<Solved>, hero_mask: u64) -> Option<TurnSolved> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = solved.rows[idx * a..(idx + 1) * a].to_vec();
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = row.len().saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
let decision = Decision::new(
choice,
p.clamp(0.0, 1.0),
format!("turn game: {}x{} combos, {} nodes, {act:?} p {p:.2}, solved in {:.0} ms", solved.combos[0], solved.combos[1], solved.nodes, solved.millis),
);
let acts = solved.acts.clone();
Some(TurnSolved { decision, row, acts, solved })
}
/// Solve the turn for `spot` with these weighted ranges (`hero`, `villain`, as `gewichtete_listen`
/// gives them) and decide; no cache. `None` outside a heads-up turn decision or off the tree.
pub fn solve_turn(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig) -> Option<TurnSolved> {
if spot.hero_cards.len() != 2 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let solved = solve_core(spot, hero, villain_list, cfg, Some(hero_mask))?;
decide_from(spot, Arc::new(solved), hero_mask)
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
/// An entry is a few kilobytes (one row of probabilities per hero combo).
const CACHE_MAX: usize = 4096;
/// Identity of the public state and the solve budget (not hero's cards).
fn public_key(spot: &Spot, cfg: &TurnConfig) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
format!("{:?}", spot.board).hash(&mut h);
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
spot.live_villains().for_each(|v| (v.seat, v.stack.to_bits()).hash(&mut h));
(spot.hero_seat, cfg.max_combos, cfg.cover.to_bits(), cfg.river_cards, cfg.iterations, cfg.measure, cfg.river_raises).hash(&mut h);
h.finish()
}
/// The live decision: the turn game with ranges from the blueprint, or `None` (switch off, not a
/// blueprint spot, ...) and the heuristic keeps the decision.
pub fn turn_game_decision(spot: &Spot) -> Option<Decision> {
if turn_player() == TurnPlayer::Off || spot.street != Street::Turn || spot.hero_cards.len() != 2 {
return None;
}
let cfg = TurnConfig::from_env();
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let key = public_key(spot, &cfg);
let cached = CACHE.lock().ok()?.as_ref().and_then(|m| m.get(&key).cloned());
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?;
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
// A hero hand outside the pruned range (low weight at this node, or not in the blueprint range at
// all) is not in the game: `None`, the heuristic plays it.
decide_from(spot, solved, hero_mask).map(|d| d.decision)
}
// --- Stage B of "solver everywhere" (switch SOLVER_TURN, default off) ---
static UEBERALL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Stage B: the turn game decides every heads-up Hold'em turn, not only blueprint scenarios. Ranges
/// from the blueprint where it recognises the spot, else from the range model of the action history
/// (`river_spieler::model_lists`: hero's line without a read, the villain's with its gated read).
pub fn set_turn_ueberall(on: bool) {
UEBERALL.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_ueberall() -> bool {
UEBERALL.load(std::sync::atomic::Ordering::Relaxed)
}
/// `SOLVER_TURN=1`.
pub fn turn_ueberall_from_env() -> bool {
matches!(std::env::var("SOLVER_TURN").as_deref(), Ok("1") | Ok("an"))
}
/// The stage-B decision for `raw` (ungated reads; the villain range uses the gated ones), or `None`
/// (switch off, not a heads-up Hold'em turn, off the tree) and the heuristic keeps the decision. A hero
/// hand outside the pruned range gets an uncached solve with the hand in it (live asks once per
/// decision, so this is the normal live cost).
pub fn turn_solver_decision(raw: &Spot) -> Option<Decision> {
if !turn_ueberall() || raw.street != Street::Turn || raw.hero_cards.len() != 2 || raw.board.len() != 4 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let cfg = TurnConfig { max_combos: STAGE_B_COMBOS, river_cards: STAGE_B_RIVER_CARDS, budget_ms: STAGE_B_BUDGET_MS, ..TurnConfig::from_env() };
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = crate::engine::river_spieler::read_of(raw);
let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref());
let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone())));
let mut key_h = std::collections::hash_map::DefaultHasher::new();
(public_key(spot, &cfg), "ueberall").hash(&mut key_h);
spot.live_villains().for_each(|v| format!("{:?}", v.profile).hash(&mut key_h));
raw_profile.hash(&mut key_h);
let key = key_h.finish();
let tag = |mut d: Decision, src: &str| {
d.reason = format!("solver turn ({src}) {}", d.reason);
d
};
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
if let Some(t) = cached.and_then(|s| decide_from(spot, s, hero_mask)) {
return Some(tag(t.decision, "cache"));
}
// One solve per decision, inside what is left of the turn's total: the shared public-state solve
// (cached) when hero's hand survives the pruning, else a solve with hero's hand kept (not cached).
let (hero, villain, src) = lists()?;
let budget = crate::engine::frist::budget_ms(cfg.budget_ms, crate::engine::frist::TURN_MS);
if budget <= 0.0 {
return None;
}
let cfg = TurnConfig { budget_ms: budget, ..cfg };
if prune(&hero, fast7::mask(&spot.board), &cfg, None).masks.contains(&hero_mask) {
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
return decide_from(spot, solved, hero_mask).map(|t| tag(t.decision, src));
}
solve_turn(spot, &hero, &villain, &cfg).map(|t| tag(t.decision, src))
}
#[cfg(test)]
mod tests;