//! Stufe 5 of the synthetic lab: a derivative-free OPTIMIZER over the lab's objectives. //! //! The lab measures; the optimizer searches. It is a diagonal-covariance CMA evolution strategy //! (the separable CMA-ES core, Ros & Hansen 2008; constants from Hansen's 2016 tutorial, the //! covariance kept diagonal so no eigendecomposition is needed — pure, no dependencies). CMA-ES is the //! standard choice for a noisy, black-box, low-dimensional objective, which is exactly what a //! Monte-Carlo win rate over a few continuous knobs is. //! //! Two uses, one engine: //! - LAST, the polish the architecture names: tune the engine's own hyperparameters against the //! population once they are exposed as a vector. The optimizer is ready; it needs only that hook. //! - NOW, a real objective that exists today: `worst_case_opponent` searches the 6-dim ruleset space //! for the single opponent the engine does WORST against — an empirical best response in //! opponent-space, within realistic bounds. That is the tightest robustness probe there is, and it //! feeds the twin gate's defense story (`sim::twin_gate`): not "worst of six archetypes" but "worst //! of the whole continuous neighbourhood". //! //! The ES is validated on analytic functions (sphere, Rosenbrock) in the tests; the opponent search is //! deterministic in its seed (each ruleset is scored at a fixed measurement seed, so the landscape the //! ES sees is stable). use super::opponent::Opponent; use super::reader::Rules; use super::session::{measure, ReadMode, Setup}; use crate::rng::Rng; use std::thread; /// Result of a run: the best point found, its objective value, and how many evaluations it cost. #[derive(Clone, Debug)] pub struct Optimum { pub x: Vec, pub f: f64, pub evals: u32, } /// Minimize `f` from `x0` with initial step `sigma0` for `generations`, seeded by `seed`. Diagonal /// CMA-ES: samples λ points per generation, recombines the μ best, and adapts the mean, the per-axis /// step sizes and the global step. `f` may be noisy; it is called λ times per generation. The λ /// candidates of a generation are independent, so they are evaluated in PARALLEL (`f: Fn + Sync`) — /// the win rate objective is single-threaded per opponent, and this recovers the cores the population /// runs use. Sampling stays sequential, so the result is deterministic in `seed` regardless of threads. pub fn minimize f64 + Sync>( f: F, x0: &[f64], sigma0: f64, generations: u32, seed: u64, ) -> Optimum { let n = x0.len(); assert!(n >= 1, "need at least one dimension"); // --- strategy parameters (Hansen 2016 tutorial) --- let lambda = 4 + (3.0 * (n as f64).ln()).floor() as usize; let mu = lambda / 2; let mut w: Vec = (0..mu).map(|i| ((mu as f64 + 0.5).ln()) - ((i + 1) as f64).ln()).collect(); let w_sum: f64 = w.iter().sum(); w.iter_mut().for_each(|x| *x /= w_sum); let mu_eff = 1.0 / w.iter().map(|x| x * x).sum::(); let nf = n as f64; let c_sigma = (mu_eff + 2.0) / (nf + mu_eff + 5.0); let d_sigma = 1.0 + 2.0 * (0.0_f64).max(((mu_eff - 1.0) / (nf + 1.0)).sqrt() - 1.0) + c_sigma; let c_c = (4.0 + mu_eff / nf) / (nf + 4.0 + 2.0 * mu_eff / nf); let c_1 = 2.0 / ((nf + 1.3).powi(2) + mu_eff); let c_mu = (1.0 - c_1).min(2.0 * (mu_eff - 2.0 + 1.0 / mu_eff) / ((nf + 2.0).powi(2) + mu_eff)); let chi_n = nf.sqrt() * (1.0 - 1.0 / (4.0 * nf) + 1.0 / (21.0 * nf * nf)); // --- dynamic state --- let mut mean = x0.to_vec(); let mut sigma = sigma0; let mut diag = vec![1.0_f64; n]; // diagonal of C (per-axis variance) let mut p_sigma = vec![0.0_f64; n]; let mut p_c = vec![0.0_f64; n]; let mut rng = Rng::seeded(seed); let mut evals = 0u32; let (mut best_x, mut best_f) = (mean.clone(), f64::INFINITY); for gen in 0..generations { // Sample λ candidates sequentially (RNG order fixed ⇒ deterministic): x = mean + σ·sqrt(diag)⊙z. let mut cand: Vec<(Vec, Vec, Vec)> = Vec::with_capacity(lambda); // (x, z, y) for _ in 0..lambda { let mut z = vec![0.0; n]; let mut y = vec![0.0; n]; let mut x = vec![0.0; n]; for j in 0..n { let (zj, next) = gaussian(rng); rng = next; z[j] = zj; y[j] = diag[j].sqrt() * zj; x[j] = mean[j] + sigma * y[j]; } cand.push((x, z, y)); } // Evaluate the independent candidates in parallel. // At most `POKERBENCH_THREADS` at once (CLAUDE.md "Messlaeufe"); unset = all λ. The order of // the results does not depend on the chunking, so the run stays deterministic in `seed`. let width = std::env::var("POKERBENCH_THREADS").ok().and_then(|t| t.parse::().ok()).filter(|&t| t > 0).unwrap_or(lambda); let fs: Vec = cand .chunks(width) .flat_map(|chunk| { thread::scope(|s| { let handles: Vec<_> = chunk.iter().map(|(x, _, _)| s.spawn(|| f(x))).collect(); handles.into_iter().map(|h| h.join().expect("objective panicked")).collect::>() }) }) .collect(); evals += lambda as u32; // (f, z, y), tracking the best x seen. let mut pop: Vec<(f64, Vec, Vec)> = Vec::with_capacity(lambda); for ((x, z, y), fx) in cand.into_iter().zip(fs) { if fx < best_f { best_f = fx; best_x = x; } pop.push((fx, z, y)); } pop.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); // Weighted recombination of the μ best, in z- and y-space. let mut z_w = vec![0.0; n]; let mut y_w = vec![0.0; n]; for (i, wi) in w.iter().enumerate() { for j in 0..n { z_w[j] += wi * pop[i].1[j]; y_w[j] += wi * pop[i].2[j]; } } // Move the mean. for j in 0..n { mean[j] += sigma * y_w[j]; } // Step-size path and control. With diagonal C, C^{-1/2} y_w = z_w. let cs = (c_sigma * (2.0 - c_sigma) * mu_eff).sqrt(); for j in 0..n { p_sigma[j] = (1.0 - c_sigma) * p_sigma[j] + cs * z_w[j]; } let ps_norm = norm(&p_sigma); sigma *= ((c_sigma / d_sigma) * (ps_norm / chi_n - 1.0)).exp(); // Covariance path (Heaviside stall guard) and diagonal update. let denom = (1.0 - (1.0 - c_sigma).powi(2 * (gen as i32 + 1))).sqrt(); let h_sigma = if ps_norm / denom < (1.4 + 2.0 / (nf + 1.0)) * chi_n { 1.0 } else { 0.0 }; let cc = (c_c * (2.0 - c_c) * mu_eff).sqrt(); for j in 0..n { p_c[j] = (1.0 - c_c) * p_c[j] + h_sigma * cc * y_w[j]; } let delta_h = (1.0 - h_sigma) * c_c * (2.0 - c_c); for j in 0..n { let rank_mu: f64 = w.iter().enumerate().map(|(i, wi)| wi * pop[i].2[j].powi(2)).sum(); diag[j] = (1.0 - c_1 - c_mu) * diag[j] + c_1 * (p_c[j].powi(2) + delta_h * diag[j]) + c_mu * rank_mu; diag[j] = diag[j].max(1e-12); } } Optimum { x: best_x, f: best_f, evals } } /// Standard normal via Box-Muller, value-threaded through the project RNG. fn gaussian(rng: Rng) -> (f64, Rng) { let (u1, rng) = rng.unit(); let (u2, rng) = rng.unit(); let u1 = u1.max(1e-12); ((-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos(), rng) } fn norm(v: &[f64]) -> f64 { v.iter().map(|x| x * x).sum::().sqrt() } fn sigmoid(x: f64) -> f64 { 1.0 / (1.0 + (-x).exp()) } /// One realistic bound for a ruleset parameter, matching `sim::population`'s clamps. const BOUNDS: [(f64, f64); 6] = [ (0.0, 0.45), // call_margin (0.55, 0.97), // raise_at (0.45, 0.90), // bet_at (0.45, 0.85), // open_at (0.0, 0.60), // bluff (0.25, 1.30), // size ]; /// Map an unbounded search vector to a bounded `Rules` through a sigmoid per axis, so the ES searches /// freely in R^6 while every candidate is a realistic opponent. fn to_rules(x: &[f64]) -> Rules { let p = |i: usize| { let (lo, hi) = BOUNDS[i]; lo + (hi - lo) * sigmoid(x[i]) }; Rules { call_margin: p(0), raise_at: p(1), bet_at: p(2), open_at: p(3), bluff: p(4), size: p(5), } } /// The engine's luck-corrected EV (bb/100, Memory mode) against one fixed opponent ruleset, at a fixed /// measurement seed so the ES sees a stable landscape. fn engine_ev(rules: Rules, deals: u32, seed: u64) -> f64 { let setup = Setup { players: 2, opponent: Opponent::Styled(rules), deals, stack_bb: 100.0, seed, read: ReadMode::Memory, }; measure(&setup).bb_per_100 } /// The engine's worst-case individual opponent, found by the ES: the realistic ruleset that MINIMIZES /// the engine's EV. Returns the nemesis ruleset and the EV the engine makes against it (bb/100). pub fn worst_case_opponent(deals: u32, generations: u32, seed: u64) -> (Rules, f64) { let objective = |x: &[f64]| engine_ev(to_rules(x), deals, seed ^ 0xA11CE); // Start at the origin (the centre of every bounded axis) with a wide step. let opt = minimize(objective, &[0.0; 6], 1.0, generations, seed); (to_rules(&opt.x), opt.f) } #[cfg(test)] mod tests { use super::*; /// The sphere: f(x) = Σ x². The ES must drive a 4-dim sphere from a distance down near 0. #[test] fn minimizes_the_sphere() { let f = |x: &[f64]| x.iter().map(|v| v * v).sum::(); let opt = minimize(f, &[3.0, -2.5, 4.0, 1.0], 1.0, 200, 0xC0FFEE); assert!(opt.f < 1e-6, "sphere not minimized: f={:.3e}", opt.f); } /// Rosenbrock: a curved valley with the optimum at (1,1), f*=0. The classic ES stress test. /// NOTE: this is a DIAGONAL (separable) CMA-ES — it adapts a per-axis variance but not a rotation, /// so on a non-separable valley like Rosenbrock it converges into the optimum's basin but grinds /// slowly along the curved floor (the known sep-CMA-ES limitation, Ros & Hansen 2008). The test /// asserts it reaches that basin, not machine zero; the lab's objectives are low-coupling, where /// the diagonal restriction costs little and buys a dependency-free implementation. #[test] fn minimizes_rosenbrock() { let f = |x: &[f64]| { let (a, b) = (x[0], x[1]); (1.0 - a).powi(2) + 100.0 * (b - a * a).powi(2) }; let opt = minimize(f, &[-1.2, 1.0], 0.5, 800, 0xBEEF); assert!(opt.f < 2e-2, "rosenbrock basin not reached: f={:.3e} at {:?}", opt.f, opt.x); assert!((opt.x[0] - 1.0).abs() < 0.12 && (opt.x[1] - 1.0).abs() < 0.2); } /// The ES on a noisy objective still finds the region of the optimum (averaging over the /// population tolerates the noise). #[test] fn tolerates_noise() { let f = |x: &[f64]| { // sphere plus a deterministic-but-rough wobble (stands in for MC noise) let base: f64 = x.iter().map(|v| v * v).sum(); let wobble = 0.05 * (x[0] * 17.0).sin() * (x[1] * 13.0).cos(); base + wobble }; let opt = minimize(f, &[2.0, -2.0], 1.0, 300, 0xD00D); assert!(opt.f < 0.1, "noisy sphere not minimized: f={:.3e}", opt.f); } #[test] fn worst_case_opponent_runs_and_is_bounded() { // Tiny: drives the full engine per evaluation, keep small for `cargo test`. let (rules, ev) = worst_case_opponent(40, 3, 0x5EED_0001); println!("nemesis {:?} -> engine EV {:+.2} bb/100", rules, ev); assert!(ev.is_finite()); assert!((0.0..=0.45).contains(&rules.call_margin)); assert!((0.25..=1.30).contains(&rules.size)); } }