From f66208fc58a2c3475abd3e0d1c2dd63a9f06e4e5 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Tue, 1 Dec 2026 13:36:25 +0100 Subject: [PATCH] Sicherung 01.12.: ungesicherte Dateien aus Worktree D:\Projects\pokerfreak\.claude\worktrees\agent-a803783bbe758c66a (Zweig worktree-agent-a803783bbe758c66a, HEAD 52428920) 3 Dateien. Nicht enthalten: 0 Dateien (Bau, Binaer, > 25 MB, archiv/lauf, Spuren echter Haende), 0 Loeschungen nicht nachgezogen. Der Worktree selbst ist unveraendert. Co-Authored-By: Claude Opus 5.5 --- src/cfr/mod.rs | 1 + src/cfr/qre.rs | 286 ++++++++++++++++++++++++++++++++++++++++++++ src/cfr/strategy.rs | 5 + 3 files changed, 292 insertions(+) create mode 100644 src/cfr/qre.rs diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index 318baac9..088fc0bb 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -89,6 +89,7 @@ pub mod permille; pub mod plo5_bucket; pub mod push_fold3_game; pub mod push_fold_game; +pub mod qre; pub mod regret_matching; pub mod render_charts; pub mod render_equity; diff --git a/src/cfr/qre.rs b/src/cfr/qre.rs new file mode 100644 index 00000000..21e5bb2f --- /dev/null +++ b/src/cfr/qre.rs @@ -0,0 +1,286 @@ +//! Logit quantal response equilibrium (QRE): Nash at finite temperature. +//! +//! Every player plays a softmax response to the expected payoffs of its own actions, +//! `sigma(a) ~ exp(beta * Q(a))`, per decision node and hand class, where `Q` is the expected +//! payoff given the class and reaching the node (the counterfactual value divided by the +//! opponent's reach mass). Both players do so against each other: the QRE is the fixed point. +//! +//! - `beta -> inf` (T -> 0): the best response, i.e. a Nash equilibrium of the zero-sum game. +//! - `beta -> 0` (T -> inf): uniform play. +//! - A humans-play-QRE read: fish = small beta, nit / solver = large beta (`fit_temperature`). +//! +//! Solver: the logit flow `d sigma = softmax(beta Q(sigma)) - sigma` integrated with RK4 (plain +//! damped iteration `sigma <- (1-eta) sigma + eta softmax(..)` spirals out at large beta, see +//! `settle`), with beta annealed from 1 up to the target (doubling) so every stage starts at the +//! previous solution (path-following). Step size follows the response gain. Deterministic. + +use super::strategy::Strategy; +use super::tree::Tree; +use super::value_walk::{root_values, Responder, Visit}; + +const TOLERANCE: f64 = 1e-12; +const ETA_MAX: f64 = 0.5; +const ETA_MIN: f64 = 1e-7; + +/// Logit-QRE profile at inverse temperature `beta` (T = 1/beta). `iters` is the iteration cap +/// per annealing stage. +pub fn qre(tree: &Tree, beta: f64, iters: u32) -> Strategy { + let start = Strategy::uniform(tree); + if !tree.is_playable() { + return start; + } + let beta = if beta.is_finite() { beta.max(0.0) } else { 1e6 }; + stages(beta).into_iter().fold(start, |s, b| settle(tree, s, b, iters)) +} + +/// Annealing schedule: `[beta]` up to 1, else 1 and then doublings (geometric) up to `beta`. +fn stages(beta: f64) -> Vec { + if beta <= 1.0 { + return vec![beta]; + } + let n = beta.log2().ceil().max(1.0) as i32; + std::iter::once(1.0).chain((1..=n).map(|k| beta.powf(k as f64 / n as f64))).collect() +} + +type Field = Vec<(usize, Vec>)>; + +/// The logit flow `f(sigma) = softmax(beta Q(sigma)) - sigma`, its residual `max|f|` and the +/// gain scale `spread` (largest `beta * (max Q - min Q)`). +fn flow(tree: &Tree, s: &Strategy, beta: f64) -> (Field, f64, f64) { + let (mut field, spread) = logit_targets(tree, s, beta); + let mut residual = 0.0f64; + for (node, rows) in field.iter_mut() { + for (c, row) in rows.iter_mut().enumerate() { + for (t, o) in row.iter_mut().zip(s.row(*node, c)) { + *t -= o; + residual = residual.max(t.abs()); + } + } + } + (field, residual, spread) +} + +/// `s + sum_k w_k * field_k`, clamped at 0 and renormalised per row. +fn moved(s: &Strategy, fields: &[(&Field, f64)]) -> Strategy { + let nodes = &fields[0].0; + (0..nodes.len()).fold(s.clone(), |acc, i| { + let node = nodes[i].0; + acc.with_node(node, |c| { + let mut row: Vec = s + .row(node, c) + .iter() + .enumerate() + .map(|(a, o)| (o + fields.iter().map(|(f, w)| w * f[i].1[c][a]).sum::()).max(0.0)) + .collect(); + let sum: f64 = row.iter().sum(); + row.iter_mut().for_each(|x| *x /= sum); + row + }) + }) +} + +/// Integrate the logit flow at a fixed beta with classic RK4 until the residual is below +/// tolerance (or `iters` steps). Why not plain damping: the flow's linearisation in a zero-sum +/// game is a spiral (real part about -1, imaginary part about beta x payoff scale), where explicit +/// Euler needs a step ~ 1/beta^2 but RK4 is stable up to ~ 1/beta. Step `h = 2 / (1 + spread / 2)` +/// clamped to `[ETA_MIN, ETA_MAX]`; `spread` follows the current gain, so large beta takes small steps. +fn settle(tree: &Tree, start: Strategy, beta: f64, iters: u32) -> Strategy { + let mut s = start; + for _ in 0..iters { + let (k1, residual, spread) = flow(tree, &s, beta); + if residual < TOLERANCE { + break; + } + let h = (1.5 / (1.0 + 0.5 * spread)).clamp(ETA_MIN, ETA_MAX); + let (k2, _, _) = flow(tree, &moved(&s, &[(&k1, h / 2.0)]), beta); + let (k3, _, _) = flow(tree, &moved(&s, &[(&k2, h / 2.0)]), beta); + let (k4, _, _) = flow(tree, &moved(&s, &[(&k3, h)]), beta); + s = moved(&s, &[(&k1, h / 6.0), (&k2, h / 3.0), (&k3, h / 3.0), (&k4, h / 6.0)]); + } + s +} + +/// Softmax(beta Q) for every decision node of both players against the profile `s`: +/// `(node, row per class)`. A class that cannot reach the node keeps its current row. +fn logit_targets(tree: &Tree, s: &Strategy, beta: f64) -> (Vec<(usize, Vec>)>, f64) { + let n = tree.classes; + let mut out = Vec::new(); + let mut spread = 0.0f64; + for player in 0..2 { + root_values(tree, s, Responder::Follow, player, &mut |v: &Visit| { + let rows = (0..n) + .map(|c| { + let mass: f64 = (0..n) + .map(|o| v.opp[o] * if player == 0 { tree.chance[c * n + o] } else { tree.chance[o * n + c] }) + .sum(); + if mass <= 1e-300 { + return s.row(v.node, c).to_vec(); + } + let q: Vec = v.action_values.iter().map(|a| beta * a[c] / mass).collect(); + let top = q.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let low = q.iter().cloned().fold(f64::INFINITY, f64::min); + spread = spread.max(top - low); + softmax(&q) + }) + .collect(); + out.push((v.node, rows)); + }); + } + (out, spread) +} + +fn softmax(x: &[f64]) -> Vec { + let top = x.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let e: Vec = x.iter().map(|v| (v - top).exp()).collect(); + let sum: f64 = e.iter().sum(); + e.iter().map(|v| v / sum).collect() +} + +/// Observed action counts of one class at one decision node. +#[derive(Clone, Debug, PartialEq)] +pub struct Observed { + pub node: usize, + pub class: usize, + /// One count (or frequency weight) per action. + pub counts: Vec, +} + +/// Maximum-likelihood inverse temperature for observed actions: log-grid over +/// `[0.01, 1000]`, then golden-section refinement around the best cell. Likelihood need not be +/// unimodal in general; the grid guards against a poor local pick. +pub fn fit_temperature(observed: &[Observed], tree: &Tree) -> f64 { + let loglik = |beta: f64| -> f64 { + let s = qre(tree, beta, 4000); + observed + .iter() + .map(|o| { + let row = s.row(o.node, o.class); + o.counts.iter().zip(row).map(|(k, p)| k * p.max(1e-12).ln()).sum::() + }) + .sum() + }; + let (lo, hi, steps) = (0.01f64.ln(), 1000f64.ln(), 40); + let grid: Vec = (0..=steps).map(|k| lo + (hi - lo) * k as f64 / steps as f64).collect(); + let scores: Vec = grid.iter().map(|x| loglik(x.exp())).collect(); + let best = (0..grid.len()).fold(0, |b, k| if scores[k] > scores[b] { k } else { b }); + let mut a = grid[best.saturating_sub(1)]; + let mut b = grid[(best + 1).min(grid.len() - 1)]; + let phi = (5f64.sqrt() - 1.0) / 2.0; + for _ in 0..40 { + let (c, d) = (b - phi * (b - a), a + phi * (b - a)); + if loglik(c.exp()) > loglik(d.exp()) { + b = d; + } else { + a = c; + } + } + ((a + b) / 2.0).exp() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cfr::exploitability::{exploitability, game_value}; + use crate::cfr::solve::solve; + use crate::cfr::tree::{Node, Payoff}; + use crate::rng::Rng; + + /// Polarised river: hero holds air or the nuts ([0.5, 0, 0.5]), villain a bluff-catcher + /// ([0, 1, 0]); pot 2, bet 1. Classes: 0 air, 1 bluff-catcher, 2 nuts. Payoffs for hero. + fn river() -> Tree { + let n = 3; + let mut chance = vec![0.0; n * n]; + chance[0 * n + 1] = 0.5; + chance[2 * n + 1] = 0.5; + let showdown = |win: f64| Payoff::Pair((0..n * n).map(|k| if k / n == 2 { win } else { -win }).collect()); + let nodes = vec![ + Node::Decision { player: 0, name: "hero", children: vec![1, 2] }, + Node::Terminal(showdown(1.0)), // check: pot 2 split by showdown, +-1 + Node::Decision { player: 1, name: "villain", children: vec![3, 4] }, + Node::Terminal(Payoff::Flat(1.0)), // villain folds + Node::Terminal(showdown(2.0)), // villain calls: +-2 + ]; + Tree { classes: n, chance, nodes, root: 0 } + } + + fn freqs(s: &Strategy, t: &Tree) -> (f64, f64, f64) { + let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap()); + (s.probability(h, 0, 1), s.probability(h, 2, 1), s.probability(v, 1, 1)) + } + + #[test] + fn qre_interpolates_between_uniform_and_nash() { + let t = river(); + let nash = solve(&t, 20000, Rng::seeded(1)); + let (nb, nn, nc) = freqs(&nash.strategy, &t); + println!("Nash (CFR+): bluff {nb:.4} nuts-bet {nn:.4} call {nc:.4}"); + assert!((nb - 1.0 / 3.0).abs() < 0.02 && (nc - 2.0 / 3.0).abs() < 0.02); + + let betas = [0.01, 0.1, 0.3, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0, 30.0, 100.0, 300.0, 1000.0]; + println!(" beta bluff(air) bet(nuts) call(BC) exploit value"); + let rows: Vec<(f64, f64, f64, f64)> = betas + .iter() + .map(|&b| { + let s = qre(&t, b, 20000); + let (bl, nu, ca) = freqs(&s, &t); + println!( + "{b:7.2} {bl:.4} {nu:.4} {ca:.4} {:.4} {:.4}", + exploitability(&t, &s), + game_value(&t, &s) + ); + (b, bl, nu, ca) + }) + .collect(); + + // beta -> 0: uniform + let (_, bl, nu, ca) = rows[0]; + assert!((bl - 0.5).abs() < 0.01 && (nu - 0.5).abs() < 0.01 && (ca - 0.5).abs() < 0.01); + // beta -> inf: Nash frequencies + let (_, bl, nu, ca) = *rows.last().unwrap(); + assert!((bl - nb).abs() < 0.03, "bluff {bl} vs nash {nb}"); + assert!((ca - nc).abs() < 0.03, "call {ca} vs nash {nc}"); + assert!(nu > 0.97); + // Monotone approach. Not monotone from beta = 0: a uniform villain over-folds (call 1/2 < + // 2/3), so air profits from betting and the bluff first RISES above 1/2 (peak ~0.52 near + // beta 0.4) before falling to 1/3; the call frequency likewise overshoots 2/3 (peak ~0.70 + // near beta 2) before settling. After the peak both fall monotonically onto Nash. + for w in rows.windows(2) { + assert!(w[1].2 >= w[0].2 - 1e-9, "nuts bet not monotone at beta {}", w[1].0); + if w[0].0 >= 0.5 { + assert!(w[1].1 <= w[0].1 + 1e-9, "bluff not monotone at beta {}", w[1].0); + } + if w[0].0 >= 2.0 { + assert!(w[1].3 <= w[0].3 + 1e-9, "call not monotone at beta {}", w[1].0); + } + if w[0].0 >= 0.3 { + assert!(w[1].0 > 0.0 && (w[1].1 - nb).abs() <= (w[0].1 - nb).abs() + 1e-9); + } + } + assert!(rows.iter().all(|r| r.1 > nb - 1e-3 && r.1 < 0.53)); + } + + #[test] + fn qre_is_a_fixed_point_and_deterministic() { + let t = river(); + let a = qre(&t, 3.0, 20000); + assert_eq!(a, qre(&t, 3.0, 20000)); + let again = settle(&t, a.clone(), 3.0, 1); + let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap()); + assert!((again.probability(h, 0, 1) - a.probability(h, 0, 1)).abs() < 1e-9); + assert!((again.probability(v, 1, 1) - a.probability(v, 1, 1)).abs() < 1e-9); + } + + #[test] + fn fit_recovers_temperature() { + let t = river(); + let s = qre(&t, 3.0, 20000); + let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap()); + let obs: Vec = [(h, 0), (h, 2), (v, 1)] + .iter() + .map(|&(node, class)| Observed { node, class, counts: s.row(node, class).iter().map(|p| p * 10000.0).collect() }) + .collect(); + let fit = fit_temperature(&obs, &t); + println!("fit beta = {fit:.3} (true 3)"); + assert!((fit - 3.0).abs() < 0.15); + } +} diff --git a/src/cfr/strategy.rs b/src/cfr/strategy.rs index fba97494..4dea8f8a 100644 --- a/src/cfr/strategy.rs +++ b/src/cfr/strategy.rs @@ -59,6 +59,11 @@ impl Strategy { Ok(self.replaced(index, |class| rows[class].clone())) } + /// Copy with one node replaced by `row(class)` per class (for solvers outside this module). + pub(crate) fn with_node(&self, index: usize, row: impl Fn(usize) -> Vec) -> Strategy { + self.replaced(index, row) + } + fn replaced(&self, index: usize, row: impl Fn(usize) -> Vec) -> Strategy { let mut probs = self.probs.clone(); probs[index] = (0..self.classes).flat_map(row).collect();