Multiway-River: 3-/4-handed Monte-Carlo-CFR (cfr::river3, engine::river3_spieler), Schalter SOLVER_RIVER3 (aus, bit-identisch)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 22:34:46 +01:00
co-authored by Claude Opus 5.5
parent 664415ba5f
commit 41a609d74e
13 changed files with 855 additions and 3 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, ".."))
# Hand in haende.jsonl, mit welchem Engine-Stand sie gespielt wurde (runner.py liest den Arm nach
# diesem Import).
SCHALTER_DATEI = os.path.join(BASE, "..", "betrieb", "kern_schalter.txt")
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP")
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3")
# Pfade gehoeren nicht in die Arm-Marke.
OHNE_MARKE = ("GRUNDSTRATEGIE",)
+2 -2
View File
@@ -59,7 +59,7 @@ KLASSEN_NAME = {
"heuristik": "Heuristik", "enthaltung": "Enthaltung",
}
# Gleiche Liste wie entscheiden/decide.py: nur Messschalter, keine beliebige Umgebung.
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP")
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3")
OHNE_MARKE = ("GRUNDSTRATEGIE",)
IDLE_PRIORITY_CLASS = 0x00000040
KERN_KOPIE = "pokerbench-roentgen-nachspiel" + (".exe" if sys.platform == "win32" else "")
@@ -195,7 +195,7 @@ def klasse(street, grund):
return "turn_veto"
if "defensive veto" in g:
return "river_veto"
if "river solver" in g or "solver turn" in g or "solver flop" in g:
if "river solver" in g or "river3 solver" in g or "solver turn" in g or "solver flop" in g:
return "solver"
if "turn game" in g:
return "e3"
+1
View File
@@ -73,6 +73,7 @@ fn apply_arm() {
rechner::engine::river_spieler::set_river_spieler(rechner::engine::river_spieler::from_env());
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env());
use rechner::engine::turn_game::{set_turn_player, TurnPlayer};
let turn_grund = std::env::var("TURN_SPIEL").as_deref() == Ok("grund");
set_turn_player(if turn_grund { TurnPlayer::Grund } else { TurnPlayer::Off });
+1
View File
@@ -38,6 +38,7 @@ fn main() {
rechner::engine::river_spieler::set_river_spieler(rechner::engine::river_spieler::from_env());
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env());
if rechner::engine::river_spieler::river_spieler() == rechner::engine::river_spieler::RiverSpieler::An {
assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "SOLVER_RIVER=1 on LBR needs GRUNDSTRATEGIE (else it measures the model path)");
}
+1
View File
@@ -88,6 +88,7 @@ pub mod multi_walk;
pub mod open3_game;
pub mod open_game;
pub mod payoffs;
pub mod river3;
pub mod permille;
pub mod plo5_bucket;
pub mod push_fold3_game;
+398
View File
@@ -0,0 +1,398 @@
//! The 3-handed RIVER: Monte-Carlo CFR over real combos for three players (also runs with two, for the
//! tests), as Pluribus solves its multiway subgames. No equilibrium guarantee with three players (CFR
//! need not converge to a Nash equilibrium outside two-player zero-sum games); in practice the average
//! strategy is strong and is what the engine plays.
//!
//! - **Game:** one river betting round between the players in acting order. Not facing a bet: check,
//! `fracs` × pot, all-in. Facing one: fold, call, a raise to `raise_mult` × the bet, all-in, at most
//! `max_raises` raises. All amounts are this street's totals in chips (as `cfr::river_game::Act`).
//! **Stacks are capped at the smallest live stack** (named approximation: no side pots).
//! - **Solver:** external sampling with a vector traverser. Each iteration, for each player as the
//! traverser: the other players' hands are sampled jointly from their weighted lists (card-disjoint),
//! the traverser carries ALL its hands as a vector (a hand that collides with a sampled hand counts
//! zero this iteration), at the traverser's nodes every action is walked, at the others' nodes one
//! action is sampled from their current strategy. Showdown per traverser hand against the best active
//! opponent score: exact, O(hands). Regrets are linearly weighted (iteration `t`), current strategy =
//! regret matching.
//! - **Average strategy** is accumulated for every hand of every player at its own nodes, weighted by
//! `t` × the player's own reach (the standard CFR average), which is what `strategy` returns.
use crate::cfr::river_game::Act;
/// The betting menu of the 3-handed river.
#[derive(Clone, Debug, PartialEq)]
pub struct Menu3 {
pub fracs: Vec<f64>,
pub raise_mult: f64,
pub max_raises: u8,
pub allin: bool,
}
impl Menu3 {
pub fn standard() -> Menu3 {
Menu3 { fracs: vec![0.33, 0.75], raise_mult: 3.0, max_raises: 1, allin: true }
}
}
#[derive(Clone, Debug)]
pub enum Node3 {
/// `player` acts; `acts[k]` leads to `kids[k]`.
Dec { player: usize, acts: Vec<Act>, kids: Vec<usize> },
/// The hand ends: `c` = this street's contributions, `active` = bit mask of players still in.
Term { c: Vec<f64>, active: u32 },
}
/// The game tree of one river betting round.
#[derive(Clone, Debug)]
pub struct Game3 {
pub nodes: Vec<Node3>,
pub players: usize,
/// Pot before this street's bets.
pub pot: f64,
/// The common stack cap (this street's total a player can reach).
pub cap: f64,
}
#[derive(Clone)]
struct State {
c: Vec<f64>,
active: u32,
pending: u32,
raises: u8,
to_act: usize,
}
impl Game3 {
/// The tree for `players` players (index = acting order), pot `pot` before the street, every
/// player able to put in at most `cap` on this street.
pub fn build(players: usize, pot: f64, cap: f64, menu: &Menu3) -> Game3 {
let mut g = Game3 { nodes: Vec::new(), players, pot, cap };
let all = (1u32 << players) - 1;
let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0 };
g.grow(s, menu);
g
}
fn next(&self, s: &State, from: usize) -> Option<usize> {
(1..=self.players).map(|k| (from + k) % self.players).find(|p| s.pending & (1 << p) != 0)
}
fn grow(&mut self, s: State, menu: &Menu3) -> usize {
if s.active.count_ones() == 1 || s.pending == 0 {
self.nodes.push(Node3::Term { c: s.c.clone(), active: s.active });
return self.nodes.len() - 1;
}
let p = s.to_act;
let top = s.c.iter().copied().fold(0.0, f64::max);
let eps = 1e-9 * self.cap.max(1.0);
let mut acts: Vec<Act> = Vec::new();
if top > s.c[p] + eps {
acts.push(Act::Fold);
acts.push(Act::Call);
if s.raises < menu.max_raises && top < self.cap - eps {
let r = (top * menu.raise_mult).min(self.cap);
if r > top + eps && r < self.cap - eps {
acts.push(Act::Raise(r));
}
if menu.allin {
acts.push(Act::Raise(self.cap));
}
}
} else {
acts.push(Act::Check);
if self.cap > top + eps {
let pot_now = self.pot + s.c.iter().sum::<f64>();
let mut sizes: Vec<f64> = menu.fracs.iter().map(|f| f * pot_now).filter(|b| *b > eps && *b < self.cap - eps).collect();
if menu.allin {
sizes.push(self.cap);
}
sizes.sort_by(f64::total_cmp);
sizes.dedup_by(|a, b| (*a - *b).abs() < eps);
acts.extend(sizes.into_iter().map(Act::Bet));
}
}
let id = self.nodes.len();
self.nodes.push(Node3::Dec { player: p, acts: acts.clone(), kids: Vec::new() });
let mut kids = Vec::with_capacity(acts.len());
for a in &acts {
let mut t = s.clone();
t.pending &= !(1 << p);
match a {
Act::Fold => t.active &= !(1 << p),
Act::Call | Act::Check => t.c[p] = top.max(t.c[p]),
Act::Bet(x) | Act::Raise(x) => {
t.c[p] = *x;
t.raises += u8::from(matches!(a, Act::Raise(_)));
// Everyone still in and not all-in acts again.
t.pending = (0..self.players).filter(|q| *q != p && t.active & (1 << q) != 0 && t.c[*q] < self.cap - eps).fold(0, |m, q| m | (1 << q));
}
}
// An all-in caller has nothing left to decide.
if t.c[p] >= self.cap - eps {
t.pending &= !(1 << p);
}
if let Some(n) = self.next(&t, p) {
t.to_act = n;
}
kids.push(self.grow(t, menu));
}
if let Node3::Dec { kids: k, .. } = &mut self.nodes[id] {
*k = kids;
}
id
}
/// Follow an observed line from the root: each `(player, act)` must be that node's actor, the act
/// maps to the tree act of its kind (the nearest size for bets and raises). `None` if the line
/// leaves the tree.
pub fn follow(&self, line: &[(usize, Act)]) -> Option<usize> {
let mut at = 0;
for (who, a) in line {
let Node3::Dec { player, acts, kids } = &self.nodes[at] else { return None };
if player != who {
return None;
}
let k = match a {
Act::Bet(x) | Act::Raise(x) => acts
.iter()
.enumerate()
.filter_map(|(k, t)| match t {
Act::Bet(y) | Act::Raise(y) => Some((k, (y - x).abs())),
_ => None,
})
.min_by(|p, q| p.1.total_cmp(&q.1))?
.0,
_ => acts.iter().position(|t| t == a)?,
};
at = kids[k];
}
Some(at)
}
}
/// One player's hands: card masks, weights (> 0), and showdown scores with the board.
#[derive(Clone, Debug)]
pub struct Hands3 {
pub masks: Vec<u64>,
pub weights: Vec<f64>,
}
struct Xs(u64);
impl Xs {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn unit(&mut self) -> f64 {
(self.next() >> 11) as f64 / (1u64 << 53) as f64
}
}
pub struct Solver3 {
pub game: Game3,
hands: Vec<Hands3>,
score: Vec<Vec<u32>>,
cum: Vec<Vec<f64>>,
regret: Vec<Vec<f64>>,
avg: Vec<Vec<f64>>,
rng: Xs,
t: u64,
}
impl Solver3 {
/// `hands[p]` per player in acting order; `board` = the five board cards.
pub fn new(game: Game3, hands: Vec<Hands3>, board: u64, seed: u64) -> Solver3 {
assert_eq!(hands.len(), game.players);
let score = hands.iter().map(|h| h.masks.iter().map(|m| crate::hand::fast7::score(m | board)).collect()).collect();
let cum = hands
.iter()
.map(|h| {
let mut acc = 0.0;
h.weights.iter().map(|w| { acc += w.max(0.0); acc }).collect()
})
.collect();
let sized = |f: &dyn Fn(usize, usize) -> usize| -> Vec<Vec<f64>> {
game.nodes.iter().map(|n| match n {
Node3::Dec { player, acts, .. } => vec![0.0; f(*player, acts.len())],
Node3::Term { .. } => Vec::new(),
}).collect()
};
let regret = sized(&|p, a| hands[p].masks.len() * a);
let avg = sized(&|p, a| hands[p].masks.len() * a);
Solver3 { game, hands, score, cum, regret, avg, rng: Xs(seed | 1), t: 0 }
}
pub fn masks(&self, p: usize) -> &[u64] {
&self.hands[p].masks
}
fn sample(&mut self, p: usize) -> usize {
let c = &self.cum[p];
let x = self.rng.unit() * c.last().copied().unwrap_or(0.0);
c.partition_point(|v| *v <= x).min(c.len() - 1)
}
/// One iteration: every player once as the traverser.
pub fn iterate(&mut self) {
self.t += 1;
for i in 0..self.game.players {
// Sample the other players' hands jointly, card-disjoint (rejection on the whole tuple).
let mut picked = vec![usize::MAX; self.game.players];
let mut ok = false;
for _ in 0..64 {
let mut used = 0u64;
ok = true;
for p in (0..self.game.players).filter(|p| *p != i) {
let h = self.sample(p);
let m = self.hands[p].masks[h];
if m & used != 0 {
ok = false;
break;
}
used |= m;
picked[p] = h;
}
if ok {
break;
}
}
if !ok {
continue;
}
let used = (0..self.game.players).filter(|p| *p != i).fold(0u64, |m, p| m | self.hands[p].masks[picked[p]]);
let n = self.hands[i].masks.len();
let live: Vec<f64> = (0..n).map(|h| if self.hands[i].masks[h] & used == 0 { 1.0 } else { 0.0 }).collect();
let reach = live.clone();
self.walk(0, i, &picked, &live, &reach);
}
}
pub fn run(&mut self, iterations: u32) {
for _ in 0..iterations {
self.iterate();
}
}
fn current(regret: &[f64], a: usize, out: &mut [f64]) {
let pos: f64 = regret.iter().map(|r| r.max(0.0)).sum();
if pos > 0.0 {
for k in 0..a {
out[k] = regret[k].max(0.0) / pos;
}
} else {
out.iter_mut().for_each(|x| *x = 1.0 / a as f64);
}
}
/// Values for the traverser `i`'s hands (`live` = 1 where the hand is possible this iteration),
/// `reach` = the traverser's own reach per hand.
fn walk(&mut self, node: usize, i: usize, picked: &[usize], live: &[f64], reach: &[f64]) -> Vec<f64> {
let n = live.len();
match &self.game.nodes[node] {
Node3::Term { c, active } => {
let pot = self.game.pot + c.iter().sum::<f64>();
let mine = c[i];
if active & (1 << i) == 0 {
return live.iter().map(|l| -mine * l).collect();
}
if active.count_ones() == 1 {
return live.iter().map(|l| (pot - mine) * l).collect();
}
// Best active opponent score and how many share it.
let mut best = 0u32;
let mut ties = 0usize;
for p in (0..self.game.players).filter(|p| *p != i && active & (1 << p) != 0) {
let s = self.score[p][picked[p]];
if s > best {
best = s;
ties = 1;
} else if s == best {
ties += 1;
}
}
(0..n)
.map(|h| {
if live[h] == 0.0 {
return 0.0;
}
let s = self.score[i][h];
let share = if s > best {
pot
} else if s == best {
pot / (ties + 1) as f64
} else {
0.0
};
share - mine
})
.collect()
}
Node3::Dec { player, acts, kids } => {
let (p, a, kids) = (*player, acts.len(), kids.clone());
if p == i {
let mut sigma = vec![0.0; n * a];
for h in 0..n {
Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma[h * a..(h + 1) * a]);
}
let mut vals: Vec<Vec<f64>> = Vec::with_capacity(a);
for k in 0..a {
let r: Vec<f64> = (0..n).map(|h| reach[h] * sigma[h * a + k]).collect();
vals.push(self.walk(kids[k], i, picked, live, &r));
}
let t = self.t as f64;
let mut out = vec![0.0; n];
for h in 0..n {
if live[h] == 0.0 {
continue;
}
let v: f64 = (0..a).map(|k| sigma[h * a + k] * vals[k][h]).sum();
out[h] = v;
for k in 0..a {
self.regret[node][h * a + k] += t * (vals[k][h] - v);
self.avg[node][h * a + k] += t * reach[h] * sigma[h * a + k];
}
}
out
} else {
let h = picked[p];
let mut sigma = vec![0.0; a];
Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma);
let x = self.rng.unit();
let mut acc = 0.0;
let mut k = a - 1;
for (j, s) in sigma.iter().enumerate() {
acc += s;
if x < acc {
k = j;
break;
}
}
self.walk(kids[k], i, picked, live, reach)
}
}
}
}
/// The average strategy of player `p`'s hand `h` at `node` (uniform where never reached).
pub fn row(&self, node: usize, h: usize) -> Vec<f64> {
let Node3::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() };
let a = acts.len();
let s = &self.avg[node][h * a..(h + 1) * a];
let tot: f64 = s.iter().sum();
if tot > 0.0 {
s.iter().map(|x| x / tot).collect()
} else {
vec![1.0 / a as f64; a]
}
}
pub fn iterations(&self) -> u64 {
self.t
}
}
#[cfg(test)]
mod tests;
+111
View File
@@ -0,0 +1,111 @@
use super::*;
use crate::card::Card;
use crate::hand::fast7;
fn board() -> u64 {
fast7::mask(&Card::parse_list("Ah 7d 2c Ks 3h").unwrap())
}
/// Every two-card combo off the board, weight 1.
fn all_hands(board: u64) -> Hands3 {
let deck: Vec<u64> = crate::card::deck::full().into_iter().map(fast7::bit).filter(|b| b & board == 0).collect();
let mut masks = Vec::new();
for a in 0..deck.len() {
for b in (a + 1)..deck.len() {
masks.push(deck[a] | deck[b]);
}
}
let weights = vec![1.0; masks.len()];
Hands3 { masks, weights }
}
fn idx(h: &Hands3, cards: &str) -> usize {
let m = fast7::mask(&Card::parse_list(cards).unwrap());
h.masks.iter().position(|x| *x == m).unwrap()
}
fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 {
row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum()
}
#[test]
fn the_tree_closes_every_line_and_follows_observed_lines() {
let g = Game3::build(3, 10.0, 100.0, &Menu3::standard());
let terms = g.nodes.iter().filter(|n| matches!(n, Node3::Term { .. })).count();
assert!(terms > 10 && g.nodes.len() < 2000, "{} nodes, {terms} terminals", g.nodes.len());
// Check, check, check is a showdown with all three in.
let at = g.follow(&[(0, Act::Check), (1, Act::Check), (2, Act::Check)]).unwrap();
assert!(matches!(&g.nodes[at], Node3::Term { active: 7, .. }));
// Check, bet, then the third player faces the bet.
let at = g.follow(&[(0, Act::Check), (1, Act::Bet(7.0))]).unwrap();
match &g.nodes[at] {
Node3::Dec { player, acts, .. } => {
assert_eq!(*player, 2);
assert!(acts.contains(&Act::Fold) && acts.contains(&Act::Call));
}
n => panic!("{n:?}"),
}
// Bet, fold, fold ends the hand.
let at = g.follow(&[(0, Act::Bet(7.5)), (1, Act::Fold), (2, Act::Fold)]).unwrap();
assert!(matches!(&g.nodes[at], Node3::Term { active: 1, .. }));
// A line out of order leaves the tree.
assert!(g.follow(&[(1, Act::Check)]).is_none());
}
/// Three-handed, facing a bet and a call: the nuts never fold, air folds.
#[test]
fn three_handed_the_nuts_continue_and_air_folds() {
let b = board();
let h = all_hands(b);
let g = Game3::build(3, 10.0, 100.0, &Menu3::standard());
let at = g.follow(&[(0, Act::Bet(7.5)), (1, Act::Call)]).unwrap();
let mut s = Solver3::new(g, vec![h.clone(), h.clone(), h.clone()], b, 7);
s.run(20_000);
let Node3::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() };
let nuts = s.row(at, idx(&h, "As Ad"));
assert!(prob(&nuts, &acts, |a| *a == Act::Fold) < 0.05, "{nuts:?} {acts:?}");
let air = s.row(at, idx(&h, "6s 5d"));
assert!(prob(&air, &acts, |a| *a == Act::Fold) > 0.8, "{air:?} {acts:?}");
}
/// Heads-up through the same solver: top set bets for value when checked to.
#[test]
fn heads_up_top_set_bets() {
let b = board();
let h = all_hands(b);
let g = Game3::build(2, 10.0, 100.0, &Menu3::standard());
let at = g.follow(&[(0, Act::Check)]).unwrap();
let mut s = Solver3::new(g, vec![h.clone(), h.clone()], b, 3);
s.run(20_000);
let Node3::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() };
let row = s.row(at, idx(&h, "As Ad"));
assert!(prob(&row, &acts, |a| matches!(a, Act::Bet(_))) > 0.8, "{row:?} {acts:?}");
}
/// Same seed, same result.
#[test]
fn deterministic() {
let b = board();
let h = all_hands(b);
let run = || {
let g = Game3::build(3, 10.0, 100.0, &Menu3::standard());
let mut s = Solver3::new(g, vec![h.clone(), h.clone(), h.clone()], b, 11);
s.run(500);
s.row(0, 5)
};
assert_eq!(run(), run());
}
#[test]
#[ignore]
fn timing() {
let b = board();
let h = all_hands(b);
let pruned = Hands3 { masks: h.masks[..200].to_vec(), weights: vec![1.0; 200] };
let g = Game3::build(3, 10.0, 100.0, &Menu3::standard());
let nodes = g.nodes.len();
let mut s = Solver3::new(g, vec![pruned.clone(), pruned.clone(), pruned], b, 1);
let t = std::time::Instant::now();
s.run(10_000);
eprintln!("{nodes} nodes, 200 hands each, 10000 iterations: {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
}
+5
View File
@@ -102,6 +102,11 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D
if let Some(d) = super::river_spieler::river_spieler_decision(raw) {
return d.with_equity(equity.share);
}
// Multiway river (off by default, SOLVER_RIVER3): 3- and 4-handed rivers decided by
// Monte-Carlo CFR over real combos (`engine::river3_spieler`).
if let Some(d) = super::river3_spieler::river3_decision(raw) {
return d.with_equity(equity.share);
}
// Arm (off by default, TURN_SPIEL=grund): the turn+river game with ranges from the
// blueprint (`engine::turn_game`); `None` while the switch is off. Stage B supersedes it
// when on (same game, blueprint ranges where recognised, hero's hand always kept, inside
+1
View File
@@ -19,6 +19,7 @@ pub mod read_gate;
pub mod range_combos;
pub mod range_filter;
pub mod read_label;
pub mod river3_spieler;
pub mod river_spieler;
pub mod river_subgame;
pub mod run_twice;
+230
View File
@@ -0,0 +1,230 @@
//! "Solver everywhere", the MULTIWAY river: 3- and 4-handed river spots decided by Monte-Carlo CFR over
//! real combos (`cfr::river3`), as Pluribus solves multiway subgames. Switch `SOLVER_RIVER3` (default
//! off: no decision, the engine is bit-identical).
//!
//! - **Players** in post-flop acting order (small blind first, from the blinds in the history), hero
//! among them; ranges per player from the range model of the action history (`range_spec`: hero's
//! own line without a read, each villain's with its gated read), weight 1 per combo, hero's real hand
//! added at a token weight if the model range does not hold it.
//! - **The observed river line** is replayed into the tree (nearest size); a river line the tree
//! cannot hold (a folded player's bet, an inconsistent price) leaves the spot to the heuristic.
//! - **Named approximations:** no equilibrium guarantee with three players; stacks capped at the
//! smallest live stack (no side pots); two bet sizes, one raise; Monte-Carlo noise (the average
//! strategy of hero's hand after `ITERS` or the time budget).
//! - **Time:** `frist::RIVER_MS` per decision; under `MIN_ITERS` iterations the heuristic decides.
use crate::card::Card;
use crate::cfr::river3::{Game3, Hands3, Menu3, Node3, Solver3};
use crate::cfr::river_game::Act;
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::sync::atomic::{AtomicBool, Ordering};
static ON: AtomicBool = AtomicBool::new(false);
pub fn set_river3(on: bool) {
ON.store(on, Ordering::Relaxed);
}
pub fn river3() -> bool {
ON.load(Ordering::Relaxed)
}
/// `SOLVER_RIVER3=1`.
pub fn from_env() -> bool {
matches!(std::env::var("SOLVER_RIVER3").as_deref(), Ok("1") | Ok("an"))
}
/// Iteration cap (and the count under `SOLVER_ZEIT=fest`).
pub const ITERS: u32 = 40_000;
/// Fewest iterations a decision may rest on.
pub const MIN_ITERS: u32 = 3_000;
/// Own cap of one solve, inside the river's decision total.
pub const BUDGET_MS: f64 = 1500.0;
/// Most combos per player (heaviest first, model weights are equal: the first in the model's order).
pub const MAX_COMBOS: usize = 300;
const TOKEN: f64 = 1e-6;
/// The live seats (hero and the villains still in) in post-flop acting order, from the blinds:
/// the small blind acts first, then clockwise. `None` without blinds in the history.
pub fn acting_order(spot: &Spot) -> Option<Vec<u8>> {
let n = spot.seats.max(2) as i32;
let sb = spot.history.iter().find(|r| r.street == Street::Preflop && r.action == SeenAction::PostSmallBlind).map(|r| r.seat as i32);
let bb = spot.history.iter().find(|r| r.street == Street::Preflop && r.action == SeenAction::PostBigBlind).map(|r| r.seat as i32);
let first = match (sb, bb) {
(Some(s), _) => s,
(None, Some(b)) => b - 1,
_ => return None,
};
let mut seats: Vec<u8> = std::iter::once(spot.hero_seat).chain(spot.live_villains().map(|v| v.seat)).collect();
seats.sort_by_key(|s| (*s as i32 - first).rem_euclid(n));
Some(seats)
}
/// The observed river line among the live players: `(index in order, act)`, the street
/// contributions per player, and whether it is consistent with hero's price.
fn river_line(spot: &Spot, order: &[u8]) -> Option<(Vec<(usize, Act)>, Vec<f64>)> {
let mut c = vec![0.0; order.len()];
let mut line = Vec::new();
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == Street::River) {
let Some(who) = order.iter().position(|s| *s == r.seat) else {
// A player no longer in: a check or fold is harmless, money in is not representable.
if matches!(r.action, SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn | SeenAction::Call) {
return None;
}
continue;
};
let top = c.iter().copied().fold(0.0, f64::max);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => line.push((who, Act::Check)),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > top => {
line.push((who, if aggressed { Act::Raise(amount) } else { Act::Bet(amount) }));
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
line.push((who, Act::Call));
c[who] = top;
}
SeenAction::Fold => return None,
_ => {}
}
}
let me = order.iter().position(|s| *s == spot.hero_seat)?;
let top = c.iter().copied().fold(0.0, f64::max);
((top - c[me] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0)).then_some((line, c))
}
/// The model range of `who`'s line, as card masks off the board (weight 1 each), heaviest-first order
/// of the model, at most `MAX_COMBOS`; `keep` joins at a token weight if missing.
fn model_hands(spot: &Spot, who: &Villain, board: u64, keep: Option<u64>) -> Option<Hands3> {
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board);
let list: Vec<Vec<Card>> = crate::engine::range_combos::combos(&rules, &filter, &spot.board)?;
let mut masks: Vec<u64> = list.iter().filter(|c| c.len() == 2).map(|c| fast7::mask(c)).filter(|m| m & board == 0 && m.count_ones() == 2).collect();
masks.sort_unstable();
masks.dedup();
if masks.len() > MAX_COMBOS {
// Evenly strided, so the kept range keeps its shape (the model gives no weights to rank by).
let step = masks.len() as f64 / MAX_COMBOS as f64;
masks = (0..MAX_COMBOS).map(|k| masks[(k as f64 * step) as usize]).collect();
}
let mut weights = vec![1.0; masks.len()];
if let Some(k) = keep {
if !masks.contains(&k) {
masks.push(k);
weights.push(TOKEN);
}
}
(!masks.is_empty()).then_some(Hands3 { masks, weights })
}
pub struct Solved3 {
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub iterations: u64,
pub millis: f64,
pub players: usize,
pub nodes: usize,
pub combos: Vec<usize>,
}
/// Solve this 3- or 4-handed river (gated spot) and return hero's average strategy at its node.
pub fn solve_river3(spot: &Spot) -> Option<Solved3> {
let villains = spot.live_villains().count();
if spot.street != Street::River || spot.board.len() != 5 || spot.hero_cards.len() != 2 || !(2..=3).contains(&villains) {
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 order = acting_order(spot)?;
let (line, c) = river_line(spot, &order)?;
let me = order.iter().position(|s| *s == spot.hero_seat)?;
let stack_of = |seat: u8| -> f64 {
if seat == spot.hero_seat {
spot.hero_stack
} else {
spot.live_villains().find(|v| v.seat == seat).map_or(0.0, |v| v.stack)
}
};
let cap = order.iter().enumerate().map(|(i, s)| stack_of(*s) + c[i]).fold(f64::INFINITY, f64::min);
let pot = spot.pot - c.iter().sum::<f64>();
if pot <= 0.0 || !cap.is_finite() || cap <= c.iter().copied().fold(0.0, f64::max) {
return None;
}
let board = fast7::mask(&spot.board);
let hero_mask = fast7::mask(&spot.hero_cards);
let mut hands = Vec::with_capacity(order.len());
for seat in &order {
let h = if *seat == spot.hero_seat {
model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask))?
} else {
let v = spot.live_villains().find(|v| v.seat == *seat)?;
model_hands(spot, v, board, None)?
};
hands.push(h);
}
let game = Game3::build(order.len(), pot, cap, &Menu3::standard());
let at = game.follow(&line)?;
let Node3::Dec { player, acts, .. } = &game.nodes[at] else { return None };
if *player != me {
return None;
}
let acts = acts.clone();
let nodes = game.nodes.len();
let combos: Vec<usize> = hands.iter().map(|h| h.masks.len()).collect();
let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?;
let mut solver = Solver3::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15);
let mut done = 0u32;
while done < ITERS {
solver.iterate();
done += 1;
if done % 200 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget {
break;
}
}
if done < MIN_ITERS {
return None;
}
let row = solver.row(at, hero_index);
Some(Solved3 { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos })
}
/// The live multiway-river decision, or `None` and the heuristic keeps it.
pub fn river3_decision(raw: &Spot) -> Option<Decision> {
if !river3() || 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 s = solve_river3(&gated)?;
let (draw, _) = Rng::seeded(gated.seed).unit();
let mut acc = 0.0;
let mut pick = s.acts.len() - 1;
for (k, p) in s.row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = s.acts[pick];
let p = s.row[pick];
Some(Decision::new(
legal_choice(&gated, act),
p.clamp(0.0, 1.0),
format!(
"river3 solver ({} players): {:?} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
s.players, s.combos, s.nodes, s.iterations, s.millis
),
))
}
#[cfg(test)]
mod tests;
+102
View File
@@ -0,0 +1,102 @@
use super::*;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
use std::sync::Mutex;
static LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max, three-way to the river: button (hero, seat 4) opens 2.5, small blind (5) and big blind
/// (0) call; flop SB check, BB check, BTN bets 3.75, both call; turn checked through; river SB check,
/// BB bets 10, hero to act. Pot before the river 18.75.
fn three_way(hero: &str) -> Spot {
use SeenAction::*;
use Street::*;
let history = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Call, Some(2.5)),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 5, Check, None),
rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(3.75)),
rec(Flop, 5, Call, Some(3.75)),
rec(Flop, 0, Call, Some(3.75)),
rec(Turn, 5, Check, None),
rec(Turn, 0, Check, None),
rec(Turn, 4, Check, None),
rec(River, 5, Check, None),
rec(River, 0, Bet, Some(10.0)),
];
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: None,
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks 3h").unwrap(),
street: Street::River,
pot: 28.75,
to_call: 10.0,
hero_stack: 93.75,
min_raise_to: Some(20.0),
max_raise_to: Some(93.75),
legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise],
allowed_sizes: None,
villains: vec![
Villain { seat: 5, stack: 93.75, folded: false, profile: None },
Villain { seat: 0, stack: 83.75, folded: false, profile: None },
],
seed: 5,
history,
}
}
#[test]
fn acting_order_starts_at_the_small_blind() {
assert_eq!(acting_order(&three_way("Qc Jc")), Some(vec![5, 0, 4]));
}
#[test]
fn off_decides_nothing_and_heads_up_is_not_in_the_slice() {
let _g = LOCK.lock().unwrap();
set_river3(false);
assert!(river3_decision(&three_way("As Ad")).is_none());
set_river3(true);
let mut hu = three_way("As Ad");
hu.villains.pop();
assert!(river3_decision(&hu).is_none());
set_river3(false);
}
#[test]
fn on_decides_three_way_rivers_legally_and_in_time() {
let _g = LOCK.lock().unwrap();
set_river3(true);
for hero in ["As Ad", "6s 5d", "Kc Qc"] {
let spot = three_way(hero);
let t = std::time::Instant::now();
let d = river3_decision(&spot).expect("3-way river is in the slice");
assert!(t.elapsed().as_secs_f64() < 2.0);
assert!(d.reason.contains("river3 solver (3 players)"), "{}", d.reason);
assert!(matches!(d.choice, Choice::Fold | Choice::Call | Choice::Raise { .. }), "{:?}", d.choice);
}
set_river3(false);
}
#[test]
fn top_set_continues_and_air_folds_three_way() {
let s = solve_river3(&three_way("As Ad")).unwrap();
let fold = |s: &Solved3| s.row.iter().zip(&s.acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum::<f64>();
assert!(fold(&s) < 0.05, "{:?} {:?}", s.row, s.acts);
let s = solve_river3(&three_way("6s 5d")).unwrap();
assert!(fold(&s) > 0.7, "{:?} {:?}", s.row, s.acts);
}
+1
View File
@@ -40,6 +40,7 @@ fn main() {
// SOLVER_TURN=1 (stage B): every heads-up turn by the turn+river game (`turn_game::turn_solver_decision`).
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env());
let stdin = io::stdin();
let stdout = io::stdout();
if let Err(error) = serve(stdin.lock(), stdout.lock()) {
+1
View File
@@ -58,6 +58,7 @@ class Klasse(unittest.TestCase):
self.assertEqual(k("PREFLOP", "BB vs open, call top 30% -> call"), "regeln")
self.assertEqual(k("TURN", "turn game: 30x40 combos, 9 nodes, Check p 0.6, solved in 80 ms"), "e3")
self.assertEqual(k("RIVER", "river solver (modell): 300x200 combos, 21 nodes, 600 iters, Fold p 0.9, 40 ms"), "solver")
self.assertEqual(k("RIVER", "river3 solver (3 players): [300, 300, 300] combos, 271 nodes, 40000 iters, Fold p 0.9, 900 ms"), "solver")
self.assertEqual(k("TURN", "defensive turn veto: x (heuristic would call)"), "turn_veto")
self.assertEqual(k("RIVER", "defensive veto: x (heuristic would call)"), "river_veto")
self.assertEqual(k("RIVER", "MDF-Boden: Made-Hand verteidigt"), "mdf")