diff --git a/score/farm_referenz.ps1 b/score/farm_referenz.ps1 new file mode 100644 index 00000000..685a5e90 --- /dev/null +++ b/score/farm_referenz.ps1 @@ -0,0 +1,24 @@ +# Farm job: build and run the frozen reference of the score (Turn/Flop/River, exact, rake NL2) on the play machine. +# powershell -File score\farm_referenz.ps1 -Blueprint -Buckets -Out [-Workers 6] [-Ranks 0,1,2,3] [-MaxSeconds 600] [-MaxGb 6] +# Resumable: spots with a result file in -Out are skipped. Needs a Rust toolchain; builds with -j 4 at BelowNormal priority. +param( + [Parameter(Mandatory=$true)][string]$Blueprint, + [Parameter(Mandatory=$true)][string]$Buckets, + [Parameter(Mandatory=$true)][string]$Out, + [int]$Workers = 6, [string]$Ranks = "0,1,2,3", [int]$MaxSeconds = 600, [int]$MaxGb = 6, + [string]$Street = "" +) +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent $PSScriptRoot +Push-Location $root +& cargo build --release -j 4 -p sharingan-serve --bin sharingan-referenz +$exe = Join-Path $root "target\release\sharingan-referenz.exe" +$args = @("--blueprint", $Blueprint, "--buckets", $Buckets, "--sizing", "local", "--set", "flop=1", "--search-threads", "1", + "--spots", "score\spotsatz-v1.jsonl", "--out", $Out, "--ranks", $Ranks, "--workers", $Workers, + "--max-seconds", $MaxSeconds, "--max-gb", $MaxGb, "--target", "0.005", "--menu", "reich") +if ($Street -ne "") { $args += @("--street", $Street) } +$env:HYBRID_UEBERSETZUNG = "phm" +$p = Start-Process -FilePath $exe -ArgumentList $args -NoNewWindow -PassThru -RedirectStandardError (Join-Path $Out "lauf.log") +$p.PriorityClass = "BelowNormal" +$p.WaitForExit() +Pop-Location diff --git a/sharingan-1/search/src/referenz.rs b/sharingan-1/search/src/referenz.rs index 0c36c03b..67fdd603 100644 --- a/sharingan-1/search/src/referenz.rs +++ b/sharingan-1/search/src/referenz.rs @@ -17,13 +17,19 @@ use nlhe::abstraction::{ActionList, BetSizing, Menu}; use nlhe::{Action, RakeRule, Step}; pub struct RefParams { + /// First iteration count; the solve is repeated with the double until the target is met (see `solve_until`). pub iters: u64, + /// Upper bound of the iteration count. + pub max_iters: u64, + /// Stop as soon as the sum of both players' best-response gains is at most this share of the pot at the node (0.005 = 0.5 %). + pub target_pct: f64, pub floor: f64, pub rake: Option, pub big_blind: i32, pub sizing: BetSizing, pub later: BetSizing, pub max_bytes: usize, + /// Total time budget of the spot (solves and measurements); the best solve so far is kept when it runs out. pub max_millis: Option, /// Also measure the exploitability of the reference itself (extra passes). pub measure: bool, @@ -52,6 +58,9 @@ pub struct RefResult { pub bytes: usize, /// Sum of both players' best-response gains against the reference, chips (its own accuracy). pub exploit_chips: Option, + /// Number of solve rounds and whether the target was met (the rest is the `reference error`, `exploit_chips / pot`). + pub rounds: u32, + pub target_met: bool, pub rake_chips_cap: i32, } @@ -106,8 +115,7 @@ pub fn solve_reference(ctx: &RefContext, p: &RefParams, pooled: Option<&dyn Buck }; 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 (sol, exploit_chips, rounds, target_met) = solve_until(&g, p, pooled); 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)")?; @@ -129,11 +137,7 @@ pub fn solve_reference(ctx: &RefContext, p: &RefParams, pooled: Option<&dyn Buck 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 }) + Ok(RefResult { profiles: evs, node, hero, iters: sol.iters, solve_ms: sol.millis, bytes: sol.peak_bytes, exploit_chips, rounds, target_met, 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 @@ -153,3 +157,32 @@ pub fn reference_sizing(name: &str) -> Option<(BetSizing, BetSizing)> { _ => return None, }) } + +/// Solve with doubling iteration counts (from scratch each round: 2x the cost of the last round at most) until the exploitability of the +/// average strategy is at most `target_pct` of the pot, `max_iters` is reached, or the time budget is used up. With `measure` off, one solve +/// of `iters` iterations. Returns `(solution, exploitability chips (sum of both players' gains), rounds, target met)`. +pub fn solve_until(g: &VecGame, p: &RefParams, pooled: Option<&dyn Bucketing>) -> (VecSolution, Option, u32, bool) { + let t0 = std::time::Instant::now(); + let pot = g.root.pot() as f64; + let left = |t0: &std::time::Instant| p.max_millis.map(|b| b.saturating_sub(t0.elapsed().as_millis() as u64)); + let mut iters = p.iters; + let mut rounds = 0; + loop { + rounds += 1; + let vp = VecParams { iters, max_millis: left(&t0), plus: true, stratify: true, seed: p.seed, keep_all: true, max_bytes: p.max_bytes, floor: p.floor }; + let sol = solve_vec(g, &vp); + if !p.measure { + return (sol, None, rounds, false); + } + let expl = { + let (e, _) = exploitability(g, &sol.strategy(true, pooled)); + 2.0 * e + }; + let met = expl <= p.target_pct * pot; + let out_of_time = left(&t0) == Some(0) || sol.iters < iters; + if met || out_of_time || iters >= p.max_iters { + return (sol, Some(expl), rounds, met); + } + iters = (iters * 2).min(p.max_iters); + } +} diff --git a/sharingan-1/search/tests/exploit.rs b/sharingan-1/search/tests/exploit.rs index 45eb1c5b..3aad15dc 100644 --- a/sharingan-1/search/tests/exploit.rs +++ b/sharingan-1/search/tests/exploit.rs @@ -357,3 +357,29 @@ fn perfect_opponent_value_of_the_reference_mixture_and_of_a_shifted_mixture() { let capped = perfect_values(&g, &strat, &[], 0, &nv.sigma, 1).unwrap(); assert!(capped.iter().any(|x| x.is_none())); } + +#[test] +fn solve_until_stops_at_the_target_or_reports_the_rest() { + use search::referenz::{reference_sizing, solve_until, RefParams}; + 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 (rs, rl) = reference_sizing("mittel").unwrap(); + let mut p = RefParams { iters: 50, max_iters: 6400, target_pct: 0.03, floor: 2e-4, rake: None, big_blind: 100, sizing: rs, later: rl, max_bytes: 1 << 30, max_millis: None, measure: true, seed: 1 }; + let pot = root.pot() as f64; + let (_, e, rounds, met) = solve_until(&g, &p, None); + assert!(met && e.unwrap() <= 0.03 * pot, "expl {e:?} rounds {rounds}"); + assert!(rounds > 1, "the first 50 iterations should not be enough"); + // an unreachable target within a small cap: the rest is reported, not hidden + p.target_pct = 1e-9; + p.max_iters = 100; + let (_, e, _, met) = solve_until(&g, &p, None); + assert!(!met && e.unwrap() > 1e-9 * pot); + // without measuring: one solve, no number + p.measure = false; + let (_, e, rounds, _) = solve_until(&g, &p, None); + assert!(e.is_none() && rounds == 1); +} diff --git a/sharingan-1/serve/src/bin/sharingan-referenz.rs b/sharingan-1/serve/src/bin/sharingan-referenz.rs index b8302f2c..ee5ad794 100644 --- a/sharingan-1/serve/src/bin/sharingan-referenz.rs +++ b/sharingan-1/serve/src/bin/sharingan-referenz.rs @@ -4,7 +4,7 @@ //! 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 [--menu reich|mittel] [--iters N] [--floor 0.001] [--rake nl2|nl5|none] [--pooled] +//! Own flags: `--spots F --out DIR [--menu reich|mittel] [--iters N --max-iters N --target 0.005] [--floor 0.0002] [--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; @@ -14,7 +14,7 @@ use sharingan_serve::decide::Core; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; -const OWN: &[&str] = &["pi-dir", "spots", "out", "menu", "iters", "floor", "rake", "pooled", "no-measure", "only", "street", "ranks", "max", "workers", "max-gb", "max-seconds"]; +const OWN: &[&str] = &["pi-dir", "spots", "out", "menu", "iters", "max-iters", "target", "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 { @@ -55,8 +55,10 @@ fn main() { 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), + iters: num("iters", 200.0) as u64, + max_iters: num("max-iters", 100000.0) as u64, + target_pct: num("target", 0.005), + floor: num("floor", 2e-4), rake, big_blind: 100, sizing: root_sizing, diff --git a/sharingan-1/serve/src/decide.rs b/sharingan-1/serve/src/decide.rs index d6f34191..36fe1429 100644 --- a/sharingan-1/serve/src/decide.rs +++ b/sharingan-1/serve/src/decide.rs @@ -575,7 +575,7 @@ impl Core { "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, + "ref": {"iters": r.iters, "solve_ms": r.solve_ms, "bytes": r.bytes, "exploit_chips": r.exploit_chips, "referenzfehler_topf": r.exploit_chips.map(|e| e / n.pot as f64), "runden": r.rounds, "ziel_erreicht": r.target_met, "floor": rp.floor, "rake_cap_chips": r.rake_chips_cap, "pooled": pooled, "big_blind": rp.big_blind}, })) }