From d8d61fee936cecfad062ff11786e8107e17b5d6b Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 21:49:12 +0100 Subject: [PATCH] Solver ueberall: Entscheidungsfrist (frist.rs: Turn 1,25 s, Flop/River 2 s ab Entscheidungsbeginn), ein Solve je Entscheidung, Stufe B 120 Kombos x 8 Riverkarten, SOLVER_ZEIT=fest fuer Messungen Co-Authored-By: Claude Opus 5.5 --- messung_solver/abdeckung.sh | 22 + src/engine/decide.rs | 3 +- src/engine/flop_spieler.rs | 42 +- src/engine/frist.rs | 50 +++ src/engine/mod.rs | 1 + src/engine/river_spieler.rs | 792 ++++++++++++++++++------------------ src/engine/turn_game.rs | 57 ++- 7 files changed, 521 insertions(+), 446 deletions(-) create mode 100644 messung_solver/abdeckung.sh create mode 100644 src/engine/frist.rs diff --git a/messung_solver/abdeckung.sh b/messung_solver/abdeckung.sh new file mode 100644 index 00000000..bbb3bbe8 --- /dev/null +++ b/messung_solver/abdeckung.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# Abdeckung + Latenz der Stufen A/B/C auf den echten Kern-Anfragen (Schatten-Logs des Live-Baums). +# Leiht sich 1 Thread aus GRENZE.txt der Engine-Warteschlange (20 -> 19) und gibt ihn am Ende zurueck. +cd "$(dirname "$0")/.." +L=../engine-lecks-angreifen-de7b88 +G=$L/messung_engine/GRENZE.txt +K="$(pwd -W)/messung_solver/bin/${1:-pokerbench-solver-abdeckungBC2.exe}" +leihe() { python3 - "$G" "$1" "$2" <<'PY' +import sys;p,a,b=sys.argv[1:];s=open(p,newline='').read() +s=s.replace(f"threads={a}\r\n",f"threads={b}\r\n",1).replace(f"threads={a}\n",f"threads={b}\n",1) +open(p,"w",newline='').write(s) +PY +} +leihe 20 19 +E=(--env SOLVER_RIVER=1 --env SOLVER_TURN=1 --env SOLVER_FLOP=1 --env "GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten" --env MDF_UNREAD=0 --env TURN_SPIEL=grund) +for st in TURN FLOP RIVER; do + s=$(echo $st | tr A-Z a-z) + python3 lesen/solver_abdeckung.py --kern "$K" --schatten $L/betrieb/scratch "${E[@]}" --street $st --json messung_solver/abdeckung-$s.json > messung_solver/abdeckung-$s.txt 2>&1 +done +leihe 19 20 +grep -n "^threads" $G +cat messung_solver/abdeckung-turn.txt messung_solver/abdeckung-flop.txt messung_solver/abdeckung-river.txt diff --git a/src/engine/decide.rs b/src/engine/decide.rs index b748858d..8c99b146 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -160,7 +160,8 @@ pub fn decide(spot: &Spot) -> Decision { /// `decide` with an optional tournament situation (`icm`). Without one: cash. With one /// that cannot be priced: ABSTAIN. -pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision { +pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision { + super::frist::begin(); // Only act on reads we are proven to beat blind play with (`read_gate`); competent and // aggressive opponents are played blind until the exploit logic earns them on the ladder. let gated = super::read_gate::gate_reads(spot); diff --git a/src/engine/flop_spieler.rs b/src/engine/flop_spieler.rs index 90c9cdff..79830a33 100644 --- a/src/engine/flop_spieler.rs +++ b/src/engine/flop_spieler.rs @@ -198,7 +198,6 @@ pub fn flop_spieler_decision(raw: &Spot) -> Option { if spot.live_villains().count() != 1 { return None; } - let begun = std::time::Instant::now(); let cfg = FlopConfig::from_env(); let hero_mask = fast7::mask(&spot.hero_cards); if hero_mask & fast7::mask(&spot.board) != 0 { @@ -213,31 +212,30 @@ pub fn flop_spieler_decision(raw: &Spot) -> Option { h.finish() }; let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); - let solved = match cached { - Some(s) => s, - None => { - let (hero, villain, source) = lists()?; - let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?); - 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 - } - }; - if let Some(d) = decide_from(spot, &solved, hero_mask) { + if let Some(d) = cached.and_then(|s| decide_from(spot, &s, hero_mask)) { return Some(d); } - // Hero's hand was pruned away: one more solve with it kept, in what is left of the budget. - let left = cfg.budget_ms - begun.elapsed().as_secs_f64() * 1e3; - if left <= 0.0 { + // One solve per decision, inside what is left of the flop'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, source) = lists()?; + let budget = crate::engine::frist::budget_ms(cfg.budget_ms, crate::engine::frist::FLOP_MS); + if budget <= 0.0 { return None; } - let (hero, villain, source) = lists()?; - let own = solve_flop(spot, &hero, &villain, &FlopConfig { budget_ms: left, ..cfg }, Some(hero_mask), source)?; + let cfg = FlopConfig { budget_ms: budget, ..cfg }; + let pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD }; + if prune(&hero, fast7::mask(&spot.board), &pc, None).masks.contains(&hero_mask) { + let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?); + 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); + } + let own = solve_flop(spot, &hero, &villain, &cfg, Some(hero_mask), source)?; decide_from(spot, &own, hero_mask) } diff --git a/src/engine/frist.rs b/src/engine/frist.rs new file mode 100644 index 00000000..a08619b2 --- /dev/null +++ b/src/engine/frist.rs @@ -0,0 +1,50 @@ +//! The decision deadline of the postflop solvers ("Solver ueberall"): `decide_with` marks the start of +//! each decision on its thread, and a solver gets what is left of its street's total before it starts. +//! Totals per decision (live table): river and flop 2 s, turn 1.25 s, each minus `MARGIN_MS` for the +//! work after the solve. Without a mark (tests, tools calling a solver directly) the full total is left. + +use std::cell::Cell; +use std::time::Instant; + +thread_local! { + static START: Cell> = const { Cell::new(None) }; +} + +/// Total wall time of one decision per street, in ms. +pub const RIVER_MS: f64 = 2000.0; +pub const TURN_MS: f64 = 1250.0; +pub const FLOP_MS: f64 = 2000.0; +/// Kept free after the solve (strategy readout, sampling, the answer). +pub const MARGIN_MS: f64 = 100.0; + +/// Mark the start of a decision on this thread. +pub fn begin() { + START.with(|s| s.set(Some(Instant::now()))); +} + +/// Milliseconds since the mark (0 without one). +pub fn elapsed_ms() -> f64 { + START.with(|s| s.get().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3)) +} + +/// What a solver may still spend of `total_ms` (may be ≤ 0: then it must not start). +pub fn left_ms(total_ms: f64) -> f64 { + total_ms - MARGIN_MS - elapsed_ms() +} + +/// Measurement switch `SOLVER_ZEIT=fest`: solvers ignore wall time and always run their full iteration +/// count, so ladder and LBR results do not depend on machine load (read once). +pub fn fixed() -> bool { + static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); + *FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest")) +} + +/// The budget a solve gets: `cap_ms` (its own limit), cut to what is left of the street's total; +/// infinite under `SOLVER_ZEIT=fest`. +pub fn budget_ms(cap_ms: f64, total_ms: f64) -> f64 { + if fixed() { + f64::INFINITY + } else { + cap_ms.min(left_ms(total_ms)) + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 1e64f828..ecf1f40e 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -8,6 +8,7 @@ pub mod decide; pub mod double_board; pub mod effective; pub mod flop_spieler; +pub mod frist; pub mod from_plan; pub mod multiway; pub mod omaha_combos; diff --git a/src/engine/river_spieler.rs b/src/engine/river_spieler.rs index 6698d30d..cb239270 100644 --- a/src/engine/river_spieler.rs +++ b/src/engine/river_spieler.rs @@ -1,394 +1,398 @@ -//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos, -//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off). -//! -//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line -//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the -//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo -//! (no strength buckets, blockers count). -//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario -//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along -//! the line played; everywhere else both come from the engine's range model -//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's -//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range -//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario). -//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card -//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state. -//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a -//! strategy without moving the equilibrium. -//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under -//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`). -//! -//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash), -//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree. - -use crate::card::Card; -use crate::cfr::river_game::Act; -use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; -use crate::exploit::range_read::RangeRead; -use crate::engine::river_subgame::{legal_choice, river_line}; -use crate::game::{Decision, Spot, Street, Villain}; -use crate::hand::fast7; -use crate::rng::Rng; -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::{Arc, Mutex}; - -/// Who plays the heads-up river. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RiverSpieler { - /// The heuristic (default). - Aus, - /// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model. - An, - /// The solver with range-model ranges everywhere (measurement arm). - Modell, -} - -static MODE: AtomicU8 = AtomicU8::new(0); - -pub fn set_river_spieler(mode: RiverSpieler) { - MODE.store( - match mode { - RiverSpieler::Aus => 0, - RiverSpieler::An => 1, - RiverSpieler::Modell => 2, - }, - Ordering::Relaxed, - ); -} - -pub fn river_spieler() -> RiverSpieler { - match MODE.load(Ordering::Relaxed) { - 1 => RiverSpieler::An, - 2 => RiverSpieler::Modell, - _ => RiverSpieler::Aus, - } -} - -/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`. -pub fn from_env() -> RiverSpieler { - match std::env::var("SOLVER_RIVER").as_deref() { - Ok("1") | Ok("an") => RiverSpieler::An, - Ok("modell") => RiverSpieler::Modell, - _ => RiverSpieler::Aus, - } -} - -/// CFR+ iterations at most. -pub const ITERS: u32 = 600; -/// Fewer finished iterations than this (time budget hit): the heuristic decides. -pub const MIN_ITERS: u32 = 100; -/// Wall-time budget of one solve. -pub const BUDGET_MS: f64 = 1500.0; - -/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises. -fn river_menu() -> Menu { - Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true } -} - -/// One solved river node: what every hero hand at this public state shares. -pub struct Solved { - rows: Vec, - acts: Vec, - hero_masks: Vec, - pub millis: f64, - pub iterations: u32, - pub combos: [usize; 2], - pub nodes: usize, - pub source: &'static str, -} - -/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a -/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do -/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving -/// the equilibrium). -fn hands_of(list: &[(Vec, f64)], dead: u64, fill: bool) -> Hands { - let mut w: HashMap = HashMap::new(); - for (c, x) in list { - if c.len() == 2 && *x > 0.0 && x.is_finite() { - let m = fast7::mask(c); - if m & dead == 0 && m.count_ones() == 2 { - let e = w.entry(m).or_insert(0.0); - *e = e.max(*x); - } - } - } - let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12); - if fill { - let bits: Vec = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect(); - for i in 0..bits.len() { - for j in i + 1..bits.len() { - w.entry(bits[i] | bits[j]).or_insert(top * TOKEN); - } - } - } - let mut v: Vec<(u64, f64)> = w.into_iter().collect(); - v.sort_by(|a, b| a.0.cmp(&b.0)); - Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } -} - -/// Relative weight of a hero hand outside the modelled range. -const TOKEN: f64 = 1e-6; - -/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. -pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str, read: Option<&RangeRead>) -> Option { - if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { - return None; - } - let villain = spot.live_villains().next()?; - let (first, forced, c) = river_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 <= 0.0 { - return None; - } - let started = std::time::Instant::now(); - let turn = fast7::mask(&spot.board[..4]); - let river = fast7::bit(spot.board[4]); - let dead = turn | river; - let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)]; - if hands[0].masks.is_empty() || hands[1].masks.is_empty() { - return None; - } - let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() }; - let game = build_river(&bets, &forced); - let at = game.at?; - if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) { - 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 villain_weights = hands[1].weights.clone(); - let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); - if let Some(r) = read { - lock_villain(&mut solver, r, pot, dead, &villain_weights); - } - let mut done = 0; - while done < ITERS { - solver.iterate(); - done += 1; - if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS { - break; - } - } - if done < MIN_ITERS { - return None; - } - let strategy = solver.strategy(); - let rows: Vec = (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, iterations: done, combos, nodes, source }) -} - -/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed. -fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option { - 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]; - let (draw, _) = Rng::seeded(spot.seed).unit(); - let mut acc = 0.0; - let mut pick = a.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); - Some(Decision::new( - choice, - p.clamp(0.0, 1.0), - format!( - "river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", - solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis - ), - )) -} - -/// Both ranges from the range model (the action history): hero's as the model reads hero's own line -/// (no read), the villain's with its gated read. Board cards only are dead (not hero's). -pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { - let villain = spot.live_villains().next()?; - let rules = spot.rules(); - let list = |who: &Villain| { - let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board); - crate::engine::range_combos::combos(&rules, &filter, &spot.board) - }; - let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; - let eins = |l: Vec>| l.into_iter().map(|c| (c, 1.0)).collect::>(); - Some((eins(list(&me)?), eins(list(villain)?))) -} - -/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from -/// its UNGATED profile, or `None` = the plain solver. -pub fn read_of(raw: &Spot) -> Option { - if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { - return None; - } - let villain = raw.live_villains().next()?; - RangeRead::from_profile(villain.profile.as_ref()) -} - -/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within -/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. -pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec { - let score: Vec = masks.iter().map(|m| fast7::score(m | board)).collect(); - let mut order: Vec = (0..masks.len()).collect(); - order.sort_by_key(|i| score[*i]); - let total: f64 = weights.iter().sum::().max(1e-300); - let mut out = vec![0.5; masks.len()]; - let mut below = 0.0; - let mut k = 0; - while k < order.len() { - let mut e = k; - let mut tie = 0.0; - while e < order.len() && score[order[e]] == score[order[k]] { - tie += weights[order[e]]; - e += 1; - } - for &i in &order[k..e] { - out[i] = (below + tie / 2.0) / total; - } - below += tie; - k = e; - } - out -} - -/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises -/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the -/// read layer: with a read, the villain's final weights are tilted by strength percentile -/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. -pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { - let (h, mut v, source) = match mode { - RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { - Some((h, v)) => (h, v, "grund"), - None => { - let (h, v) = model_lists(spot)?; - (h, v, "modell") - } - }, - _ => { - let (h, v) = model_lists(spot)?; - (h, v, "modell") - } - }; - if let Some(r) = read.filter(|r| r.confidence > 0.0) { - let board = fast7::mask(&spot.board); - let masks: Vec = v.iter().map(|(c, _)| fast7::mask(c)).collect(); - let weights: Vec = v.iter().map(|(_, w)| *w).collect(); - let pct = percentiles(&masks, &weights, board); - let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); - for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { - *w = x; - } - } - Some((h, v, source)) -} - -/// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`): -/// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer). -/// Facing an opening bet the weight is the fold read's trust, where it may bet the bluff read's trust; -/// facing a raise the node stays free (the read says nothing about raises). Nodes the read has no -/// opinion on stay pure CFR. -fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { - let pct = percentiles(solver.masks(1), villain_weights, board); - // The action that led into each node (a raise faced vs an opening bet faced). - let mut incoming: Vec> = vec![None; solver.game.nodes.len()]; - for (k, n) in solver.game.nodes.iter().enumerate() { - if let TNode::Dec { kids, .. } = n { - for (c, kid) in kids.iter().enumerate() { - incoming[*kid] = solver.game.acts[k].get(c).copied(); - } - } - } - let nodes: Vec<(usize, Vec)> = solver - .game - .nodes - .iter() - .enumerate() - .filter_map(|(k, n)| match n { - TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), - _ => None, - }) - .collect(); - for (node, acts) in nodes { - let facing = acts.contains(&Act::Fold); - if facing && !matches!(incoming[node], Some(Act::Bet(_))) { - continue; - } - let rows: Option> = pct.iter().map(|p| read.believed_row(2, &acts, pot, *p)).collect::>>>().map(|r| r.concat()); - if let Some(rows) = rows { - solver.lock(node, rows, read.trust(!facing, 2)); - } - } -} - -static CACHE: Mutex>>> = Mutex::new(None); -const CACHE_MAX: usize = 4096; - -/// Identity of the public state, the villain's read and the mode (not hero's cards). -fn public_key(spot: &Spot, mode: RiverSpieler) -> 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); - format!("{:?}", v.profile).hash(&mut h); - }); - (spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h); - h.finish() -} - -/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not -/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries -/// the ungated reads; the villain range uses the gated ones, as the heuristic's does. -pub fn river_spieler_decision(raw: &Spot) -> Option { - let mode = river_spieler(); - if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 { - return None; - } - let gated = crate::engine::read_gate::gate_reads(raw); - let spot = &gated; - if spot.live_villains().count() != 1 { - return None; - } - let hero_mask = fast7::mask(&spot.hero_cards); - if hero_mask & fast7::mask(&spot.board) != 0 { - return None; - } - let read = read_of(raw); - let mut key = public_key(spot, mode); - if read.is_some() { - let mut h = std::collections::hash_map::DefaultHasher::new(); - (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); - key = h.finish(); - } - let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); - let solved = match cached { - Some(s) => s, - None => { - let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; - let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); - 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 - } - }; - decide_from(spot, &solved, hero_mask) -} - -#[cfg(test)] -mod tests; +//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos, +//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off). +//! +//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line +//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the +//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo +//! (no strength buckets, blockers count). +//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario +//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along +//! the line played; everywhere else both come from the engine's range model +//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's +//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range +//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario). +//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card +//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state. +//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a +//! strategy without moving the equilibrium. +//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under +//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`). +//! +//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash), +//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree. + +use crate::card::Card; +use crate::cfr::river_game::Act; +use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; +use crate::exploit::range_read::RangeRead; +use crate::engine::river_subgame::{legal_choice, river_line}; +use crate::game::{Decision, Spot, Street, Villain}; +use crate::hand::fast7; +use crate::rng::Rng; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex}; + +/// Who plays the heads-up river. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RiverSpieler { + /// The heuristic (default). + Aus, + /// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model. + An, + /// The solver with range-model ranges everywhere (measurement arm). + Modell, +} + +static MODE: AtomicU8 = AtomicU8::new(0); + +pub fn set_river_spieler(mode: RiverSpieler) { + MODE.store( + match mode { + RiverSpieler::Aus => 0, + RiverSpieler::An => 1, + RiverSpieler::Modell => 2, + }, + Ordering::Relaxed, + ); +} + +pub fn river_spieler() -> RiverSpieler { + match MODE.load(Ordering::Relaxed) { + 1 => RiverSpieler::An, + 2 => RiverSpieler::Modell, + _ => RiverSpieler::Aus, + } +} + +/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`. +pub fn from_env() -> RiverSpieler { + match std::env::var("SOLVER_RIVER").as_deref() { + Ok("1") | Ok("an") => RiverSpieler::An, + Ok("modell") => RiverSpieler::Modell, + _ => RiverSpieler::Aus, + } +} + +/// CFR+ iterations at most. +pub const ITERS: u32 = 600; +/// Fewer finished iterations than this (time budget hit): the heuristic decides. +pub const MIN_ITERS: u32 = 100; +/// Wall-time budget of one solve. +pub const BUDGET_MS: f64 = 1500.0; + +/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises. +fn river_menu() -> Menu { + Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true } +} + +/// One solved river node: what every hero hand at this public state shares. +pub struct Solved { + rows: Vec, + acts: Vec, + hero_masks: Vec, + pub millis: f64, + pub iterations: u32, + pub combos: [usize; 2], + pub nodes: usize, + pub source: &'static str, +} + +/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a +/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do +/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving +/// the equilibrium). +fn hands_of(list: &[(Vec, f64)], dead: u64, fill: bool) -> Hands { + let mut w: HashMap = HashMap::new(); + for (c, x) in list { + if c.len() == 2 && *x > 0.0 && x.is_finite() { + let m = fast7::mask(c); + if m & dead == 0 && m.count_ones() == 2 { + let e = w.entry(m).or_insert(0.0); + *e = e.max(*x); + } + } + } + let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12); + if fill { + let bits: Vec = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect(); + for i in 0..bits.len() { + for j in i + 1..bits.len() { + w.entry(bits[i] | bits[j]).or_insert(top * TOKEN); + } + } + } + let mut v: Vec<(u64, f64)> = w.into_iter().collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } +} + +/// Relative weight of a hero hand outside the modelled range. +const TOKEN: f64 = 1e-6; + +/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. +pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str, read: Option<&RangeRead>) -> Option { + if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { + return None; + } + let villain = spot.live_villains().next()?; + let (first, forced, c) = river_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 <= 0.0 { + return None; + } + let budget = crate::engine::frist::budget_ms(BUDGET_MS, crate::engine::frist::RIVER_MS); + if budget <= 0.0 { + return None; + } + let started = std::time::Instant::now(); + let turn = fast7::mask(&spot.board[..4]); + let river = fast7::bit(spot.board[4]); + let dead = turn | river; + let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)]; + if hands[0].masks.is_empty() || hands[1].masks.is_empty() { + return None; + } + let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() }; + let game = build_river(&bets, &forced); + let at = game.at?; + if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) { + 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 villain_weights = hands[1].weights.clone(); + let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); + if let Some(r) = read { + lock_villain(&mut solver, r, pot, dead, &villain_weights); + } + let mut done = 0; + while done < ITERS { + solver.iterate(); + done += 1; + if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget { + break; + } + } + if done < MIN_ITERS { + return None; + } + let strategy = solver.strategy(); + let rows: Vec = (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, iterations: done, combos, nodes, source }) +} + +/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed. +fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option { + 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]; + let (draw, _) = Rng::seeded(spot.seed).unit(); + let mut acc = 0.0; + let mut pick = a.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); + Some(Decision::new( + choice, + p.clamp(0.0, 1.0), + format!( + "river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", + solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis + ), + )) +} + +/// Both ranges from the range model (the action history): hero's as the model reads hero's own line +/// (no read), the villain's with its gated read. Board cards only are dead (not hero's). +pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + let villain = spot.live_villains().next()?; + let rules = spot.rules(); + let list = |who: &Villain| { + let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board); + crate::engine::range_combos::combos(&rules, &filter, &spot.board) + }; + let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; + let eins = |l: Vec>| l.into_iter().map(|c| (c, 1.0)).collect::>(); + Some((eins(list(&me)?), eins(list(villain)?))) +} + +/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from +/// its UNGATED profile, or `None` = the plain solver. +pub fn read_of(raw: &Spot) -> Option { + if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { + return None; + } + let villain = raw.live_villains().next()?; + RangeRead::from_profile(villain.profile.as_ref()) +} + +/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within +/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. +pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec { + let score: Vec = masks.iter().map(|m| fast7::score(m | board)).collect(); + let mut order: Vec = (0..masks.len()).collect(); + order.sort_by_key(|i| score[*i]); + let total: f64 = weights.iter().sum::().max(1e-300); + let mut out = vec![0.5; masks.len()]; + let mut below = 0.0; + let mut k = 0; + while k < order.len() { + let mut e = k; + let mut tie = 0.0; + while e < order.len() && score[order[e]] == score[order[k]] { + tie += weights[order[e]]; + e += 1; + } + for &i in &order[k..e] { + out[i] = (below + tie / 2.0) / total; + } + below += tie; + k = e; + } + out +} + +/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises +/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the +/// read layer: with a read, the villain's final weights are tilted by strength percentile +/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. +pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { + let (h, mut v, source) = match mode { + RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { + Some((h, v)) => (h, v, "grund"), + None => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }, + _ => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }; + if let Some(r) = read.filter(|r| r.confidence > 0.0) { + let board = fast7::mask(&spot.board); + let masks: Vec = v.iter().map(|(c, _)| fast7::mask(c)).collect(); + let weights: Vec = v.iter().map(|(_, w)| *w).collect(); + let pct = percentiles(&masks, &weights, board); + let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); + for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { + *w = x; + } + } + Some((h, v, source)) +} + +/// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`): +/// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer). +/// Facing an opening bet the weight is the fold read's trust, where it may bet the bluff read's trust; +/// facing a raise the node stays free (the read says nothing about raises). Nodes the read has no +/// opinion on stay pure CFR. +fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { + let pct = percentiles(solver.masks(1), villain_weights, board); + // The action that led into each node (a raise faced vs an opening bet faced). + let mut incoming: Vec> = vec![None; solver.game.nodes.len()]; + for (k, n) in solver.game.nodes.iter().enumerate() { + if let TNode::Dec { kids, .. } = n { + for (c, kid) in kids.iter().enumerate() { + incoming[*kid] = solver.game.acts[k].get(c).copied(); + } + } + } + let nodes: Vec<(usize, Vec)> = solver + .game + .nodes + .iter() + .enumerate() + .filter_map(|(k, n)| match n { + TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), + _ => None, + }) + .collect(); + for (node, acts) in nodes { + let facing = acts.contains(&Act::Fold); + if facing && !matches!(incoming[node], Some(Act::Bet(_))) { + continue; + } + let rows: Option> = pct.iter().map(|p| read.believed_row(2, &acts, pot, *p)).collect::>>>().map(|r| r.concat()); + if let Some(rows) = rows { + solver.lock(node, rows, read.trust(!facing, 2)); + } + } +} + +static CACHE: Mutex>>> = Mutex::new(None); +const CACHE_MAX: usize = 4096; + +/// Identity of the public state, the villain's read and the mode (not hero's cards). +fn public_key(spot: &Spot, mode: RiverSpieler) -> 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); + format!("{:?}", v.profile).hash(&mut h); + }); + (spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h); + h.finish() +} + +/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not +/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries +/// the ungated reads; the villain range uses the gated ones, as the heuristic's does. +pub fn river_spieler_decision(raw: &Spot) -> Option { + let mode = river_spieler(); + if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 { + return None; + } + let gated = crate::engine::read_gate::gate_reads(raw); + let spot = &gated; + if spot.live_villains().count() != 1 { + return None; + } + let hero_mask = fast7::mask(&spot.hero_cards); + if hero_mask & fast7::mask(&spot.board) != 0 { + return None; + } + let read = read_of(raw); + let mut key = public_key(spot, mode); + if read.is_some() { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); + key = h.finish(); + } + let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); + let solved = match cached { + Some(s) => s, + None => { + let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; + let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); + 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 + } + }; + decide_from(spot, &solved, hero_mask) +} + +#[cfg(test)] +mod tests; diff --git a/src/engine/turn_game.rs b/src/engine/turn_game.rs index 4f3b169e..36b7ea50 100644 --- a/src/engine/turn_game.rs +++ b/src/engine/turn_game.rs @@ -75,8 +75,12 @@ pub struct TurnConfig { /// Fewest iterations a budgeted solve may decide with. pub const MIN_ITERS: u32 = 60; -/// Stage B's per-decision budget (all solves of one decision together). +/// 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 }; @@ -379,8 +383,7 @@ pub fn turn_solver_decision(raw: &Spot) -> Option { if spot.live_villains().count() != 1 { return None; } - let begun = std::time::Instant::now(); - let cfg = TurnConfig { budget_ms: STAGE_B_BUDGET_MS, ..TurnConfig::from_env() }; + 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; @@ -393,38 +396,34 @@ pub fn turn_solver_decision(raw: &Spot) -> Option { 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 cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); - let mut source = ""; - let solved = match cached { - Some(s) => s, - None => { - let (hero, villain, src) = lists()?; - source = src; - 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 - } - }; let tag = |mut d: Decision, src: &str| { - d.reason = format!("solver turn ({}) {}", if src.is_empty() { "cache" } else { src }, d.reason); + d.reason = format!("solver turn ({src}) {}", d.reason); d }; - if let Some(t) = decide_from(spot, solved, hero_mask) { - return Some(tag(t.decision, source)); + 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")); } - // Hero's hand was pruned away: one more solve with it kept, in what is left of the budget. - let left = STAGE_B_BUDGET_MS - begun.elapsed().as_secs_f64() * 1e3; - if left <= 0.0 { + // 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 (hero, villain, src) = lists()?; - solve_turn(spot, &hero, &villain, &TurnConfig { budget_ms: left, ..cfg }).map(|t| tag(t.decision, src)) + 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)]