diff --git a/src/bin/grundstrategie.rs b/src/bin/grundstrategie.rs index 6ec0cf73..50ea8343 100644 --- a/src/bin/grundstrategie.rs +++ b/src/bin/grundstrategie.rs @@ -1,64 +1,78 @@ -//! 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); - } -} +//! 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::lbr::lbr; +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); + // Gate E2d: LBR every 20 rounds and at the end (bb/100, lower bound on exploitability). + if tab.runden % 20 == 0 || tab.runden == runden { + let t = Instant::now(); + let n = if tab.runden == runden { 400_000 } else { 20_000 }; + let e = lbr(&spiel, &tab, n, threads, 0x1B2 ^ tab.runden); + let zeile = format!( + "Runde {} LBR {:+.1} ±{:.1} bb/100 (BB {:+.1}, BTN {:+.1}), {} Haende, {:.0}s", + tab.runden, e.bb100, e.ci95, e.je_sitz[0], e.je_sitz[1], e.haende, t.elapsed().as_secs_f64() + ); + println!("{zeile}"); + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(out.join("LBR.txt")).unwrap(); + writeln!(f, "{zeile}").unwrap(); + } + } +} diff --git a/src/blueprint/lbr.rs b/src/blueprint/lbr.rs new file mode 100644 index 00000000..cedacc39 --- /dev/null +++ b/src/blueprint/lbr.rs @@ -0,0 +1,221 @@ +//! Local Best Response (Lisý/Bowling 2017) against the blueprint: the gate of plan E2d. +//! +//! LBR plays real cards against the blueprint's average strategy. It tracks the opponent's range +//! card by card (preflop chart weights times the blueprint's probability of every action taken, +//! per combo through its class), and at each own decision picks the action with the best value +//! under the assumption that afterwards both players only check or call: +//! +//! - fold: lose what is in; check / call: equity share of the pot after calling; +//! - bet / raise: the opponent folds with the probability its range folds at that node, otherwise +//! calls (a raise counts as a call), and LBR gets its equity against the calling part. +//! +//! The opponent then acts by its strategy for its real hand. LBR's average result over both seats is +//! a lower bound on the blueprint's exploitability (bb per hand; the gate is < 0.3, i.e. 30 bb/100). + +use super::abstraktion::river_ehs; +use super::iso; +use super::mccfr::{Knoten, Spiel, Tabellen, Zufall}; +use super::s1::{Aktion, S1}; +use crate::hand::fast7; +use crate::rng::split_mix::Rng; + +/// Flop equity: run-outs sampled per decision (turn and river enumerate exactly). +const FLOP_RUNOUTS: usize = 64; + +pub struct Ergebnis { + /// LBR's mean result in bb/100, averaged over both seats, and its 95 % half-width. + pub bb100: f64, + pub ci95: f64, + pub haende: usize, + /// bb/100 as player 0 (big blind) and as player 1 (button). + pub je_sitz: [f64; 2], +} + +/// LBR's equity (win + tie/2) against every combo given the street's board, by exact enumeration +/// on turn and river and by `FLOP_RUNOUTS` sampled run-outs on the flop. Combos that touch the +/// board or the hand get 0. +fn equities(s: &S1, hand: u64, board: u64, rng: &mut Zufall) -> Vec { + let deck = iso::deck(); + let tot = hand | board; + let runouts: Vec = match board.count_ones() { + 5 => vec![0], + 4 => deck.iter().copied().filter(|c| c & tot == 0).collect(), + _ => (0..FLOP_RUNOUTS) + .map(|_| loop { + let (a, b) = (deck[rng.below(52)], deck[rng.below(52)]); + if a != b && (a | b) & tot == 0 { + break a | b; + } + }) + .collect(), + }; + let mut win = vec![0f32; s.alle.len()]; + let mut n = vec![0f32; s.alle.len()]; + for r in &runouts { + let full = board | r; + let me = fast7::score(full | hand); + for (i, c) in s.alle.iter().enumerate() { + if c & (full | hand) == 0 { + let o = fast7::score(full | c); + win[i] += if me > o { 1.0 } else if me == o { 0.5 } else { 0.0 }; + n[i] += 1.0; + } + } + } + win.iter().zip(&n).map(|(w, n)| if *n > 0.0 { w / n } else { 0.0 }).collect() +} + +/// Equity against a weighted range (0.5 if the range is empty). +fn gegen(eq: &[f32], w: &[f64]) -> f64 { + let (mut a, mut b) = (0.0, 0.0); + for (e, x) in eq.iter().zip(w) { + a += *e as f64 * x; + b += x; + } + if b > 0.0 { a / b } else { 0.5 } +} + +/// One hand with LBR in seat `l`; returns LBR's result in bb. +fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { + let o = 1 - l; + let d = s.ziehen(rng); + let baum = &s.baum; + let mut w: Vec = s.alle.iter().zip(&s.gewicht[o]).map(|(c, g)| if c & d.hand[l] == 0 { *g } else { 0.0 }).collect(); + let boards = [d.board[0] | d.board[1] | d.board[2], d.board[0] | d.board[1] | d.board[2] | d.board[3], d.board.iter().fold(0, |m, c| m | c)]; + let ehs_river = river_ehs(boards[2], &s.alle); + let mut strasse_da = usize::MAX; + let mut klassen: Vec = Vec::new(); + let mut eq: Vec = Vec::new(); + let mut k = baum.baum.wurzel; + loop { + let (spieler, strasse, kinder) = match &baum.baum.knoten[k] { + Knoten::Ende(e) => return s.wert(&d, *e)[l], + Knoten::Zug { spieler, strasse, kinder } => (*spieler, *strasse, kinder), + }; + let board = boards[strasse]; + if strasse != strasse_da { + strasse_da = strasse; + for (i, c) in s.alle.iter().enumerate() { + if c & board != 0 { + w[i] = 0.0; + } + } + klassen = s.alle.iter().zip(&w).map(|(c, x)| if *x > 0.0 { s.klasse_von(*c, board, strasse, &ehs_river) } else { 0 }).collect(); + eq = equities(s, d.hand[l], board, rng); + } + let n = kinder.len(); + if spieler == o { + let sigma = tab.durchschnitt(k, s.klasse_von(d.hand[o], board, strasse, &ehs_river), n); + let mut x = rng.unit(); + let mut a = 0; + while a + 1 < n && x >= sigma[a] { + x -= sigma[a]; + a += 1; + } + for i in 0..w.len() { + if w[i] > 0.0 { + w[i] *= tab.durchschnitt(k, klassen[i], n)[a]; + } + } + k = kinder[a]; + continue; + } + let c = baum.beitrag[k]; + let (pot, mine) = (c[0] + c[1], c[l]); + let wp = gegen(&eq, &w); + let mut best = (f64::NEG_INFINITY, kinder[0]); + for &kind in kinder { + let v = match baum.aktion[kind] { + Some(Aktion::Fold) => -mine, + Some(Aktion::Check) | Some(Aktion::Call) => { + let after = baum.beitrag[kind][o].max(c[o]); + wp * 2.0 * after - after + } + Some(Aktion::Bet(to)) | Some(Aktion::Raise(to)) => { + // The opponent's fold probability per combo at the child node (fold = child 0). + let (mut fold, mut all) = (0.0, 0.0); + let mut call_w = vec![0f64; w.len()]; + if let Knoten::Zug { kinder: ck, .. } = &baum.baum.knoten[kind] { + let m = ck.len(); + for i in 0..w.len() { + if w[i] > 0.0 { + let pf = tab.durchschnitt(kind, klassen[i], m)[0]; + fold += w[i] * pf; + all += w[i]; + call_w[i] = w[i] * (1.0 - pf); + } + } + } + let fp = if all > 0.0 { fold / all } else { 0.0 }; + fp * (pot - mine) + (1.0 - fp) * (gegen(&eq, &call_w) * 2.0 * to - to) + } + None => unreachable!("every child has an action"), + }; + if v > best.0 { + best = (v, kind); + } + } + k = best.1; + } +} + +/// LBR over `haende` hands (alternating seats) on `threads` threads. +pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) -> Ergebnis { + let je = haende.div_ceil(threads.max(1)); + let teile: Vec<[(f64, f64, usize); 2]> = std::thread::scope(|sc| { + let hs: Vec<_> = (0..threads.max(1) as u64) + .map(|th| { + sc.spawn(move || { + let mut rng = Zufall(Rng::seeded(Rng::seeded(seed ^ (th << 40)).next_u64().0)); + let mut acc = [(0.0, 0.0, 0usize); 2]; + for i in 0..je { + let l = i % 2; + let v = hand(s, tab, l, &mut rng); + acc[l].0 += v; + acc[l].1 += v * v; + acc[l].2 += 1; + } + acc + }) + }) + .collect(); + hs.into_iter().map(|h| h.join().unwrap()).collect() + }); + let mut t = [(0.0, 0.0, 0usize); 2]; + for p in &teile { + for l in 0..2 { + t[l].0 += p[l].0; + t[l].1 += p[l].1; + t[l].2 += p[l].2; + } + } + let mean = |x: (f64, f64, usize)| x.0 / x.2.max(1) as f64; + let var = |x: (f64, f64, usize)| (x.1 / x.2.max(1) as f64 - mean(x).powi(2)) / x.2.max(1) as f64; + let m = 0.5 * (mean(t[0]) + mean(t[1])); + let se = 0.5 * (var(t[0]) + var(t[1])).sqrt(); + Ergebnis { bb100: 100.0 * m, ci95: 196.0 * se, haende: t[0].2 + t[1].2, je_sitz: [100.0 * mean(t[0]), 100.0 * mean(t[1])] } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blueprint::abstraktion::river_cuts; + use crate::blueprint::mccfr::rechnen; + use crate::blueprint::s1::Abstraktion; + + /// LBR crushes an untrained (uniform) blueprint and does less against a trained one. + #[test] + fn lbr_punishes_a_uniform_strategy_more_than_a_trained_one() { + let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let mut tab = Tabellen::neu(&s); + let roh = lbr(&s, &tab, 2000, 2, 11); + eprintln!("uniform: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", roh.bb100, roh.ci95, roh.je_sitz[0], roh.je_sitz[1]); + assert!(roh.bb100 - roh.ci95 > 500.0, "uniform must be very exploitable"); + rechnen(&s, &mut tab, 20, 20_000, 2, 3); + let trainiert = lbr(&s, &tab, 2000, 2, 11); + eprintln!("trained: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", trainiert.bb100, trainiert.ci95, trainiert.je_sitz[0], trainiert.je_sitz[1]); + // Without tables flop and turn have one class (the strategy cannot see its cards there), + // so the trained strategy stays very exploitable; it must still be clearly less so. + assert!(trainiert.bb100 < roh.bb100, "{} vs {}", trainiert.bb100, roh.bb100); + } +} diff --git a/src/blueprint/mod.rs b/src/blueprint/mod.rs index a0341b76..068a6697 100644 --- a/src/blueprint/mod.rs +++ b/src/blueprint/mod.rs @@ -2,5 +2,6 @@ pub mod abstraktion; pub mod iso; +pub mod lbr; pub mod mccfr; pub mod s1; diff --git a/src/blueprint/s1.rs b/src/blueprint/s1.rs index fc65630f..3f1fdd3d 100644 --- a/src/blueprint/s1.rs +++ b/src/blueprint/s1.rs @@ -47,12 +47,15 @@ pub struct Einsatzbaum { pub baum: Baum, pub enden: Vec, pub aktion: Vec>, + /// Contributions of both players (preflop included) when the node is reached. + pub beitrag: Vec<[f64; 2]>, } struct Bauer { knoten: Vec, enden: Vec, aktion: Vec>, + beitrag: Vec<[f64; 2]>, } impl Bauer { @@ -60,6 +63,10 @@ impl Bauer { self.enden.push(e); self.knoten.push(Knoten::Ende(self.enden.len() - 1)); self.aktion.push(Some(a)); + self.beitrag.push(match e { + Ende::Fold { c, .. } => c, + Ende::Showdown { c } => [c, c], + }); self.knoten.len() - 1 } @@ -78,6 +85,7 @@ impl Bauer { let me = self.knoten.len(); self.knoten.push(Knoten::Zug { spieler: p, strasse: s, kinder: Vec::new() }); self.aktion.push(a); + self.beitrag.push(c); let o = 1 - p; let pot = c[0] + c[1]; let facing = c[o] - c[p]; @@ -116,9 +124,9 @@ impl Bauer { impl Einsatzbaum { pub fn s1() -> Einsatzbaum { - let mut b = Bauer { knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new() }; + let mut b = Bauer { knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new(), beitrag: 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 } + Einsatzbaum { baum: Baum { knoten: b.knoten, wurzel }, enden: b.enden, aktion: b.aktion, beitrag: b.beitrag } } } @@ -155,7 +163,7 @@ pub struct Deal { pub struct S1 { pub baum: Einsatzbaum, pub abstraktion: Abstraktion, - alle: Vec, + pub alle: Vec, /// Preflop weight per combo: [big blind call, button open]. pub gewicht: [Vec; 2], } @@ -187,6 +195,18 @@ impl S1 { } } +impl S1 { + /// Class of `hand` on `strasse` with the street's board `board` (3, 4 or 5 cards); on the river + /// `ehs` must be `river_ehs(board)`. + pub fn klasse_von(&self, hand: u64, board: u64, strasse: usize, ehs: &[f32]) -> usize { + match strasse { + 0 => self.abstraktion.flop.as_ref().map_or(0, |(s, t)| t[s.index(board, hand).unwrap() as usize] as usize), + 1 => self.abstraktion.turn.as_ref().map_or(0, |(s, t)| t[s.index(board, hand).unwrap() as usize] as usize), + _ => river_class(ehs[combo_index(hand)], &self.abstraktion.river) as usize, + } + } +} + impl Spiel for S1 { type Deal = Deal;