Ersetzt die irrefuehrende Oracle-Leiter durch eine ehrliche Messmethodik (Oracle aus, Read via Memory/Posterior gegen eine gezogene Gegner-Population). Stufen: - 0 Exploitation-Luecke: +18.98 bb/100 gegen die gezogene Population - 1 Kalibrierung an echte HUD-Daten (lesen/kalibrierung.py) - 2 Zwillings-Tor (EGTA + Exploitability-Waechter): Offense +43.95, Boden gto -36.25 (verliert gegen Balancierte - die Oracle-verdeckte Wurzel) - 3 Adaptive Liga L0-L3 (reaktiv / modellierend / Liga) - 4 Sim-to-Real: HUD-Gap (sim::simreal) + Outcome-Abgleich (lesen/liveabgleich.py): real -266.75 vs Sim +43.95 => Gap -311; A/B-Pipeline + Runbook fertig, nur der geldechte Live-Lauf unter beiden Armen bleibt offen - 5 Optimizer (Diagonal-CMA-ES, parallel): Nemesis -414.81 bb/100 Befunde und Architektur in docs/notizen/. Lab-Tests gruen (Rust lib 92/0, python liveabgleich/kalibrierung/gegnersignal gruen). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
361 lines
16 KiB
Rust
361 lines
16 KiB
Rust
//! Stufe 3 of the synthetic lab: ADAPTIVE opponents — the mind-game frontier.
|
||
//!
|
||
//! The static population (`sim::population`, Stufe 0) measures exploitation: the engine infers a
|
||
//! *fixed* hidden type and attacks it. But a real opponent is a moving target — they watch the hero
|
||
//! and shift. That is where image, sequencing and mind-games live, and the fixed-bot ladder (and even
|
||
//! the static population) cannot touch it.
|
||
//!
|
||
//! Here the opponent carries a running model of the hero (`HeroModel`: the hero's observed postflop
|
||
//! aggression) and re-derives its own ruleset every hand (`adapt`), played through the
|
||
//! `Opponent::Styled(Rules)` seam built in Stufe 0 — so NO table change is needed, the opponent is
|
||
//! just handed a fresh `Rules` each hand. Two reaction styles bracket the realistic human responses to
|
||
//! an aggressor:
|
||
//!
|
||
//! - `Tighten`: gives the aggressor no action — needs a stronger hand to call, bluffs less. A good
|
||
//! engine should *increase* its bluffing against this (they fold too much).
|
||
//! - `Loosen`: the hero-caller — suspects bluffs and calls down lighter. A good engine should bluff
|
||
//! *less* and value-bet thinner against this.
|
||
//!
|
||
//! The measurement is paired: the SAME drawn opponent and the SAME deals are played once with the
|
||
//! opponent `Static` (the Stufe-0 memory baseline) and once `adapt`ing. The per-deal difference,
|
||
//! pooled over the field, is the bb/100 the opponent's adaptation costs (or, if negative for the
|
||
//! opponent, earns) the engine — i.e. how much the engine's *stationary* read is worth against a
|
||
//! *moving* target. A negative delta is the mind-game tax the engine pays for not tracking the shift;
|
||
//! a positive delta means the opponent's reaction opens a leak the engine already exploits.
|
||
|
||
use super::memory::SessionMemory;
|
||
use super::opponent::Opponent;
|
||
use super::paired::compare;
|
||
use super::population::Population;
|
||
use super::reader::Rules;
|
||
use super::sequential::ConfSeq;
|
||
use super::table::{deal, play_hand_history, HandRead, HandSetup, TableCost};
|
||
use crate::game::Street;
|
||
use crate::rng::Rng;
|
||
use std::thread;
|
||
|
||
const STACK_BB: f64 = 100.0;
|
||
const PLAYERS: u8 = 2;
|
||
|
||
/// Hands the opponent watches before it starts adapting: an early, noisy read of the hero would
|
||
/// swing the ruleset on nothing. Matches the spirit of the engine's own `memory::WARMUP_HANDS`.
|
||
const ADAPT_WARMUP: u32 = 20;
|
||
/// The hero aggression the base ruleset is tuned for; the opponent reacts to the deviation from it.
|
||
const REF_AGGRESSION: f64 = 0.30;
|
||
/// How hard the opponent swings its calling threshold per unit of excess hero aggression.
|
||
const ADAPT_GAIN: f64 = 0.7;
|
||
|
||
/// How a league opponent reacts to the hero it observes.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Adapt {
|
||
/// Ignores the hero entirely — the Stufe-0 behaviour, the paired control (league L0).
|
||
Static,
|
||
/// L1 reactive: tightens against an aggressive hero on the raw frequency — raises its calling bar,
|
||
/// bluffs less ("he's a maniac, give him nothing").
|
||
Tighten,
|
||
/// L1 reactive: loosens against an aggressive hero on the raw frequency — calls down lighter to
|
||
/// catch bluffs ("he bluffs too much").
|
||
Loosen,
|
||
/// L2 modelling: keeps a Beta posterior over the hero's bluff rate and counters only by how much a
|
||
/// one-sigma LOWER confidence bound exceeds the reference. Against a balanced or thinly-sampled hero
|
||
/// the posterior is wide, the lower bound stays near the reference, and it does not overadjust —
|
||
/// the Bayesian answer to L1's twitchiness, and the opponent-side mirror of the engine's own
|
||
/// confidence-gated exploitation.
|
||
Model,
|
||
}
|
||
|
||
impl Adapt {
|
||
pub fn name(self) -> &'static str {
|
||
match self {
|
||
Adapt::Static => "static",
|
||
Adapt::Tighten => "tighten",
|
||
Adapt::Loosen => "loosen",
|
||
Adapt::Model => "model",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The opponent's running model of the hero: postflop aggressive vs passive action counts.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||
pub struct HeroModel {
|
||
aggressive: u32,
|
||
passive: u32,
|
||
}
|
||
|
||
impl HeroModel {
|
||
pub fn new() -> Self {
|
||
Self::default()
|
||
}
|
||
|
||
/// Fold the hero's postflop actions of one finished hand into the model. `hero_seat` is 1-based,
|
||
/// matching `ActionRecord::seat`.
|
||
pub fn observe(&mut self, history: &[crate::game::ActionRecord], hero_seat: u8) {
|
||
for r in history.iter().filter(|r| r.seat == hero_seat && r.street != Street::Preflop) {
|
||
if r.action.is_aggressive() {
|
||
self.aggressive += 1;
|
||
} else if matches!(r.action, crate::game::SeenAction::Call | crate::game::SeenAction::Check)
|
||
{
|
||
self.passive += 1;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Observed postflop aggression frequency, or the neutral reference before any postflop action.
|
||
pub fn aggression(&self) -> f64 {
|
||
let n = self.aggressive + self.passive;
|
||
if n == 0 {
|
||
REF_AGGRESSION
|
||
} else {
|
||
self.aggressive as f64 / n as f64
|
||
}
|
||
}
|
||
|
||
/// One-sigma LOWER confidence bound on the hero's bluff (aggression) rate under a Beta(1+aggr,
|
||
/// 1+passive) posterior: mean − sqrt(variance). Wide (thin or balanced) posteriors pull this toward
|
||
/// the prior, so a counter gated on it does not overreact to noise. Used by `Adapt::Model` (L2).
|
||
pub fn bluff_lcb(&self) -> f64 {
|
||
let a = 1.0 + self.aggressive as f64;
|
||
let b = 1.0 + self.passive as f64;
|
||
let s = a + b;
|
||
let mean = a / s;
|
||
let var = a * b / (s * s * (s + 1.0));
|
||
(mean - var.sqrt()).max(0.0)
|
||
}
|
||
|
||
pub fn actions_seen(&self) -> u32 {
|
||
self.aggressive + self.passive
|
||
}
|
||
}
|
||
|
||
/// Re-derive the opponent's ruleset for the next hand from its model of the hero. `Static` and the
|
||
/// warmup both return `base` unchanged, so a `Static` run reproduces the Stufe-0 memory baseline
|
||
/// exactly. Only *excess* aggression (above the reference) moves the thresholds — a passive hero gets
|
||
/// the base ruleset either way.
|
||
pub fn adapt(base: Rules, model: &HeroModel, style: Adapt) -> Rules {
|
||
if style == Adapt::Static || model.actions_seen() < ADAPT_WARMUP {
|
||
return base;
|
||
}
|
||
let excess = (model.aggression() - REF_AGGRESSION).max(0.0);
|
||
let mut r = base;
|
||
match style {
|
||
Adapt::Static => {}
|
||
Adapt::Tighten => {
|
||
r.call_margin = (base.call_margin + ADAPT_GAIN * excess).clamp(0.0, 0.6);
|
||
r.bluff = (base.bluff - 0.5 * ADAPT_GAIN * excess).clamp(0.0, 1.0);
|
||
}
|
||
Adapt::Loosen => {
|
||
r.call_margin = (base.call_margin - ADAPT_GAIN * excess).clamp(0.0, 0.6);
|
||
}
|
||
Adapt::Model => {
|
||
// Beta(1+aggr, 1+passive) posterior over the hero's bluff rate; counter by the one-sigma
|
||
// LOWER bound's excess over the reference, so uncertainty (a wide posterior) yields no
|
||
// move and only a confidently-high bluff rate loosens the calling bar.
|
||
let lcb_excess = (model.bluff_lcb() - REF_AGGRESSION).max(0.0);
|
||
r.call_margin = (base.call_margin - ADAPT_GAIN * lcb_excess).clamp(0.0, 0.6);
|
||
}
|
||
}
|
||
r
|
||
}
|
||
|
||
fn mix(seed: u64, n: u64) -> u64 {
|
||
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
|
||
}
|
||
|
||
/// Play one heads-up session against ONE drawn opponent, threading the hero's read (`SessionMemory`,
|
||
/// the real inference path) and the opponent's model of the hero across every hand, duplicating each
|
||
/// deal over both seats so position and card luck cancel within a sample. Returns the per-deal
|
||
/// luck-corrected hero result in bb. With `Adapt::Static` this is exactly the Stufe-0 memory run.
|
||
pub fn session_samples(base: Rules, deals: u32, seed: u64, style: Adapt) -> Vec<f64> {
|
||
let mut hero_mem = SessionMemory::new();
|
||
let mut hero_model = HeroModel::new();
|
||
let mut samples = Vec::with_capacity(deals as usize);
|
||
for d in 0..deals {
|
||
let (cards, _) = deal(PLAYERS as usize, Rng::seeded(mix(seed, d as u64)));
|
||
let mut sum = 0.0;
|
||
for hero_seat in 1..=PLAYERS {
|
||
let rules = adapt(base, &hero_model, style);
|
||
let hand = HandSetup {
|
||
deal: &cards,
|
||
hero_seat,
|
||
opponent: Opponent::Styled(rules),
|
||
stack_bb: STACK_BB,
|
||
// The hero infers the opponent from its own observed actions, same as memory mode.
|
||
read: HandRead::Given(hero_mem.read()),
|
||
seed: mix(seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
|
||
};
|
||
let (r, history) = play_hand_history(&hand, TableCost::FREE);
|
||
sum += r.hero_net - r.luck;
|
||
hero_mem.observe_hand(&history, hero_seat as usize - 1, PLAYERS as usize);
|
||
hero_model.observe(&history, hero_seat);
|
||
}
|
||
samples.push(sum / PLAYERS as f64);
|
||
}
|
||
samples
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
pub struct AdaptReport {
|
||
pub style: &'static str,
|
||
pub opponents: usize,
|
||
pub deals_each: u32,
|
||
/// Engine win rate against the field with the opponent static (the Stufe-0 memory baseline).
|
||
pub static_bb_per_100: f64,
|
||
/// Engine win rate against the field with the opponent adapting to the hero.
|
||
pub adaptive_bb_per_100: f64,
|
||
/// adaptive - static, pooled and paired over the SAME deals (card luck cancels). The mind-game
|
||
/// effect on the engine's edge: negative = the engine's stationary read bleeds against the shift.
|
||
pub delta_bb_per_100: f64,
|
||
/// Paired 95 % half width of the delta (`sim::paired`).
|
||
pub ci95: f64,
|
||
/// Anytime 95 % half width of the delta (`sim::sequential`) — valid under peeking.
|
||
pub anytime_ci95: f64,
|
||
}
|
||
|
||
struct One {
|
||
stat: Vec<f64>,
|
||
adap: Vec<f64>,
|
||
}
|
||
|
||
fn run_one(pop: &Population, k: usize, deals: u32, seed: u64, style: Adapt) -> One {
|
||
let (draw, _) = pop.sample(Rng::seeded(seed ^ (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)));
|
||
let base = draw.rules;
|
||
let hand_seed = seed ^ (k as u64).wrapping_mul(0xD1B5_4A32_D192_ED03);
|
||
One {
|
||
stat: session_samples(base, deals, hand_seed, Adapt::Static),
|
||
adap: session_samples(base, deals, hand_seed, style),
|
||
}
|
||
}
|
||
|
||
/// Measure how much an `adapt`ing field changes the engine's edge versus the same field held static.
|
||
/// Deterministic in `seed`; threaded over opponents.
|
||
pub fn adaptive_effect(
|
||
pop: &Population,
|
||
opponents: usize,
|
||
deals: u32,
|
||
seed: u64,
|
||
style: Adapt,
|
||
) -> AdaptReport {
|
||
let results: Vec<One> = thread::scope(|scope| {
|
||
let handles: Vec<_> = (0..opponents)
|
||
.map(|k| scope.spawn(move || run_one(pop, k, deals, seed, style)))
|
||
.collect();
|
||
handles.into_iter().map(|h| h.join().expect("an opponent panicked")).collect()
|
||
});
|
||
|
||
let mut stat_all = Vec::new();
|
||
let mut adap_all = Vec::new();
|
||
let mut cs = ConfSeq::new(0.05, (opponents as u64 * deals as u64).max(1));
|
||
for one in &results {
|
||
for (s, a) in one.stat.iter().zip(&one.adap) {
|
||
stat_all.push(*s);
|
||
adap_all.push(*a);
|
||
cs.push(a - s);
|
||
}
|
||
}
|
||
let cmp = compare(&stat_all, &adap_all).expect("non-empty paired diffs");
|
||
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len().max(1) as f64;
|
||
AdaptReport {
|
||
style: style.name(),
|
||
opponents,
|
||
deals_each: deals,
|
||
static_bb_per_100: mean(&stat_all),
|
||
adaptive_bb_per_100: mean(&adap_all),
|
||
delta_bb_per_100: cmp.delta_bb_per_100,
|
||
ci95: cmp.ci95,
|
||
anytime_ci95: 100.0 * cs.radius(),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn hero_model_counts_postflop_aggression() {
|
||
use crate::game::{ActionRecord, SeenAction};
|
||
let h = |street, seat, action| ActionRecord { street, seat, action, amount: None };
|
||
let history = vec![
|
||
h(Street::Preflop, 1, SeenAction::Raise), // preflop ignored
|
||
h(Street::Flop, 1, SeenAction::Bet), // aggressive
|
||
h(Street::Turn, 1, SeenAction::Check), // passive
|
||
h(Street::River, 1, SeenAction::Bet), // aggressive
|
||
h(Street::Flop, 2, SeenAction::Call), // other seat, ignored for hero_seat 1
|
||
];
|
||
let mut m = HeroModel::new();
|
||
m.observe(&history, 1);
|
||
assert_eq!(m.actions_seen(), 3);
|
||
assert!((m.aggression() - 2.0 / 3.0).abs() < 1e-9);
|
||
}
|
||
|
||
#[test]
|
||
fn adapt_is_identity_when_static_or_in_warmup() {
|
||
let base = crate::sim::reader::Style::Reg.rules();
|
||
let mut model = HeroModel::new();
|
||
model.aggressive = 100;
|
||
model.passive = 0; // hyper-aggressive, but...
|
||
// static always returns base
|
||
assert_eq!(adapt(base, &model, Adapt::Static), base);
|
||
// a fresh model is in warmup -> base even under Tighten
|
||
let fresh = HeroModel::new();
|
||
assert_eq!(adapt(base, &fresh, Adapt::Tighten), base);
|
||
}
|
||
|
||
#[test]
|
||
fn tighten_raises_the_calling_bar_against_an_aggressor() {
|
||
let base = crate::sim::reader::Style::Reg.rules();
|
||
let mut model = HeroModel::new();
|
||
model.aggressive = 80;
|
||
model.passive = 20; // 0.8 aggression, well above the 0.30 reference
|
||
let t = adapt(base, &model, Adapt::Tighten);
|
||
assert!(t.call_margin > base.call_margin, "tighten should fold more");
|
||
assert!(t.bluff <= base.bluff, "tighten should bluff no more");
|
||
let l = adapt(base, &model, Adapt::Loosen);
|
||
assert!(l.call_margin < base.call_margin, "loosen should call lighter");
|
||
}
|
||
|
||
#[test]
|
||
fn a_passive_hero_leaves_the_ruleset_at_base() {
|
||
let base = crate::sim::reader::Style::Reg.rules();
|
||
let mut model = HeroModel::new();
|
||
model.aggressive = 5;
|
||
model.passive = 95; // below the reference -> no excess -> no change
|
||
assert_eq!(adapt(base, &model, Adapt::Tighten), base);
|
||
}
|
||
|
||
#[test]
|
||
fn l2_model_waits_for_confidence_before_it_counters() {
|
||
// Same 70 % bluff FREQUENCY, two sample sizes. L1 (Tighten/Loosen) reacts to the frequency
|
||
// regardless; L2 (Model) gates on the posterior's lower bound, so the thin sample must not move
|
||
// the ruleset while the thick one does.
|
||
let base = crate::sim::reader::Style::Reg.rules();
|
||
let mut thin = HeroModel::new();
|
||
thin.aggressive = 21; // past the warmup, but a wide posterior
|
||
thin.passive = 9;
|
||
let mut thick = HeroModel::new();
|
||
thick.aggressive = 210; // same 0.70 mean, a tight posterior
|
||
thick.passive = 90;
|
||
assert!((thin.aggression() - thick.aggression()).abs() < 1e-9, "same frequency");
|
||
|
||
// L1 loosens on both (frequency-driven).
|
||
assert!(adapt(base, &thin, Adapt::Loosen).call_margin < base.call_margin);
|
||
assert!(adapt(base, &thick, Adapt::Loosen).call_margin < base.call_margin);
|
||
|
||
// L2 counters harder when confident: the thick sample loosens strictly more than the thin one.
|
||
let thin_cm = adapt(base, &thin, Adapt::Model).call_margin;
|
||
let thick_cm = adapt(base, &thick, Adapt::Model).call_margin;
|
||
assert!(thick_cm < thin_cm, "confident over-bluff must loosen more: thin={thin_cm:.3} thick={thick_cm:.3}");
|
||
assert!(thick_cm < base.call_margin, "confident over-bluff must loosen below base");
|
||
}
|
||
|
||
#[test]
|
||
fn effect_runs_and_is_finite() {
|
||
let pop = Population::micro();
|
||
let r = adaptive_effect(&pop, 4, 25, 0x5EED_0001, Adapt::Tighten);
|
||
println!(
|
||
"static {:+.1} adaptive {:+.1} delta {:+.2} +-{:.2} (anytime +-{:.2})",
|
||
r.static_bb_per_100, r.adaptive_bb_per_100, r.delta_bb_per_100, r.ci95, r.anytime_ci95
|
||
);
|
||
assert!(r.delta_bb_per_100.is_finite() && r.ci95.is_finite());
|
||
}
|
||
}
|