WIP (pausiert, ungemessen): node-locked River-Best-Response (river_br.rs) + br_ladder
Gestoppt auf Owner-Wunsch. SHIPPED=0 (bit-identisch). Stuecke D1/D2/O1/O2 noch nicht auf 4000 Deals gemessen; Smoke 300 Deals: kein Profil signifikant. Unit-Tests ungeprueft. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
//! Paired, luck-corrected ladder for the node-locked river best response (`engine::river_br`).
|
||||
//! Base = shipped set (river fold-veto + per-street fold read), candidate = `pieces`. Each profile
|
||||
//! runs in its own thread (the piece switch is thread-local) on the SAME deals, Memory read.
|
||||
//!
|
||||
//! Run: `br_ladder <pieces-bitmask> [deals] [seed-hex]` (pieces: 1 promote, 2 demote, 4 value, 8 bet->check)
|
||||
|
||||
use rechner::engine::river_br::set_pieces;
|
||||
use rechner::sim::opponent::Opponent;
|
||||
use rechner::sim::paired::compare;
|
||||
use rechner::sim::reader::{Rules, Style};
|
||||
use rechner::sim::session::{deal_samples, ReadMode, Setup};
|
||||
|
||||
const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 };
|
||||
const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 };
|
||||
const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 };
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
let pieces: u8 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||
let deals: u32 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4000);
|
||||
let seed: u64 =
|
||||
a.get(3).and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok()).unwrap_or(0x5EED_0001);
|
||||
let profiles: Vec<(&str, Opponent)> = vec![
|
||||
("station", Opponent::CallingStation),
|
||||
("fish", Opponent::Reader(Style::Fish)),
|
||||
("reg", Opponent::Reader(Style::Reg)),
|
||||
("nit", Opponent::Reader(Style::Nit)),
|
||||
("maniac", Opponent::Reader(Style::Maniac)),
|
||||
("nemesis-1", Opponent::Styled(N1)),
|
||||
("nemesis-2", Opponent::Styled(N2)),
|
||||
("nemesis-3", Opponent::Styled(N3)),
|
||||
];
|
||||
println!("pieces={pieces} deals={deals} seed={seed:#x}");
|
||||
let handles: Vec<_> = profiles
|
||||
.into_iter()
|
||||
.map(|(name, opp)| {
|
||||
std::thread::spawn(move || {
|
||||
let setup = Setup { players: 2, opponent: opp, deals, stack_bb: 100.0, seed, read: ReadMode::Memory };
|
||||
set_pieces(None);
|
||||
let (base, mb) = deal_samples(&setup);
|
||||
set_pieces(Some(pieces));
|
||||
let (cand, mc) = deal_samples(&setup);
|
||||
let c = compare(&base, &cand).expect("same deals");
|
||||
format!(
|
||||
"{name:<10} base {:>+8.2} cand {:>+8.2} delta {:>+7.2} +-{:>6.2} changed {:>4} {:?}",
|
||||
mb.bb_per_100, mc.bb_per_100, c.delta_bb_per_100, c.ci95, c.changed_deals, c.verdict
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for h in handles {
|
||||
println!("{}", h.join().expect("thread"));
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,10 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D
|
||||
// the offline/value-function form, not a live fold-veto. The turn solver + per-street belief
|
||||
// stay as tested primitives. See BEFUND-stage-b-turn-river-solver.md.
|
||||
if premium <= 0.0 {
|
||||
return super::river_subgame::fold_veto(raw, floored);
|
||||
let vetoed = super::river_subgame::fold_veto(raw, floored);
|
||||
// Node-locked trust-region best response (Pillar 3): deviates from the heuristic only
|
||||
// on a confident read with a worst-case-proven gain; identity unless pieces are on.
|
||||
return super::river_br::refine(raw, vetoed);
|
||||
}
|
||||
floored
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod read_gate;
|
||||
pub mod range_combos;
|
||||
pub mod range_filter;
|
||||
pub mod read_label;
|
||||
pub mod river_br;
|
||||
pub mod river_subgame;
|
||||
pub mod run_twice;
|
||||
pub mod semibluff;
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! 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::exploit::profile::Profile;
|
||||
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 {
|
||||
let active = pieces();
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,16 @@ impl Subgame {
|
||||
/// plays actually be unexploitable; the coarse symmetric-uniform first cut was not, and measured
|
||||
/// worse than the heuristic. `None` for fewer than two distinct strengths.
|
||||
fn subgame(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], pot: f64, bet: f64) -> Option<Subgame> {
|
||||
let (ladder, chance) = ladder_chance(spot, hero_combos, villain_combos)?;
|
||||
let tree = tree_with_chance(ladder.len(), chance, pot, bet);
|
||||
let solved = solve(&tree, ITERS, Rng::seeded(spot.seed));
|
||||
Some(Subgame { tree, solved, ladder })
|
||||
}
|
||||
|
||||
/// The shared strength ladder and the card-exact joint deal table (no solve): what `subgame` builds
|
||||
/// its tree from, and what the node-locked best response (`engine::river_br`) reuses to evaluate hero
|
||||
/// against a fixed villain without paying for a CFR solve.
|
||||
pub(crate) fn ladder_chance(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>]) -> Option<(Vec<Strength>, Vec<f64>)> {
|
||||
let rules = spot.rules();
|
||||
let judged = |combos: &[Vec<Card>]| -> Vec<(Vec<Card>, Strength)> {
|
||||
combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s))).collect()
|
||||
@@ -167,9 +177,7 @@ fn subgame(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>],
|
||||
return None;
|
||||
}
|
||||
chance.iter_mut().for_each(|x| *x /= total);
|
||||
let tree = tree_with_chance(n, chance, pot, bet);
|
||||
let solved = solve(&tree, ITERS, Rng::seeded(spot.seed));
|
||||
Some(Subgame { tree, solved, ladder })
|
||||
Some((ladder, chance))
|
||||
}
|
||||
|
||||
/// The believed villain strategy over the river tree, read off the opponent's `Profile`: how this
|
||||
@@ -406,6 +414,12 @@ pub fn river_mix(spot: &Spot) -> Option<RiverPlan> {
|
||||
/// thin read. `None` outside the v1 slice or below the confidence floor, so the caller keeps the
|
||||
/// heuristic.
|
||||
pub fn river_exploit_mix(spot: &Spot) -> Option<RiverPlan> {
|
||||
let (list, profile) = belief_combos(spot)?;
|
||||
river_exploit_plan(spot, &list, profile.as_ref())
|
||||
}
|
||||
|
||||
/// The villain's believed river range (raw, ungated read) and his profile; heads-up river only.
|
||||
pub(crate) fn belief_combos(spot: &Spot) -> Option<(Vec<Vec<Card>>, Option<Profile>)> {
|
||||
if spot.street != Street::River {
|
||||
return None;
|
||||
}
|
||||
@@ -413,7 +427,7 @@ pub fn river_exploit_mix(spot: &Spot) -> Option<RiverPlan> {
|
||||
return None;
|
||||
}
|
||||
let villain = spot.live_villains().next()?;
|
||||
let profile = villain.profile.as_ref();
|
||||
let profile = villain.profile;
|
||||
let rules = spot.rules();
|
||||
let filter = crate::engine::range_filter::range_filter(
|
||||
&crate::exploit::range_model::range_spec(spot, villain),
|
||||
@@ -423,7 +437,7 @@ pub fn river_exploit_mix(spot: &Spot) -> Option<RiverPlan> {
|
||||
);
|
||||
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
|
||||
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
|
||||
river_exploit_plan(spot, &list, profile)
|
||||
Some((list, profile))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user