From 16e57c56668da742446bc4daf5ccfd046ab36f46 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Thu, 19 Nov 2026 11:04:33 +0100 Subject: [PATCH] Latenz: alle Entscheidungen unter 1,5 s an 12 Tischen (0 von 480, live 23), bitgleich Der langsame Pfad war das E3-Turn-Spiel im frischen Kern-Prozess je Stapel. - Abstraktion einmal laden (Arc), im Hintergrund vorladen - iso::Index: Index nur fuer gefragte Boards (Burnside-Zaehlung) - kein Solve, wenn die eigene Hand ausgeduennt ist - TrSolver::run_parallel: Solve auf 5 Faeden (TURN_FAEDEN, nur Kern-Binary), Bit fuer Bit gleich run Pflicht 38/43; 5 von 480 anders, alle Iterationsrauschen des Solver-Kern-Turns. messung/solver_kern/LATENZ.md Co-Authored-By: Claude Opus 5.5 --- docs/notizen/PLAN-weltklasse.md | 1 + docs/notizen/STAND-weltklasse.md | 20 ++ docs/notizen/STATUS-weltklasse.md | 2 + messung/perf/werkzeug/stichprobe.py | 10 +- messung/solver_kern/LATENZ.md | 76 ++++++ messung/solver_kern/latenz-dauer-kern30.json | 19 ++ messung/solver_kern/latenz-frisch-kern30.json | 13 ++ messung/solver_kern/latenz-frisch-live.json | 182 +++++++++++++++ messung/solver_kern/pflicht-latenz.txt | 45 ++++ messung/solver_kern/werk/latenz_frisch.py | 53 +++++ src/blueprint/iso.rs | 111 +++++++++ src/blueprint/ranges.rs | 23 +- src/blueprint/s1.rs | 19 +- src/cfr/turn_river_game.rs | 221 ++++++++++++++++++ src/cfr/turn_river_game/tests.rs | 40 ++++ src/engine/turn_game.rs | 21 +- src/main.rs | 4 + 17 files changed, 846 insertions(+), 14 deletions(-) create mode 100644 messung/solver_kern/LATENZ.md create mode 100644 messung/solver_kern/latenz-dauer-kern30.json create mode 100644 messung/solver_kern/latenz-frisch-kern30.json create mode 100644 messung/solver_kern/latenz-frisch-live.json create mode 100644 messung/solver_kern/pflicht-latenz.txt create mode 100644 messung/solver_kern/werk/latenz_frisch.py diff --git a/docs/notizen/PLAN-weltklasse.md b/docs/notizen/PLAN-weltklasse.md index 69e10275..e4d30a0f 100644 --- a/docs/notizen/PLAN-weltklasse.md +++ b/docs/notizen/PLAN-weltklasse.md @@ -196,6 +196,7 @@ Es bleibt bei Heuristik plus Vetos. Erlaubt sind weiter: Fixes für in echten H - **Solver-Kern Stufe 3 Flop „ohne Luft“ (solver-kern, 19.11. nachts):** Live-Kandidat `SOLVER_KERN=river+turn+tnur=offen+tohne=nichts+wu=heur+flop+fnur=offen+fohne=nichts` (Kern ab 55c713d4). Heads-up-Flop in offenen Lagen aus Flop+Turn-Solve (River als Equity, 16 Turn-Karten, 120 Kombos), Luft und ungelesene Gegner bei der Heuristik. Fluss Dev +21 031 [+14 677, +28 733] ≈ +1,49 bb/100; Holdout einmal +12 061 [+7 820, +16 327] ≈ +1,62 bb/100 (statisch +1,06 [+0,81, +1,33]). Voller Arm verliert mit Luft (Holdout −4 232). Pflicht 38/43, Latenz 12 Tische max 981 ms. Offen: Eigen-Replay am Flop (Läufer schreibt den Flop-Spot nicht), Flop gegen Einsatz. `messung/solver_kern/STUFE3.md`. - **Solver-Kern Stufe 3b Flop gegen Einsatz (solver-kern, 19.11.):** Live-Kandidat `SOLVER_KERN=river+turn+tnur=offen+tohne=nichts+wu=heur+flop+fohne=nichts` (Kern ab dem Commit dieses Eintrags: `fohne` am Flop nur offen). Fold/Call/Raise gegen einen Flop-Einsatz aus dem Flop+Turn-Solve, alle Klassen; Raise-Antwort des Pools aus einer neu gemessenen Fold-Kurve gegen Flop-Raises. Fluss Dev +15 309 [+10 377, +20 943] ≈ +1,07 bb/100; Holdout einmal +8 215 [+5 315, +11 574] ≈ +1,10 bb/100 (statisch +0,68 [+0,41, +0,98]), keine Klasse negativ; Pflicht 38/43, Latenz max 798 ms. Zusätzlich zu Stufe 3 (andere Lagen). `messung/solver_kern/STUFE3.md`. - **Solver-Kern Stufe 2b Turn gegen Einsatz (solver-kern, 19.11.):** Live-Kandidat `SOLVER_KERN=river+turn+tohne=nichts+tgohne=zug/paar_schwach+tgstark+wu=heur+flop+fohne=nichts` (neue Kern-Schalter `tgohne`, `tgstark`; mit `tnur=offen` ohne Wirkung). Fold/Call/Raise gegen einen Turn-Einsatz aus dem Flop+Turn-Solve, ohne Züge und schwache Paare (dort Heuristik), Folds mit zwei Paaren oder besser an die Heuristik. Fluss Dev +7 128 [+4 641, +9 939] ≈ +0,51 bb/100; Holdout einmal +2 361 [+874, +3 881] ≈ +0,31 [+0,12, +0,52] bb/100, statisch n. s. (−0,05); Drilling-Fallen auf dem Holdout negativ (−624). Pflicht 38/43 (Verlusthand 178593300919 bleibt Fold), Eigen-Replay 38/395 anders, Solver max 1 262 ms. Tor knapp bestanden, Gewinn klein. `messung/solver_kern/STUFE2.md`. +- **Latenz unter 1,5 s (solver-kern, 19.11.):** Kein Schalter, nur Kern-Code. Der langsame Pfad war das E3-Turn-Spiel im frischen Prozess je Stapel. Behebung: Abstraktion einmal laden, Index nur für gefragte Boards, kein Solve für ausgedünnte Hände, Solve auf 5 Fäden (bitgleich). 12 Tische wie live: 0 von 480 über 1,5 s (live 23), max 1 192 ms. Pflicht 38/43, Entscheidungen bitgleich bis auf Iterationsrauschen des Solver-Kern-Turns. `messung/solver_kern/LATENZ.md`. - Neuer Anlauf echter Postflop-Spieler (Grundstrategie + Echtzeit-Suche), gemessen auf M6. **16.11. vorgezogen** (Owner: „kein Run mehr, auf echte Weltklasse“): Session postflop-suche baut tiefenbegrenzte sichere Teilspiel-Suche ab dem Flop plus KL-Ausnutzung, Tor LBR S1 < 30, Leiter ohne Verlierer inkl. pool-nl2-echt. 1. **Jetzt:** nächster Micro-Lauf mit `MDF_UNREAD=0` (O2 entschieden). In den Pausen LBR vorher/nachher diff --git a/docs/notizen/STAND-weltklasse.md b/docs/notizen/STAND-weltklasse.md index bdcbf78f..89c7e0a4 100644 --- a/docs/notizen/STAND-weltklasse.md +++ b/docs/notizen/STAND-weltklasse.md @@ -614,3 +614,23 @@ Live-Kandidat `SOLVER_KERN=river+turn+tohne=nichts+tgohne=zug/paar_schwach+tgsta - Latenz: Solver max 1 262 ms. Heuristik-Fälle über 1,5 s: 17 statt live 26. - Tor knapp bestanden, der Gewinn ist klein. Die Entscheidung liegt beim Orchestrator. +## 34. Nachtrag 19.11.: Latenz, alle Entscheidungen unter 1,5 s (`messung/solver_kern/LATENZ.md`) + +Auftrag Orchestrator: der langsame Pfad ohne Solver (17 von 480 über 1,5 s). Die Ursache war das Turn-Spiel E3 (`TURN_SPIEL=grund`), nicht die Heuristik. Live startet je Stapel ein frischer Kern, darum zahlte jeder E3-Spot alles Laden neu und rechnete den Solve auf einem Faden. + +Behebung ohne Zahlenänderung: +- Abstraktion einmal laden, im Hintergrund vorladen. +- Index nur für die gefragten Boards. +- Kein Solve, wenn die eigene Hand ausgedünnt ist. +- Solve auf 5 Fäden (`TrSolver::run_parallel`, Test Bit für Bit gleich `run`). + +| 12 Tische, 480 Turn-Spots | über 1,5 s | max | +|---|---|---| +| live, frischer Prozess je Aufruf | 23 | 2 728 ms | +| **neu, frischer Prozess je Aufruf** | **0** | **1 192 ms** | +| neu, ein Prozess je Tisch | 0 | 1 138 ms | + +- Bitgleich: 5 von 480 anders, alle Iterationsrauschen des Solver-Kern-Turns (Kappe in Rechenzeit). Gegenprobe live gegen live: 4. +- Pflichtfälle 38/43. +- Offen für den Betrieb: ein dauerhafter Kern statt eines frischen Prozesses je Stapel. + diff --git a/docs/notizen/STATUS-weltklasse.md b/docs/notizen/STATUS-weltklasse.md index 0f960708..91911218 100644 --- a/docs/notizen/STATUS-weltklasse.md +++ b/docs/notizen/STATUS-weltklasse.md @@ -115,6 +115,8 @@ Neu ist ein einziges Tor für jeden Kandidaten (`werkzeuge/tor_echt.py`), dazu s **Solver-Kern Turn gegen Einsatz (solver-kern, 19.11.):** Auch die Antwort auf einen Turn-Einsatz kann aus dem Solver kommen, außer mit Zügen und schwachen Paaren. Starke Hände foldet er nie gegen live. Der Gewinn ist klein: bei den versiegelten Spielern etwa +0,3 bb/100 [+0,12, +0,52], auf Dev +0,5. Pflichtfälle bestanden, auch die bekannte Verlusthand mit 99. Schalter `SOLVER_KERN=river+turn+tohne=nichts+tgohne=zug/paar_schwach+tgstark+wu=heur+flop+fohne=nichts`, Entscheidung beim Orchestrator. +**Schnellere Entscheidungen (solver-kern, 19.11.):** Kein Spot braucht mehr über 1,5 s, auch an 12 Tischen. Vorher waren es 23 von 480, langsam war das Turn-Spiel beim Laden und Rechnen. Die Entscheidungen bleiben dieselben. Live wird es mit dem nächsten Kern-Bau. + **Eigene Wetten (18.11., eigene-wetten):** - Gemessen, was der NL2-Pool auf unsere Einsätze tut: Er foldet am River öfter, als ein Bluff braucht, und callt All-ins weit. Wir bluffen am River kaum und setzen Value fast immer mit 2/3 Pot. diff --git a/messung/perf/werkzeug/stichprobe.py b/messung/perf/werkzeug/stichprobe.py index fe638bc4..77159a3d 100644 --- a/messung/perf/werkzeug/stichprobe.py +++ b/messung/perf/werkzeug/stichprobe.py @@ -1,7 +1,9 @@ """Sampling profiler for Windows without admin rights (no xperf/wpr): suspends the target's threads every few ms, walks their stacks with dbghelp (StackWalk64, the exe's PDB), resumes them. - python stichprobe.py [--env-file f] [--cwd d] [--prio idle] -- + python stichprobe.py [--env-file f] [--cwd d] [--stdin f] [--prio idle] -- + +`--stdin f` feeds the file to the target's stdin (the engine `rechner` reads one request per line). Writes self time (innermost frame) and inclusive time (function anywhere on the stack) per function, plus the heaviest call paths. Build the target with line tables (`CARGO_PROFILE_RELEASE_DEBUG= @@ -134,6 +136,7 @@ def main(): cmd = a[a.index("--") + 1:] env = dict(os.environ) cwd = None + ein = None i = 0 while i < len(rest): if rest[i] == "--env-file": @@ -142,6 +145,9 @@ def main(): k, v = kv.split("=", 1) env[k] = v i += 2 + elif rest[i] == "--stdin": + ein = open(rest[i + 1], "rb") + i += 2 elif rest[i] == "--cwd": cwd = rest[i + 1] i += 2 @@ -149,7 +155,7 @@ def main(): i += 1 env.setdefault("POKERBENCH_THREADS", "1") p = subprocess.Popen(cmd, env=env, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - creationflags=0x40) # IDLE_PRIORITY_CLASS + stdin=ein, creationflags=0x40) # IDLE_PRIORITY_CLASS hproc = k32.OpenProcess(0x1F0FFF, False, p.pid) time.sleep(1.0) exedir = os.path.dirname(os.path.abspath(cmd[0])) diff --git a/messung/solver_kern/LATENZ.md b/messung/solver_kern/LATENZ.md new file mode 100644 index 00000000..59d83a56 --- /dev/null +++ b/messung/solver_kern/LATENZ.md @@ -0,0 +1,76 @@ +# Latenz: der langsame Pfad ohne Solver (19.11.) + +Auftrag Orchestrator 19.11.: Den langsamen Heuristik-Pfad profilieren und beheben. Gemeldet waren 17 von 480 +Entscheidungen über 1,5 s, ohne Solver. Ziel: alle Entscheidungen unter 1,5 s an 12 Tischen, mit bitgleichen +Entscheidungen. + +## Ergebnis: alle Entscheidungen unter 1,5 s + +Gemessen auf 480 Turn-Spots gegen Einsatz (`spotsTG-latenz.jsonl`), 12 Tische, mit dem Live-Schalter von Stufe 2b. + +| Messung | Kern | über 1,5 s | p99 | max | +|---|---|---|---|---| +| Wie live: frischer Prozess je Aufruf (`latenz-frisch-*.json`) | live (main 9828629b) | 23 von 480 | 2 528 ms | 2 728 ms | +| Wie live: frischer Prozess je Aufruf | **neu** | **0 von 480** | 1 138 ms | 1 192 ms | +| Ein Prozess je Tisch (`latenz-dauer-kern30.json`) | **neu** | **0 von 480** | 1 090 ms | 1 138 ms | + +Beim Lauf „ein Prozess je Tisch“ hatte live 17 Fälle über 1,5 s (Stufe 2b). + +## Ursache + +Die 17 langsamen Fälle waren keine Heuristik. Es war das Turn-Spiel E3 (`TURN_SPIEL=grund`): Es entscheidet die +Turn-Lagen, die der Solver-Kern an die Heuristik zurückgibt (Züge, schwache Paare, ungelesene Gegner). + +**Wie live gerufen wird:** `entscheiden/decide.py` startet für jeden Stapel einen frischen Kern-Prozess. Darum +bezahlt jeder Aufruf alles Laden neu, und der Cache des Kerns hilft nie. + +**Was ein E3-Turn kostete:** Gemessen wurde ein einzelner frischer Prozess, das Profil kommt aus +`messung/perf/werkzeug/stichprobe.py --stdin`. +- Live dauerte ein E3-Spot 2,2 bis 2,7 s. +- Im Profil: + - `TrSolver::walk`: 46 % + - `show_into`: 28 % + - Aufbau der Indextabellen für alle Flop- und Turn-Boards (`Street::new`): rund 21 % +- Dazu kam das Laden der Kartenabstraktion. +- Nach dem Laden blieb der Solve, rund 1,1 bis 1,4 s Rechenzeit auf einem Faden. +- Manche Hände fallen beim Ausdünnen aus dem Spiel. Auch für sie wurde gerechnet, danach wurde doch die Heuristik + genommen. + +## Behebung, ohne eine Zahl zu ändern + +1. **Abstraktion nur einmal laden.** `blueprint::ranges` teilt sie über alle Szenarien (`Arc`). Der Kern lädt sie + im Hintergrund vor (`ranges::vorladen`), sobald `TURN_SPIEL=grund` gesetzt ist. + - Nur die Abstraktion wird vorgeladen, die Szenarien nicht. Deren Gewichte hängen am Faden-Kontext der ersten + Entscheidung, zum Beispiel am Rake-Bereich. Im Hintergrund gebaut, änderten sie Ranges (160×121 → 160×131). +2. **Index nur für die Boards, die gefragt werden** (`iso::Index`). + - Die Zahl der Hände je Board kommt aus Burnside statt aus dem vollen Durchlauf. + - Die sortierten Schlüssel eines Boards entstehen erst beim ersten Zugriff. + - Test `index_matches_street`: Offsets und Indizes gleich wie bisher, auf allen Flops, jedem 37. Turn-Board + und je einer Kopie mit vertauschten Farben. +3. **Kein Solve, wenn die eigene Hand ausgedünnt ist.** Die Prüfung kommt jetzt vor dem Solve, das Ergebnis ist + ohnehin die Heuristik. + - Der Solve hat keine Frist und ist deterministisch. Der fehlende Cache-Eintrag ändert also keine spätere + Entscheidung. +4. **Solve auf 5 Fäden** (`TrSolver::run_parallel`, `TURN_FAEDEN`, Vorgabe 5, nur im Kern-Binary). + - Jede River-Karte schreibt nur ihre eigenen Zeilen. + - Der Hauptfaden summiert die Kartenwerte in Kartenreihenfolge. + - Jede Zahl ist die von `run`: Test `run_parallel_is_run_bit_for_bit` vergleicht Regrets und Summen Bit für + Bit (beide Startspieler, Knotensperre, Flop-Form). + - Bibliothek, Sims und Benches bleiben bei einem Faden. + +## Tore + +| Prüfung | Ergebnis | +|---|---| +| Bitgleich, 480 Spots, live gegen neu | 5 Spots anders, alle im Solver-Kern-Turn: Iterationszahl 25–40 je nach Rechenzeit-Kappe. Kein E3- und kein Heuristik-Spot anders. Die Gegenprobe live gegen live zeigt 4 Spots derselben Art | +| Pflichtfälle (`pflicht-latenz.txt`) | BESTANDEN, 38 von 43 wie live | +| Tests | `run_parallel_is_run_bit_for_bit` und `index_matches_street` grün. Bibliothek 364 von 365 grün. `sim::lerner::wechsler_wechselt_nach_n_haenden` scheitert nur im Gesamtlauf mit 8 Fäden und besteht allein. Die Datei ist hier unberührt | + +## Offen (für den Orchestrator) + +- **Frischer Prozess je Stapel.** Ein dauerhafter Kern je Läufer spart das Laden ganz und lässt den Cache wirken. + Das ist eine Änderung am Betrieb (`decide.py`), nicht am Kern. +- **Szenario-Gewichte hängen am Faden-Kontext der ersten Entscheidung.** Das ist alt und betrifft nur Prozesse + mit mehreren Entscheidungen. Es ist nicht behoben, nur nicht verschlimmert. +- **Der Solver-Kern-Turn ist zwischen Läufen nicht bitgleich.** Die Kappe zählt Rechenzeit, die Iterationszahl + schwankt. Das betrifft Fälle mit EV-Abstand um 0,01 bb. diff --git a/messung/solver_kern/latenz-dauer-kern30.json b/messung/solver_kern/latenz-dauer-kern30.json new file mode 100644 index 00000000..d4165fc9 --- /dev/null +++ b/messung/solver_kern/latenz-dauer-kern30.json @@ -0,0 +1,19 @@ +{ + "tische": 12, + "entscheidungen": 480, + "solver": 210, + "alle_ms": { + "p50": 24.234200001956197, + "p90": 569.5261000000755, + "p99": 1089.607400001114, + "max": 1137.652600002184 + }, + "solver_ms": { + "p50": 232.2932999995828, + "p90": 826.0498999989068, + "p99": 1103.0027000015252, + "max": 1137.652600002184 + }, + "ueber_1500ms": 0, + "langsam": [] +} \ No newline at end of file diff --git a/messung/solver_kern/latenz-frisch-kern30.json b/messung/solver_kern/latenz-frisch-kern30.json new file mode 100644 index 00000000..aab959db --- /dev/null +++ b/messung/solver_kern/latenz-frisch-kern30.json @@ -0,0 +1,13 @@ +{ + "tische": 12, + "stapel": 1, + "aufrufe": 480, + "alle_ms": { + "p50": 84.15099999911035, + "p90": 616.1062000028323, + "p99": 1137.9797000008693, + "max": 1191.6390000005777 + }, + "ueber_1500ms": 0, + "langsam": [] +} \ No newline at end of file diff --git a/messung/solver_kern/latenz-frisch-live.json b/messung/solver_kern/latenz-frisch-live.json new file mode 100644 index 00000000..ffb63e8d --- /dev/null +++ b/messung/solver_kern/latenz-frisch-live.json @@ -0,0 +1,182 @@ +{ + "tische": 12, + "stapel": 1, + "aufrufe": 480, + "alle_ms": { + "p50": 79.29530000183149, + "p90": 926.5109000007214, + "p99": 2528.2924999992247, + "max": 2727.6545999993687 + }, + "ueber_1500ms": 23, + "langsam": [ + [ + 2728, + [ + "177596100130.10" + ], + false + ], + [ + 2713, + [ + "166614200264.11" + ], + true + ], + [ + 2620, + [ + "164047600812.11" + ], + true + ], + [ + 2554, + [ + "162436300171.10" + ], + false + ], + [ + 2528, + [ + "172321901553.10" + ], + false + ], + [ + 2473, + [ + "176955100271.11" + ], + true + ], + [ + 2436, + [ + "170120900284.8" + ], + false + ], + [ + 2407, + [ + "176170700054.8" + ], + true + ], + [ + 2358, + [ + "160773500489.8" + ], + true + ], + [ + 2351, + [ + "169706000395.11" + ], + false + ], + [ + 2243, + [ + "171205001207.9" + ], + false + ], + [ + 2236, + [ + "175141400222.10" + ], + true + ], + [ + 2202, + [ + "176417400508.11" + ], + true + ], + [ + 2165, + [ + "171421700038.8" + ], + true + ], + [ + 2151, + [ + "164799400128.9" + ], + false + ], + [ + 2145, + [ + "178718000731.11" + ], + true + ], + [ + 2100, + [ + "164043800254.8" + ], + false + ], + [ + 2093, + [ + "175211500482.10" + ], + true + ], + [ + 2052, + [ + "164634302000.8" + ], + true + ], + [ + 1839, + [ + "170357300245.9" + ], + true + ], + [ + 1689, + [ + "177796100736.10" + ], + false + ], + [ + 1628, + [ + "165103201033.9" + ], + false + ], + [ + 1579, + [ + "163477500546.10" + ], + false + ], + [ + 1466, + [ + "177541900118.10" + ], + false + ] + ] +} \ No newline at end of file diff --git a/messung/solver_kern/pflicht-latenz.txt b/messung/solver_kern/pflicht-latenz.txt new file mode 100644 index 00000000..f916c1cf --- /dev/null +++ b/messung/solver_kern/pflicht-latenz.txt @@ -0,0 +1,45 @@ +PFLICHTFÄLLE Kandidat SOLVER_KERN=river+turn+tohne=nichts+tgohne=zug/paar_schwach+tgstark+wu=heur+flop+fohne=nichts: BESTANDEN + Soll getroffen: Live 38 von 43, Kandidat 38 von 43; Ziele (live noch falsch) behoben: 0 von 3 + 178593300919 TURN Soll FOLD (tol. CALL) live FOLD -> FOLD Soll 9d9h | 4h7d8s Jc | TURN toCall 0.66 Pot 1.32 + 178593300919 RIVER Soll FOLD live FOLD -> FOLD Soll 9d9h | 4h7d8s Jc 7h | RIVER toCall 0.89 Pot 3.0 + 177599200076 RIVER Soll FOLD live FOLD -> FOLD Soll 7cTh | 4c2d7s 6h Js | RIVER toCall 0.39 Pot 1.88 + 177536500401 RIVER Soll FOLD live FOLD -> FOLD Soll 6c6d | 7dTdJc Qh 8s | RIVER toCall 0.2 Pot 0.61 + 177536500403 RIVER Soll FOLD live FOLD -> FOLD Soll 7c7d | Ts3dKc 4s 2h | RIVER toCall 0.38 Pot 1.13 + 177536500421 RIVER Soll FOLD live FOLD -> FOLD Soll 8h6c | JdKd2h 8d As | RIVER toCall 0.12 Pot 0.35 + 177613400152 RIVER Soll FOLD live FOLD -> FOLD Soll Qs4h | JdKhQc 7d Ah | RIVER toCall 0.19 Pot 0.43 + 177619300146 RIVER Soll FOLD live FOLD -> FOLD Soll Ad7s | 7dQcTs 8h Jh | RIVER toCall 1.1 Pot 2.02 + 177600300575 RIVER Soll FOLD live FOLD -> FOLD Soll Tc6c | Ts9sKs 3s 2h | RIVER toCall 0.4 Pot 0.75 + 177599200076 TURN Soll FOLD live CALL -> CALL verfehlt Soll (wie Live) 7cTh | 4c2d7s 6h | TURN toCall 0.37 Pot 1.12 + 177718400199 TURN Soll FOLD live CALL -> CALL verfehlt Soll (wie Live) TdTs | Jh5hKh 8d | TURN toCall 0.41 Pot 0.96 + 177113201687 FLOP Soll FOLD/CALL live CALL -> CALL Soll 7h8d | 8h9dJc | FLOP toCall 0.16 Pot 0.37 + 177087901694 FLOP Soll FOLD/CALL live CALL -> CALL Soll QsAd | Qh8c9c | FLOP toCall 0.31 Pot 0.62 + 177862900036 TURN Soll FOLD/CALL live CALL -> CALL Soll 5hAd | Qc7dAc 8s | TURN toCall 0.3 Pot 0.6 + 178854100443 RIVER Soll CHECK (tol. RAISE<=1.0) live RAISE 0.67P -> RAISE 0.67P toleriert JdAc | 6cAh2c Kd Js | RIVER toCall 0.0 Pot 0.79 + 178870300411 RIVER Soll FOLD live FOLD -> FOLD Soll 7dJd | 9c9hTc 8c 2c | RIVER toCall 0.28 Pot 0.66 + 178903200610 RIVER Soll RAISE (tol. CHECK) live RAISE 0.33P -> RAISE 0.33P Soll 7hAs | AhJdTh Ac 4h | RIVER toCall 0.0 Pot 0.19 + 179095600052 RIVER Soll RAISE (tol. CHECK) live RAISE 0.88P -> RAISE 0.88P Soll AcJc | Js7h6d Jh Tc | RIVER toCall 0.0 Pot 1.13 + 178908100701 RIVER Soll RAISE (tol. CHECK) live CHECK -> CHECK toleriert 9hKh | 9dTdTh 2c Ts | RIVER toCall 0.0 Pot 0.5 + 177113201683 FLOP Soll CALL (tol. FOLD) live RAISE 2.85P -> RAISE 2.85P verfehlt Soll (wie Live) QsKd | JhKs2s | FLOP toCall 0.32 Pot 0.74 + 177113202312 RIVER Soll CALL (tol. FOLD) live CALL -> CALL Soll JcJd | 7s9dTs 5d 2c | RIVER toCall 0.3 Pot 0.9 + 179003200362 RIVER Soll CALL (tol. FOLD) live CALL -> CALL Soll 2cAh | 3sAd3d Qs 6s | RIVER toCall 0.41 Pot 1.59 + 178933500669 RIVER Soll CHECK live CHECK -> CHECK Soll AsAh | Tc4d9s 6c Kd | RIVER toCall 0.0 Pot 1.12 + 178907801564 RIVER Soll CHECK (tol. RAISE<=1.0) live CHECK -> CHECK Soll Ac8h | 7sJh8d 5s Jc | RIVER toCall 0.0 Pot 0.68 + 179404400152 PREFLOP Soll FOLD live FOLD -> FOLD Soll 9cAh | - | PREFLOP toCall 2.58 Pot 6.24 + 177613400122 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.56 live CALL -> CALL Soll 8s5s | JsTs2d | FLOP toCall 0.08 Pot 0.29 + 177679200513 TURN Soll CHECK/CALL/FOLD/RAISE<=1.77 live RAISE 1.77P -> RAISE 1.77P Soll QdAc | Js8sTh 6c | TURN toCall 0.15 Pot 0.39 + 177776800160 TURN Soll CHECK/CALL/FOLD/RAISE<=1.71 live RAISE 1.25P -> RAISE 1.25P Soll 9dQd | JhTc9h Js | TURN toCall 0.19 Pot 0.54 + 177689800533 RIVER Soll CHECK/CALL/FOLD/RAISE<=1.43 live RAISE 1.42P -> RAISE 1.42P Soll Ah8h | 9d8d4d Tc 8s | RIVER toCall 0.04 Pot 0.19 + 177689800544 RIVER Soll CHECK/CALL/FOLD/RAISE<=1.80 live CALL -> CALL Soll AsQh | 2c4cTs 4d Ac | RIVER toCall 0.19 Pot 0.48 + 177087902397 TURN Soll CHECK/CALL/FOLD/RAISE<=1.80 live CALL -> CALL Soll JsQc | AsKs4s 8c | TURN toCall 0.04 Pot 0.1 + 177810700200 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.89 live CALL -> RAISE 1.41P Soll KdJd | 4hTsJs | FLOP toCall 0.12 Pot 0.27 + 177730700400 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.65 live CALL -> CALL Soll Th8h | 4sAh3h | FLOP toCall 0.1 Pot 0.31 + 178371400594 TURN Soll CHECK/CALL/FOLD/RAISE<=1.41 live RAISE 1.40P -> RAISE 1.40P Soll Jd8d | Qd6h3s 7d | TURN toCall 0.02 Pot 0.1 + 178543200043 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.76 live RAISE 1.30P -> CALL Soll QhJc | 3sJdJs | FLOP toCall 0.19 Pot 0.5 + 178493100165 FLOP Soll CHECK/CALL/FOLD/RAISE<=2.00 live FOLD -> CALL Soll 8sAh | 7d8d6c | FLOP toCall 0.28 Pot 0.56 + 178805500097 RIVER Soll CHECK/CALL/FOLD/RAISE<=1.0 live RAISE 0.33P -> RAISE 0.33P Soll KhKd | 9s6hQd Kc Th | RIVER toCall 0.0 Pot 0.88 + 178702201349 RIVER Soll CHECK/CALL/FOLD/RAISE<=1.0 live CHECK -> CHECK Soll QhAc | As4c3h Td 7d | RIVER toCall 0.0 Pot 1.8 + 179003500246 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.50 live RAISE 1.50P -> RAISE 1.50P Soll 7c7s | 4c7h2h | FLOP toCall 0.12 Pot 0.48 + 179132701195 RIVER Soll CHECK/CALL/FOLD/RAISE<=1.0 live RAISE 0.33P -> RAISE 0.33P Soll Tc7s | 4hTd7h 4s 9h | RIVER toCall 0.0 Pot 0.88 + 179403500241 TURN Soll CHECK/CALL/FOLD/RAISE<=1.67 live RAISE 1.67P -> CALL Soll 9cKc | 4h2hKh Ks | TURN toCall 0.05 Pot 0.15 + 178887301815 FLOP Soll CHECK/CALL/FOLD/RAISE<=1.86 live RAISE 1.86P -> CALL Soll KhKd | 5d6d4d | FLOP toCall 0.68 Pot 1.59 + 179394000343 TURN Soll CHECK/CALL/FOLD/RAISE<=1.65 live RAISE 0.77P -> RAISE 0.77P Soll JhQh | 2dJd8d 9h | TURN toCall 0.12 Pot 0.37 diff --git a/messung/solver_kern/werk/latenz_frisch.py b/messung/solver_kern/werk/latenz_frisch.py new file mode 100644 index 00000000..7e0666b4 --- /dev/null +++ b/messung/solver_kern/werk/latenz_frisch.py @@ -0,0 +1,53 @@ +"""Latenz wie live: `entscheiden/decide.py` startet für jeden Stapel einen frischen Kern (`subprocess.run`), die +Lösung des Turnspiels (E3) und die Grundstrategie-Dateien laden also bei jeder Entscheidung neu. N Tische parallel, +je Spot ein frischer Prozess, gemessen von Start bis Antwort. +Aufruf: latenz_frisch.py [N] [je] [stapel]""" +import json, os, subprocess, sys, threading, time + +spots_pfad, exe, baum, aus, arm = sys.argv[1:6] +n = int(sys.argv[6]) if len(sys.argv) > 6 else 12 +je = int(sys.argv[7]) if len(sys.argv) > 7 else 40 +stapel = int(sys.argv[8]) if len(sys.argv) > 8 else 1 +sys.path.insert(0, os.path.join(baum, "lesen")) +import roentgen # noqa: E402 + +env = dict(os.environ) +env.update(roentgen.lies_schalter(os.path.join(baum, "betrieb", "kern_schalter.txt"))) +env.update(dict(kv.split("=", 1) for kv in arm.split(";") if kv)) +env.pop("SOLVER_ZEIT", None) +env.setdefault("KERN_NOTBREMSE_MS", "8000") # wie decide.py +spots = [json.loads(z) for z in open(spots_pfad, encoding="utf-8")] +spots = [s for s in spots if s["topf"] >= 20][: n * je] +erg, sperre = [], threading.Lock() + + +def tisch(k): + mein = spots[k::n] + for i in range(0, len(mein), stapel): + teil = mein[i:i + stapel] + t0 = time.perf_counter() + r = subprocess.run([exe], input="\n".join(json.dumps(s["req"]) for s in teil) + "\n", capture_output=True, + text=True, env=env, timeout=60) + ms = (time.perf_counter() - t0) * 1e3 + gruende = [json.loads(z).get("reason") or "" for z in r.stdout.strip().split("\n") if z.strip()] + with sperre: + erg.append((ms, [s["id"] for s in teil], any("turn game" in g or "Turnspiel" in g for g in gruende))) + + +th = [threading.Thread(target=tisch, args=(k,)) for k in range(n)] +[t.start() for t in th] +[t.join() for t in th] + + +def q(v, p): + v = sorted(v) + return v[min(len(v) - 1, int(p * len(v)))] if v else None + + +alle = [m for m, _, _ in erg] +r = {"tische": n, "stapel": stapel, "aufrufe": len(alle), + "alle_ms": {"p50": q(alle, .5), "p90": q(alle, .9), "p99": q(alle, .99), "max": max(alle)}, + "ueber_1500ms": sum(m > 1500 for m in alle), + "langsam": sorted([(round(m), i, e3) for m, i, e3 in erg if m > 1300], key=lambda x: -x[0])} +json.dump(r, open(aus, "w", encoding="utf-8", newline="\n"), indent=1) +print(json.dumps({k: v for k, v in r.items() if k != "langsam"})) diff --git a/src/blueprint/iso.rs b/src/blueprint/iso.rs index 94c368cd..b579472d 100644 --- a/src/blueprint/iso.rs +++ b/src/blueprint/iso.rs @@ -116,6 +116,95 @@ impl Street { } } +/// The dense index of `Street` without enumerating the street: the same numbers, built in milliseconds instead of +/// about a second for the turn (13.96 M deals). The engine loads the card abstraction in every process (the live +/// bridge starts a fresh kern per decision batch) but looks up only the boards of its spot. +/// - Boards: every canonical board key, sorted as in `Street`. +/// - Offsets: the number of canonical hands of each board, counted with Burnside's lemma over the suit +/// permutations that keep the board (`hands_on_board`), instead of listing them. +/// - Hands: the sorted deal keys of a board, built on its first lookup (one board, 1 326 hole pairs). +pub struct Index { + board_keys: Vec, + offset: Vec, + hand_keys: Vec>>, +} + +/// Canonical hands of a board (by its key): orbits of the hole pairs off the board under the suit +/// permutations g that keep every suit's board ranks (Burnside: the mean of the pairs each g fixes). A pair +/// is fixed when both cards are (their suits stay) or when g swaps their suits and the cards are one rank. +fn hands_on_board(key: u64) -> u32 { + let lane = |s: usize| ((key >> (13 * (3 - s))) & 0x1FFF) as u32; + let r = [lane(0), lane(1), lane(2), lane(3)]; + let free = |s: usize| 13 - r[s].count_ones(); + let (mut sum, mut group) = (0u32, 0u32); + for a in 0..4 { + for b in 0..4 { + for c in 0..4 { + for d in 0..4 { + let g = [a, b, c, d]; + if a == b || a == c || a == d || b == c || b == d || c == d || (0..4).any(|s| r[g[s]] != r[s]) { + continue; + } + group += 1; + let fixed: u32 = (0..4).filter(|s| g[*s] == *s).map(free).sum(); + let swapped: u32 = (0..4).filter(|s| g[*s] > *s && g[g[*s]] == *s).map(free).sum(); + sum += fixed * fixed.saturating_sub(1) / 2 + swapped; + } + } + } + } + sum / group +} + +impl Index { + pub fn new(board_cards: usize) -> Index { + let mut board_keys: Vec = subsets(board_cards).into_iter().map(board_key).collect(); + board_keys.sort_unstable(); + board_keys.dedup(); + let mut offset = Vec::with_capacity(board_keys.len() + 1); + let mut total = 0u32; + for k in &board_keys { + offset.push(total); + total += hands_on_board(*k); + } + offset.push(total); + let hand_keys = board_keys.iter().map(|_| std::sync::OnceLock::new()).collect(); + Index { board_keys, offset, hand_keys } + } + + /// Number of canonical deals (as `Street::count`). + pub fn count(&self) -> usize { + *self.offset.last().unwrap_or(&0) as usize + } + + /// As `Street::index`. + pub fn index(&self, board: u64, hand: u64) -> Option { + if board & hand != 0 { + return None; + } + let bi = self.board_keys.binary_search(&board_key(board)).ok()?; + // Every board of a class has the same set of deal keys (a suit renaming maps one onto the other), + // so the board asked about stands in for the class's representative. + let keys = self.hand_keys[bi].get_or_init(|| { + let d = deck(); + let mut ks: Vec = Vec::with_capacity(1326); + for i in 0..52 { + for j in i + 1..52 { + let h = d[i] | d[j]; + if h & board == 0 { + ks.push(deal_key(board, h)); + } + } + } + ks.sort_unstable(); + ks.dedup(); + ks + }); + let hi = keys.binary_search(&deal_key(board, hand)).ok()?; + Some(self.offset[bi] + hi as u32) + } +} + /// A canonical deal's cards: `(board, hand)` of the representative at `index`. pub fn deal_at(street: &Street, index: u32) -> (u64, u64) { let bi = street.offset.partition_point(|o| *o <= index) - 1; @@ -144,6 +233,28 @@ mod tests { assert_eq!(s.count(), 13_960_050); } + /// `Index` gives `Street`'s numbers: same offsets on every flop and turn board, same index for every + /// flop deal and for every hand on a stride of turn boards (each in a suit-renamed copy too). + #[test] + fn index_matches_street() { + for cards in [3, 4] { + let s = Street::new(cards); + let ix = Index::new(cards); + assert_eq!(ix.board_keys, s.board_keys); + assert_eq!(ix.offset, s.offset); + assert_eq!(ix.count(), s.count()); + let stride = if cards == 3 { 1 } else { 37 }; + let swap = |m: u64| ((m & 0xFFFF) << 16) | ((m >> 16) & 0xFFFF) | (m & !0xFFFF_FFFF); + for (bi, b) in s.boards.iter().enumerate().step_by(stride) { + for h in &s.hands[bi] { + let want = s.index(*b, *h); + assert_eq!(ix.index(*b, *h), want); + assert_eq!(ix.index(swap(*b), swap(*h)), want); + } + } + } + } + #[test] fn a_suit_renaming_keeps_the_index() { let s = Street::new(3); diff --git a/src/blueprint/ranges.rs b/src/blueprint/ranges.rs index fe59e198..b426808d 100644 --- a/src/blueprint/ranges.rs +++ b/src/blueprint/ranges.rs @@ -105,6 +105,24 @@ fn karten_maske(cards: &[Card]) -> u64 { static GRUND: [std::sync::OnceLock>; ALLE.len()] = [const { std::sync::OnceLock::new() }; ALLE.len()]; +/// The card abstraction of `$GRUNDSTRATEGIE/abstraktion/`, loaded once and shared by every scenario (building +/// its turn street takes about a second; it used to be built again for each scenario on its first spot). +fn abstraktion(dir: &std::path::Path) -> Option> { + static ABS: std::sync::OnceLock>> = std::sync::OnceLock::new(); + ABS.get_or_init(|| super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok().map(std::sync::Arc::new)).clone() +} + +/// Load the card abstraction now (live start with `TURN_SPIEL=grund`, on a background thread): the first turn +/// spot no longer waits about a second for it. Only the abstraction, which is plain file data: a scenario's +/// game (`Grund::mit`) takes its preflop weights from the charts, which read the deciding thread's context +/// (built on another thread its ranges differ), so the scenarios still load lazily inside a decision, as +/// before. A decision that arrives during the load waits for it. +pub fn vorladen() { + if let Some(dir) = std::env::var_os("GRUNDSTRATEGIE") { + let _ = abstraktion(std::path::Path::new(&dir)); + } +} + /// The blueprint of scenario `sz`, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and /// `$GRUNDSTRATEGIE/grundstrategie/`: with `GRUNDSTRATEGIE_TEXTUR=1` the board-texture refinement `-t.ckpt` where one exists /// (and matches `Textur::standard()`), else the plain `.ckpt`; `None` without the variable or @@ -114,18 +132,17 @@ pub fn grundstrategie_fuer(sz: &Szenario) -> Option<&'static (Grund, Tabellen)> .get_or_init(|| { let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); let sz = ALLE.iter().find(|z| z.id == sz.id)?; - let abs = dir.join("abstraktion"); let ckpt = dir.join("grundstrategie"); let fein = ckpt.join(format!("{}-t.ckpt", sz.id)); // Opt-in until the refined run has passed its gate (a run rewrites the file every round). if std::env::var_os("GRUNDSTRATEGIE_TEXTUR").is_some_and(|v| v == "1") && fein.exists() { - let s = Grund::mit_textur(sz, super::s1::Abstraktion::laden(&abs).ok()?, super::textur::Textur::standard()); + let s = Grund::mit_textur(sz, abstraktion(&dir)?, super::textur::Textur::standard()); let mut tab = Tabellen::neu(&s); if super::textur::ckpt_passt(&fein, tab.eintraege()) && tab.datei_lesen(&fein) { return Some((s, tab)); } } - let s = Grund::mit(sz, super::s1::Abstraktion::laden(&abs).ok()?); + let s = Grund::mit(sz, abstraktion(&dir)?); let mut tab = Tabellen::neu(&s); tab.datei_lesen(&ckpt.join(format!("{}.ckpt", sz.id))).then_some((s, tab)) }) diff --git a/src/blueprint/s1.rs b/src/blueprint/s1.rs index 60ca4fcc..7605f04b 100644 --- a/src/blueprint/s1.rs +++ b/src/blueprint/s1.rs @@ -10,7 +10,7 @@ //! by the card abstraction (`abstraktion`): flop / turn classes from the tables, river by EHS. use super::abstraktion::{combo_index, combos, river_class, river_ehs, CLASSES}; -use super::iso::{self, Street}; +use super::iso::{self, Index}; use super::mccfr::{Baum, Knoten, Spiel, Zufall}; use super::szenario::Szenario; use super::textur::Textur; @@ -155,8 +155,9 @@ impl Einsatzbaum { /// Card abstraction tables; `None` = one class on that street (for tests without tables). pub struct Abstraktion { - pub flop: Option<(Street, Vec)>, - pub turn: Option<(Street, Vec)>, + /// Lazy dense index (`iso::Index`, the numbers of `iso::Street`) and the class per deal. + pub flop: Option<(Index, Vec)>, + pub turn: Option<(Index, Vec)>, pub river: Vec, } @@ -167,7 +168,7 @@ impl Abstraktion { let flop = lies("flop.u8")?; let turn = lies("turn.u8")?; let river = lies("river.f32")?.chunks(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); - let (s3, s4) = (Street::new(3), Street::new(4)); + let (s3, s4) = (Index::new(3), Index::new(4)); assert_eq!(flop.len(), s3.count(), "flop table does not match the flop street"); assert_eq!(turn.len(), s4.count(), "turn table does not match the turn street"); Ok(Abstraktion { flop: Some((s3, flop)), turn: Some((s4, turn)), river }) @@ -189,7 +190,8 @@ pub type S1 = Grund; pub struct Grund { pub sz: &'static Szenario, pub baum: Einsatzbaum, - pub abstraktion: Abstraktion, + /// Shared between the scenarios of one process (`ranges::grundstrategie_fuer` loads the tables once). + pub abstraktion: std::sync::Arc, pub alle: Vec, /// Preflop weight per combo of each player (0 = out of position, 1 = in position); S1: [big /// blind call, button open]. @@ -210,20 +212,21 @@ fn gewichte(alle: &[u64], f: impl Fn(Card, Card) -> f64) -> Vec { impl Grund { /// The game with the board-texture refinement (checkpoint `-t.ckpt`). - pub fn mit_textur(sz: &'static Szenario, abstraktion: Abstraktion, textur: Textur) -> Grund { + pub fn mit_textur(sz: &'static Szenario, abstraktion: impl Into>, textur: Textur) -> Grund { let mut g = Grund::mit(sz, abstraktion); g.textur = Some(textur); g } - pub fn neu(abstraktion: Abstraktion) -> Grund { + pub fn neu(abstraktion: impl Into>) -> Grund { Grund::mit(Szenario::s1(), abstraktion) } /// The game of scenario `sz` with ranges from the engine's preflop charts at its stack: /// the opener's open frequency (times its call frequency against the 3-bet in a 3-bet pot) and /// the big blind's call (3-bet) frequency against that open. - pub fn mit(sz: &'static Szenario, abstraktion: Abstraktion) -> Grund { + pub fn mit(sz: &'static Szenario, abstraktion: impl Into>) -> Grund { + let abstraktion = abstraktion.into(); let alle = combos(); let (depth, opener) = (sz.stapel, sz.eroeffner); let klasse = |a: Card, b: Card| class_of(a, b).unwrap(); diff --git a/src/cfr/turn_river_game.rs b/src/cfr/turn_river_game.rs index c9005c2d..2247f710 100644 --- a/src/cfr/turn_river_game.rs +++ b/src/cfr/turn_river_game.rs @@ -286,6 +286,26 @@ pub struct TrSolver { spare: Vec>, } +/// Rows and spare buffers of `run_parallel`: the turn rows, or one dealt card's rows of the second street. +struct Store { + regret: Vec>, + sums: Vec>, + spare: Vec>, +} + +impl Store { + /// As `TrSolver::take`: `n` zeros from the spares, room for `most`. + fn take(&mut self, n: usize, most: usize) -> Vec { + let mut v = self.spare.pop().unwrap_or_default(); + v.clear(); + if v.capacity() < n { + v.reserve(n.max(most)); + } + v.resize(n, 0.0); + v + } +} + /// The average strategy: per decision node, per copy (1 on the turn, one per river card on the /// river), per hand, the action probabilities. #[derive(Clone, Debug)] @@ -797,6 +817,207 @@ impl TrSolver { } } + /// `run` with the subtrees below each chance node (one per dealt card) on `threads` worker threads. + /// Every number is the one `run` computes, in the same order: a card's subtree writes only that card's + /// rows of its nodes (`regret` / `sums` at `r * n * a`), the main thread sums the card values in card + /// order, and each operation is `walk`'s. Only wall time changes. For solves without a deadline: a + /// deadline counts the CPU time of the calling thread, which the workers do not spend. + pub fn run_parallel(&mut self, iterations: u32, threads: usize) { + let k = self.rc.len(); + if threads < 2 || k < 2 { + return self.run(iterations); + } + use std::sync::{mpsc, Mutex}; + type Job = (usize, usize, usize, Vec, Vec, f64); + // Turn rows stay whole; each card's rows of the second-street nodes move into that card's store. + let mut turn = Store { regret: std::mem::take(&mut self.regret), sums: std::mem::take(&mut self.sums), spare: std::mem::take(&mut self.spare) }; + let second: Vec = self.game.nodes.iter().map(|x| matches!(x, TNode::Dec { street, .. } if *street != 0)).collect(); + let rivers: Vec> = (0..k) + .map(|r| { + let cut = |v: &Vec>| -> Vec> { + v.iter() + .enumerate() + .map(|(node, x)| { + if second[node] { + let w = x.len() / k; + x[r * w..(r + 1) * w].to_vec() + } else { + Vec::new() + } + }) + .collect() + }; + Mutex::new(Store { regret: cut(&turn.regret), sums: cut(&turn.sums), spare: Vec::new() }) + }) + .collect(); + let most = self.n[0].max(self.n[1]) * self.game.acts.iter().map(Vec::len).max().unwrap_or(1).max(1); + let start = self.iterations; + { + let me = &*self; + let rivers = &rivers; + let turn = &mut turn; + let (task_tx, task_rx) = mpsc::channel::(); + let task_rx = Mutex::new(task_rx); + let task_rx = &task_rx; + let (done_tx, done_rx) = mpsc::channel::<(usize, Vec)>(); + std::thread::scope(|sc| { + for _ in 0..threads.min(k) { + let done_tx = done_tx.clone(); + sc.spawn(move || loop { + let job = match task_rx.lock() { + Ok(g) => g.recv().ok(), + Err(_) => None, + }; + let Some((child, p, r, own, opp, weight)) = job else { return }; + let v = match rivers[r].lock() { + Ok(mut st) => me.walk_store(&mut st, most, child, p, &own, &opp, r, weight, &mut |_, _, _, _, _| unreachable!("one chance node per path")), + Err(_) => return, + }; + if done_tx.send((r, v)).is_err() { + return; + } + }); + } + drop(done_tx); + let mut deal = |child: usize, p: usize, own: &[f64], opp: &[f64], weight: f64| -> Vec> { + for r in 0..k { + let o: Vec = own.iter().zip(&me.rc[r].free[p]).map(|(v, f)| v * f).collect(); + let q: Vec = opp.iter().zip(&me.rc[r].free[1 - p]).map(|(v, f)| v * f).collect(); + task_tx.send((child, p, r, o, q, weight)).expect("worker alive"); + } + let mut out: Vec> = vec![Vec::new(); k]; + for _ in 0..k { + let (r, v) = done_rx.recv().expect("worker alive"); + out[r] = v; + } + out + }; + for it in 0..iterations { + let weight = (start + it + 1) as f64; + for p in 0..2 { + let own = vec![1.0; me.n[p]]; + let opp = me.weights[1 - p].clone(); + let v = me.walk_store(turn, most, me.game.root, p, &own, &opp, NO_CARD, weight, &mut deal); + turn.spare.push(v); + } + } + drop(task_tx); + }); + } + // The card rows back into their nodes. + for (r, m) in rivers.into_iter().enumerate() { + let st = m.into_inner().expect("no worker panicked"); + for node in 0..second.len() { + if second[node] { + let w = st.regret[node].len(); + turn.regret[node][r * w..(r + 1) * w].copy_from_slice(&st.regret[node]); + turn.sums[node][r * w..(r + 1) * w].copy_from_slice(&st.sums[node]); + } + } + } + self.regret = turn.regret; + self.sums = turn.sums; + self.spare = turn.spare; + self.iterations = start + iterations; + } + + /// `walk` on a `Store` (the rows of one card, or the turn rows), offsets 0. A chance node goes to + /// `deal`, which returns each card's values; they are summed here in card order as in `walk`. + #[allow(clippy::too_many_arguments)] + fn walk_store( + &self, + st: &mut Store, + most: usize, + node: usize, + p: usize, + own: &[f64], + opp: &[f64], + r: usize, + weight: f64, + deal: &mut dyn FnMut(usize, usize, &[f64], &[f64], f64) -> Vec>, + ) -> Vec { + match self.game.nodes[node] { + TNode::Fold { folder, amt, rake } => { + let v = if folder == p { -amt } else { amt - rake }; + let mut out = st.take(self.n[p], most); + self.fold_into(p, opp, v, &mut out); + out + } + TNode::Show { half, rake } if rake == 0.0 => { + let mut out = st.take(self.n[p], most); + self.show_into(p, r, opp, half, &mut out); + out + } + TNode::Show { half, rake } => { + let mut out = st.take(self.n[p], most); + self.show_raked_into(p, r, opp, half, rake, &mut out); + out + } + TNode::Chance { child } => { + let mut total = st.take(self.n[p], most); + let vs = deal(child, p, own, opp, weight); + for (ri, v) in vs.into_iter().enumerate() { + let free = &self.rc[ri].free[p]; + for i in 0..total.len() { + total[i] += self.wr * v[i] * free[i]; + } + } + total + } + TNode::Dec { player, ref kids, .. } => { + let a = kids.len(); + let n = self.n[player]; + let mut sigma = st.take(n * a, most); + matched(&st.regret[node][..n * a], a, &mut sigma); + if let Some(Some((believed, w))) = self.lock.get(node) { + for (x, b) in sigma.iter_mut().zip(believed) { + *x = (1.0 - w) * *x + w * b; + } + } + if player == p { + let mut values: Vec> = Vec::with_capacity(a); + let mut reach = st.take(n, most); + for (k, kid) in kids.iter().enumerate() { + for (i, x) in reach.iter_mut().enumerate() { + *x = own[i] * sigma[i * a + k]; + } + values.push(self.walk_store(st, most, *kid, p, &reach, opp, r, weight, deal)); + } + st.spare.push(reach); + let mut node_value = st.take(n, most); + let (regret, sums) = (&mut st.regret[node], &mut st.sums[node]); + for i in 0..n { + node_value[i] = (0..a).map(|k| sigma[i * a + k] * values[k][i]).sum(); + for k in 0..a { + let reg = &mut regret[i * a + k]; + *reg = (*reg + values[k][i] - node_value[i]).max(0.0); + sums[i * a + k] += weight * own[i] * sigma[i * a + k]; + } + } + for v in values { + st.spare.push(v); + } + st.spare.push(sigma); + node_value + } else { + let mut total = st.take(self.n[p], most); + let mut reach = st.take(n, most); + for (k, kid) in kids.iter().enumerate() { + for (j, x) in reach.iter_mut().enumerate() { + *x = opp[j] * sigma[j * a + k]; + } + let v = self.walk_store(st, most, *kid, p, own, &reach, r, weight, deal); + total.iter_mut().zip(&v).for_each(|(t, x)| *t += x); + st.spare.push(v); + } + st.spare.push(reach); + st.spare.push(sigma); + total + } + } + } + } + /// The average strategy so far (uniform where a hand was never reached). pub fn strategy(&self) -> TrStrategy { let mut actions = Vec::new(); diff --git a/src/cfr/turn_river_game/tests.rs b/src/cfr/turn_river_game/tests.rs index a0b4abf0..b12bc873 100644 --- a/src/cfr/turn_river_game/tests.rs +++ b/src/cfr/turn_river_game/tests.rs @@ -379,3 +379,43 @@ fn timing_probe() { } } } + +/// `run_parallel` computes `run`'s numbers bit for bit: regrets and strategy sums of every node, on the +/// rank showdown and the equity table (flop game), with a node lock, after a mixed sequential start. +#[test] +fn run_parallel_is_run_bit_for_bit() { + let bits = |v: &[Vec]| v.iter().map(|x| x.iter().map(|y| y.to_bits()).collect::>()).collect::>(); + for (case, first) in [(0, 0), (1, 1), (2, 0), (3, 1)] { + let bets = TrBets::standard(20.0, 80.0, first); + let make = || { + let game = build(&bets, &[]); + let hands = [random_hands(40, 11 + case, 0), random_hands(36, 23 + case, 0)]; + let mut s = TrSolver::new(game, hands, board(), Some(if case == 3 { 7 } else { 10 })); + if case == 2 { + let at = s.game.root; + if let TNode::Dec { kids, .. } = &s.game.nodes[at] { + let a = kids.len(); + let n = s.hands(first); + s.lock(at, (0..n * a).map(|i| if i % a == 0 { 0.7 } else { 0.3 / (a - 1) as f64 }).collect(), 0.6); + } + } + if case == 3 { + // The flop form: three board cards, the dealt card is the turn, the showdown an equity table. + let flop = fast7::mask(&Card::parse_list("Ah 7d 2c").unwrap()); + let game = build(&bets, &[]); + let hands = [random_hands(30, 41, 0), random_hands(28, 43, 0)]; + s = TrSolver::new(game, hands, flop, Some(7)).with_river_equity(flop); + } + s + }; + let mut a = make(); + let mut b = make(); + a.run(5); + b.run(5); + a.run(17); + b.run_parallel(17, 4); + assert_eq!(a.iterations, b.iterations); + assert_eq!(bits(&a.regret), bits(&b.regret), "case {case}: regrets"); + assert_eq!(bits(&a.sums), bits(&b.sums), "case {case}: strategy sums"); + } +} diff --git a/src/engine/turn_game.rs b/src/engine/turn_game.rs index 7c5a6908..f5b97bcb 100644 --- a/src/engine/turn_game.rs +++ b/src/engine/turn_game.rs @@ -73,6 +73,19 @@ pub struct TurnConfig { pub budget_ms: f64, } +static FAEDEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1); + +/// Worker threads of a solve without a deadline (`TrSolver::run_parallel`, same numbers as one thread, only +/// faster). 1 (default) = sequential: libraries, sims and benches keep their thread budget; the live kern +/// (`main.rs`) sets `TURN_FAEDEN`, default 5. +pub fn set_faeden(n: usize) { + FAEDEN.store(n.max(1), std::sync::atomic::Ordering::Relaxed); +} + +fn faeden() -> usize { + FAEDEN.load(std::sync::atomic::Ordering::Relaxed) +} + /// Fewest iterations a budgeted solve may decide with. pub const MIN_ITERS: u32 = 60; /// Stage B's own cap on one solve; the decision total is `frist::TURN_MS`. @@ -253,7 +266,7 @@ fn solve_core(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec return None; } } else { - solver.run(cfg.iterations); + solver.run_parallel(cfg.iterations, faeden()); } let strategy = solver.strategy(); let exploit = cfg.measure.then(|| solver.exploitability(&strategy)); @@ -335,6 +348,12 @@ pub fn turn_game_decision(spot: &Spot) -> Option { Some(s) => s, None => { let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?; + // Hero's hand pruned out of the game: the solve could not decide it (`decide_from` finds no + // row), so it is not run (it took ~1 s CPU for nothing). The solve is deterministic (no + // budget), so skipping its cache entry changes no later decision. + if !prune(&hero, fast7::mask(&spot.board), &cfg, None).masks.contains(&hero_mask) { + return None; + } let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?); if let Ok(mut m) = CACHE.lock() { let map = m.get_or_insert_with(HashMap::new); diff --git a/src/main.rs b/src/main.rs index dc8c2bd6..281de05a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,10 @@ fn main() { // returns None), so a missing folder never breaks a decision. if std::env::var("TURN_SPIEL").as_deref() == Ok("grund") { rechner::engine::turn_game::set_turn_player(rechner::engine::turn_game::TurnPlayer::Grund); + // The turn game solves without a deadline, on worker threads (same numbers, ~1.2 s CPU -> wall a fraction). + rechner::engine::turn_game::set_faeden(std::env::var("TURN_FAEDEN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(5)); + // Load the card abstraction in the background (about a second on the first turn spot). + std::thread::spawn(rechner::blueprint::ranges::vorladen); } // SOLVER_RIVER (stage A, solver everywhere): the heads-up river decided by an equilibrium solve // (`engine::river_spieler`); blueprint ranges where GRUNDSTRATEGIE recognises the spot, else the