Files
pokerfreak/src/cfr/dbr.rs
T
mmintelandClaude Opus 5.5 ff418fe005 River-DBR (Roadmap #1) gemessen: Verlierer, Arm bleibt aus
Data-Biased Robust Counter-Strategy (cfr::dbr) als Heads-up-River-Spieler mit
Read-Konfidenz je Knoten. Leiter gegen zaehl: -32.74 +-2.91 bb/100, alle
gemessenen Profile verlieren, auch balancierte. Arm RIVER_DBR aus, aus = bit-identisch.
Dazu: Zaehlungen je Read (COUNTS=1, eich_sim.py), Session-Memory-API,
geparktes Check-Raise-Modell (RAISE_MODEL, aus).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:45:51 +01:00

274 lines
12 KiB
Rust

//! Data-Biased Robust counter-strategy (Johanson & Bowling, "Data Biased Robust Counter Strategies",
//! AISTATS 2009) - safe exploitation of a modelled opponent.
//!
//! CFR+ on a restricted game: at each of the modelled player's decision nodes it plays the MODEL
//! with weight `w[node]` and a freely learned (regret-matched) strategy with weight `1 - w`. The other
//! player - hero - solves this game with plain CFR+; its average strategy is the counter-strategy.
//!
//! - `w = 0` everywhere: the ordinary game, hero's strategy is a Nash equilibrium (unexploitable).
//! - `w = 1` everywhere: the opponent is the model, hero's strategy is a best response to it
//! (maximal exploitation, unbounded exploitability).
//! - in between: the opponent may deviate from the model wherever the data is thin, so hero only
//! exploits as far as the data reaches. Johanson & Bowling show the result is on (or near) the
//! Pareto frontier of "value against the model" versus "worst case against anyone".
//!
//! Unlike the KL tilt around GTO (`cfr::kl_br`), the counter-strategy's support is free: it can play
//! actions an equilibrium never plays (the thin value bet against a station), which is exactly the
//! offense the KL tilt could not reach (`docs/notizen/BEFUND-river-gearbox-belief-trust.md`).
//!
//! `w` is per node - the confidence of the model AT THAT NODE (how much of the villain's play there
//! the data has seen): a fold-to-bet read can be strong while the bluff read is thin.
use super::regret_matching::matched;
use super::solver_state::SolverState;
use super::strategy::{average_strategy, Strategy};
use super::terminal_value::terminal_value;
use super::tree::{Node, Tree};
use super::value_walk::{root_values, Responder};
/// The modelled player, its model and the per-node weight of the model (0 = free, 1 = fixed).
pub struct Restriction<'a> {
pub player: usize,
pub model: &'a Strategy,
/// One weight per tree node; only the modelled player's decision nodes are read.
pub weight: Vec<f64>,
}
impl Restriction<'_> {
fn w(&self, node: usize) -> f64 {
self.weight.get(node).copied().unwrap_or(0.0).clamp(0.0, 1.0)
}
/// The modelled player's effective row block at `node`: `w * model + (1 - w) * free`.
fn mix(&self, node: usize, free: &[f64], classes: usize, actions: usize) -> Vec<f64> {
let w = self.w(node);
(0..classes * actions)
.map(|k| {
let model = self.model.row(node, k / actions).get(k % actions).copied().unwrap_or(0.0);
w * model + (1.0 - w) * free[k]
})
.collect()
}
}
/// One CFR+ iteration of the restricted game (alternating, linear averaging, as `cfr::iterate`).
pub fn iterate_restricted(tree: &Tree, state: SolverState, r: &Restriction) -> SolverState {
let (iteration, mut regret, mut sums) = state.into_parts();
let next = iteration.saturating_add(1);
if tree.is_playable() && regret.len() == tree.nodes.len() {
let ones = vec![1.0; tree.classes];
for player in 0..2 {
let mut pass = Pass { tree, r, player, weight: next as f64, regret: &mut regret, sums: &mut sums };
pass.walk(tree.root, &ones, &ones);
}
}
SolverState::from_parts(next, regret, sums)
}
/// Solve the restricted game for `iterations` and return the joint strategy: the counter-player's
/// average strategy, and for the modelled player its effective mix (model weighted with its average
/// free strategy) - so `value_walk` on the result evaluates the counter-strategy against the
/// restricted opponent it was trained on.
pub fn solve_restricted(tree: &Tree, r: &Restriction, iterations: u32) -> Strategy {
let mut state = SolverState::fresh(tree);
for _ in 0..iterations {
state = iterate_restricted(tree, state, r);
}
let avg = average_strategy(tree, &state);
let mut out = avg.clone();
for (node, n) in tree.nodes.iter().enumerate() {
if let Node::Decision { player, name, children } = n {
if *player == r.player {
let a = children.len();
let free: Vec<f64> = (0..tree.classes).flat_map(|c| avg.row(node, c).to_vec()).collect();
let mixed = r.mix(node, &free, tree.classes, a);
out = out.with_rows(tree, name, |c| mixed[c * a..(c + 1) * a].to_vec()).unwrap_or(out);
}
}
}
out
}
/// What player `hero` wins with `strategy`'s hero rows when the other player best-responds (the
/// worst case over all opponents), summed over the deal like `exploitability::game_value`.
pub fn worst_case_value(tree: &Tree, strategy: &Strategy, hero: usize) -> f64 {
let hero = hero.min(1);
let other: f64 = root_values(tree, strategy, Responder::Best, 1 - hero, &mut |_| {}).iter().sum();
-other
}
/// What player `hero` wins with `strategy`'s hero rows against the opponent rows of `opponent`.
pub fn value_against(tree: &Tree, strategy: &Strategy, opponent: &Strategy, hero: usize) -> f64 {
let hero = hero.min(1);
let mut joint = strategy.clone();
for (node, n) in tree.nodes.iter().enumerate() {
if let Node::Decision { player, name, .. } = n {
if *player != hero {
joint = joint.with_rows(tree, name, |c| opponent.row(node, c).to_vec()).unwrap_or(joint);
}
}
}
root_values(tree, &joint, Responder::Follow, hero, &mut |_| {}).iter().sum()
}
struct Pass<'a> {
tree: &'a Tree,
r: &'a Restriction<'a>,
player: usize,
weight: f64,
regret: &'a mut Vec<Vec<f64>>,
sums: &'a mut Vec<Vec<f64>>,
}
impl Pass<'_> {
/// The strategy a decision node is played with this iteration: regret matching, mixed with the
/// model at the modelled player's nodes. Also returns the free (regret-matched) part.
fn sigma(&self, node: usize, player: usize, actions: usize) -> (Vec<f64>, Vec<f64>) {
let free = matched(&self.regret[node], actions);
if player == self.r.player {
(self.r.mix(node, &free, self.tree.classes, actions), free)
} else {
(free.clone(), free)
}
}
fn walk(&mut self, node: usize, own: &[f64], opp: &[f64]) -> Vec<f64> {
let tree = self.tree;
let n = tree.classes;
match tree.nodes.get(node) {
None => vec![0.0; n],
Some(Node::Terminal(payoff)) => terminal_value(payoff, &tree.chance, n, self.player, opp),
Some(Node::Chance(branches)) => {
let mut total = vec![0.0; n];
for (p, child) in branches {
let scaled: Vec<f64> = opp.iter().map(|x| x * p).collect();
let value = self.walk(*child, own, &scaled);
total.iter_mut().zip(&value).for_each(|(t, v)| *t += v);
}
total
}
Some(Node::Decision { player, children, .. }) => {
let actions = children.len();
if actions == 0 {
return vec![0.0; n];
}
let (sigma, free) = self.sigma(node, *player, actions);
if *player == self.player {
self.own_node(node, children, &sigma, &free, own, opp)
} else {
let mut total = vec![0.0; n];
for (a, child) in children.iter().enumerate() {
let reach: Vec<f64> = (0..n).map(|j| opp[j] * sigma[j * actions + a]).collect();
let value = self.walk(*child, own, &reach);
total.iter_mut().zip(&value).for_each(|(t, v)| *t += v);
}
total
}
}
}
}
/// The traverser's node: reach flows with the played (`sigma`) strategy; regrets and averages
/// belong to the free part (the model part is not chosen, so it carries no regret).
fn own_node(&mut self, node: usize, children: &[usize], sigma: &[f64], free: &[f64], own: &[f64], opp: &[f64]) -> Vec<f64> {
let n = self.tree.classes;
let actions = children.len();
let values: Vec<Vec<f64>> = children
.iter()
.enumerate()
.map(|(a, child)| {
let reach: Vec<f64> = (0..n).map(|i| own[i] * sigma[i * actions + a]).collect();
self.walk(*child, &reach, opp)
})
.collect();
let mut played = vec![0.0; n];
for i in 0..n {
played[i] = (0..actions).map(|a| sigma[i * actions + a] * values[a][i]).sum();
let free_value: f64 = (0..actions).map(|a| free[i * actions + a] * values[a][i]).sum();
for a in 0..actions {
let r = &mut self.regret[node][i * actions + a];
*r = (*r + values[a][i] - free_value).max(0.0);
self.sums[node][i * actions + a] += self.weight * own[i] * free[i * actions + a];
}
}
played
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cfr::exploitability::{exploitability, game_value};
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::rng::Rng;
/// A 6-bucket river with a uniform independent deal, pot 6, bet 4.
fn river() -> Tree {
let n = 6;
tree_with_chance(n, vec![1.0 / (n * n) as f64; n * n], 6.0, 4.0)
}
/// A calling station: calls every bet, never bets when checked to.
fn station(tree: &Tree) -> Strategy {
let base = Strategy::uniform(tree);
let s = base.with_rows(tree, "v_bet", |_| vec![0.0, 1.0]).unwrap_or(base);
s.with_rows(tree, "v_check", |_| vec![1.0, 0.0]).unwrap_or(s)
}
fn weights(tree: &Tree, w: f64) -> Vec<f64> {
tree.nodes
.iter()
.map(|n| match n {
Node::Decision { player: 1, .. } => w,
_ => 0.0,
})
.collect()
}
#[test]
fn zero_weight_is_nash() {
let tree = river();
let model = station(&tree);
let r = Restriction { player: 1, model: &model, weight: weights(&tree, 0.0) };
let s = solve_restricted(&tree, &r, 4000);
assert!(exploitability(&tree, &s) < 0.02, "{}", exploitability(&tree, &s));
}
#[test]
fn the_counter_strategy_trades_worst_case_for_value_against_the_model() {
let tree = river();
let model = station(&tree);
let nash = solve(&tree, 4000, Rng::seeded(1)).strategy;
let v_star = game_value(&tree, &nash);
let mut last_model_value = f64::NEG_INFINITY;
let mut last_worst = f64::INFINITY;
for w in [0.0, 0.5, 0.8, 1.0] {
let r = Restriction { player: 1, model: &model, weight: weights(&tree, w) };
let s = solve_restricted(&tree, &r, 4000);
let vs_model = value_against(&tree, &s, &model, 0);
let worst = worst_case_value(&tree, &s, 0);
// More trust in the model: never less value against it, never a better worst case.
assert!(vs_model >= last_model_value - 1e-3, "w {w}: {vs_model} < {last_model_value}");
assert!(worst <= last_worst + 1e-3, "w {w}: {worst} > {last_worst}");
assert!(worst <= v_star + 1e-2);
last_model_value = vs_model;
last_worst = worst;
}
// Against the station the counter-strategy beats the equilibrium clearly.
assert!(last_model_value > value_against(&tree, &nash, &model, 0) + 0.1);
}
#[test]
fn it_value_bets_thin_where_the_equilibrium_never_bets() {
// Bucket 3 of 6 (a medium hand): the equilibrium checks it; against a station that calls
// everything it is a value bet (beats half the calling range). The KL tilt cannot reach this.
let tree = river();
let model = station(&tree);
let r = Restriction { player: 1, model: &model, weight: weights(&tree, 1.0) };
let s = solve_restricted(&tree, &r, 4000);
assert!(s.row(0, 4)[1] > 0.9, "{:?}", s.row(0, 4));
assert!(s.row(0, 0)[1] < 0.1, "{:?}", s.row(0, 0)); // never bluffs a station
}
}