From 0dc0e162bb15c73e2913615cb86025a755a2649d Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 00:47:35 +0100 Subject: [PATCH] Szenario S1 (E2c): Einsatzbaum, Ranges aus den Engine-Charts, Rechenlauf mit Pruefpunkten - blueprint::s1: BTN-Open 2,5 bb / BB-Call, 100 bb; Flop 33/75, Turn 50/100, River 33/75/125 %, All-in als Bet ueberall, Raise auf 3x und All-in, hoechstens 3 Einsaetze je Strasse: 2470 Entscheidungen, 4353 Enden, etwa 2,2 M Tabelleneintraege. - Hand-Ranges aus preflop::generated_lookup (BTN-Open 41,5 %, BB-Call 57,3 % der Combos). - bin/grundstrategie: rechnet Runden, schreibt nach jeder Runde einen Pruefpunkt, setzt fort. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + src/bin/grundstrategie.rs | 64 ++++++++ src/blueprint/mod.rs | 1 + src/blueprint/s1.rs | 313 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 379 insertions(+) create mode 100644 src/bin/grundstrategie.rs create mode 100644 src/blueprint/s1.rs diff --git a/.gitignore b/.gitignore index 4e921bfb..4c06c39b 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ mac/build/ # E2b: Abstraktionstabellen sind aus dem Saatwert reproduzierbar (src/bin/abstraktion.rs) daten/abstraktion/*.u8 daten/abstraktion/*.f32 +daten/grundstrategie/ diff --git a/src/bin/grundstrategie.rs b/src/bin/grundstrategie.rs new file mode 100644 index 00000000..6ec0cf73 --- /dev/null +++ b/src/bin/grundstrategie.rs @@ -0,0 +1,64 @@ +//! Computes the S1 blueprint (plan E2d) with checkpoints, so a run can stop any time (live first). +//! +//! grundstrategie [periode] threads: POKERBENCH_THREADS +//! +//! Resumes from `/s1.ckpt` if present. After every round the checkpoint is rewritten +//! (atomically via a temp file). Bench copies: `pokerbench-engine-grundstrategie.exe`. + +use rechner::blueprint::mccfr::{rechnen, Tabellen}; +use rechner::blueprint::s1::{Abstraktion, S1}; +use std::io::{Read, Write}; +use std::path::Path; +use std::time::Instant; + +fn schreiben(pfad: &Path, tab: &Tabellen) { + let (r, s, t) = tab.sichern(); + let mut b = Vec::with_capacity(16 + 16 * r.len()); + b.extend_from_slice(&t.to_le_bytes()); + b.extend_from_slice(&(r.len() as u64).to_le_bytes()); + r.iter().chain(&s).for_each(|x| b.extend_from_slice(&x.to_le_bytes())); + let tmp = pfad.with_extension("tmp"); + std::fs::File::create(&tmp).unwrap().write_all(&b).unwrap(); + std::fs::rename(&tmp, pfad).unwrap(); +} + +pub fn lesen(pfad: &Path, tab: &mut Tabellen) -> bool { + let Ok(mut f) = std::fs::File::open(pfad) else { return false }; + let mut b = Vec::new(); + f.read_to_end(&mut b).unwrap(); + let u = |i: usize| u64::from_le_bytes(b[i..i + 8].try_into().unwrap()); + let (t, n) = (u(0), u(8) as usize); + let v: Vec = (0..2 * n).map(|k| f64::from_le_bytes(b[16 + 8 * k..24 + 8 * k].try_into().unwrap())).collect(); + tab.laden(&v[..n], &v[n..], t); + true +} + +fn main() { + let a: Vec = std::env::args().collect(); + if a.len() < 4 { + panic!("grundstrategie [periode]"); + } + let runden: u64 = a[3].parse().unwrap(); + let periode: u64 = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(1_000_000); + let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(2).max(1); + let out = Path::new(&a[2]); + std::fs::create_dir_all(out).unwrap(); + // The abstraction build writes BERICHT.txt last; wait for it (both may sit in one queue). + while !Path::new(&a[1]).join("BERICHT.txt").exists() { + std::thread::sleep(std::time::Duration::from_secs(30)); + } + let spiel = S1::neu(Abstraktion::laden(Path::new(&a[1])).expect("abstraction tables")); + let mut tab = Tabellen::neu(&spiel); + let ckpt = out.join("s1.ckpt"); + if lesen(&ckpt, &mut tab) { + println!("fortgesetzt bei Runde {}", tab.runden); + } + println!("S1: {} Eintraege, {threads} Threads, Periode {periode}", tab.eintraege()); + while tab.runden < runden { + let t = Instant::now(); + rechnen(&spiel, &mut tab, 1, periode, threads, 0xE2D_5EED); + schreiben(&ckpt, &tab); + let s = t.elapsed().as_secs_f64(); + println!("Runde {} fertig: {:.1}s, {:.0} Iterationen/s", tab.runden, s, periode as f64 / s); + } +} diff --git a/src/blueprint/mod.rs b/src/blueprint/mod.rs index 8334aae7..a0341b76 100644 --- a/src/blueprint/mod.rs +++ b/src/blueprint/mod.rs @@ -3,3 +3,4 @@ pub mod abstraktion; pub mod iso; pub mod mccfr; +pub mod s1; diff --git a/src/blueprint/s1.rs b/src/blueprint/s1.rs new file mode 100644 index 00000000..fc65630f --- /dev/null +++ b/src/blueprint/s1.rs @@ -0,0 +1,313 @@ +//! Scenario S1 of the blueprint (design `DESIGN-E2-grundstrategie.md`): 100 bb, the button opens to +//! 2.5 bb, the small blind folds, the big blind calls; flop pot 5 bb, heads-up postflop. The ranges +//! are the 6-max ones (button open 41.5 %, big-blind call 57.3 % of combos), the commonest pot at +//! the live tables. Player 0 = big blind (first to act on every +//! street), player 1 = button. +//! +//! Bet abstraction: flop 33 / 75 %, turn 50 / 100 %, river 33 / 75 / 125 % of the pot, all-in as a +//! bet everywhere; raises to 3x the bet faced and all-in; at most 3 bets (bet + 2 raises) a street. +//! Hands come from the engine's own preflop charts (button open, big-blind call at 100 bb), cards +//! by the card abstraction (`abstraktion`): flop / turn classes from the tables, river by EHS. + +use super::abstraktion::{combo_index, combos, river_class, river_ehs, CLASSES}; +use super::iso::{self, Street}; +use super::mccfr::{Baum, Knoten, Spiel, Zufall}; +use crate::card::Card; +use crate::cfr::hand_class::class_of; +use crate::cfr::seat::Seat; +use crate::hand::fast7; +use crate::preflop::generated_lookup::{open_frequency, vs_open}; +use crate::variant::Variant; + +pub const STACK: f64 = 100.0; +pub const OPEN: f64 = 2.5; +pub const MAX_EINSAETZE: usize = 3; +const BETS: [&[f64]; 3] = [&[0.33, 0.75], &[0.5, 1.0], &[0.33, 0.75, 1.25]]; +const RAISE: f64 = 3.0; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Aktion { + Check, + Bet(f64), + Call, + Raise(f64), + Fold, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Ende { + /// `verlierer` folded; `c` = total contributions of both (preflop included). + Fold { verlierer: usize, c: [f64; 2] }, + /// Equal contributions, cards decide. + Showdown { c: f64 }, +} + +/// The S1 betting tree with the action of every edge (`aktion[child]` = how the child was reached). +pub struct Einsatzbaum { + pub baum: Baum, + pub enden: Vec, + pub aktion: Vec>, +} + +struct Bauer { + knoten: Vec, + enden: Vec, + aktion: Vec>, +} + +impl Bauer { + fn ende(&mut self, e: Ende, a: Aktion) -> usize { + self.enden.push(e); + self.knoten.push(Knoten::Ende(self.enden.len() - 1)); + self.aktion.push(Some(a)); + self.knoten.len() - 1 + } + + /// Street `s` is over with equal contributions `c`. + fn strasse_zu(&mut self, s: usize, c: f64, a: Aktion) -> usize { + if s == 2 || c >= STACK { + self.ende(Ende::Showdown { c }, a) + } else { + self.zug(s + 1, [c, c], 0, 0, false, Some(a)) + } + } + + /// Decision of `p` on street `s`; `einsaetze` bets so far on this street; `geprueft` = player 0 + /// checked (only possible with no bet). + fn zug(&mut self, s: usize, c: [f64; 2], p: usize, einsaetze: usize, geprueft: bool, a: Option) -> usize { + let me = self.knoten.len(); + self.knoten.push(Knoten::Zug { spieler: p, strasse: s, kinder: Vec::new() }); + self.aktion.push(a); + let o = 1 - p; + let pot = c[0] + c[1]; + let facing = c[o] - c[p]; + let mut kinder = Vec::new(); + if facing <= 0.0 { + kinder.push(if geprueft || p == 1 { self.strasse_zu(s, c[p], Aktion::Check) } else { self.zug(s, c, o, 0, true, Some(Aktion::Check)) }); + let mut sizes: Vec = BETS[s].iter().map(|f| (c[p] + f * pot).min(STACK)).collect(); + sizes.push(STACK); + sizes.dedup_by(|x, y| (*x - *y).abs() < 1e-9); + for to in sizes { + if to > c[p] { + let mut n = c; + n[p] = to; + kinder.push(self.zug(s, n, o, einsaetze + 1, false, Some(Aktion::Bet(to)))); + } + } + } else { + kinder.push(self.ende(Ende::Fold { verlierer: p, c }, Aktion::Fold)); + kinder.push(self.strasse_zu(s, c[o], Aktion::Call)); + if einsaetze < MAX_EINSAETZE && c[o] < STACK { + let mut sizes = vec![(c[p] + RAISE * facing).min(STACK), STACK]; + sizes.dedup_by(|x, y| (*x - *y).abs() < 1e-9); + for to in sizes { + let mut n = c; + n[p] = to; + kinder.push(self.zug(s, n, o, einsaetze + 1, false, Some(Aktion::Raise(to)))); + } + } + } + if let Knoten::Zug { kinder: k, .. } = &mut self.knoten[me] { + *k = kinder; + } + me + } +} + +impl Einsatzbaum { + pub fn s1() -> Einsatzbaum { + let mut b = Bauer { knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new() }; + let wurzel = b.zug(0, [OPEN, OPEN], 0, 0, false, None); + Einsatzbaum { baum: Baum { knoten: b.knoten, wurzel }, enden: b.enden, aktion: b.aktion } + } +} + +/// Card abstraction tables; `None` = one class on that street (for tests without tables). +pub struct Abstraktion { + pub flop: Option<(Street, Vec)>, + pub turn: Option<(Street, Vec)>, + pub river: Vec, +} + +impl Abstraktion { + /// Load `flop.u8`, `turn.u8`, `river.f32` from `dir` (built by `bin/abstraktion`). + pub fn laden(dir: &std::path::Path) -> std::io::Result { + let lies = |n: &str| std::fs::read(dir.join(n)); + let flop = lies("flop.u8")?; + let turn = lies("turn.u8")?; + let river = lies("river.f32")?.chunks(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); + let (s3, s4) = (Street::new(3), Street::new(4)); + assert_eq!(flop.len(), s3.count(), "flop table does not match the flop street"); + assert_eq!(turn.len(), s4.count(), "turn table does not match the turn street"); + Ok(Abstraktion { flop: Some((s3, flop)), turn: Some((s4, turn)), river }) + } +} + +/// One dealt hand: cards and the class of both players on every street. +pub struct Deal { + pub hand: [u64; 2], + pub board: [u64; 5], + pub klasse: [[u8; 3]; 2], + /// +1 player 0 wins the showdown, -1 player 1, 0 split. + pub sieger: i8, +} + +pub struct S1 { + pub baum: Einsatzbaum, + pub abstraktion: Abstraktion, + alle: Vec, + /// Preflop weight per combo: [big blind call, button open]. + pub gewicht: [Vec; 2], +} + +/// Range weight per combo of `combos()` from a chart frequency per hand class. +fn gewichte(alle: &[u64], f: impl Fn(Card, Card) -> f64) -> Vec { + let deck = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As").unwrap(); + let karte = |bit: u64| *deck.iter().find(|c| fast7::bit(**c) == bit).unwrap(); + alle.iter().map(|h| f(karte(h & h.wrapping_neg()), karte(h & (h - 1)))).collect() +} + +impl S1 { + pub fn neu(abstraktion: Abstraktion) -> S1 { + let alle = combos(); + let depth = STACK; + let bb = gewichte(&alle, |a, b| vs_open(Variant::Nlhe, Seat::Button, depth, class_of(a, b).unwrap()).map_or(0.0, |f| f.call)); + let btn = gewichte(&alle, |a, b| open_frequency(Variant::Nlhe, Seat::Button, depth, class_of(a, b).unwrap()).map_or(0.0, |f| f.raise)); + S1 { baum: Einsatzbaum::s1(), abstraktion, alle, gewicht: [bb, btn] } + } + + fn hand_ziehen(&self, p: usize, tot: u64, rng: &mut Zufall) -> u64 { + loop { + let i = rng.below(self.alle.len()); + let h = self.alle[i]; + if h & tot == 0 && rng.unit() < self.gewicht[p][i] { + return h; + } + } + } +} + +impl Spiel for S1 { + type Deal = Deal; + + fn baum(&self) -> &Baum { + &self.baum.baum + } + + fn klassen(&self, _: usize) -> usize { + CLASSES + } + + fn ziehen(&self, rng: &mut Zufall) -> Deal { + let h1 = self.hand_ziehen(1, 0, rng); + let h0 = self.hand_ziehen(0, h1, rng); + let deck = iso::deck(); + let mut tot = h0 | h1; + let mut board = [0u64; 5]; + for b in board.iter_mut() { + loop { + let c = deck[rng.below(52)]; + if c & tot == 0 { + *b = c; + tot |= c; + break; + } + } + } + let flop = board[0] | board[1] | board[2]; + let turn = flop | board[3]; + let river = turn | board[4]; + let ehs = river_ehs(river, &self.alle); + let hand = [h0, h1]; + let klasse = hand.map(|h| { + let f = self.abstraktion.flop.as_ref().map_or(0, |(s, t)| t[s.index(flop, h).unwrap() as usize]); + let t = self.abstraktion.turn.as_ref().map_or(0, |(s, t)| t[s.index(turn, h).unwrap() as usize]); + [f, t, river_class(ehs[combo_index(h)], &self.abstraktion.river)] + }); + let (a, b) = (fast7::score(river | h0), fast7::score(river | h1)); + Deal { hand, board, klasse, sieger: (a > b) as i8 - (a < b) as i8 } + } + + fn klasse(&self, d: &Deal, spieler: usize, strasse: usize) -> usize { + d.klasse[spieler][strasse] as usize + } + + fn wert(&self, d: &Deal, ende: usize) -> [f64; 2] { + match self.baum.enden[ende] { + Ende::Fold { verlierer, c } => { + let v = c[verlierer]; + if verlierer == 0 { [-v, v] } else { [v, -v] } + } + Ende::Showdown { c } => { + let v = c * d.sieger as f64; + [v, -v] + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blueprint::abstraktion::river_cuts; + use crate::blueprint::mccfr::{rechnen, Tabellen}; + use crate::rng::split_mix::Rng; + + #[test] + fn the_s1_tree_is_well_formed() { + let t = Einsatzbaum::s1(); + let zuege = t.baum.knoten.iter().filter(|k| matches!(k, Knoten::Zug { .. })).count(); + eprintln!("S1: {} Knoten, {} Zuege, {} Enden", t.baum.knoten.len(), zuege, t.enden.len()); + for e in &t.enden { + match e { + Ende::Fold { verlierer, c } => { + assert!(c[*verlierer] < c[1 - verlierer], "only the player facing a bet folds"); + assert!(c.iter().all(|x| *x <= STACK + 1e-9)); + } + Ende::Showdown { c } => assert!(*c >= OPEN && *c <= STACK + 1e-9), + } + } + // Per street at most 3 bets: no path has a 4th Bet/Raise in a row without a street change. + fn tiefe(t: &Einsatzbaum, k: usize, s: usize, n: usize) { + if let Knoten::Zug { strasse, kinder, .. } = &t.baum.knoten[k] { + let n = if *strasse != s { 0 } else { n }; + for c in kinder { + let m = n + matches!(t.aktion[*c], Some(Aktion::Bet(_) | Aktion::Raise(_))) as usize; + assert!(m <= MAX_EINSAETZE); + tiefe(t, *c, *strasse, m); + } + } + } + tiefe(&t, t.baum.wurzel, 0, 0); + assert!(zuege < 20_000, "{zuege} decisions"); + } + + #[test] + fn the_preflop_ranges_are_the_engine_charts() { + let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let anteil = |p: usize| s.gewicht[p].iter().sum::() / 1326.0; + let (bb, btn) = (anteil(0), anteil(1)); + eprintln!("BB call {:.3}, BTN open {:.3}", bb, btn); + assert!(btn > 0.30 && btn < 0.70, "button open {btn}"); + assert!(bb > 0.15 && bb < 0.70, "big blind call {bb}"); + } + + /// A short run on the real tree: deals are legal, values zero-sum, the tables move. + #[test] + fn s1_runs_and_stays_zero_sum() { + let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let mut rng = Zufall(Rng::seeded(9)); + for _ in 0..200 { + let d = s.ziehen(&mut rng); + let all = d.hand[0] | d.hand[1] | d.board.iter().fold(0, |m, c| m | c); + assert_eq!(all.count_ones(), 9); + for e in 0..s.baum.enden.len() { + let w = s.wert(&d, e); + assert_eq!(w[0], -w[1]); + } + } + let mut tab = Tabellen::neu(&s); + rechnen(&s, &mut tab, 2, 200, 1, 3); + assert!(tab.sichern().0.iter().any(|r| *r != 0.0)); + } +}