Files
pokerfreak/src/cfr/river3.rs
T

581 lines
24 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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,
/// Players who never decide: they check, and call every bet up to the cap (the pooled field of a
/// 5+-handed spot, their hands still sampled and in the showdown). Bit mask, 0 = none.
pub passive: u32,
/// The observed line the tree is built for (`build_linie`): its bets and raises are in the tree at their exact size.
line: Vec<(usize, Act)>,
me: usize,
}
#[derive(Clone)]
struct State {
c: Vec<f64>,
active: u32,
pending: u32,
raises: u8,
to_act: usize,
/// Position in the observed line while the walk is on it (`build_linie`).
lp: Option<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 {
Self::build_passiv(players, pot, cap, menu, 0)
}
/// As `build`, the players in the bit mask `passive` only check or call.
pub fn build_passiv(players: usize, pot: f64, cap: f64, menu: &Menu3, passive: u32) -> Game3 {
Self::build_linie(players, pot, cap, menu, passive, &[], 0)
}
/// As `build_passiv`, with the observed `line` in the tree at its exact sizes: an observed bet or raise of a size the menu
/// does not hold is an extra act at its node (the nearest menu size would change the price hero faces: a min-bet of 2 %
/// of the pot became a third of the pot). `me` = hero's index; a player before him whose act is not in the line is
/// skipped as `follow_nachsicht` does. Empty `line`: the plain tree.
pub fn build_linie(players: usize, pot: f64, cap: f64, menu: &Menu3, passive: u32, line: &[(usize, Act)], me: usize) -> Game3 {
let mut g = Game3 { nodes: Vec::new(), players, pot, cap, passive, line: line.to_vec(), me };
let all = (1u32 << players) - 1;
let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0, lp: if line.is_empty() { None } else { Some(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 self.passive & (1 << p) != 0 {
acts.push(if top > s.c[p] + eps { Act::Call } else { Act::Check });
} else 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));
}
}
// The observed line: which act it takes here (`on`), and the exact size of an observed bet or raise.
let mut on: Option<(usize, bool)> = None;
if let Some(i) = s.lp {
if let Some((who, obs)) = self.line.get(i).cloned() {
if who == p {
match obs {
Act::Bet(x) | Act::Raise(x) => {
let kind = |t: &Act| matches!((&obs, t), (Act::Bet(_), Act::Bet(_)) | (Act::Raise(_), Act::Raise(_)));
let facing = top > s.c[p] + eps;
let erlaubt = x > top + eps && x < self.cap - eps && !acts.iter().any(|t| kind(t) && matches!(t, Act::Bet(y) | Act::Raise(y) if (y - x).abs() < eps));
let platz = if facing { s.raises < menu.max_raises && matches!(obs, Act::Raise(_)) } else { matches!(obs, Act::Bet(_)) };
if erlaubt && platz && self.passive & (1 << p) == 0 {
let at = acts.iter().position(|t| matches!(t, Act::Bet(y) | Act::Raise(y) if kind(t) && *y > x)).unwrap_or(acts.len());
// An all-in raise stays last; the new size goes in front of it.
acts.insert(at, if matches!(obs, Act::Bet(_)) { Act::Bet(x) } else { Act::Raise(x) });
}
on = acts
.iter()
.enumerate()
.filter_map(|(k, t)| match t {
Act::Bet(y) | Act::Raise(y) if kind(t) => Some((k, (y - x).abs())),
_ => None,
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(k, _)| (k, true));
}
_ => on = acts.iter().position(|t| *t == obs).map(|k| (k, true)),
}
} else if p != self.me {
on = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call))).map(|k| (k, false));
}
}
}
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 (j, a) in acts.iter().enumerate() {
let mut t = s.clone();
t.lp = match (s.lp, on) {
(Some(i), Some((k, eigene))) if k == j => Some(if eigene { i + 1 } else { i }),
_ => None,
};
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)
}
/// As `follow`, but a player whose turn comes before the next recorded act and who is not `me` is taken
/// to have folded when a bet is open, else checked (a live player without a recorded act: the history is incomplete,
/// the pot says he put nothing more in). Ends at `me`'s next node.
pub fn follow_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option<usize> {
let mut at = 0;
let skip = |at: usize, me: usize| -> Option<usize> {
let Node3::Dec { player, acts, kids, .. } = &self.nodes[at] else { return None };
if *player == me {
return None;
}
let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?;
Some(kids[k])
};
for (who, a) in line {
loop {
let Node3::Dec { player, .. } = &self.nodes[at] else { return None };
if player == who {
break;
}
at = skip(at, me)?;
}
at = self.step(at, a)?;
}
while let Node3::Dec { player, .. } = &self.nodes[at] {
if *player == me {
break;
}
at = skip(at, me)?;
}
Some(at)
}
/// The nodes the observed line passes (node, index of the act taken), as `follow_nachsicht` walks it: a player whose
/// turn comes before his recorded act and who is not `me` folds (bet open) or checks. Ends at `me`'s next node.
pub fn pfad_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option<Vec<(usize, usize)>> {
let mut at = 0;
let mut pfad = Vec::new();
let skip = |at: usize, pfad: &mut Vec<(usize, usize)>| -> Option<usize> {
let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { return None };
let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?;
pfad.push((at, k));
Some(kids[k])
};
for (who, a) in line {
loop {
let Node3::Dec { player, .. } = &self.nodes[at] else { return None };
if player == who {
break;
}
if *player == me {
return None;
}
at = skip(at, &mut pfad)?;
}
let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { 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)?,
};
pfad.push((at, k));
at = kids[k];
}
while let Node3::Dec { player, .. } = &self.nodes[at] {
if *player == me {
break;
}
at = skip(at, &mut pfad)?;
}
Some(pfad)
}
/// The child of `at` that the observed act `a` leads to (nearest size for bets and raises).
fn step(&self, at: usize, a: &Act) -> Option<usize> {
let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { 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)?,
};
Some(kids[k])
}
}
/// 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,
/// Per node: the measured pool's row per hand (hand-major) and its weight; the player plays `(1 - w) * CFR + w * row`
/// where the others see him (node-locking as in the heads-up core, `TrSolver::lock`).
locks: Vec<Option<(Vec<f64>, f64)>>,
}
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);
let locks = vec![None; game.nodes.len()];
Solver3 { game, hands, score, cum, regret, avg, rng: Xs(seed | 1), t: 0, locks }
}
/// Lock `node`'s player to the pool rows `rows` (one row per hand over the node's acts) with weight `w`.
pub fn lock(&mut self, node: usize, rows: Vec<f64>, w: f64) {
self.locks[node] = Some((rows, w.clamp(0.0, 1.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 {
if self.game.passive & (1 << i) != 0 {
continue;
}
// 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);
if let Some((rows, w)) = &self.locks[node] {
for (k, s) in sigma.iter_mut().enumerate() {
*s = (1.0 - w) * *s + w * rows[h * a + k];
}
}
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]
}
}
/// Diagnosis: the hand's regrets at `node` per action, scaled to chips (weighted mean of `value(a) - value(strategy)`).
pub fn regret_chips(&self, node: usize, h: usize) -> Vec<f64> {
let Node3::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() };
let a = acts.len();
let z = (self.t * (self.t + 1)) as f64 / 2.0;
self.regret[node][h * a..(h + 1) * a].iter().map(|r| r / z).collect()
}
pub fn iterations(&self) -> u64 {
self.t
}
}
#[cfg(test)]
mod tests;