diff --git a/docs/notizen/BEFUND-river-gto-leck.md b/docs/notizen/BEFUND-river-gto-leck.md new file mode 100644 index 00000000..39825d8a --- /dev/null +++ b/docs/notizen/BEFUND-river-gto-leck.md @@ -0,0 +1,48 @@ +# Befund Stage A: reines River-GTO schlägt die Exploit-Heuristik nicht + +**Messung** (volle Leiter gegen Basislinie `201a115+lokal`, River-Subgame-Solver für den +Heads-up-River-am-Zug-Slice in `engine::decide` eingespeist): + +``` +GESAMT -73.95 ± 5.25 bb/100 2856 geändert SCHLECHTER +heads-up calling station -240.99 ±24.57 566 geändert SCHLECHTER +heads-up fish -114.94 ±21.51 290 geändert SCHLECHTER +heads-up reg / nit / maniac ~0 (im Rauschen) nicht unterscheidbar +6-max reg / nit / maniac / fish ~0 nicht unterscheidbar +``` + +Der Verlust sitzt **ausschließlich bei den Over-Callern** (Station callt 98 %, Fish 93 %). Gegen +Gegner, die man nicht ausbeuten kann (Reg, Nit), ist reines GTO neutral. + +## Mechanismus + +Reines GTO ist **unausbeutbar, aber nicht ausbeuterisch**. Der River-Solver löst das Gleichgewicht: +beide Seiten optimieren. Gegen einen Station, der nie foldet, ist das falsch an beiden Enden — +- GTO blufft einen ausbalancierten Luft-Anteil hinein, der immer gecallt wird (verbranntes Geld), +- GTO checkt mittlere Hände zurück statt thin zu valuebetten (liegengelassenes Geld). + +Die **ausgelieferte Heuristik beutet genau das aus** (valuebettet thin, blufft Nicht-Folder nie) und +gewinnt gegen Station/Fish zweistellig bis dreistellig. GTO macht diesen Vorsprung kaputt. + +## Schlussfolgerung (bestätigt die Vision) + +1. **Pure GTO ≠ stompen.** Das ist der empirische Beweis für den Kern von [[engine-math-vision]]: + gebraucht wird **Best-Response gegen den _modellierten_ Gegner**, nicht das Gleichgewicht + (Kronengleichung `max E_belief[EV(σ)] − λ·KL(σ‖σ_GTO)`, λ→0 bei belastbarem Read). + +2. **Stage A kann die Leiter auch mit Best-Response nicht gewinnen.** Eine Einzelstraßen-Best-Response + auf dem River ≈ das, was die Heuristik schon rechnet (EV jeder Aktion gegen die modellierte + Fold/Call-Frequenz). Der River ist die Straße, auf der die Einzelstraßen-Heuristik am wenigsten + falsch liegt. Der Gewinn liegt **mehrstraßig** (Stage B: Turn+River), wo die Myopie der Heuristik + der eigentliche Leak ist — der Over-Barrel in genutzte Ranges (siehe BEFUND-nit-read-leck). + +## Was bleibt / was als Nächstes + +- **Reverted:** die `decide`-Einspeisung ist raus; die ausgelieferte Engine ist unverändert + (kein Loser wird ausgeliefert). +- **Behalten als Fundament:** `src/cfr/river.rs` (gegen Lehrbuch-GTO bewiesen: Bluff-Verhältnis + `s/(P+s)`, MDF `P/(P+s)`) und `src/engine/river_subgame.rs` (die Bucketing-Brücke Combos→Stärke + via `judge`). Stage B wiederverwendet beides. +- **Nächster Schritt — Stage B:** Turn+River-Baum mit River-Chance-Knoten, gelöst als Best-Response + gegen die modellierte Gegner-Continuation, damit die Barrel-Entscheidung die River-Konsequenz + sieht. Dort stirbt der Over-Barrel-Leak. diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index 318baac9..aaa82969 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -92,6 +92,7 @@ pub mod push_fold_game; pub mod regret_matching; pub mod render_charts; pub mod render_equity; +pub mod river; pub mod render_multi; pub mod run_plan; pub mod seat; diff --git a/src/cfr/river.rs b/src/cfr/river.rs new file mode 100644 index 00000000..89a620e0 --- /dev/null +++ b/src/cfr/river.rs @@ -0,0 +1,148 @@ +//! A heads-up river subgame as a `Tree`, solved by the shared CFR+ core (`solve`). +//! +//! The river is terminal: the board is complete, so there are no chance nodes and a showdown is +//! exact. Hands are abstract **strength buckets**, 0 = weakest, `buckets - 1` = strongest, with a +//! monotone showdown (higher bucket wins, equal buckets split). Both players draw from the same +//! bucket set; `chance[i * buckets + j]` is the joint probability that hero (player 0) holds bucket +//! `i` and villain (player 1) holds bucket `j` (independent product of the two range vectors in this +//! first version; card removal between the ranges is a later refinement). +//! +//! Betting (v1): hero acts first, one bet size `s` (chips), no raises. Hero checks or bets; after a +//! check villain checks (showdown) or bets and hero folds or calls; after a bet villain folds or +//! calls. Enough to reproduce the textbook river results (`tests`): with pot `P` and bet `s`, the +//! polarised bettor's bluff-to-value ratio is `s / (P + s)` and the bluff-catcher defends `P / (P + s)` +//! (minimum defence frequency). Sizes and raises come in later versions. +//! +//! Payoffs are hero's net in chips from the river onward, zero-sum (each player is treated as having +//! put `P/2` into the pot). A showdown for total pot `Q` pays hero `+Q/2` when his bucket is higher, +//! `-Q/2` when lower, `0` on a tie. An uncalled bet returns, so a fold just moves the dead pot `±P/2`. + +use super::solve::{solve, Solved}; +use super::tree::{Node, Payoff, Tree}; +use crate::rng::Rng; + +/// A solved heads-up river subgame and the bucket count it was built over. +pub struct RiverSolve { + pub solved: Solved, + pub buckets: usize, +} + +impl RiverSolve { + /// Hero's action probabilities at the root (index 0 = check, 1 = bet) for a hand in `bucket`. + pub fn hero_root(&self, bucket: usize) -> Vec { + self.solved.strategy.row(0, bucket).to_vec() + } +} + +/// The monotone showdown payoff for a total pot `q`: `+q/2` when hero's bucket beats villain's, +/// `-q/2` when it loses, `0` on a tie. +fn showdown(buckets: usize, q: f64) -> Payoff { + let mut pair = vec![0.0; buckets * buckets]; + for i in 0..buckets { + for j in 0..buckets { + pair[i * buckets + j] = match i.cmp(&j) { + std::cmp::Ordering::Greater => q / 2.0, + std::cmp::Ordering::Less => -q / 2.0, + std::cmp::Ordering::Equal => 0.0, + }; + } + } + Payoff::Pair(pair) +} + +/// The joint deal table `chance[i * buckets + j] = hero[i] * villain[j]`, normalised to sum 1. +/// Independent product (card removal between the two ranges is a later refinement). Falls back to a +/// uniform table when a range is empty or non-finite, so the tree stays playable. +fn chance(hero: &[f64], villain: &[f64]) -> Vec { + let buckets = hero.len(); + let mut table = vec![0.0; buckets * buckets]; + let mut total = 0.0; + for i in 0..buckets { + for j in 0..buckets { + let w = (hero[i].max(0.0)) * (villain[j].max(0.0)); + let w = if w.is_finite() { w } else { 0.0 }; + table[i * buckets + j] = w; + total += w; + } + } + if total > 0.0 { + table.iter_mut().for_each(|x| *x /= total); + } else { + table.iter_mut().for_each(|x| *x = 1.0 / (buckets * buckets) as f64); + } + table +} + +/// Build the v1 heads-up river tree: hero first to act, one bet size `s` (chips) into pot `p`, +/// no raises. Node 0 is hero's root decision (check, bet). +fn tree(hero: &[f64], villain: &[f64], p: f64, s: f64) -> Tree { + let buckets = hero.len(); + let pot_called = p + 2.0 * s; + // Node indices are wired by hand; see the module doc for the shape. + let nodes = vec![ + Node::Decision { player: 0, name: "hero", children: vec![1, 2] }, // 0: check -> 1, bet -> 2 + Node::Decision { player: 1, name: "v_check", children: vec![3, 4] }, // 1: v check -> 3, v bet -> 4 + Node::Decision { player: 1, name: "v_bet", children: vec![5, 6] }, // 2: v fold -> 5, v call -> 6 + Node::Terminal(showdown(buckets, p)), // 3: check-check showdown + Node::Decision { player: 0, name: "hero_vs_bet", children: vec![7, 8] }, // 4: hero fold -> 7, call -> 8 + Node::Terminal(Payoff::Flat(p / 2.0)), // 5: hero bet, villain folds + Node::Terminal(showdown(buckets, pot_called)), // 6: hero bet, villain calls + Node::Terminal(Payoff::Flat(-p / 2.0)), // 7: hero checks, bets, hero folds + Node::Terminal(showdown(buckets, pot_called)), // 8: hero checks, bets, hero calls + ]; + Tree { classes: buckets, chance: chance(hero, villain), nodes, root: 0 } +} + +/// Solve the v1 heads-up river subgame: hero (player 0) first to act, one bet size `s` chips into +/// pot `p`, no raises. `hero` / `villain` are strength-bucket weight vectors of equal length +/// (0 = weakest). Runs `iterations` of CFR+. +pub fn solve_river(hero: &[f64], villain: &[f64], p: f64, s: f64, iterations: u32, seed: u64) -> RiverSolve { + let t = tree(hero, villain, p, s); + RiverSolve { solved: solve(&t, iterations, Rng::seeded(seed)), buckets: hero.len() } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Convergence budget for the toy trees (tiny, so this is plenty). + const ITERS: u32 = 20_000; + const SEED: u64 = 0x5EED_21AA; + + /// Polarised river: hero holds only air (bucket 0) and nuts (bucket 2) in equal weight; + /// villain holds only a bluff-catcher (bucket 1). Pot 2, half-pot bet 1. Textbook GTO: + /// - hero value-bets the nuts ~100 %, + /// - hero bluffs the air at the frequency making bluff-to-value = s/(P+s) = 1/3, i.e. since + /// value = all nuts, the air bets ~1/3 of the time, + /// - the bluff-catcher calls at MDF = P/(P+s) = 2/3. + #[test] + fn polarised_river_matches_textbook_gto() { + let hero = [0.5, 0.0, 0.5]; // air, (unused mid), nuts + let villain = [0.0, 1.0, 0.0]; // pure bluff-catcher + let (p, s) = (2.0, 1.0); + let r = solve_river(&hero, &villain, p, s, ITERS, SEED); + + let nuts_bet = r.hero_root(2)[1]; + let air_bet = r.hero_root(0)[1]; + // Villain calling the bluff-catcher facing hero's bet: node "v_bet" (index 2), action 1 = call. + let villain_call = r.solved.strategy.probability(2, 1, 1); + + assert!(nuts_bet > 0.95, "nuts should value-bet ~always, got {nuts_bet:.3}"); + assert!((air_bet - 1.0 / 3.0).abs() < 0.06, "air bluff freq ~1/3, got {air_bet:.3}"); + assert!((villain_call - 2.0 / 3.0).abs() < 0.06, "bluff-catcher calls ~2/3 (MDF), got {villain_call:.3}"); + } + + /// Quarter-pot bet changes the numbers the same way theory says: bluff-to-value = s/(P+s) and + /// MDF = P/(P+s). Pot 2, bet 0.5: air bluffs ~ (0.5/2.5)=1/5 of the time, villain calls ~ 2/2.5 = 4/5. + #[test] + fn smaller_bet_shifts_frequencies_as_theory_says() { + let hero = [0.5, 0.0, 0.5]; + let villain = [0.0, 1.0, 0.0]; + let (p, s) = (2.0, 0.5); + let r = solve_river(&hero, &villain, p, s, ITERS, SEED); + let air_bet = r.hero_root(0)[1]; + let villain_call = r.solved.strategy.probability(2, 1, 1); + assert!((air_bet - 0.2).abs() < 0.06, "air bluff freq ~1/5, got {air_bet:.3}"); + assert!((villain_call - 0.8).abs() < 0.06, "bluff-catcher calls ~4/5, got {villain_call:.3}"); + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 00cd9fc1..4d7e2dfe 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -16,6 +16,7 @@ pub mod read_gate; pub mod range_combos; pub mod range_filter; pub mod read_label; +pub mod river_subgame; pub mod run_twice; pub mod semibluff; pub mod size_policy; diff --git a/src/engine/river_subgame.rs b/src/engine/river_subgame.rs new file mode 100644 index 00000000..ca5db698 --- /dev/null +++ b/src/engine/river_subgame.rs @@ -0,0 +1,93 @@ +//! Engine bridge from a live river spot to the pure CFR river solver (`cfr::river`). +//! +//! This is the Stage-A wiring: it turns the engine's own belief (hero's hand + the villain range +//! model, already built in `engine::decide::postflop`) into strength buckets, solves the heads-up +//! river subgame to equilibrium, and reads back hero's root action. All poker-specific sourcing +//! lives here; the solver stays a pure game over abstract buckets. +//! +//! First slice (v1), chosen so it maps exactly onto the solver's hero-to-act tree: **heads-up, +//! hero to act, not facing a bet** (`to_call == 0`) on the river. Every other river shape — facing +//! a bet, multiway — returns `None` so the caller keeps the heuristic. The solver equilibrium is +//! the unexploitable baseline; whether it beats the exploit heuristic on the ladder is a measured +//! question, not an assumption. +//! +//! Bucketing: villain combos are ranked by exact showdown strength (`hand::showdown::judge`, +//! `Strength: Ord`, monotone at showdown) and cut into `BUCKETS` equal-count (quantile) buckets, so +//! a higher bucket index always wins the showdown. Hero's single known hand is placed at the bucket +//! matching its rank among the villain hands (ties split), as a point mass. The tie approximation +//! inside hero's shared bucket shrinks with `BUCKETS`. + +use crate::card::Card; +use crate::cfr::river::solve_river; +use crate::game::{Choice, Spot, Street}; +use crate::hand::showdown::judge; +use crate::sizing::candidates::candidates; + +/// Strength buckets for the villain range. Small: the tree is `BUCKETS * BUCKETS` showdown cells, +/// and the quantile cut makes even a coarse grid monotone. Enough to separate value/bluff-catch/air. +const BUCKETS: usize = 16; +/// CFR+ iterations per live solve. The tree is tiny (9 nodes), so this converges well inside a +/// decision budget; kept modest because the sim ladder calls it once per qualifying river spot. +const ITERS: u32 = 3000; +/// Target bet size as a fraction of the pot; the nearest legal candidate is used. +const TARGET_BET_FRACTION: f64 = 0.66; + +/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable. +fn bet_to(spot: &Spot) -> Option { + let target = TARGET_BET_FRACTION * spot.pot; + candidates(spot) + .into_iter() + .filter(|to| *to > 0.0 && *to <= spot.hero_stack) + .min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs())) +} + +/// Hero's solver-chosen river action for the v1 slice, or `None` when the slice does not apply and +/// the caller should keep the heuristic decision. `villain_combos` is the believed range of the one +/// live villain (the `combos` list already computed in `postflop`). +pub fn river_choice(spot: &Spot, villain_combos: &[Vec]) -> Option { + if spot.street != Street::River || spot.to_call != 0.0 { + return None; + } + if spot.live_villains().count() != 1 || villain_combos.is_empty() { + return None; + } + let rules = spot.rules(); + let hero = judge(&rules, &spot.hero_cards, &spot.board).ok()?; + + let mut strengths: Vec<_> = villain_combos + .iter() + .filter_map(|c| judge(&rules, c, &spot.board).ok()) + .collect(); + if strengths.is_empty() { + return None; + } + strengths.sort(); + let n = strengths.len(); + + // Equal-count buckets over villain strengths: bucket index = rank quantile, monotone in strength. + let mut villain_range = vec![0.0; BUCKETS]; + for rank in 0..n { + let b = (rank * BUCKETS / n).min(BUCKETS - 1); + villain_range[b] += 1.0; + } + + // Hero placed by its rank among villain hands (strictly weaker + half the ties), same scale. + let weaker = strengths.iter().filter(|s| **s < hero).count(); + let ties = strengths.iter().filter(|s| **s == hero).count(); + let hero_pos = weaker as f64 + ties as f64 / 2.0; + let hero_bucket = ((hero_pos / n as f64 * BUCKETS as f64) as usize).min(BUCKETS - 1); + let mut hero_range = vec![0.0; BUCKETS]; + hero_range[hero_bucket] = 1.0; + + let bet = bet_to(spot)?; + let solved = solve_river(&hero_range, &villain_range, spot.pot, bet, ITERS, spot.seed); + let probs = solved.hero_root(hero_bucket); // [check, bet] + + // Deterministic engine: collapse the GTO mix to its majority action. Value (bet ~1) bets, clear + // give-ups check; a mixed bluff falls to whichever side the equilibrium weights above half. + if probs.get(1).copied().unwrap_or(0.0) > 0.5 { + Some(Choice::Raise { to: bet }) + } else { + Some(Choice::Check) + } +}