From 7df143589c37620ff1cf6c0dca72dd4119642a4c Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Fri, 4 Dec 2026 16:01:40 +0100 Subject: [PATCH] score: reference solver (exact heads-up, rake, perturbed game), sharingan-referenz binary, node values Q(h,a), value against the perfect opponent after each root action, menu mapping and loss in Python with specs Co-Authored-By: Claude Opus 5.5 --- score/messung.py | 82 +++++++ score/test_messung.py | 55 +++++ sharingan-1/search/src/lib.rs | 1 + sharingan-1/search/src/policy.rs | 29 +++ sharingan-1/search/src/referenz.rs | 155 ++++++++++++ sharingan-1/search/src/solver.rs | 2 +- sharingan-1/search/src/vector.rs | 224 +++++++++++++++++- sharingan-1/search/tests/exploit.rs | 34 +++ .../serve/src/bin/sharingan-referenz.rs | 134 +++++++++++ sharingan-1/serve/src/decide.rs | 57 +++++ 10 files changed, 769 insertions(+), 4 deletions(-) create mode 100644 score/messung.py create mode 100644 score/test_messung.py create mode 100644 sharingan-1/search/src/referenz.rs create mode 100644 sharingan-1/serve/src/bin/sharingan-referenz.rs diff --git a/score/messung.py b/score/messung.py new file mode 100644 index 00000000..c50bca3d --- /dev/null +++ b/score/messung.py @@ -0,0 +1,82 @@ +"""Pure parts of the score: map an answer of a version onto the reference menu, and the loss against the frozen reference. + +Reference file of a spot (written by `sharingan-referenz`): `actions` (fold / check / call / raise with `to`, `frac` = raise size as a +fraction of the pot after calling, `all_in`), `hands` [{c, w, q: [chips per action], sigma}], `pot`, `to_call`, `cur_bet`, `max_raise_to`. +Loss of a version at a spot (chips): sum_h w(h) * ( max_a Q(h,a) - sum_a pi(a|h) Q(h,a) ), where pi is the version's mixture over the menu. +""" +JAM_SHARE = 0.97 # a raise of at least this share of the largest legal raise is the all-in +CHIPS_PER_BB = 100 + + +def harmonic(fracs, f): + """Pseudo-harmonic mapping (Ganzfried/Sandholm) of the pot fraction `f` onto the sorted fractions `fracs`: {index: probability}.""" + if f <= fracs[0]: + return {0: 1.0} + if f >= fracs[-1]: + return {len(fracs) - 1: 1.0} + j = max(i for i, x in enumerate(fracs) if x <= f) + a, b = fracs[j], fracs[j + 1] + if f == a: + return {j: 1.0} + pa = (b - f) * (1 + a) / ((b - a) * (1 + f)) + return {j: pa, j + 1: 1.0 - pa} + + +def round_half_up(x): + import math + return int(math.floor(x + 0.5)) + + +def map_answer(ref, answer, big_blind): + """-> ({action index: probability}, distance in pot fractions or None). `answer` = {action, size} of the motor, size in money.""" + acts = ref["actions"] + idx = {k: [i for i, a in enumerate(acts) if a["kind"] == k] for k in ("fold", "check", "call", "raise")} + passive = (idx["check"] or idx["call"])[0] + kind = answer.get("action") + if kind == "FOLD": + return ({idx["fold"][0]: 1.0} if idx["fold"] else {passive: 1.0}), None + if kind in ("CHECK", "CALL"): + return {passive: 1.0}, None + raises = idx["raise"] + if kind not in ("RAISE", "BET", "ALL_IN") or not raises: + return {passive: 1.0}, None + jam = [i for i in raises if acts[i].get("all_in")] + to = None if kind == "ALL_IN" else round_half_up(answer["size"] / big_blind * CHIPS_PER_BB) + if kind == "ALL_IN" or to >= JAM_SHARE * ref["max_raise_to"]: + return {(jam or raises)[-1]: 1.0}, 0.0 + basis = ref["pot"] + ref["to_call"] + f = (to - ref["cur_bet"]) / basis + fracs = [acts[i]["frac"] for i in raises] + m = harmonic(fracs, f) + dist = min(abs(f - x) for x in fracs) + return {raises[j]: p for j, p in m.items()}, dist + + +def mixture(ref, answers, big_blind): + """Empirical mixture over the menu from the answers of several seeds: ({index: p}, mean distance).""" + pi, dist, nd = {}, 0.0, 0 + for a in answers: + m, d = map_answer(ref, a, big_blind) + for i, p in m.items(): + pi[i] = pi.get(i, 0.0) + p / len(answers) + if d is not None: + dist += d + nd += 1 + return pi, (dist / nd if nd else None) + + +def loss_chips(ref, pi_of_hand): + """Loss of a version at one spot, chips: `pi_of_hand[c]` = {action index: p} for hand string `c`; hands without answer count as full loss-free? + No: a missing hand is an error (raises KeyError) so that a gap never counts as zero.""" + total = 0.0 + for h in ref["hands"]: + pi = pi_of_hand[h["c"]] + best = max(h["q"]) + total += h["w"] * (best - sum(p * h["q"][i] for i, p in pi.items())) + return total + + +def reference_loss_chips(ref): + """Loss of the reference's own root strategy: the noise floor of the score at this spot (0 for an exact equilibrium).""" + pi = {h["c"]: {i: p for i, p in enumerate(h["sigma"])} for h in ref["hands"]} + return loss_chips(ref, pi) diff --git a/score/test_messung.py b/score/test_messung.py new file mode 100644 index 00000000..a8bb7975 --- /dev/null +++ b/score/test_messung.py @@ -0,0 +1,55 @@ +"""Spec of the mapping and the loss (python3 -m unittest score/test_messung.py).""" +import os, sys, unittest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import messung as M + +REF = {"pot": 200, "to_call": 0, "cur_bet": 0, "max_raise_to": 1000, + "actions": [{"kind": "check"}, {"kind": "raise", "to": 100, "frac": 0.5}, {"kind": "raise", "to": 200, "frac": 1.0}, + {"kind": "raise", "to": 1000, "frac": 5.0, "all_in": True}], + "hands": [{"c": "AsKs", "w": 0.25, "q": [10.0, 30.0, 20.0, 0.0], "sigma": [0.0, 1.0, 0.0, 0.0]}, + {"c": "7c2d", "w": 0.75, "q": [-5.0, -9.0, -20.0, -50.0], "sigma": [1.0, 0.0, 0.0, 0.0]}]} + + +class Messung(unittest.TestCase): + def test_harmonic_between_two_sizes_hand_computed(self): + m = M.harmonic([0.5, 1.0], 0.75) # pA = (1-.75)*1.5 / (.5*1.75) + self.assertAlmostEqual(m[0], 0.375 / 0.875) + self.assertAlmostEqual(m[1], 1 - 0.375 / 0.875) + + def test_harmonic_on_a_size_and_outside_the_grid(self): + self.assertEqual(M.harmonic([0.5, 1.0], 0.5), {0: 1.0}) + self.assertEqual(M.harmonic([0.5, 1.0], 0.2), {0: 1.0}) + self.assertEqual(M.harmonic([0.5, 1.0], 3.0), {1: 1.0}) + + def test_answers_map_onto_the_menu(self): + self.assertEqual(M.map_answer(REF, {"action": "CHECK"}, 0.02), ({0: 1.0}, None)) + m, d = M.map_answer(REF, {"action": "RAISE", "size": 0.02}, 0.02) # 100 chips = 0.5 pot: on the menu + self.assertEqual(m, {1: 1.0}) + self.assertAlmostEqual(d, 0.0) + m, d = M.map_answer(REF, {"action": "RAISE", "size": 0.03}, 0.02) # 150 chips = 0.75 pot + self.assertAlmostEqual(m[1], 0.375 / 0.875) + self.assertAlmostEqual(d, 0.25) + m, d = M.map_answer(REF, {"action": "RAISE", "size": 0.2}, 0.02) # 1000 chips = the jam + self.assertEqual(m, {3: 1.0}) + + def test_fold_without_fold_option_is_the_passive_action(self): + self.assertEqual(M.map_answer(REF, {"action": "FOLD"}, 0.02)[0], {0: 1.0}) + + def test_loss_is_zero_for_the_best_action_and_weighted(self): + best = {"AsKs": {1: 1.0}, "7c2d": {0: 1.0}} + self.assertAlmostEqual(M.loss_chips(REF, best), 0.0) + # always check: AsKs loses 20 (30-10), 7c2d loses 0: 0.25 * 20 + self.assertAlmostEqual(M.loss_chips(REF, {"AsKs": {0: 1.0}, "7c2d": {0: 1.0}}), 5.0) + # a mixture: AsKs 50/50 between 30 and 20 loses 5 + self.assertAlmostEqual(M.loss_chips(REF, {"AsKs": {1: 0.5, 2: 0.5}, "7c2d": {0: 1.0}}), 0.25 * 5.0) + + def test_a_missing_hand_is_an_error_not_a_zero(self): + with self.assertRaises(KeyError): + M.loss_chips(REF, {"AsKs": {1: 1.0}}) + + def test_reference_noise_floor(self): + self.assertAlmostEqual(M.reference_loss_chips(REF), 0.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/sharingan-1/search/src/lib.rs b/sharingan-1/search/src/lib.rs index a9c60109..8474c4ed 100644 --- a/sharingan-1/search/src/lib.rs +++ b/sharingan-1/search/src/lib.rs @@ -4,6 +4,7 @@ pub mod beliefs; pub mod bp; pub mod exploit; pub mod policy; +pub mod referenz; pub mod rundenspeicher; pub mod solver; pub mod table; diff --git a/sharingan-1/search/src/policy.rs b/sharingan-1/search/src/policy.rs index f47a3e02..d1dee5de 100644 --- a/sharingan-1/search/src/policy.rs +++ b/sharingan-1/search/src/policy.rs @@ -133,6 +133,19 @@ impl PolicyFactory for SearchPolicy { } } +/// The decision to be valued by the score's reference (see `SearchPlayer::reference_context`). +pub struct RefContext { + pub root: State, + /// State at the decision (after the in-round actions). + pub node: State, + pub board: Vec, + pub beliefs: Arc, + pub hero_seat: usize, + pub hole: Option<[Card; 2]>, + /// `(seat, action)` of the betting round so far, in order. + pub in_round: Vec<(usize, Action)>, +} + #[derive(Clone)] struct Ev { seat: usize, @@ -239,6 +252,22 @@ impl SearchPlayer { pub fn searches_run(&self) -> u64 { self.n_searches } + /// Everything the score's reference solver needs to rebuild the current decision as an exact heads-up game: the round root, the + /// board, the beliefs at the root, and the actions taken in this round up to now (`state` is the node after them). + pub fn reference_context(&self) -> Option { + if self.root.is_terminal() || self.root.street() == Street::Preflop { + return None; + } + Some(RefContext { + root: self.root, + node: self.state, + board: self.board.clone(), + beliefs: self.root_beliefs.clone(), + hero_seat: self.seat, + hole: self.hole, + in_round: self.events.iter().map(|e| (e.seat, e.action)).collect(), + }) + } /// Root state and blueprint history of the current betting round, and the board so far. pub fn round_root(&self) -> (State, Shadow, &[Card]) { (self.root, self.root_sh, &self.board) diff --git a/sharingan-1/search/src/referenz.rs b/sharingan-1/search/src/referenz.rs new file mode 100644 index 00000000..0c36c03b --- /dev/null +++ b/sharingan-1/search/src/referenz.rs @@ -0,0 +1,155 @@ +//! Reference of the score: the exact heads-up solution from a recorded decision to the end of the hand, with rake, frozen once per spot +//! and independent of the version being scored. +//! +//! The game is the betting round of the decision (root = start of the round) with a rich action menu, solved to the end of the hand +//! (later streets: `later`) by the vector solver in the perturbed game (`VecParams::floor`), so that every action of every node +//! keeps a positive reach and the values of actions the equilibrium never plays are meaningful. The ranges at the root come from +//! the replay (`SearchPlayer::reference_context`), exactly as in `sharingan-teilspiel`. The off-menu bets and raises that were really +//! made in the round are added to the tree (`extras`), so the node of the decision is reached exactly. +//! +//! Output (`node_values`): for the decision node and every hero hand `h` with positive reach: the probability `w(h)` that the hero +//! holds `h` there, and `Q(h, a)` in chips, the value of each action `a` when both sides continue with the solution. +use crate::policy::RefContext; +use crate::tree::{search_actions, step_path, Extras}; +use crate::vector::{exploitability, node_values, solve_vec, NodeValues, VecGame, VecParams, VecSolution, Bucketing}; +use crate::beliefs::hole_mask; +use nlhe::abstraction::{ActionList, BetSizing, Menu}; +use nlhe::{Action, RakeRule, Step}; + +pub struct RefParams { + pub iters: u64, + pub floor: f64, + pub rake: Option, + pub big_blind: i32, + pub sizing: BetSizing, + pub later: BetSizing, + pub max_bytes: usize, + pub max_millis: Option, + /// Also measure the exploitability of the reference itself (extra passes). + pub measure: bool, + pub seed: u64, +} + +/// A version's mixture at the decision: `hand string -> probability per menu action`. +pub type Profile = std::collections::HashMap>; + +/// Value of a profile against the perfect opponent (see `vector::perfect_values`): per hand `ev[h]` = sum_a pi(a|h) QBR(h,a), and the +/// total over the hands' probabilities; `None` when the best-response policies did not fit. +pub struct ProfileEv { + pub name: String, + pub ev: Option, + pub ev_hand: Vec, + /// `qbr[a][h]`, `None` per action that did not fit. + pub qbr: Vec>>, +} + +pub struct RefResult { + pub profiles: Vec, + pub node: NodeValues, + pub hero: usize, + pub iters: u64, + pub solve_ms: f64, + pub bytes: usize, + /// Sum of both players' best-response gains against the reference, chips (its own accuracy). + pub exploit_chips: Option, + pub rake_chips_cap: i32, +} + +static NONE_FROZEN: std::sync::OnceLock> = std::sync::OnceLock::new(); + +fn game<'a>(ctx: &'a RefContext, seats: [usize; 2], extras: &'a Extras, p: &'a RefParams, rake: nlhe::Rake, pooled: Option<&'a dyn Bucketing>) -> VecGame<'a> { + let bm = cards::mask_of(&ctx.board); + let ranges = seats.map(|s| ctx.beliefs.w[s].iter().enumerate().map(|(i, &x)| if hole_mask(i) & bm == 0 { x as f64 } else { 0.0 }).collect::>()); + VecGame { + root: ctx.root, + board: &ctx.board, + seats, + ranges, + sizing: &p.sizing, + later: &p.later, + extras, + me: None, + my_hole: None, + frozen: NONE_FROZEN.get_or_init(std::collections::HashMap::new), + pooled, + rake, + } +} + +/// Off-menu actions really taken this round, as extras of the nodes they were taken at. +fn round_extras(ctx: &RefContext, sizing: &BetSizing) -> Extras { + let mut ex = Extras::new(); + let (mut st, mut key) = (ctx.root, 0u64); + for &(_, a) in &ctx.in_round { + if let Action::RaiseTo(t) = a { + let mut list = ActionList::new(); + search_actions(&st, sizing, ex.get(&key).map_or(&[], |v| v.as_slice()), &mut list); + if !list.as_slice().contains(&a) { + ex.entry(key).or_default().push(t); + } + } + if !matches!(st.apply(a), Step::Continue) { + break; + } + key = step_path(key, a); + } + ex +} + +/// `pooled`: later streets pooled by these buckets (approximation, far less memory); `None` = exact per hand. +pub fn solve_reference(ctx: &RefContext, p: &RefParams, pooled: Option<&dyn Bucketing>, profiles: &[(String, Profile)]) -> Result { + let seats = VecGame::live_seats(&ctx.root).ok_or("not heads-up at the round root")?; + let hero = seats.iter().position(|&s| s == ctx.hero_seat).ok_or("hero is not live")?; + let rake = match &p.rake { + None => nlhe::Rake::NONE, + Some(r) => r.in_chips(ctx.root.num_players(), p.big_blind)?, + }; + let extras = round_extras(ctx, &p.sizing); + let g = game(ctx, seats, &extras, p, rake, pooled); + let vp = VecParams { iters: p.iters, max_millis: p.max_millis, plus: true, stratify: true, seed: p.seed, keep_all: true, max_bytes: p.max_bytes, floor: p.floor }; + let sol: VecSolution = solve_vec(&g, &vp); + let strat = sol.strategy(true, pooled); + let path: Vec = ctx.in_round.iter().map(|x| x.1).collect(); + let node = node_values(&g, &strat, &path, hero).ok_or("the decision is not a node of the reference tree (action missing from the menu, or not the hero's turn)")?; + let hl = crate::beliefs::holes(); + let names: Vec = node.holes.iter().map(|&i| cards::cards_str(&hl[i as usize])).collect(); + let n_act = node.actions.len(); + let mut evs = Vec::new(); + // always evaluated: the reference mixture itself ("gg") and the calling station (never fold, never raise: check, else call) + let passive = node.actions.iter().position(|a| matches!(a, Action::Check | Action::Call)).unwrap_or(0); + let station: Profile = names.iter().map(|c| (c.clone(), (0..n_act).map(|a| (a == passive) as u8 as f64).collect())).collect(); + let mut all: Vec<(String, Profile)> = vec![("gg".into(), Profile::new()), ("station".into(), station)]; + all.extend(profiles.iter().cloned()); + for (name, prof) in &all { + // pi[a][h] over the compact hands; a hand the profile does not know plays the reference mixture + let pi: Vec> = (0..n_act).map(|a| names.iter().enumerate().map(|(h, c)| prof.get(c).map_or(node.sigma[a][h], |v| v[a])).collect()).collect(); + let qbr = crate::vector::perfect_values(&g, &strat, &path, hero, &pi, p.max_bytes).ok_or("perfect_values: node not reachable")?; + let complete = qbr.iter().all(|x| x.is_some()); + let ev_hand: Vec = (0..names.len()).map(|h| (0..n_act).map(|a| qbr[a].as_ref().map_or(0.0, |v| pi[a][h] * v[h])).sum()).collect(); + let ev = complete.then(|| (0..names.len()).map(|h| node.w[h] * ev_hand[h]).sum()); + evs.push(ProfileEv { name: name.clone(), ev, ev_hand, qbr }); + } + let exploit_chips = p.measure.then(|| { + let (e, _) = exploitability(&g, &strat); + 2.0 * e + }); + Ok(RefResult { profiles: evs, node, hero, iters: sol.iters, solve_ms: sol.millis, bytes: sol.peak_bytes, exploit_chips, rake_chips_cap: rake.cap }) +} + +/// The action menus of the reference by name: `(root round, later rounds)`. `reich`: a fine grid on the round of the decision, so that the +/// sizes of every version map close (pseudo-harmonic) onto it; `mittel`: the coarse menu of the live service. +pub fn reference_sizing(name: &str) -> Option<(BetSizing, BetSizing)> { + let m = Menu::new; + let all = |d: &[Menu], max: u8| BetSizing::new([d, d, d, d], [max; 4]); + Some(match name { + "reich" => ( + all(&[m(&[0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.5], true), m(&[0.5, 1.0, 1.75], true), m(&[1.0], true)], 4), + all(&[m(&[0.33, 0.66, 1.0], true), m(&[1.0], true), m(&[], true)], 3), + ), + "mittel" => ( + all(&[m(&[0.33, 0.66, 1.0], true), m(&[1.0], true), m(&[], true)], 3), + all(&[m(&[1.0], true), m(&[], true)], 3), + ), + _ => return None, + }) +} diff --git a/sharingan-1/search/src/solver.rs b/sharingan-1/search/src/solver.rs index 6d4c08b1..787ffe8c 100644 --- a/sharingan-1/search/src/solver.rs +++ b/sharingan-1/search/src/solver.rs @@ -435,7 +435,7 @@ fn solve_vector(sg: &Subgame, seats: [usize; 2], start: Instant) -> Solution { rake: nlhe::Rake::NONE, }; let iters = p.vec_iters[(root.street().idx() - 1).min(2)]; - let vp = VecParams { iters, max_millis: p.max_millis, plus: p.vec_plus, stratify: true, seed: sg.seed, keep_all: p.vec_keep_all, max_bytes: 2 << 30 }; + let vp = VecParams { iters, max_millis: p.max_millis, plus: p.vec_plus, stratify: true, seed: sg.seed, keep_all: p.vec_keep_all, max_bytes: 2 << 30, floor: 0.0 }; let vs = solve_vec(&g, &vp); Solution { table: Table::new(1, 8), diff --git a/sharingan-1/search/src/vector.rs b/sharingan-1/search/src/vector.rs index c2ba5f06..95767ac2 100644 --- a/sharingan-1/search/src/vector.rs +++ b/sharingan-1/search/src/vector.rs @@ -235,6 +235,11 @@ struct Core<'a> { bk_cache: HashMap<(u64, u8), Rc>>, /// Root belief per player over the compact hands (regret weights of pooled infosets). w: [Vec; 2], + /// When set, `br` records at every node of the best-responding player the best action per hand (key: `vkey`). + pol: Option>>, + /// Policy storage cap in bytes (entries x hands) and whether it was hit. + pol_cap: usize, + pol_over: bool, } impl<'a> Core<'a> { @@ -245,6 +250,9 @@ impl<'a> Core<'a> { Core { g, w, + pol: None, + pol_cap: usize::MAX, + pol_over: false, bk_cache: HashMap::new(), hands, board: g.board.to_vec(), @@ -487,11 +495,15 @@ pub struct VecParams { pub keep_all: bool, /// Stop the solve (keeping the passes done) once node storage exceeds this many bytes. pub max_bytes: usize, + /// Perturbed game (trembling hand): every strategy used in the traversal is `(1-floor) * sigma + floor / n`, so every action + /// of every node keeps a positive reach and the opponent's continuation after an action the equilibrium never plays is still + /// trained (needed for the value of off-equilibrium root actions, `node_values`). 0 = the plain solve. + pub floor: f64, } impl Default for VecParams { fn default() -> Self { - VecParams { iters: 300, max_millis: None, plus: false, stratify: true, seed: 1, keep_all: false, max_bytes: 3 << 30 } + VecParams { iters: 300, max_millis: None, plus: false, stratify: true, seed: 1, keep_all: false, max_bytes: 3 << 30, floor: 0.0 } } } @@ -502,6 +514,7 @@ struct Solver<'a> { plus: bool, frozen_m: Option, bytes: usize, + floor: f64, } pub fn solve_vec(g: &VecGame, p: &VecParams) -> VecSolution { @@ -511,7 +524,7 @@ pub fn solve_vec(g: &VecGame, p: &VecParams) -> VecSolution { u32::MAX => None, m => Some(m as usize), }); - let mut sv = Solver { core, nodes: HashMap::new(), t: 0.0, plus: p.plus, frozen_m, bytes: 0 }; + let mut sv = Solver { core, nodes: HashMap::new(), t: 0.0, plus: p.plus, frozen_m, bytes: 0, floor: p.floor }; let r0: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[0][i as usize]).collect(); let r1: Vec = sv.core.hands.idx.iter().map(|&i| g.ranges[1][i as usize]).collect(); let root = g.root; @@ -580,9 +593,13 @@ impl<'a> Solver<'a> { } } let uni = 1.0 / n as f64; + let fl = self.floor; for a in 0..n { for ((s, &r), &t) in sigb[a * width..(a + 1) * width].iter_mut().zip(&node.reg[a * width..(a + 1) * width]).zip(&tot) { *s = if t > 0.0 { r.max(0.0) / t } else { uni }; + if fl > 0.0 { + *s = (1.0 - fl) * *s + fl * uni; + } } } let mut sig = if let Some(bk) = &bk { @@ -853,6 +870,7 @@ impl<'a> Core<'a> { } let dummy = vec![0.0; m]; let mut best = vec![f64::NEG_INFINITY; m]; + let mut arg: Vec = if actor == p && play_br && self.pol.is_some() { vec![0; m] } else { vec![] }; let mut sum = vec![0.0; m]; for a in 0..n { let act = list.get(a); @@ -890,7 +908,12 @@ impl<'a> Core<'a> { self.path.pop(); if actor == p && play_br { for h in 0..m { - best[h] = best[h].max(c[h]); + if c[h] > best[h] { + best[h] = c[h]; + if !arg.is_empty() { + arg[h] = a as u8; + } + } } } else if actor == p { for h in 0..m { @@ -903,11 +926,206 @@ impl<'a> Core<'a> { } } if actor == p && play_br { + if !arg.is_empty() { + if let Some(pol) = self.pol.as_mut() { + if pol.len().saturating_mul(m) < self.pol_cap { + pol.insert(vkey, arg); + } else { + self.pol_over = true; + } + } + } best } else { sum } } + + /// Counterfactual value vector (player `p`, weighted by `opp`) of taking `act` at `st`. + #[allow(clippy::too_many_arguments)] + fn child_cfv(&mut self, st: &State, akey: u64, vkey: u64, act: Action, p: usize, opp: &[f64], s: &dyn Strat, play_br: bool) -> Vec { + let m = self.hands.len(); + let q = 1 - p; + let dummy = vec![0.0; m]; + let mut s2 = *st; + let step = s2.apply(act); + let akey2 = step_path(akey, act); + let vkey2 = step_path(vkey, act); + self.path.push(act); + let c = match step { + Step::Terminal => { + let mut reach: [&[f64]; 2] = [&dummy, &dummy]; + reach[q] = opp; + let mut v = self.terminal(&s2, reach, vkey2); + std::mem::take(&mut v[p]) + } + Step::NewStreet(_) => { + let mut acc = vec![0.0; m]; + for (cd, w) in self.deal(vkey2) { + let nrm = self.masked(opp, cd); + self.board.push(cd); + let mut v = self.br(s2, akey2, mix(vkey2, cd as u64 + 1), p, &nrm, s, play_br); + self.board.pop(); + for &h in &self.hands.by_card[cd as usize] { + v[h as usize] = 0.0; + } + for i in 0..m { + acc[i] += w * v[i]; + } + } + acc + } + Step::Continue => self.br(s2, akey2, vkey2, p, opp, s, play_br), + }; + self.path.pop(); + c + } } pub const _MAX: usize = MAX_ACTIONS; + +/// Values of the actions at one decision node of the hero (`p`) under the profile `s` (both sides follow `s` after the node): the +/// reference of the score. `path` = actions from the game's root to the node (inside the root round). +pub struct NodeValues { + pub actions: Vec, + /// Hole index (0..1326) of each compact hand. + pub holes: Vec, + /// Probability of each hand being the hero's hand at the node: reach (under `s`) times compatible opponent mass, normalised. + pub w: Vec, + /// `q[a][h]`: chips (relative to the start of the hand, rake included) the hand wins on average with action `a`, then `s` for both. + pub q: Vec>, + /// The hero's strategy at the node under `s`, `sigma[a][h]`. + pub sigma: Vec>, + pub pot: i32, + pub call_amount: i32, + pub cur_bet: i32, +} + +/// The node of the decision reached through `path` under `s`, with the reach of both players there. +struct Descent<'a> { + core: Core<'a>, + st: State, + akey: u64, + vkey: u64, + r: [Vec; 2], + list: ActionList, + sig: Vec, +} + +fn descend<'a>(g: &'a VecGame<'a>, s: &dyn Strat, path: &[Action], p: usize) -> Option> { + let mut core = Core::new(g, 0, true, false); + let m = core.hands.len(); + let mut r: [Vec; 2] = [0, 1].map(|x| core.hands.idx.iter().map(|&i| g.ranges[x][i as usize]).collect()); + let (mut st, mut akey, mut vkey) = (g.root, 0u64, 0u64); + let strat_at = |core: &mut Core, st: &State, akey: u64, vkey: u64, n: usize, seat: usize| -> Vec { + let mut sig = vec![0.0f64; n * m]; + let board = core.board.clone(); + let hands = std::mem::replace(&mut core.hands, Hands { idx: vec![], cards: vec![], of_hole: vec![], by_card: vec![] }); + let qy = Query { akey, vkey, street: st.street(), board: &board, seat, hands: &hands, st, path: &core.path }; + s.probs(&qy, n, &mut sig); + core.hands = hands; + sig + }; + for &a in path { + let seat = st.to_act()?; + let actor = core.player_of(seat); + let mut list = ActionList::new(); + core.actions(&st, akey, &mut list); + let n = list.len(); + let k = list.as_slice().iter().position(|x| *x == a)?; + let sig = strat_at(&mut core, &st, akey, vkey, n, seat); + for h in 0..m { + r[actor][h] *= sig[k * m + h]; + } + if !matches!(st.apply(a), Step::Continue) { + return None; + } + akey = step_path(akey, a); + vkey = step_path(vkey, a); + core.path.push(a); + } + let seat = st.to_act()?; + if core.player_of(seat) != p { + return None; + } + let mut list = ActionList::new(); + core.actions(&st, akey, &mut list); + let sig = strat_at(&mut core, &st, akey, vkey, list.len(), seat); + Some(Descent { core, st, akey, vkey, r, list, sig }) +} + +/// `None` when `path` does not lie in the tree of `g` (an action missing from the menu, a street change) or the node is not the hero's. +pub fn node_values(g: &VecGame, s: &dyn Strat, path: &[Action], p: usize) -> Option { + let Descent { mut core, st, akey, vkey, r, list, sig } = descend(g, s, path, p)?; + let m = core.hands.len(); + let q = 1 - p; + let n = list.len(); + let comp = compat(&core.hands, &r[q]); + let mut qv = Vec::with_capacity(n); + for a in 0..n { + let c = core.child_cfv(&st, akey, vkey, list.get(a), p, &r[q], s, false); + qv.push((0..m).map(|h| if comp[h] > 0.0 { c[h] / comp[h] } else { 0.0 }).collect::>()); + } + let z: f64 = (0..m).map(|h| r[p][h] * comp[h]).sum(); + let w: Vec = (0..m).map(|h| r[p][h] * comp[h] / z).collect(); + let sigma: Vec> = (0..n).map(|a| sig[a * m..(a + 1) * m].to_vec()).collect(); + let l = st.legal(); + Some(NodeValues { actions: list.as_slice().to_vec(), holes: core.hands.idx.clone(), w, q: qv, sigma, pot: st.pot(), call_amount: l.call_amount, cur_bet: st.cur_bet() }) +} + +/// Opponent nodes play their recorded best response, everything else follows `hero`. +struct PolStrat<'a> { + hero: &'a dyn Strat, + pol: HashMap>, +} + +impl Strat for PolStrat<'_> { + fn probs(&self, q: &Query, n: usize, out: &mut [f64]) { + match self.pol.get(&q.vkey) { + Some(pv) => { + let m = q.hands.len(); + for a in 0..n { + for h in 0..m { + out[a * m + h] = (pv[h] as usize == a) as u8 as f64; + } + } + } + None => self.hero.probs(q, n, out), + } + } +} + +/// Value of the hero's root actions against the PERFECT opponent: after action `a` the opponent plays an exact best response in the +/// subgame to the hero's range after `a` (`reach * pi[a]`, `pi[a][h]` = the version's probability of `a` with hand `h`, over the compact +/// hands), the hero continues with the frozen `s`. Returns `[a][h]` chips like `NodeValues::q`, plus the number of stored policy entries. +/// `max_policy_bytes`: `None` is returned for an action whose best-response policy would not fit. +pub fn perfect_values(g: &VecGame, s: &dyn Strat, path: &[Action], p: usize, pi: &[Vec], max_policy_bytes: usize) -> Option>>> { + let Descent { mut core, st, akey, vkey, r, list, .. } = descend(g, s, path, p)?; + let m = core.hands.len(); + let q = 1 - p; + let comp = compat(&core.hands, &r[q]); + let mut out = Vec::with_capacity(list.len()); + for a in 0..list.len() { + let act = list.get(a); + let reach_a: Vec = (0..m).map(|h| r[p][h] * pi[a][h]).collect(); + if reach_a.iter().sum::() <= 0.0 { + out.push(Some(vec![0.0; m])); + continue; + } + // 1. the opponent's best response to the hero's range after `a`, recorded + core.pol = Some(HashMap::new()); + core.pol_cap = max_policy_bytes; + core.pol_over = false; + let _ = core.child_cfv(&st, akey, vkey, act, q, &reach_a, s, true); + let pol = core.pol.take().unwrap(); + if core.pol_over { + out.push(None); + continue; + } + // 2. what the hero's hands win against that policy + let strat = PolStrat { hero: s, pol }; + let c = core.child_cfv(&st, akey, vkey, act, p, &r[q], &strat, false); + out.push(Some((0..m).map(|h| if comp[h] > 0.0 { c[h] / comp[h] } else { 0.0 }).collect())); + } + Some(out) +} diff --git a/sharingan-1/search/tests/exploit.rs b/sharingan-1/search/tests/exploit.rs index 764707ad..45eb1c5b 100644 --- a/sharingan-1/search/tests/exploit.rs +++ b/sharingan-1/search/tests/exploit.rs @@ -323,3 +323,37 @@ fn with_a_rake_the_gain_sum_is_still_nonnegative_and_matches_the_profile_values( // values add up to the pot minus the expected rake, strictly less than without assert!(rep.value[0] + rep.value[1] < rep.dead - 1e-9); } + +// ---- value against the perfect opponent (root best response) ---------------------------------------------------------------- + +#[test] +fn perfect_opponent_value_of_the_reference_mixture_and_of_a_shifted_mixture() { + use search::vector::{node_values, perfect_values}; + let root = check_down(2, Street::River); + let board = cs("2c7d9hJsKc"); + let (sz, later) = (search::tree::small_sizing(), later_sizing()); + let (none, frozen) = (Extras::new(), HashMap::new()); + let mut g = river_game(root, &board, &sz, &later, &none, &frozen); + g.rake = test_rule().in_chips(2, 100).unwrap(); + let sol = solve_vec(&g, &VecParams { iters: 1500, plus: true, keep_all: true, floor: 1e-3, ..Default::default() }); + let strat = sol.strategy(true, None); + let nv = node_values(&g, &strat, &[], 0).expect("root node of player 0"); + let (n, m) = (nv.actions.len(), nv.w.len()); + let value = |q: &Vec>, pi: &Vec>| -> f64 { (0..m).map(|h| nv.w[h] * (0..n).map(|a| pi[a][h] * q[a][h]).sum::()).sum() }; + let pot = root.pot() as f64; + // the reference mixture: its value against the perfect opponent equals its value against the reference continuation (it is an equilibrium) + let val_gg = value(&nv.q, &nv.sigma); + let qbr_sigma: Vec> = perfect_values(&g, &strat, &[], 0, &nv.sigma, usize::MAX).unwrap().into_iter().map(|x| x.unwrap()).collect(); + let pv_sigma = value(&qbr_sigma, &nv.sigma); + assert!((val_gg - pv_sigma).abs() < 0.03 * pot, "reference mixture: {val_gg} vs perfect {pv_sigma}"); + // a shifted mixture (always the first action) loses at least its regret against the reference continuation + let shifted: Vec> = (0..n).map(|a| vec![(a == 0) as u8 as f64; m]).collect(); + let qbr_shift: Vec> = perfect_values(&g, &strat, &[], 0, &shifted, usize::MAX).unwrap().into_iter().map(|x| x.unwrap()).collect(); + let loss_perfect = val_gg - value(&qbr_shift, &shifted); + let regret: f64 = (0..m).map(|h| nv.w[h] * ((0..n).map(|a| nv.q[a][h]).fold(f64::NEG_INFINITY, f64::max) - nv.q[0][h])).sum(); + assert!(regret > 0.0, "the shifted mixture must have a regret"); + assert!(loss_perfect >= regret - 0.03 * pot, "perfect-opponent loss {loss_perfect} below regret {regret}"); + // a policy cap that is too small yields None for the action, never a wrong number + let capped = perfect_values(&g, &strat, &[], 0, &nv.sigma, 1).unwrap(); + assert!(capped.iter().any(|x| x.is_none())); +} diff --git a/sharingan-1/serve/src/bin/sharingan-referenz.rs b/sharingan-1/serve/src/bin/sharingan-referenz.rs new file mode 100644 index 00000000..cbcac5de --- /dev/null +++ b/sharingan-1/serve/src/bin/sharingan-referenz.rs @@ -0,0 +1,134 @@ +//! `sharingan-referenz`: the frozen reference of the score (see `search::referenz`). +//! +//! Reads the spot set (`score/spotsatz-v1.jsonl`: one spot per line with the SHARINGAN request in `req`), solves each decision as an +//! exact heads-up game to the end of the hand with the real rake and writes ONE file per spot, `/.json`, atomically +//! (existing files are never touched, so a run resumes). The file holds `Q(h, a)` for every hero hand with positive reach. +//! +//! Own flags: `--spots F --out DIR [--sizing reich|mittel] [--iters N] [--floor 0.001] [--rake nl2|nl5|none] [--pooled] +//! [--pi-dir DIR] [--no-measure] [--only ID,ID] [--street FLOP|TURN|RIVER] [--ranks 0,1,2] [--max N] [--workers N] [--max-gb N] [--max-seconds S]`; +//! everything else is `sharingan-serve`'s configuration (`--blueprint`, `--buckets`, `--set`, ...). +use serde_json::Value; +use sharingan_serve::api::ActRequest; +use sharingan_serve::config::Config; +use sharingan_serve::decide::Core; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const OWN: &[&str] = &["pi-dir", "spots", "out", "sizing", "iters", "floor", "rake", "pooled", "no-measure", "only", "street", "ranks", "max", "workers", "max-gb", "max-seconds"]; +const FLAGS: &[&str] = &["pooled", "no-measure"]; + +fn file_name(id: &str) -> String { + id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect::() + ".json" +} + +fn main() { + let raw: Vec = std::env::args().skip(1).collect(); + let mut own: HashMap = HashMap::new(); + let mut rest: Vec = vec!["--no-auth".into()]; + let mut i = 0; + while i < raw.len() { + let k = raw[i].trim_start_matches("--").to_string(); + if raw[i].starts_with("--") && OWN.contains(&k.as_str()) { + if FLAGS.contains(&k.as_str()) { + own.insert(k, "1".into()); + i += 1; + } else { + own.insert(k, raw.get(i + 1).cloned().unwrap_or_default()); + i += 2; + } + } else { + rest.push(raw[i].clone()); + i += 1; + } + } + let die = |m: String| -> ! { + eprintln!("{m}"); + std::process::exit(2) + }; + let cfg = Config::parse(&|k| std::env::var(k).ok(), &rest).unwrap_or_else(|e| die(e.to_string())); + let (Some(spots_path), Some(out_dir)) = (own.get("spots"), own.get("out")) else { die("--spots F and --out DIR are required".into()) }; + let num = |k: &str, d: f64| own.get(k).and_then(|v| v.parse::().ok()).unwrap_or(d); + let sizing = own.get("sizing").map_or("reich", |s| s.as_str()); + let (root_sizing, later) = search::referenz::reference_sizing(sizing).unwrap_or_else(|| die(format!("--sizing {sizing}: unknown"))); + let rake = match own.get("rake").map_or("nl2", |s| s.as_str()) { + "none" => None, + limit => Some(nlhe::RakeRule::measured(limit).unwrap_or_else(|| die(format!("--rake {limit}: no measured rule")))), + }; + let rp = search::referenz::RefParams { + iters: num("iters", 400.0) as u64, + floor: num("floor", 1e-3), + rake, + big_blind: 100, + sizing: root_sizing, + later, + max_bytes: (num("max-gb", 6.0) * 1e9) as usize, + max_millis: own.get("max-seconds").and_then(|v| v.parse::().ok()).map(|s| (s * 1e3) as u64), + measure: !own.contains_key("no-measure"), + seed: 1, + }; + let pooled = own.contains_key("pooled"); + let only: Option> = own.get("only").map(|s| s.split(',').map(String::from).collect()); + let ranks: Option> = own.get("ranks").map(|s| s.split(',').filter_map(|x| x.parse().ok()).collect()); + let street = own.get("street").cloned(); + std::fs::create_dir_all(out_dir).unwrap_or_else(|e| die(format!("{out_dir}: {e}"))); + let text = std::fs::read_to_string(spots_path).unwrap_or_else(|e| die(format!("{spots_path}: {e}"))); + let todo: Vec<(String, Value)> = text + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter(|v| only.as_ref().is_none_or(|o| o.iter().any(|x| Some(x.as_str()) == v["id"].as_str()))) + .filter(|v| ranks.as_ref().is_none_or(|r| r.contains(&v["rang"].as_u64().unwrap_or(u64::MAX)))) + .filter(|v| street.as_ref().is_none_or(|s| v["stratum"].as_str().is_some_and(|x| x.starts_with(s.as_str())))) + .filter(|v| !std::path::Path::new(out_dir).join(file_name(v["id"].as_str().unwrap_or("?"))).exists()) + .map(|v| (v["id"].as_str().unwrap_or("?").to_string(), v)) + .take(num("max", f64::MAX) as usize) + .collect(); + let core = Core::new(&cfg).unwrap_or_else(|e| die(format!("error: {e}"))); + let sets = cfg.sets.clone(); + let next = AtomicUsize::new(0); + let workers = num("workers", 1.0) as usize; + eprintln!("{} spots to do, {workers} workers, sizing {sizing}, iters {}, floor {}", todo.len(), rp.iters, rp.floor); + std::thread::scope(|sc| { + for _ in 0..workers.max(1) { + sc.spawn(|| loop { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some((id, v)) = todo.get(k) else { break }; + let req = match serde_json::from_value::(v["req"].clone()) { + Ok(r) => r, + Err(e) => { + eprintln!("{id}: bad request: {e}"); + continue; + } + }; + // profiles of versions at this spot: `/.json` = {"profiles": {"version": {"AsKd": [p per menu action], ...}}} + let profiles: Vec<(String, search::referenz::Profile)> = own + .get("pi-dir") + .and_then(|d| std::fs::read_to_string(std::path::Path::new(d).join(file_name(id))).ok()) + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| { + v["profiles"].as_object().map(|o| { + o.iter() + .map(|(name, hands)| { + let prof = hands.as_object().map_or_else(Default::default, |h| h.iter().map(|(c, ps)| (c.clone(), ps.as_array().map_or(vec![], |a| a.iter().filter_map(|x| x.as_f64()).collect()))).collect()); + (name.clone(), prof) + }) + .collect() + }) + }) + .unwrap_or_default(); + let t = std::time::Instant::now(); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| core.referenz(&req, &sets, &rp, pooled, id, &profiles))); + let out = match res { + Ok(Ok(j)) => j, + Ok(Err(e)) => serde_json::json!({"tag": id, "fehler": e.body()}), + Err(_) => serde_json::json!({"tag": id, "fehler": "panic"}), + }; + let mut out = out; + out["wall_ms"] = serde_json::json!(t.elapsed().as_secs_f64() * 1e3); + let path = std::path::Path::new(out_dir).join(file_name(id)); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, out.to_string()).and_then(|_| std::fs::rename(&tmp, &path)).unwrap_or_else(|e| eprintln!("{id}: write: {e}")); + eprintln!("[{k}] {id} {:.1}s {}", t.elapsed().as_secs_f64(), if out["fehler"].is_null() { "ok" } else { "FEHLER" }); + }); + } + }); +} diff --git a/sharingan-1/serve/src/decide.rs b/sharingan-1/serve/src/decide.rs index d114cfef..d6f34191 100644 --- a/sharingan-1/serve/src/decide.rs +++ b/sharingan-1/serve/src/decide.rs @@ -523,6 +523,63 @@ impl Core { Ok(report_json(&r, it, ms)) } + /// The reference of the score (`search::referenz`): replay `req`, rebuild the decision as an exact heads-up game with rake and a rich + /// menu, solve it to the end of the hand and return the value `Q(h, a)` of every action for every hero hand, as JSON. + /// `blueprint_pooled`: later streets pooled by the blueprint's buckets (approximation, far less memory). + pub fn referenz(&self, req: &ActRequest, sets: &str, rp: &search::referenz::RefParams, pooled: bool, tag: &str, profiles: &[(String, search::referenz::Profile)]) -> Result { + let mut prm = self.prm.clone(); + apply_sets(&mut prm, sets).map_err(|e| ApiError::invalid("bad_sets", e))?; + prm.max_millis = None; + let seed = req.options.seed.unwrap_or(1); + let policy = SearchPolicy::new("referenz", self.blueprint.clone(), prm); + let mut hand = Hand::replay(req, Some(&policy), req.options.track_seed.map_or(mix(seed, 1), |t| mix(t, 1)))?; + if let Some(why) = hand.desync.clone() { + return Err(ApiError::invalid("desync", why)); + } + let player = hand.player.take().ok_or_else(|| ApiError::invalid("no_player", "hero has no search player"))?; + let ctx = player.reference_context().ok_or_else(|| ApiError::invalid("no_subgame", "no postflop round to value"))?; + let r = search::referenz::solve_reference(&ctx, rp, if pooled { Some(&self.blueprint as &dyn search::vector::Bucketing) } else { None }, profiles).map_err(|e| ApiError::invalid("reference", e))?; + let n = &r.node; + let hl = search::beliefs::holes(); + let lg = ctx.node.legal(); + let basis = (n.pot + n.call_amount) as f64; + let actions: Vec = n + .actions + .iter() + .map(|a| match a { + nlhe::Action::Fold => json!({"kind": "fold"}), + nlhe::Action::Check => json!({"kind": "check"}), + nlhe::Action::Call => json!({"kind": "call", "to": n.cur_bet}), + nlhe::Action::RaiseTo(t) => json!({"kind": "raise", "to": t, "frac": (*t - n.cur_bet) as f64 / basis, "all_in": *t == lg.max_raise_to}), + }) + .collect(); + let r3 = |x: f64| (x * 1e3).round() / 1e3; + let r5 = |x: f64| (x * 1e5).round() / 1e5; + let hands: Vec = (0..n.holes.len()) + .filter(|&h| n.w[h] > 1e-12) + .map(|h| { + let c = hl[n.holes[h] as usize]; + json!({"c": cards::cards_str(&c), "w": n.w[h], "q": n.q.iter().map(|v| r3(v[h])).collect::>(), "sigma": n.sigma.iter().map(|v| r5(v[h])).collect::>()}) + }) + .collect(); + let perfect: Vec = r + .profiles + .iter() + .map(|pe| { + let ev_hand: Vec = pe.ev_hand.iter().map(|x| r3(*x)).collect(); + json!({"name": pe.name, "ev_chips": pe.ev, "ev_hand": ev_hand}) + }) + .collect(); + Ok(json!({ + "perfect": perfect, "tag": tag, "street": format!("{:?}", ctx.node.street()), "board": cards::cards_str(&ctx.board), "pot": n.pot, "to_call": n.call_amount, + "cur_bet": n.cur_bet, "min_raise_to": lg.min_raise_to, "max_raise_to": lg.max_raise_to, "hero_seat": ctx.hero_seat, + "in_round": ctx.in_round.iter().map(|(s, a)| format!("{s}:{a:?}")).collect::>(), + "actions": actions, "hands": hands, + "ref": {"iters": r.iters, "solve_ms": r.solve_ms, "bytes": r.bytes, "exploit_chips": r.exploit_chips, "floor": rp.floor, + "rake_cap_chips": r.rake_chips_cap, "pooled": pooled, "big_blind": rp.big_blind}, + })) + } + /// Run the search on a worker thread; blueprint on timeout / panic / no free slot. fn guarded_search(&self, player: &mut SearchPlayer, view: &View, hole: [Card; 2], budget: Duration) -> (Dist, &'static str, Option, f64) { let t0 = Instant::now();