Files
pokerfreak/src/sim/twin_gate.rs
T
mmintelandClaude Opus 4.8 1492fb6a38 Synthetik-Labor: Population, Zwillings-Tor, adaptive Liga, Optimizer, Sim-to-Real
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>
2026-11-11 09:57:32 +01:00

334 lines
13 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Stufe 2 of the synthetic lab: the TWIN GATE — the accept/reject rule that replaces the bb/100
//! ladder.
//!
//! The ladder asked one question: does the win rate against five fixed bots go up? That is blind to
//! both of the things that matter for a real exploiter — it hides the exploitation signal (oracle read
//! handed over, `BEFUND-exploitation-luecke-population`) and it never checks that a win came from sound
//! play rather than from overfitting a bot (a balanced opponent would punish the overfit, but the
//! ladder's bots never best-respond).
//!
//! The twin gate makes "never ship a loser" rigorous and multi-axis. A change may ship only if it
//! clears THREE axes at once:
//!
//! 1. OFFENSE — population EV. The engine's Memory-mode win rate against a drawn population
//! (`sim::exploit_pop`): it must still exploit a varied field.
//! 2. ROBUSTNESS FLOOR — a tiny EGTA. A population adversary best-responds by picking the single
//! archetype the engine does worst against (linear ⇒ the min over archetypes is the worst mix).
//! The engine's EV against that worst archetype is the floor: no change may lower it. This is the
//! axis that catches a fix that crushes fish but bleeds against the balanced player.
//! 3. DEFENSE CAP — river exploitability. An exact best-response distance on a fixed battery of river
//! subgames (`sim::exploit_river`): no change may raise it. This is the axis that catches a change
//! that buys EV against the field by playing an exploitable, unbalanced strategy.
//!
//! `TwinReport` carries all three for one engine build; `Gate::passes` is the pure comparator between a
//! baseline build and a candidate, with per-axis tolerances. The river battery is a FIXED, hand-built
//! set of canonical polar spots — not all of poker, but the same probe applied to baseline and
//! candidate, which is what a regression gate needs.
use super::exploit_pop::exploitation_gap;
use super::exploit_river::{exploitability_river, RiverSpec};
use super::opponent::Opponent;
use super::population::Population;
use super::reader::Style;
use super::session::{measure, ReadMode, Setup};
use crate::card::Card;
const STACK_BB: f64 = 100.0;
/// The archetypes the robustness floor scans: the four threshold styles plus the two balanced range
/// players. The balanced pair is the point of the floor — an exploiter that overfits the threshold
/// bots gets punished here.
const ARCHETYPES: [Style; 6] =
[Style::Reg, Style::Nit, Style::Maniac, Style::Fish, Style::Gto, Style::GtoSmall];
#[derive(Clone, Debug)]
pub struct TwinReport {
// --- offense ---
/// Engine Memory-mode win rate against the drawn population, bb/100.
pub population_ev_bb_per_100: f64,
/// memory − blind against the population (the exploitation the read earns), bb/100.
pub exploitation_gap_bb_per_100: f64,
// --- robustness floor (EGTA worst archetype) ---
pub worst_archetype: String,
/// Engine EV against the single worst archetype — the population adversary's best response.
pub worst_ev_bb_per_100: f64,
pub worst_ci95: f64,
/// Every archetype's (name, ev bb/100, ci95), for the full picture.
pub archetypes: Vec<(String, f64, f64)>,
// --- defense cap (river exploitability) ---
/// Mean exact exploitability over the river battery, bb/100 (≥ 0, 0 = unexploitable there).
pub mean_exploitability_bb_per_100: f64,
/// The worst single subgame's exploitability, bb/100.
pub max_exploitability_bb_per_100: f64,
pub subgames: usize,
}
/// Per-axis tolerances for the gate: a candidate may give up at most this much on each axis before it
/// is a "loser". All in bb/100.
#[derive(Clone, Copy, Debug)]
pub struct Gate {
pub ev_tol: f64,
pub floor_tol: f64,
pub exploit_tol: f64,
}
impl Default for Gate {
fn default() -> Self {
// Noise-sized slack: a change inside the measurement CI is not a real loss, but anything
// beyond it on any axis is.
Gate { ev_tol: 2.0, floor_tol: 2.0, exploit_tol: 1.0 }
}
}
impl Gate {
/// The accept rule: the candidate ships only if it loses no axis beyond tolerance — population EV
/// holds, the worst-archetype floor holds, and exploitability does not rise.
pub fn passes(&self, baseline: &TwinReport, candidate: &TwinReport) -> bool {
candidate.population_ev_bb_per_100 >= baseline.population_ev_bb_per_100 - self.ev_tol
&& candidate.worst_ev_bb_per_100 >= baseline.worst_ev_bb_per_100 - self.floor_tol
&& candidate.mean_exploitability_bb_per_100
<= baseline.mean_exploitability_bb_per_100 + self.exploit_tol
}
/// Which axes a candidate fails against a baseline (empty = passes), for a readable verdict.
pub fn failures(&self, baseline: &TwinReport, candidate: &TwinReport) -> Vec<&'static str> {
let mut f = Vec::new();
if candidate.population_ev_bb_per_100 < baseline.population_ev_bb_per_100 - self.ev_tol {
f.push("population-EV");
}
if candidate.worst_ev_bb_per_100 < baseline.worst_ev_bb_per_100 - self.floor_tol {
f.push("robustness-floor");
}
if candidate.mean_exploitability_bb_per_100
> baseline.mean_exploitability_bb_per_100 + self.exploit_tol
{
f.push("exploitability");
}
f
}
}
/// The engine's EV (luck-corrected, bb/100, with 95 % half width) against one archetype, Memory mode
/// — the realistic deployed read, not the handed-over oracle.
fn archetype_ev(style: Style, deals: u32, seed: u64) -> (f64, f64) {
let setup = Setup {
players: 2,
opponent: Opponent::Reader(style),
deals,
stack_bb: STACK_BB,
seed,
read: ReadMode::Memory,
};
let m = measure(&setup);
(m.bb_per_100, m.ci95)
}
/// A canonical river spot with owned cards, so a battery of them can be built and borrowed.
struct OwnedSpot {
board: Vec<Card>,
hero: Vec<Vec<Card>>,
villain: Vec<Vec<Card>>,
pot: f64,
bet: f64,
}
fn combos(list: &[&str]) -> Vec<Vec<Card>> {
list.iter().map(|s| Card::parse_list(s).expect("valid combo")).collect()
}
/// A fixed battery of canonical polar river spots: hero holds nuts + air, villain holds bluff-catchers,
/// across dry / wet / paired textures. Fixed by design — the same probe for baseline and candidate.
fn battery() -> Vec<OwnedSpot> {
let b = |s: &str| Card::parse_list(s).expect("valid board");
vec![
// Dry ace-high: polar hero, villain caps at second pair.
OwnedSpot {
board: b("Ah Kd 7c 2s 9h"),
hero: combos(&["Ac Qc", "Ad Jd", "5d 4d", "6c 5c"]),
villain: combos(&["Kh Qs", "7h 7d", "Th 9s", "Qd Jh"]),
pot: 6.0,
bet: 4.5,
},
// Wet, connected: straights and flushes live, villain has one-pair / weak made hands.
OwnedSpot {
board: b("9h 8h 5c 2d Qs"),
hero: combos(&["Jh Th", "Qh Jc", "7c 6c", "Ah 4h"]),
villain: combos(&["9c 9d", "8d 8c", "Kh Qd", "Th 9s"]),
pot: 8.0,
bet: 6.0,
},
// Paired board: full houses and trips vs under-pairs.
OwnedSpot {
board: b("Kc Ks 6h 6d 2c"),
hero: combos(&["Kh Qd", "6c 5s", "Ah Jh", "9c 8c"]),
villain: combos(&["Qh Qd", "Jc Js", "Ts 9d", "Ad Tc"]),
pot: 5.0,
bet: 3.5,
},
// Monotone flush board: made flushes vs non-flush strong hands.
OwnedSpot {
board: b("Qd 9d 4d 7s 2d"),
hero: combos(&["Ad Kc", "Kd Jh", "Ts Tc", "8c 7c"]),
villain: combos(&["Qh Jc", "9c 9s", "Jd Th", "Ac Ah"]),
pot: 7.0,
bet: 5.0,
},
// Low disconnected: overpairs vs air, a thin-value texture.
OwnedSpot {
board: b("8c 5h 3d Ts 2c"),
hero: combos(&["Ah As", "Td 9d", "Kc Qc", "7h 6h"]),
villain: combos(&["9c 9h", "Jd Jc", "Ac Kd", "6s 4s"]),
pot: 4.0,
bet: 3.0,
},
]
}
/// Mean and max exact river exploitability over the fixed battery, bb/100, and how many subgames were
/// non-degenerate.
fn river_exploitability(iters: u32, seed: u64) -> (f64, f64, usize) {
let spots = battery();
let mut vals = Vec::new();
for s in &spots {
let spec = RiverSpec {
board: &s.board,
hero_range: &s.hero,
villain_range: &s.villain,
villain_profile: None,
pot: s.pot,
bet: s.bet,
};
if let Some(r) = exploitability_river(&spec, iters, seed) {
vals.push(r.exploitability.max(0.0));
}
}
let n = vals.len();
let mean = if n == 0 { 0.0 } else { vals.iter().sum::<f64>() / n as f64 };
let max = vals.iter().cloned().fold(0.0_f64, f64::max);
(mean, max, n)
}
/// How much work each axis does. Keep the ladder-scale defaults for a real run; the tests use tiny ones.
#[derive(Clone, Copy, Debug)]
pub struct TwinBudget {
pub pop_opponents: usize,
pub pop_deals: u32,
pub archetype_deals: u32,
pub river_iters: u32,
}
impl Default for TwinBudget {
fn default() -> Self {
TwinBudget { pop_opponents: 48, pop_deals: 400, archetype_deals: 4000, river_iters: 12_000 }
}
}
/// Evaluate one engine build on all three axes. Deterministic in `seed`.
pub fn evaluate(pop: &Population, budget: TwinBudget, seed: u64) -> TwinReport {
let gap = exploitation_gap(pop, budget.pop_opponents, budget.pop_deals, seed);
let mut archetypes = Vec::new();
let (mut worst_archetype, mut worst_ev, mut worst_ci) = (String::new(), f64::INFINITY, 0.0);
for (i, style) in ARCHETYPES.iter().enumerate() {
let (ev, ci) = archetype_ev(*style, budget.archetype_deals, seed ^ (i as u64 + 1));
archetypes.push((style.name().to_string(), ev, ci));
if ev < worst_ev {
worst_ev = ev;
worst_ci = ci;
worst_archetype = style.name().to_string();
}
}
let (mean_expl, max_expl, subgames) = river_exploitability(budget.river_iters, seed);
TwinReport {
population_ev_bb_per_100: gap.memory_bb_per_100,
exploitation_gap_bb_per_100: gap.gap_bb_per_100,
worst_archetype,
worst_ev_bb_per_100: worst_ev,
worst_ci95: worst_ci,
archetypes,
mean_exploitability_bb_per_100: mean_expl,
max_exploitability_bb_per_100: max_expl,
subgames,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn evaluate_fills_all_three_axes() {
// Tiny budget: this drives the full engine on every axis, so keep it small for `cargo test`.
let pop = Population::micro();
let budget = TwinBudget {
pop_opponents: 3,
pop_deals: 20,
archetype_deals: 60,
river_iters: 2_000,
};
let r = evaluate(&pop, budget, 0x5EED_0001);
println!(
"pop-EV {:+.1} gap {:+.1} | worst {} {:+.1}±{:.1} | expl mean {:.2} max {:.2} ({} spots)",
r.population_ev_bb_per_100,
r.exploitation_gap_bb_per_100,
r.worst_archetype,
r.worst_ev_bb_per_100,
r.worst_ci95,
r.mean_exploitability_bb_per_100,
r.max_exploitability_bb_per_100,
r.subgames,
);
assert!(r.population_ev_bb_per_100.is_finite());
assert_eq!(r.archetypes.len(), 6);
assert!(r.worst_ev_bb_per_100.is_finite() && r.worst_ev_bb_per_100 <= f64::INFINITY);
assert!(r.mean_exploitability_bb_per_100 >= 0.0);
assert!(r.subgames >= 1);
}
fn report(pop_ev: f64, floor: f64, expl: f64) -> TwinReport {
TwinReport {
population_ev_bb_per_100: pop_ev,
exploitation_gap_bb_per_100: 0.0,
worst_archetype: "gto".into(),
worst_ev_bb_per_100: floor,
worst_ci95: 0.0,
archetypes: vec![],
mean_exploitability_bb_per_100: expl,
max_exploitability_bb_per_100: expl,
subgames: 5,
}
}
#[test]
fn the_gate_accepts_a_strict_improvement_and_rejects_each_regression() {
let gate = Gate::default();
let base = report(40.0, -3.0, 5.0);
// Better on every axis -> passes, no failures.
let better = report(45.0, 0.0, 3.0);
assert!(gate.passes(&base, &better));
assert!(gate.failures(&base, &better).is_empty());
// Within tolerance everywhere -> still passes (noise is not a loss).
let noise = report(39.0, -4.0, 5.5);
assert!(gate.passes(&base, &noise));
// Loses population EV beyond tolerance -> fails on that axis only.
let ev_loss = report(30.0, 0.0, 3.0);
assert!(!gate.passes(&base, &ev_loss));
assert_eq!(gate.failures(&base, &ev_loss), vec!["population-EV"]);
// Buys EV but bleeds the balanced floor -> fails the floor (the overfit catcher).
let overfit = report(60.0, -8.0, 3.0);
assert!(!gate.passes(&base, &overfit));
assert_eq!(gate.failures(&base, &overfit), vec!["robustness-floor"]);
// Buys EV by playing exploitably -> fails the defense cap.
let exploitable = report(60.0, 0.0, 9.0);
assert!(!gate.passes(&base, &exploitable));
assert_eq!(gate.failures(&base, &exploitable), vec!["exploitability"]);
}
}