Files
pokerfreak/src/engine/river_br.rs
T
mmintelandClaude Opus 5.5 0355c382e2 D1d: Diagnose (warum Lesen nur 1,04 % aendert) + Micro-Pool als Ausnutzungsquelle (GEGNER_POOL, aus)
- engine::read_exploit::diagnose hinter GEGNER_BREIT_DIAG, Gegenprobe ohne Schranke GEGNER_BREIT_ROH
  (beide nur Messung, Standard bitgleich). Ergebnis: nicht Stichprobe/Schranke, sondern fehlende Kanaele
  (~65 %) und multiway (~24 %).
- exploit::pool: Stufen-Pool aus d2_priors.json, nur passive Achsen mit CV-Untergrenze > 0, Einzel-Read
  uebernimmt mit Stichprobe, Aggressor-Wache. Replay: 0 zusaetzliche Zuege.
- Queue: pool-basis/pool-an, pool-lbr-*; Korrektur breit-basis-k.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:10:08 +01:00

274 lines
11 KiB
Rust

//! Node-locked, trust-region exploitative best response on the heads-up river (Pillar 3).
//!
//! The full "gearbox" (solver plays every action, anchored at GTO) was a measured loser: a KL ball
//! around GTO cannot reach the thin value bets / light calls the heuristic uses to farm stations, so
//! replacing the heuristic bled exactly where it wins. This module therefore anchors at the
//! **heuristic's own decision** and only *deviates* where a node-locked best response proves a gain:
//!
//! 1. **Node-lock.** Villain's two nodes (`v_check`, `v_bet`) are fixed to read-derived strategies
//! (fold-to-bet, aggression). Hero's best response over the card-exact river tree is exact
//! (`value_walk`, `Responder::Best`): no CFR solve, so it is cheap and noise-free.
//! 2. **Uncertainty.** The read is not a point: the best response is evaluated on a box of beliefs
//! around it (fold-to-bet and aggression, radius shrinking with the read's confidence but never
//! below `DELTA_MIN`, since model misfit does not vanish with sample size). The gain used is the
//! WORST case over the box.
//! 3. **Trust region.** Deviate from the heuristic only if the worst-case gain exceeds a margin, and
//! mix the deviation in with weight `w <= 1 - exp(-KL_BUDGET * confidence)` (the KL budget of the
//! deviation from the heuristic grows with confidence). No read / thin read: the heuristic's
//! decision is returned untouched (bit-identical).
//!
//! Pieces are independently switchable (`PIECE_*`) so each can be proven alone on the ladder.
use crate::cfr::strategy::Strategy;
use crate::cfr::tree::Tree;
use crate::cfr::value_walk::{root_values, Responder};
use crate::cfr::river::tree_with_chance;
use crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET;
use crate::exploit::posterior::DEFAULT_AGGRESSION;
use crate::game::{Choice, Decision, SeenAction, Spot, Street};
use crate::hand::showdown::judge;
use crate::rng::Rng;
use crate::sizing::candidates::candidates;
use std::cell::Cell;
/// Facing a bet: heuristic Fold -> Call when the worst-case EV of calling is clearly positive.
pub const PIECE_PROMOTE_CALL: u8 = 1;
/// Facing a bet: heuristic Call -> Fold when even the best case EV of calling is clearly negative.
pub const PIECE_DEMOTE_CALL: u8 = 2;
/// Aggressor: heuristic Check -> Bet (best size) when the worst-case gain is clearly positive.
pub const PIECE_VALUE_BET: u8 = 4;
/// Aggressor: heuristic Bet -> Check when even the best case gain of betting is clearly negative.
pub const PIECE_BET_TO_CHECK: u8 = 8;
/// Shipped set. Only proven pieces are on.
pub const SHIPPED: u8 = 0;
thread_local! {
static OVERRIDE: Cell<Option<u8>> = const { Cell::new(None) };
}
/// Measurement hook: override the active pieces on this thread (`None` = shipped set).
pub fn set_pieces(p: Option<u8>) {
OVERRIDE.with(|c| c.set(p));
}
fn pieces() -> u8 {
OVERRIDE.with(|c| c.get()).unwrap_or(SHIPPED)
}
/// Below this confidence the module stands down entirely.
const CONFIDENCE_FLOOR: f64 = 0.25;
/// Belief box half-width at zero confidence, shrinking as `(1 - c)`.
const DELTA0: f64 = 0.30;
/// Belief box half-width that never shrinks (model misfit).
const DELTA_MIN: f64 = 0.10;
/// Required worst-case gain as a fraction of the pot.
const MARGIN: f64 = 0.04;
/// Gain (fraction of pot) at which the deviation weight saturates.
const GAIN_FULL: f64 = 0.20;
/// KL budget scale: weight cap `1 - exp(-KL_BUDGET * c)`.
const KL_BUDGET: f64 = 3.0;
/// Bet sizes (pot fractions) tried by the value-bet piece.
const SIZES: [f64; 3] = [0.33, 0.66, 1.0];
/// Villain's believed strategy for a given fold-to-bet `f` and aggression `a`; `ip` = hero acts last
/// (villain already checked, so `v_check` is "check").
fn believed(tree: &Tree, n: usize, f: f64, a: f64, pot: f64, bet: f64, ip: bool) -> Strategy {
let rank = |c: usize| if n <= 1 { 1.0 } else { c as f64 / (n - 1) as f64 };
let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 };
let bluff = (gto_bluff * a / DEFAULT_AGGRESSION).clamp(0.0, 1.0);
let base = Strategy::uniform(tree);
let s = base
.with_rows(tree, "v_bet", |c| if rank(c) >= f { vec![0.0, 1.0] } else { vec![1.0, 0.0] })
.unwrap_or(base);
s.with_rows(tree, "v_check", |c| {
let r = rank(c);
let p = if ip {
0.0
} else if r >= 0.60 {
1.0
} else if r <= 0.30 {
bluff
} else {
0.0
};
vec![1.0 - p, p]
})
.unwrap_or(s)
}
/// Hero's conditional action values (chips, relative) at `node` for bucket `hb`, hero best-responding
/// below, villain node-locked to `strat`.
fn cond_values(tree: &Tree, strat: &Strategy, node: usize, hb: usize) -> Option<Vec<f64>> {
let n = tree.classes;
let mut out = None;
root_values(tree, strat, Responder::Best, 0, &mut |v| {
if v.node == node {
let mass: f64 = (0..n).map(|o| tree.chance[hb * n + o] * v.opp[o]).sum();
if mass > 1e-12 {
out = Some(v.action_values.iter().map(|a| a[hb] / mass).collect());
}
}
});
out
}
/// (min, max) over the belief box of `value(action 1) - value(action 0)` at `node`.
#[allow(clippy::too_many_arguments)]
fn gain_range(
ladder_n: usize,
chance: &[f64],
pot: f64,
bet: f64,
node: usize,
hb: usize,
f: f64,
a: f64,
delta: f64,
ip: bool,
) -> Option<(f64, f64)> {
let tree = tree_with_chance(ladder_n, chance.to_vec(), pot, bet);
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
let pts = [(0.0, 0.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)];
for (df, da) in pts {
let strat = believed(&tree, ladder_n, (f + df * delta).clamp(0.0, 1.0), (a + da * delta).clamp(0.0, 1.0), pot, bet, ip);
let q = cond_values(&tree, &strat, node, hb)?;
let g = q.get(1)? - q.first()?;
lo = lo.min(g);
hi = hi.max(g);
}
Some((lo, hi))
}
fn weight(gain: f64, pot: f64, conf: f64) -> f64 {
let cap = 1.0 - (-KL_BUDGET * conf).exp();
(gain / (GAIN_FULL * pot)).clamp(0.0, 1.0).min(cap)
}
fn villain_checked_river(spot: &Spot) -> bool {
let Some(v) = spot.live_villains().next() else { return false };
spot.history.iter().any(|r| r.street == Street::River && r.seat == v.seat && r.action == SeenAction::Check)
}
/// Refine the (floored, vetoed) heuristic decision on the river. Identity unless a shipped/active
/// piece fires on a confident read with a worst-case-proven gain.
pub fn refine(raw: &Spot, base: Decision) -> Decision {
refine_with(raw, base, pieces())
}
/// `refine` with an explicit piece mask (`engine::read_exploit` maps its river letters onto pieces).
pub fn refine_with(raw: &Spot, base: Decision, active: u8) -> Decision {
if active == 0 || raw.street != Street::River {
return base;
}
let facing = raw.to_call > 0.0;
let relevant = match (&base.choice, facing) {
(Choice::Fold, true) => active & PIECE_PROMOTE_CALL != 0,
(Choice::Call, true) => active & PIECE_DEMOTE_CALL != 0,
(Choice::Check, false) => active & PIECE_VALUE_BET != 0,
(Choice::Raise { .. }, false) => active & PIECE_BET_TO_CHECK != 0,
_ => false,
};
if !relevant {
return base;
}
let Some((combos, profile)) = super::river_subgame::belief_combos(raw) else { return base };
let Some(profile) = profile else { return base };
let conf = profile.confidence.filter(|c| !c.is_nan()).unwrap_or(0.0);
// Measurement counterfactual (`GEGNER_BREIT_ROH`): full trust, narrowest belief box.
let conf = if super::read_exploit::raw_reads() { 1.0 } else { conf };
if conf < CONFIDENCE_FLOOR {
return base;
}
let Ok(hero) = judge(&raw.rules(), &raw.hero_cards, &raw.board) else { return base };
let Some((ladder, chance)) = super::river_subgame::ladder_chance(raw, &combos, &combos) else { return base };
let hb = ladder.partition_point(|d| *d < hero).min(ladder.len() - 1);
let n = ladder.len();
let f = profile.street_fold_to_bet[2].or(profile.fold_to_bet).filter(|x| !x.is_nan()).unwrap_or(DEFAULT_FOLD_TO_BET);
let a = profile.river_aggression.or(profile.aggression).filter(|x| !x.is_nan()).unwrap_or(DEFAULT_AGGRESSION);
let delta = (DELTA0 * (1.0 - conf)).max(DELTA_MIN);
let ip = villain_checked_river(raw);
let deviate = |choice: Choice, gain: f64, pot: f64, what: &str| -> Decision {
let w = weight(gain, pot, conf);
let (u, _) = Rng::seeded(raw.seed ^ 0xB4_5E_ED).unit();
if u < w {
Decision { choice, reason: format!("node-locked BR {what}: worst-case gain {gain:.2} (w {w:.2})"), ..base.clone() }
} else {
base.clone()
}
};
if facing {
let pot = raw.pot - raw.to_call;
if pot <= 0.0 {
return base;
}
let Some((lo, hi)) = gain_range(n, &chance, pot, raw.to_call, 4, hb, f, a, delta, false) else { return base };
match base.choice {
Choice::Fold if lo > MARGIN * pot => deviate(Choice::Call, lo, pot, "fold->call"),
Choice::Call if hi < -MARGIN * pot => deviate(Choice::Fold, -hi, pot, "call->fold"),
_ => base,
}
} else {
let pot = raw.pot;
match base.choice {
Choice::Check => {
let mut best: Option<(f64, f64)> = None; // (lo, size)
for frac in SIZES {
let target = frac * pot;
let Some(size) = candidates(raw)
.into_iter()
.filter(|t| *t > 0.0 && *t <= raw.hero_stack)
.min_by(|x, y| (x - target).abs().total_cmp(&(y - target).abs()))
else {
continue;
};
let Some((lo, _)) = gain_range(n, &chance, pot, size, 0, hb, f, a, delta, ip) else { continue };
if best.is_none_or(|(b, _)| lo > b) {
best = Some((lo, size));
}
}
match best {
Some((lo, size)) if lo > MARGIN * pot => deviate(Choice::Raise { to: size }, lo, pot, "check->bet"),
_ => base,
}
}
Choice::Raise { to } => {
let Some((_, hi)) = gain_range(n, &chance, pot, to.min(raw.hero_stack), 0, hb, f, a, delta, ip) else { return base };
if hi < -MARGIN * pot {
deviate(Choice::Check, -hi, pot, "bet->check")
} else {
base
}
}
_ => base,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn weight_is_capped_by_confidence_and_zero_without_gain() {
assert_eq!(weight(0.0, 10.0, 0.9), 0.0);
assert!(weight(100.0, 10.0, 0.3) < weight(100.0, 10.0, 0.9));
assert!(weight(100.0, 10.0, 0.9) <= 1.0 - (-KL_BUDGET * 0.9f64).exp() + 1e-12);
assert_eq!(weight(100.0, 10.0, 0.0), 0.0);
}
#[test]
fn belief_box_never_collapses() {
for c in [0.0, 0.5, 0.99] {
assert!((DELTA0 * (1.0 - c)).max(DELTA_MIN) >= DELTA_MIN);
}
}
#[test]
fn shipped_set_is_identity() {
set_pieces(None);
assert_eq!(pieces(), SHIPPED);
}
}