M4: LBR gegen die Live-Engine als fortsetzbarer Lauf (pokerbench-engine-lbr), Stichprobe gemessen und verworfen

lbr_hand/lbr_werte: jede Hand auf eigenem Strom (gepaart, threadunabhaengig, fortsetzbar).
Range-Stichprobe gegen exakt auf der echten Grundstrategie (4000 Haende gepaart):
k=24 -155, k=48 -112, k=96 -35, k=192 -14 +-46 bb/100 - zu stark verzerrt, um zu sparen.
Der Engine-Lauf rechnet exakt (~25 s/Hand), 20000 Haende in der Warteschlange.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 01:49:36 +01:00
co-authored by Claude Opus 5.5
parent dece40b62a
commit e00dc74932
4 changed files with 423 additions and 226 deletions
+5 -1
View File
@@ -19,4 +19,8 @@ zaehl|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\mes
#dbr-an|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-dbr.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\dbr-an 2000 4000 4 all|RIVER_DBR=1;POKERBENCH_THREADS=28|
#river-nash|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-rivernash.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-nash 2000 4000 4 all|RIVER_DBR=nash;POKERBENCH_THREADS=28|
#river-spiel|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-riverspiel.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-spiel 2000 4000 4 all|RIVER_DBR=spiel|
river-spiel-bal|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-riverspiel.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-spiel 2000 4000 4 gto,balanciert,reg|RIVER_DBR=spiel|
#river-spiel-bal|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-riverspiel.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-spiel 2000 4000 4 gto,balanciert,reg|RIVER_DBR=spiel|
abstraktion|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-abstraktion.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion 400000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88
grundstrategie-s1|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundstrategie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 400 1000000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88
river-grund|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-rivergrund.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-grund 2000 4000 4 all|RIVER_DBR=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;FRUEHSTOPP=arme\zaehl|
engine-lbr|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\lbr\engine-s1.txt 20000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88
+86
View File
@@ -0,0 +1,86 @@
//! LBR against the live engine on scenario S1 (plan M4, Messregel 1a): how much the best local counter
//! wins against the engine's default play, flop to river, button vs big blind in a single-raised pot.
//!
//! Exact range tracking (subsampling was measured biased: k=48 −112, k=96 −35 bb/100 against the exact
//! value on the real blueprint, `lbr::tests::bias_on_the_real_blueprint`). One hand costs ~27 s, so the
//! run is resumable: hand `i` is deterministic (`lbr::lbr_hand`), every result is appended to the out
//! file as `i value_bb` at once, and a restart computes only the missing hands.
//!
//! Run: `engine_lbr <out-file> <hands> [seed]`, threads from `POKERBENCH_THREADS` (default 1).
//! The engine runs with its default switches (no env arms).
use rechner::blueprint::abstraktion::river_cuts;
use rechner::blueprint::engine_gegner::EngineGegner;
use rechner::blueprint::lbr::lbr_hand;
use rechner::blueprint::s1::{Abstraktion, S1};
use std::io::Write;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
eprintln!("engine_lbr <out-file> <hands> [seed]");
std::process::exit(2);
}
let out = std::path::PathBuf::from(&args[1]);
let haende: u64 = args[2].parse().expect("hands");
let seed: u64 = args.get(3).map(|x| x.parse().expect("seed")).unwrap_or(7);
let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|x| x.parse().ok()).unwrap_or(1).max(1);
let mut fertig = vec![None; haende as usize];
if let Ok(t) = std::fs::read_to_string(&out) {
for z in t.lines() {
let mut f = z.split_whitespace();
if let (Some(i), Some(v)) = (f.next().and_then(|x| x.parse::<usize>().ok()), f.next().and_then(|x| x.parse::<f64>().ok())) {
if i < fertig.len() {
fertig[i] = Some(v);
}
}
}
}
let offen: Vec<u64> = (0..haende).filter(|i| fertig[*i as usize].is_none()).collect();
eprintln!("{} of {haende} hands done, {} to go, {threads} threads", haende as usize - offen.len(), offen.len());
// The engine never sees the blueprint's classes, so the tables are not needed (flop/turn unclassed).
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
let g = EngineGegner::default();
let next = AtomicUsize::new(0);
let datei = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&out).expect("out file"));
let werte = Mutex::new(fertig);
let t0 = std::time::Instant::now();
std::thread::scope(|sc| {
for _ in 0..threads {
sc.spawn(|| loop {
let j = next.fetch_add(1, Ordering::Relaxed);
let Some(&i) = offen.get(j) else { break };
let v = lbr_hand(&s, &g, i, seed, None);
writeln!(datei.lock().unwrap(), "{i} {v}").expect("write");
let mut w = werte.lock().unwrap();
w[i as usize] = Some(v);
let n = j + 1;
if n % 20 == 0 || n == offen.len() {
let (m, ci, k) = bericht(&w);
eprintln!("{n}/{} new, {k} total: LBR {m:+.1} ±{ci:.1} bb/100, {:.1} s/hand", offen.len(), t0.elapsed().as_secs_f64() * threads as f64 / n as f64);
}
});
}
});
let (m, ci, k) = bericht(&werte.lock().unwrap());
println!("LBR gegen Engine (S1, exakt): {m:+.1} ±{ci:.1} bb/100 ueber {k} Haende");
}
/// Mean over both seats and its 95 % half-width, in bb/100, over the hands done.
fn bericht(w: &[Option<f64>]) -> (f64, f64, usize) {
let mut t = [(0.0, 0.0, 0usize); 2];
for (i, v) in w.iter().enumerate() {
if let Some(v) = v {
t[i % 2].0 += v;
t[i % 2].1 += v * v;
t[i % 2].2 += 1;
}
}
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;
(50.0 * (mean(t[0]) + mean(t[1])), 98.0 * (var(t[0]) + var(t[1])).sqrt(), t[0].2 + t[1].2)
}
+196 -196
View File
@@ -1,196 +1,196 @@
//! The live engine as the opponent of LBR on scenario S1 (plan M4): the engine's exploitability
//! on flop, turn and river with the same yardstick as the blueprint's.
//!
//! At an S1 node the engine is asked (`engine::decide`) with a spot built from the tree: six seats as
//! in the simulator (button 1, small blind 2, big blind 3, the rest folded preflop), the preflop
//! line, the postflop line up to the node as `history`, the real pot including the folded small
//! blind. Its choice is mapped back onto the node's children (sizes pseudo-harmonically, as for real
//! hands in `ranges`). The engine is deterministic per spot seed, so the row is pure.
//!
//! Named approximations: the engine sees no read on LBR (profile `None`), so this is the engine's
//! default play; its own size menu is mapped onto the tree's (an off-tree size is rounded to a tree
//! size, which LBR then exploits as if the engine had used it).
use super::lbr::Gegner;
use super::mccfr::Knoten;
use super::ranges::harmonisch;
use super::s1::{Aktion, OPEN, S1, STACK};
use crate::card::Card;
use crate::engine::decide::decide;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::variant::Variant;
/// Seats of the S1 players in the built spot: player 0 = big blind, player 1 = button.
const SITZ: [u8; 2] = [3, 1];
const SB_TOT: f64 = 0.5;
pub struct EngineGegner {
deck: Vec<Card>,
}
impl Default for EngineGegner {
fn default() -> Self {
EngineGegner {
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(),
}
}
}
const STRASSEN: [Street; 3] = [Street::Flop, Street::Turn, Street::River];
impl EngineGegner {
fn karten(&self, m: u64) -> Vec<Card> {
self.deck.iter().copied().filter(|c| fast7::bit(*c) & m != 0).collect()
}
/// The spot of S1 node `k` for the acting player holding `hand`; also the contributions at the
/// start of the node's street.
pub fn spot(&self, s: &S1, k: usize, hand: u64, board: u64) -> Option<(Spot, f64)> {
let Knoten::Zug { spieler: p, strasse, kinder } = &s.baum.baum.knoten[k] else { return None };
let (p, strasse) = (*p, *strasse);
// Path root -> k.
let mut pfad = vec![k];
while let Some(&e) = pfad.last().map(|x| &s.baum.eltern[*x]) {
if e == usize::MAX {
break;
}
pfad.push(e);
}
pfad.reverse();
let rec = |street, seat, action, amount| ActionRecord { street, seat, action, amount };
let mut history = vec![
rec(Street::Preflop, 2, SeenAction::PostSmallBlind, Some(SB_TOT)),
rec(Street::Preflop, 3, SeenAction::PostBigBlind, Some(1.0)),
rec(Street::Preflop, 4, SeenAction::Fold, None),
rec(Street::Preflop, 5, SeenAction::Fold, None),
rec(Street::Preflop, 6, SeenAction::Fold, None),
rec(Street::Preflop, 1, SeenAction::Raise, Some(OPEN)),
rec(Street::Preflop, 2, SeenAction::Fold, None),
rec(Street::Preflop, 3, SeenAction::Call, Some(OPEN)),
];
let mut start = OPEN;
let mut start_strasse = 0;
for w in pfad.windows(2) {
let (q, child) = (w[0], w[1]);
let Knoten::Zug { spieler: a, strasse: st, .. } = &s.baum.baum.knoten[q] else { return None };
if *st != start_strasse {
start_strasse = *st;
start = s.baum.beitrag[q][0];
}
let street_total = s.baum.beitrag[child][*a] - start;
let (action, amount) = match s.baum.aktion[child]? {
Aktion::Check => (SeenAction::Check, None),
Aktion::Call => (SeenAction::Call, Some(street_total)),
Aktion::Bet(_) => (SeenAction::Bet, Some(street_total)),
Aktion::Raise(_) => (SeenAction::Raise, Some(street_total)),
Aktion::Fold => (SeenAction::Fold, None),
};
history.push(rec(STRASSEN[*st], SITZ[*a], action, amount));
}
if strasse != start_strasse {
start = s.baum.beitrag[k][0];
}
let c = s.baum.beitrag[k];
let o = 1 - p;
let to_call = c[o] - c[p];
let raises = kinder.iter().any(|x| matches!(s.baum.aktion[*x], Some(Aktion::Bet(_) | Aktion::Raise(_))));
let mut legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call] } else { vec![ActionKind::Check] };
if raises {
legal.push(ActionKind::Raise);
}
let (mine_street, theirs_street) = (c[p] - start, c[o] - start);
let min_raise_to = theirs_street + to_call.max(1.0);
let max_raise_to = mine_street + (STACK - c[p]);
let villains = (1..=6u8)
.filter(|x| *x != SITZ[p])
.map(|x| Villain { seat: x, stack: if x == SITZ[o] { STACK - c[o] } else { STACK }, folded: x != SITZ[o], profile: None })
.collect();
let spot = Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: SITZ[p],
button_seat: Some(1),
hero_cards: self.karten(hand),
board: self.karten(board),
street: STRASSEN[strasse],
pot: c[0] + c[1] + SB_TOT,
to_call,
hero_stack: STACK - c[p],
min_raise_to: raises.then_some(min_raise_to.min(max_raise_to)),
max_raise_to: raises.then_some(max_raise_to),
legal,
allowed_sizes: None,
villains,
seed: crate::rng::split_mix::Rng::seeded(hand ^ (k as u64) << 52).next_u64().0,
history,
};
Some((spot, start))
}
/// The child of node `k` the engine's choice maps to.
fn kind(&self, s: &S1, k: usize, choice: Choice, start: f64) -> Option<usize> {
let Knoten::Zug { spieler: p, kinder, .. } = &s.baum.baum.knoten[k] else { return None };
let finde = |a: Aktion| kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(a));
let c = s.baum.beitrag[k];
let passiv = finde(Aktion::Check).or_else(|| finde(Aktion::Call));
match choice {
Choice::Fold => finde(Aktion::Fold).or(passiv),
Choice::Check | Choice::Call | Choice::Abstain => passiv,
Choice::Raise { to } => {
let pot = c[0] + c[1];
let all_in = start + to >= STACK - 1e-6;
let kand: Vec<(f64, usize)> = kinder
.iter()
.filter_map(|x| match s.baum.aktion[*x] {
Some(Aktion::Bet(t) | Aktion::Raise(t)) => Some((t, *x)),
_ => None,
})
.collect();
if all_in {
if let Some((_, x)) = kand.iter().find(|(t, _)| *t >= STACK - 1e-9) {
return Some(*x);
}
}
let frac: Vec<(f64, usize)> = kand.iter().map(|(t, x)| ((t - c[*p]) / pot, *x)).collect();
// The real pot carries the dead small blind; the fraction is taken against it.
harmonisch((start + to - c[*p]) / (pot + SB_TOT), &frac).or(passiv)
}
}
}
}
impl Gegner for EngineGegner {
fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, _: usize) -> Vec<f64> {
let Knoten::Zug { kinder, .. } = &s.baum.baum.knoten[k] else { return Vec::new() };
let mut row = vec![0.0; kinder.len()];
let pick = self.spot(s, k, hand, board).and_then(|(spot, start)| self.kind(s, k, decide(&spot).choice, start));
let i = pick.and_then(|c| kinder.iter().position(|x| *x == c)).unwrap_or(0);
row[i] = 1.0;
row
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blueprint::abstraktion::river_cuts;
use crate::blueprint::lbr::lbr_gegen;
use crate::blueprint::s1::Abstraktion;
#[test]
fn the_engine_answers_on_s1_nodes_and_lbr_runs_against_it() {
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
let g = EngineGegner::default();
let m = |t: &str| fast7::mask(&Card::parse_list(t).unwrap());
// Root: big blind first on the flop.
let (spot, _) = g.spot(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c")).unwrap();
assert_eq!((spot.hero_seat, spot.pot, spot.to_call), (3, 5.5, 0.0));
let row = g.zeile(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c"), 0);
assert_eq!(row.iter().sum::<f64>(), 1.0);
let t = std::time::Instant::now();
let e = lbr_gegen(&s, &g, 20, 1, 5);
eprintln!("LBR vs engine (20 hands, no tables): {:+.0} bb/100, {:?} per hand", e.bb100, t.elapsed() / 20);
}
}
//! The live engine as the opponent of LBR on scenario S1 (plan M4): the engine's exploitability
//! on flop, turn and river with the same yardstick as the blueprint's.
//!
//! At an S1 node the engine is asked (`engine::decide`) with a spot built from the tree: six seats as
//! in the simulator (button 1, small blind 2, big blind 3, the rest folded preflop), the preflop
//! line, the postflop line up to the node as `history`, the real pot including the folded small
//! blind. Its choice is mapped back onto the node's children (sizes pseudo-harmonically, as for real
//! hands in `ranges`). The engine is deterministic per spot seed, so the row is pure.
//!
//! Named approximations: the engine sees no read on LBR (profile `None`), so this is the engine's
//! default play; its own size menu is mapped onto the tree's (an off-tree size is rounded to a tree
//! size, which LBR then exploits as if the engine had used it).
use super::lbr::Gegner;
use super::mccfr::Knoten;
use super::ranges::harmonisch;
use super::s1::{Aktion, OPEN, S1, STACK};
use crate::card::Card;
use crate::engine::decide::decide;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::variant::Variant;
/// Seats of the S1 players in the built spot: player 0 = big blind, player 1 = button.
const SITZ: [u8; 2] = [3, 1];
const SB_TOT: f64 = 0.5;
pub struct EngineGegner {
deck: Vec<Card>,
}
impl Default for EngineGegner {
fn default() -> Self {
EngineGegner {
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(),
}
}
}
const STRASSEN: [Street; 3] = [Street::Flop, Street::Turn, Street::River];
impl EngineGegner {
fn karten(&self, m: u64) -> Vec<Card> {
self.deck.iter().copied().filter(|c| fast7::bit(*c) & m != 0).collect()
}
/// The spot of S1 node `k` for the acting player holding `hand`; also the contributions at the
/// start of the node's street.
pub fn spot(&self, s: &S1, k: usize, hand: u64, board: u64) -> Option<(Spot, f64)> {
let Knoten::Zug { spieler: p, strasse, kinder } = &s.baum.baum.knoten[k] else { return None };
let (p, strasse) = (*p, *strasse);
// Path root -> k.
let mut pfad = vec![k];
while let Some(&e) = pfad.last().map(|x| &s.baum.eltern[*x]) {
if e == usize::MAX {
break;
}
pfad.push(e);
}
pfad.reverse();
let rec = |street, seat, action, amount| ActionRecord { street, seat, action, amount };
let mut history = vec![
rec(Street::Preflop, 2, SeenAction::PostSmallBlind, Some(SB_TOT)),
rec(Street::Preflop, 3, SeenAction::PostBigBlind, Some(1.0)),
rec(Street::Preflop, 4, SeenAction::Fold, None),
rec(Street::Preflop, 5, SeenAction::Fold, None),
rec(Street::Preflop, 6, SeenAction::Fold, None),
rec(Street::Preflop, 1, SeenAction::Raise, Some(OPEN)),
rec(Street::Preflop, 2, SeenAction::Fold, None),
rec(Street::Preflop, 3, SeenAction::Call, Some(OPEN)),
];
let mut start = OPEN;
let mut start_strasse = 0;
for w in pfad.windows(2) {
let (q, child) = (w[0], w[1]);
let Knoten::Zug { spieler: a, strasse: st, .. } = &s.baum.baum.knoten[q] else { return None };
if *st != start_strasse {
start_strasse = *st;
start = s.baum.beitrag[q][0];
}
let street_total = s.baum.beitrag[child][*a] - start;
let (action, amount) = match s.baum.aktion[child]? {
Aktion::Check => (SeenAction::Check, None),
Aktion::Call => (SeenAction::Call, Some(street_total)),
Aktion::Bet(_) => (SeenAction::Bet, Some(street_total)),
Aktion::Raise(_) => (SeenAction::Raise, Some(street_total)),
Aktion::Fold => (SeenAction::Fold, None),
};
history.push(rec(STRASSEN[*st], SITZ[*a], action, amount));
}
if strasse != start_strasse {
start = s.baum.beitrag[k][0];
}
let c = s.baum.beitrag[k];
let o = 1 - p;
let to_call = c[o] - c[p];
let raises = kinder.iter().any(|x| matches!(s.baum.aktion[*x], Some(Aktion::Bet(_) | Aktion::Raise(_))));
let mut legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call] } else { vec![ActionKind::Check] };
if raises {
legal.push(ActionKind::Raise);
}
let (mine_street, theirs_street) = (c[p] - start, c[o] - start);
let min_raise_to = theirs_street + to_call.max(1.0);
let max_raise_to = mine_street + (STACK - c[p]);
let villains = (1..=6u8)
.filter(|x| *x != SITZ[p])
.map(|x| Villain { seat: x, stack: if x == SITZ[o] { STACK - c[o] } else { STACK }, folded: x != SITZ[o], profile: None })
.collect();
let spot = Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: SITZ[p],
button_seat: Some(1),
hero_cards: self.karten(hand),
board: self.karten(board),
street: STRASSEN[strasse],
pot: c[0] + c[1] + SB_TOT,
to_call,
hero_stack: STACK - c[p],
min_raise_to: raises.then_some(min_raise_to.min(max_raise_to)),
max_raise_to: raises.then_some(max_raise_to),
legal,
allowed_sizes: None,
villains,
seed: crate::rng::split_mix::Rng::seeded(hand ^ (k as u64) << 52).next_u64().0,
history,
};
Some((spot, start))
}
/// The child of node `k` the engine's choice maps to.
fn kind(&self, s: &S1, k: usize, choice: Choice, start: f64) -> Option<usize> {
let Knoten::Zug { spieler: p, kinder, .. } = &s.baum.baum.knoten[k] else { return None };
let finde = |a: Aktion| kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(a));
let c = s.baum.beitrag[k];
let passiv = finde(Aktion::Check).or_else(|| finde(Aktion::Call));
match choice {
Choice::Fold => finde(Aktion::Fold).or(passiv),
Choice::Check | Choice::Call | Choice::Abstain => passiv,
Choice::Raise { to } => {
let pot = c[0] + c[1];
let all_in = start + to >= STACK - 1e-6;
let kand: Vec<(f64, usize)> = kinder
.iter()
.filter_map(|x| match s.baum.aktion[*x] {
Some(Aktion::Bet(t) | Aktion::Raise(t)) => Some((t, *x)),
_ => None,
})
.collect();
if all_in {
if let Some((_, x)) = kand.iter().find(|(t, _)| *t >= STACK - 1e-9) {
return Some(*x);
}
}
let frac: Vec<(f64, usize)> = kand.iter().map(|(t, x)| ((t - c[*p]) / pot, *x)).collect();
// The real pot carries the dead small blind; the fraction is taken against it.
harmonisch((start + to - c[*p]) / (pot + SB_TOT), &frac).or(passiv)
}
}
}
}
impl Gegner for EngineGegner {
fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, _: usize) -> Vec<f64> {
let Knoten::Zug { kinder, .. } = &s.baum.baum.knoten[k] else { return Vec::new() };
let mut row = vec![0.0; kinder.len()];
let pick = self.spot(s, k, hand, board).and_then(|(spot, start)| self.kind(s, k, decide(&spot).choice, start));
let i = pick.and_then(|c| kinder.iter().position(|x| *x == c)).unwrap_or(0);
row[i] = 1.0;
row
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blueprint::abstraktion::river_cuts;
use crate::blueprint::lbr::lbr_gegen;
use crate::blueprint::s1::Abstraktion;
#[test]
fn the_engine_answers_on_s1_nodes_and_lbr_runs_against_it() {
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
let g = EngineGegner::default();
let m = |t: &str| fast7::mask(&Card::parse_list(t).unwrap());
// Root: big blind first on the flop.
let (spot, _) = g.spot(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c")).unwrap();
assert_eq!((spot.hero_seat, spot.pot, spot.to_call), (3, 5.5, 0.0));
let row = g.zeile(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c"), 0);
assert_eq!(row.iter().sum::<f64>(), 1.0);
let t = std::time::Instant::now();
let e = lbr_gegen(&s, &g, 2, 1, 5);
eprintln!("LBR vs engine (2 hands, exact): {:+.0} bb/100, {:?} per hand", e.bb100, t.elapsed() / 2);
}
}
+136 -29
View File
@@ -97,7 +97,15 @@ impl Gegner for Blaupause<'_> {
/// One hand with LBR in seat `l`; returns LBR's result in bb. Rows are cached per hand (the
/// engine opponent is expensive to ask).
fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall) -> f64 {
///
/// `stichprobe = Some(k)`: the opponent's range is not tracked over every combo but over a uniform
/// random subset of its support (a fresh permutation per hand), extended at each LBR decision until
/// `k` combos carry posterior weight (prior times the opponent's probability of every action taken).
/// Fold probability and equity are then self-normalised estimates over that subset - consistent, with
/// an error of order `1/sqrt(k)`. `None` tracks every combo (exact). The subset is drawn from its own
/// stream (`mischen`), so exact and subsampled LBR play the same deal (paired comparison). Noise can
/// only make LBR choose worse, so the subsampled value is still a lower bound on exploitability.
fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall, mischen: &mut Zufall, stichprobe: Option<usize>) -> f64 {
let mut cache: std::collections::HashMap<(usize, usize), Vec<f64>> = std::collections::HashMap::new();
let mut zeile = |k: usize, i: usize, board: u64, klasse: usize| -> Vec<f64> {
cache.entry((k, i)).or_insert_with(|| g.zeile(s, k, s.alle[i], board, klasse)).clone()
@@ -105,9 +113,24 @@ fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall) -> f64 {
let o = 1 - l;
let d = s.ziehen(rng);
let baum = &s.baum;
let mut w: Vec<f64> = s.alle.iter().zip(&s.gewicht[o]).map(|(c, g)| if c & d.hand[l] == 0 { *g } else { 0.0 }).collect();
let w0: Vec<f64> = 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);
// Subsampling: the support in random order; `m` of it is active, the rest weighs 0 until drawn.
let mut reihe: Vec<usize> = Vec::new();
let mut m = 0;
let mut w = match stichprobe {
None => w0.clone(),
Some(_) => {
reihe = (0..w0.len()).filter(|i| w0[*i] > 0.0).collect();
for j in (1..reihe.len()).rev() {
reihe.swap(j, mischen.below(j + 1));
}
vec![0.0; w0.len()]
}
};
// The opponent's actions so far: (node, action, street).
let mut verlauf: Vec<(usize, usize, usize)> = Vec::new();
let mut strasse_da = usize::MAX;
let mut klassen: Vec<usize> = Vec::new();
let mut eq: Vec<f32> = Vec::new();
@@ -125,7 +148,8 @@ fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall) -> f64 {
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();
let lebt = |i: usize| if stichprobe.is_some() { w0[i] > 0.0 && s.alle[i] & board == 0 } else { w[i] > 0.0 };
klassen = (0..s.alle.len()).map(|i| if lebt(i) { s.klasse_von(s.alle[i], board, strasse, &ehs_river) } else { 0 }).collect();
eq = equities(s, d.hand[l], board, rng);
}
let n = kinder.len();
@@ -142,9 +166,34 @@ fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall) -> f64 {
w[i] *= zeile(k, i, board, klassen[i])[a];
}
}
verlauf.push((k, a, strasse));
k = kinder[a];
continue;
}
if let Some(ziel) = stichprobe {
// Top up the subset until `ziel` combos are consistent with the line (or the support is spent).
let mut lebend = w.iter().filter(|x| **x > 0.0).count();
while lebend < ziel && m < reihe.len() {
let i = reihe[m];
m += 1;
let c = s.alle[i];
if c & board != 0 {
continue;
}
let mut x = w0[i];
for &(kv, av, sv) in &verlauf {
if x <= 0.0 {
break;
}
let kl = s.klasse_von(c, boards[sv], sv, &ehs_river);
x *= zeile(kv, i, boards[sv], kl)[av];
}
w[i] = x;
if x > 0.0 {
lebend += 1;
}
}
}
let c = baum.beitrag[k];
let (pot, mine) = (c[0] + c[1], c[l]);
let wp = gegen(&eq, &w);
@@ -190,33 +239,17 @@ pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) ->
/// LBR against any opponent over `haende` hands (alternating seats) on `threads` threads.
pub fn lbr_gegen<G: Gegner>(s: &S1, g: &G, 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, g, 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()
});
lbr_stichprobe(s, g, haende, threads, seed, None)
}
/// `lbr_gegen` with the opponent range subsampled to `stichprobe` live combos per decision (see `hand`).
pub fn lbr_stichprobe<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Ergebnis {
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;
}
for (i, v) in lbr_werte(s, g, haende, threads, seed, stichprobe).into_iter().enumerate() {
let l = i % 2;
t[l].0 += v;
t[l].1 += v * v;
t[l].2 += 1;
}
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;
@@ -225,6 +258,37 @@ pub fn lbr_gegen<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed:
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])] }
}
/// The stream of hand `i`: hashed twice from the seed, so neighbouring hands do not share a stream.
fn strom(seed: u64, i: u64, art: u64) -> Zufall {
let a = Rng::seeded(seed ^ art.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0;
Zufall(Rng::seeded(Rng::seeded(a ^ i.wrapping_mul(0x9E37_79B9_7F4A_7C15)).next_u64().0))
}
/// LBR's result in bb for hand `i` alone (seat `i % 2`): the same value `lbr_werte` gives for it, so a
/// long run can be split into pieces and resumed.
pub fn lbr_hand<G: Gegner>(s: &S1, g: &G, i: u64, seed: u64, stichprobe: Option<usize>) -> f64 {
hand(s, g, (i % 2) as usize, &mut strom(seed, i, 0), &mut strom(seed, i, 1), stichprobe)
}
/// LBR's result in bb for every hand `i` (seat `i % 2`), each hand on its own stream: the values do not
/// depend on the thread count, and two calls with the same seed play the same deals (paired).
pub fn lbr_werte<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Vec<f64> {
let threads = threads.max(1);
let mut werte = vec![0.0; haende];
std::thread::scope(|sc| {
for (th, teil) in werte.chunks_mut(haende.div_ceil(threads).max(1)).enumerate() {
let start = th * haende.div_ceil(threads).max(1);
sc.spawn(move || {
for (j, v) in teil.iter_mut().enumerate() {
let i = (start + j) as u64;
*v = lbr_hand(s, g, i, seed, stichprobe);
}
});
}
});
werte
}
#[cfg(test)]
mod tests {
use super::*;
@@ -247,4 +311,47 @@ mod tests {
// so the trained strategy stays very exploitable; it must still be clearly less so.
assert!(trainiert.bb100 < roh.bb100, "{} vs {}", trainiert.bb100, roh.bb100);
}
/// Mean and 95 % half-width of `b - a` per hand, in bb/100.
fn gepaart(a: &[f64], b: &[f64]) -> (f64, f64) {
let d: Vec<f64> = a.iter().zip(b).map(|(x, y)| y - x).collect();
let n = d.len() as f64;
let m = d.iter().sum::<f64>() / n;
let v = d.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0);
(100.0 * m, 196.0 * (v / n).sqrt())
}
/// The real blueprint (`$GRUNDSTRATEGIE`): how far subsampled LBR falls below the exact one, paired.
/// `cargo test --release lbr::tests::bias_on_the_real_blueprint -- --ignored --nocapture`
#[test]
#[ignore]
fn bias_on_the_real_blueprint() {
let (s, tab) = crate::blueprint::ranges::grundstrategie().expect("GRUNDSTRATEGIE");
let g = Blaupause(tab);
let n: usize = std::env::var("LBR_HAENDE").ok().and_then(|x| x.parse().ok()).unwrap_or(2000);
let voll = lbr_werte(s, &g, n, 1, 31, None);
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len() as f64;
eprintln!("exact {:+.1} bb/100 over {n} hands", mean(&voll));
for k in [24, 48, 96, 192] {
let teil = lbr_werte(s, &g, n, 1, 31, Some(k));
let (m, ci) = gepaart(&voll, &teil);
eprintln!("k={k}: {:+.1} bb/100, minus exact {m:+.1} ±{ci:.1}", mean(&teil));
}
}
/// The subsampled range estimate lands where the exact one does (against a cheap opponent where
/// both can run): same hands, same seed stream for the deals is not guaranteed, so compare within
/// the joint interval.
#[test]
fn subsampled_lbr_agrees_with_the_exact_one() {
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
let mut tab = Tabellen::neu(&s);
rechnen(&s, &mut tab, 20, 20_000, 2, 3);
let g = Blaupause(&tab);
let voll = lbr_werte(&s, &g, 4000, 2, 21, None);
let teil = lbr_werte(&s, &g, 4000, 2, 21, Some(48));
let (m, ci) = gepaart(&voll, &teil);
eprintln!("paired k=48 minus exact: {m:+.1} ±{ci:.1} bb/100");
assert!(m.abs() < ci + 50.0, "{m} ±{ci}");
}
}