diff --git a/lesen/solver_abnahme.py b/lesen/solver_abnahme.py new file mode 100644 index 00000000..1dbda9be --- /dev/null +++ b/lesen/solver_abnahme.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Abnahme der Stufen A/B gegen das D4-Entscheidungs-Audit: holt der Solver den Heuristik-Verlust zurück? + +Jede eindeutige echte Heads-up-Anfrage an Turn und River (Schatten-Logs, `anfrage`) geht durch zwei +Kern-Kopien: Arm H = Live-Schalter (Heuristik, wie gespielt), Arm S = dieselben plus `SOLVER_RIVER=1`, +`SOLVER_TURN=1` (`SOLVER_ZEIT=fest`: volle Iterationen, die Latenz misst `solver_abdeckung.py`). Beide +Antworten bewertet das Audit (`src/bin/audit.rs`, D4: Verlust = EV(beste) - EV(gespielt) gegen den +Gleichgewichts-Gegner der angenommenen Ranges, in bb). Ausgabe: Verlust H, Verlust S, Differenz, +je Street und je Entscheider in H, plus die größten Rückholungen und Verschlechterungen. + +LESART: Das Audit misst gegen das Gleichgewicht desselben River- bzw. Turn+River-Spiels, das die +Stufen A/B lösen (andere Kombozahl/Riverkarten/Größen). Die Rückholung ist darum zum großen Teil +konstruktionsbedingt; sie zeigt, dass der Solver live greift und wie nah er an seiner eigenen +Messlatte spielt, NICHT, dass er gegen echte Gegner gewinnt. Das sagen LBR und Leiter. + +Ein Prozess zur Zeit, Priorität Idle. + + python3 lesen/solver_abnahme.py --kern K.exe --audit A.exe --schatten DIR --env K=V ... --aus ERG.json +""" +import argparse +import collections +import json +import os +import subprocess +import sys + +_HIER = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, _HIER) +import roentgen # noqa: E402 +import solver_abdeckung as sa # noqa: E402 + +IDLE = 0x00000040 + + +def kern_antworten(kern, env, liste): + extra = {"creationflags": IDLE} if sys.platform == "win32" else {} + p = subprocess.Popen([kern], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + encoding="utf-8", env=env, bufsize=1, **extra) + out = [] + for a in liste: + p.stdin.write(json.dumps(a) + "\n") + p.stdin.flush() + try: + out.append(json.loads(p.stdout.readline())) + except ValueError: + out.append({}) + p.stdin.close() + p.wait() + return out + + +def genommen(a, d): + act = str(d.get("action") or "").upper() + if act in ("BET", "RAISE"): + return {"action": act, "amount": d.get("size")} + if act == "ALL_IN": + return {"action": act, "amount": d.get("size") or a.get("maxRaiseTo")} + if act in ("FOLD", "CHECK", "CALL"): + return {"action": act, "amount": None} + return None + + +def audit_lauf(audit, env, zeilen, pfad): + with open(pfad, "w", encoding="utf-8") as f: + for z in zeilen: + f.write(json.dumps(z) + "\n") + extra = {"creationflags": IDLE} if sys.platform == "win32" else {} + r = subprocess.run([audit, pfad], capture_output=True, text=True, encoding="utf-8", env=env, **extra) + erg = {} + for zeile in r.stdout.splitlines(): + try: + d = json.loads(zeile) + except ValueError: + continue + erg[d.get("id")] = d + return erg + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--kern", required=True) + ap.add_argument("--audit", required=True) + ap.add_argument("--schatten", required=True) + ap.add_argument("--env", action="append", default=[], help="Live-Schalter (Arm H und S)") + ap.add_argument("--solver", action="append", default=["SOLVER_RIVER=1", "SOLVER_TURN=1", "SOLVER_ZEIT=fest"]) + ap.add_argument("--aus", required=True) + args = ap.parse_args() + basis = {k: v for k, v in os.environ.items() if k not in roentgen.BEKANNTE_SCHALTER} + for kv in args.env: + k, v = kv.split("=", 1) + basis[k] = v + env_s = dict(basis) + for kv in args.solver: + k, v = kv.split("=", 1) + env_s[k] = v + liste = [a for a in sa.anfragen(args.schatten, {"TURN", "RIVER"}) if sa.spieler(a) == 1] + print(f"{len(liste)} Heads-up-Anfragen Turn/River", flush=True) + h = kern_antworten(args.kern, basis, liste) + print("Arm H fertig", flush=True) + s = kern_antworten(args.kern, env_s, liste) + print("Arm S fertig", flush=True) + zeilen = [] + for i, a in enumerate(liste): + for arm, d in (("h", h[i]), ("s", s[i])): + t = genommen(a, d) + if t is not None and (arm == "h" or t != genommen(a, h[i])): + zeilen.append(dict(a, taken=t, id=f"{i}{arm}")) + erg = audit_lauf(args.audit, basis, zeilen, args.aus + ".audit-ein.jsonl") + print(f"Audit fertig: {len(erg)} Zeilen", flush=True) + summe = collections.defaultdict(lambda: [0, 0.0, 0.0, 0]) # n, loss h, loss s, geaendert + faelle = [] + for i, a in enumerate(liste): + eh = erg.get(f"{i}h") + if not eh or eh.get("status") != "ok": + continue + es = erg.get(f"{i}s", eh) + if es.get("status") != "ok": + continue + lh, ls = float(eh.get("loss_bb") or 0), float(es.get("loss_bb") or 0) + st = str(a.get("street")).upper() + wer = roentgen.klasse(st, h[i].get("reason") or "") + for key in ((st, "alle"), (st, wer), ("ALLE", "alle")): + summe[key][0] += 1 + summe[key][1] += lh + summe[key][2] += ls + summe[key][3] += int(f"{i}s" in erg) + faelle.append({"i": i, "street": st, "karten": a.get("heroCards"), "board": a.get("board"), + "h": genommen(a, h[i]), "s": genommen(a, s[i]), "loss_h": round(lh, 2), + "loss_s": round(ls, 2), "grund_s": s[i].get("reason", "")[:120]}) + print(f"{'Street':6} {'Entscheider H':14} {'n':>5} {'Verlust H':>10} {'Verlust S':>10} {'zurueck':>9} {'geaendert':>9}") + tab = {} + for (st, wer), (n, lh, ls, g) in sorted(summe.items()): + print(f"{st:6} {wer:14} {n:5} {lh:10.1f} {ls:10.1f} {lh - ls:9.1f} {g:9}") + tab[f"{st}/{wer}"] = {"n": n, "verlust_h": round(lh, 2), "verlust_s": round(ls, 2), "geaendert": g} + faelle.sort(key=lambda f: f["loss_s"] - f["loss_h"]) + print("Groesste Rueckholungen:") + for f in faelle[:8]: + print(" ", json.dumps(f, ensure_ascii=False)) + print("Groesste Verschlechterungen:") + for f in [f for f in faelle if f["loss_s"] > f["loss_h"] + 0.05][-8:]: + print(" ", json.dumps(f, ensure_ascii=False)) + with open(args.aus, "w", encoding="utf-8") as f: + json.dump({"tabelle": tab, "faelle": faelle}, f, ensure_ascii=False, indent=1) + + +if __name__ == "__main__": + main() diff --git a/messung_solver/abnahme.sh b/messung_solver/abnahme.sh new file mode 100644 index 00000000..53a43289 --- /dev/null +++ b/messung_solver/abnahme.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Turn-Abdeckung (mit Zeilen) + D4-Abnahme (Heuristik- vs Solver-Verlust), ein Prozess zur Zeit, +# 1 Thread aus GRENZE.txt geliehen (20 -> 19) und zurueckgegeben. +cd "$(dirname "$0")/.." +L=../engine-lecks-angreifen-de7b88 +G=$L/messung_engine/GRENZE.txt +B="$(pwd -W)/messung_solver/bin" +leihe() { python3 - "$G" "$1" "$2" <<'PY' +import sys;p,a,b=sys.argv[1:];s=open(p,newline='').read() +s=s.replace(f"threads={a}\r\n",f"threads={b}\r\n",1).replace(f"threads={a}\n",f"threads={b}\n",1) +open(p,"w",newline='').write(s) +PY +} +leihe 20 19 +GS="GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten" +LIVE=(--env MDF_UNREAD=0 --env TURN_SPIEL=grund --env OPEN_JAM=1 --env "$GS") +python3 lesen/solver_abdeckung.py --kern "$B/pokerbench-solver-abdeckungBC4.exe" --schatten $L/betrieb/scratch "${LIVE[@]}" --env SOLVER_RIVER=1 --env SOLVER_TURN=1 --env SOLVER_FLOP=1 --street TURN --street FLOP --json messung_solver/abdeckung-bc4.json --zeilen messung_solver/abdeckung-bc4-zeilen.jsonl > messung_solver/abdeckung-bc4.txt 2>&1 +python3 lesen/solver_abnahme.py --kern "$B/pokerbench-solver-abdeckungBC4.exe" --audit "$B/pokerbench-solver-audit.exe" --schatten $L/betrieb/scratch "${LIVE[@]}" --aus messung_solver/abnahme-d4.json > messung_solver/abnahme-d4.txt 2>&1 +leihe 19 20 +grep -n "^threads" $G diff --git a/src/engine/flop_spieler.rs b/src/engine/flop_spieler.rs index 79830a33..d2fa0300 100644 --- a/src/engine/flop_spieler.rs +++ b/src/engine/flop_spieler.rs @@ -133,7 +133,7 @@ pub fn solve_flop(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec cfg.budget_ms { + if started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { break; } } diff --git a/src/engine/frist.rs b/src/engine/frist.rs index a08619b2..0d7c5674 100644 --- a/src/engine/frist.rs +++ b/src/engine/frist.rs @@ -1,50 +1,50 @@ -//! The decision deadline of the postflop solvers ("Solver ueberall"): `decide_with` marks the start of -//! each decision on its thread, and a solver gets what is left of its street's total before it starts. -//! Totals per decision (live table): river and flop 2 s, turn 1.25 s, each minus `MARGIN_MS` for the -//! work after the solve. Without a mark (tests, tools calling a solver directly) the full total is left. - -use std::cell::Cell; -use std::time::Instant; - -thread_local! { - static START: Cell> = const { Cell::new(None) }; -} - -/// Total wall time of one decision per street, in ms. -pub const RIVER_MS: f64 = 2000.0; -pub const TURN_MS: f64 = 1250.0; -pub const FLOP_MS: f64 = 2000.0; -/// Kept free after the solve (strategy readout, sampling, the answer). -pub const MARGIN_MS: f64 = 100.0; - -/// Mark the start of a decision on this thread. -pub fn begin() { - START.with(|s| s.set(Some(Instant::now()))); -} - -/// Milliseconds since the mark (0 without one). -pub fn elapsed_ms() -> f64 { - START.with(|s| s.get().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3)) -} - -/// What a solver may still spend of `total_ms` (may be ≤ 0: then it must not start). -pub fn left_ms(total_ms: f64) -> f64 { - total_ms - MARGIN_MS - elapsed_ms() -} - -/// Measurement switch `SOLVER_ZEIT=fest`: solvers ignore wall time and always run their full iteration -/// count, so ladder and LBR results do not depend on machine load (read once). -pub fn fixed() -> bool { - static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); - *FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest")) -} - -/// The budget a solve gets: `cap_ms` (its own limit), cut to what is left of the street's total; -/// infinite under `SOLVER_ZEIT=fest`. -pub fn budget_ms(cap_ms: f64, total_ms: f64) -> f64 { - if fixed() { - f64::INFINITY - } else { - cap_ms.min(left_ms(total_ms)) - } -} +//! The decision deadline of the postflop solvers ("Solver ueberall"): `decide_with` marks the start of +//! each decision on its thread, and a solver gets what is left of its street's total before it starts. +//! Totals per decision (live table): river and flop 2 s, turn 1.25 s, each minus `MARGIN_MS` for the +//! work after the solve. Without a mark (tests, tools calling a solver directly) the full total is left. + +use std::cell::Cell; +use std::time::Instant; + +thread_local! { + static START: Cell> = const { Cell::new(None) }; +} + +/// Total wall time of one decision per street, in ms. +pub const RIVER_MS: f64 = 2000.0; +pub const TURN_MS: f64 = 1250.0; +pub const FLOP_MS: f64 = 2000.0; +/// Kept free after the solve (strategy readout, sampling, the answer). +pub const MARGIN_MS: f64 = 150.0; + +/// Mark the start of a decision on this thread. +pub fn begin() { + START.with(|s| s.set(Some(Instant::now()))); +} + +/// Milliseconds since the mark (0 without one). +pub fn elapsed_ms() -> f64 { + START.with(|s| s.get().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3)) +} + +/// What a solver may still spend of `total_ms` (may be ≤ 0: then it must not start). +pub fn left_ms(total_ms: f64) -> f64 { + total_ms - MARGIN_MS - elapsed_ms() +} + +/// Measurement switch `SOLVER_ZEIT=fest`: solvers ignore wall time and always run their full iteration +/// count, so ladder and LBR results do not depend on machine load (read once). +pub fn fixed() -> bool { + static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); + *FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest")) +} + +/// The budget a solve gets: `cap_ms` (its own limit), cut to what is left of the street's total; +/// infinite under `SOLVER_ZEIT=fest`. +pub fn budget_ms(cap_ms: f64, total_ms: f64) -> f64 { + if fixed() { + f64::INFINITY + } else { + cap_ms.min(left_ms(total_ms)) + } +} diff --git a/src/engine/turn_game.rs b/src/engine/turn_game.rs index 36b7ea50..f24e8fe6 100644 --- a/src/engine/turn_game.rs +++ b/src/engine/turn_game.rs @@ -244,7 +244,7 @@ fn solve_core(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec while done < cfg.iterations { solver.iterate(); done += 1; - if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { + if started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { break; } }