Bewiesen auf der gepaarten Leiter (19 Gegner, 95 %-CI, kein Profil verliert): - MDF-Floor/Veto-Fix: in der Sim bit-identisch, echte Haende Overfold 36 -> 7.5 bb. - Aggressions-Vertrauen, Strassen-Reads (Turn/River-Aggression, Fold-auf-Bet je Strasse, Bayes-geschrumpft zum Gesamt-Read), Zug-Logging der Gegnerprofile, Replay mit geloggten Profilen. - Leichter 3-Bet gegen 3-Bet-Folder (EV-Break-even risk/(pot+risk)): +6.62 +-5.23 bb/100 gegen den 3-Bet-Folder, sonst unveraendert. - Fold-auf-C-Bet preist die C-Bet: neutral. - Welt-Archetypen cbet-folder, 3bet-folder, check-raiser; ab_zelle (Zellen-Leiter, fortsetzbar), Warteschlange mit Thread-Budget, ab.py. Nicht drin: der Check-Raise-Abschlag (drei Varianten, keine sauber; wird durch ein Spielbaum-Modell ersetzt), der River-Showdown-Read bleibt aus (Verlierer -1.31). Ergebnisse: messung_engine/ERGEBNISSE.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
371 lines
16 KiB
Python
371 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Replay-Benchmark: der EHRLICHE Postflop-Massstab aus echten Hand-Histories.
|
|
|
|
Statt bb/100 gegen selbstgeschriebene Bots (die nur messen, ob wir die EIGENEN Fische schlagen)
|
|
treibt dieser Benchmark die ECHTE, AKTUELLE Engine ueber jede Hero-Entscheidung einer realen Session
|
|
und benotet sie gegen einen UNABHAENGIGEN Evaluator (`eval7`) auf den tatsaechlich gezeigten
|
|
Gegnerkarten. Jeder Hero-Spot wird aus der Hand-History als Wire-Anfrage rekonstruiert (board, pot,
|
|
toCall, Stacks, history, Profile) und neu entschieden - so misst der Benchmark FIXES, nicht nur die
|
|
alte Session.
|
|
|
|
Vier Masse:
|
|
* TREUE: reproduziert die Re-Decision die geloggte Linie? (Rekonstruktion korrekt?)
|
|
* EV-VERLUST: wo der Gegner zeigt - foldet die Engine +EV-Calls weg / callt sie -EV-Spots? (bb)
|
|
* EQUITY-BIAS: Engine-Equity minus WAHRE Equity (negativ = unterschaetzt -> Overfold-Wurzel)
|
|
* FOLD/MDF: Fold-gegen-Bet je Street gegen die Minimum-Defense-Frequency
|
|
|
|
COINPOKER_EXPORT=/pfad/zur/session.md python3 entscheiden/replay.py
|
|
COINPOKER_KERN=.../target/release/rechner.exe # Engine-Binary (Default: target/release/rechner)
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
from collections import Counter
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
import decide
|
|
from eval7 import equity_vs, karten
|
|
|
|
HERO = "mmintel"
|
|
RANG = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT",
|
|
"7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"}
|
|
FARBE = {"s": "SPADES", "h": "HEARTS", "d": "DIAMONDS", "c": "CLUBS"}
|
|
STREETS = ["PREFLOP", "FLOP", "TURN", "RIVER"]
|
|
|
|
|
|
def _wire_card(t):
|
|
return {"rank": RANG[t[0]], "suit": FARBE[t[1]]}
|
|
|
|
|
|
def _wire_cards(txt):
|
|
return [_wire_card(x) for x in txt.split()]
|
|
|
|
|
|
def _board_dict(board_cards):
|
|
"""5-Karten-Board (Textliste) -> Wire-Board-Dict bis zur erreichten Street."""
|
|
d = {}
|
|
if len(board_cards) >= 3:
|
|
d["FLOP"] = [_wire_card(c) for c in board_cards[:3]]
|
|
if len(board_cards) >= 4:
|
|
d["TURN"] = [_wire_card(board_cards[3])]
|
|
if len(board_cards) >= 5:
|
|
d["RIVER"] = [_wire_card(board_cards[4])]
|
|
return d
|
|
|
|
|
|
# ---------------------------------------------------------------- HH-Parser
|
|
ACT_RE = re.compile(r'^(\S+): (posts small blind|posts big blind|posts the ante|folds|checks|'
|
|
r'bets|calls|raises)(?: \$?([0-9.]+))?(?: to \$?([0-9.]+))?', re.M)
|
|
|
|
|
|
def parse_hand(block):
|
|
"""MD-Handblock -> dict mit allem fuer die Rekonstruktion, oder None wenn unbrauchbar."""
|
|
hid = block.split(" ", 1)[0].lstrip("#")
|
|
mhole = re.search(r'Hero Hole Cards:\*\* `([^`]+)`', block)
|
|
mhh = re.search(r'```text\n(.*?)```', block, re.S)
|
|
if not mhole or not mhh:
|
|
return None
|
|
hero_cards = mhole.group(1).split()
|
|
hh = mhh.group(1)
|
|
|
|
# Engine-Entscheidungen (Street, board, pot, toCall, action) in Dokumentreihenfolge
|
|
dec_re = re.compile(r'`(PREFLOP|FLOP|TURN|RIVER)` \| board=`([^`]*)` \| '
|
|
r'pot=\$([0-9.]+) toCall=\$([0-9.]+) \| \*\*([A-Z]+)\*\* \| '
|
|
r'eq=([0-9.]+|None) \| (.*)')
|
|
decisions = [{"street": m.group(1), "board": m.group(2).split(), "pot": float(m.group(3)),
|
|
"to_call": float(m.group(4)), "action": m.group(5),
|
|
"eq": None if m.group(6) == "None" else float(m.group(6)), "reason": m.group(7)}
|
|
for m in dec_re.finditer(block)]
|
|
if not decisions:
|
|
return None
|
|
|
|
# VPIP/Hands je Name aus der Players-Zeile
|
|
prof = {}
|
|
for mm in re.finditer(r'S\d+ (\S+) \(\$[0-9.]+, VPIP (\d+)%/(\d+)h\)', block):
|
|
prof[mm.group(1)] = {"vpip": int(mm.group(2)) / 100.0, "hands": int(mm.group(3))}
|
|
|
|
# Sitze, Stacks, Button, Blinds, Showdown-Karten aus der HH
|
|
seats = {} # name -> seat
|
|
stacks = {} # name -> start stack
|
|
for mm in re.finditer(r'^Seat (\d+): (\S+) \(\$([0-9.]+) in chips\)', hh, re.M):
|
|
seats[mm.group(2)] = int(mm.group(1))
|
|
stacks[mm.group(2)] = float(mm.group(3))
|
|
mb = re.search(r'Seat #(\d+) is the button', hh)
|
|
button = int(mb.group(1)) if mb else None
|
|
mbb = re.search(r'\(\$([0-9.]+)/\$([0-9.]+)', hh)
|
|
sb, bb = (float(mbb.group(1)), float(mbb.group(2))) if mbb else (0.01, 0.02)
|
|
shown = {}
|
|
for mm in re.finditer(r'^(\S+): shows \[([^\]]+)\]', hh, re.M):
|
|
shown[mm.group(1)] = mm.group(2).split()
|
|
for mm in re.finditer(r'^Seat \d+: (\S+) showed \[([^\]]+)\]', hh, re.M):
|
|
shown.setdefault(mm.group(1), mm.group(2).split())
|
|
|
|
if HERO not in seats:
|
|
return None
|
|
return {"hid": hid, "hero_cards": hero_cards, "hh": hh, "decisions": decisions,
|
|
"prof": prof, "seats": seats, "stacks": stacks, "button": button,
|
|
"sb": sb, "bb": bb, "shown": shown}
|
|
|
|
|
|
def _seat_name(seats):
|
|
return {v: k for k, v in seats.items()}
|
|
|
|
|
|
def geloggte_gegner(pfad=None):
|
|
"""{(hand, street): {sitz: profil}} aus dem Zug-Log (archiv/lauf/zuege.jsonl, Feld `gegner`, ab
|
|
13.11.): was der Kern live ueber die Gegner wusste. Fehlt es, bleibt das Export-Profil (nur VPIP)."""
|
|
pfad = pfad or os.environ.get("COINPOKER_ZUEGE") or os.path.join(
|
|
os.path.dirname(os.path.abspath(__file__)), "..", "archiv", "lauf", "zuege.jsonl")
|
|
out = {}
|
|
if not os.path.exists(pfad):
|
|
return out
|
|
for zeile in open(pfad, encoding="utf-8"):
|
|
try:
|
|
z = json.loads(zeile)
|
|
except ValueError:
|
|
continue
|
|
if z.get("hand") is not None and z.get("gegner"):
|
|
out[(str(z["hand"]), z.get("street"))] = z["gegner"]
|
|
return out
|
|
|
|
|
|
GELOGGT = None
|
|
|
|
|
|
def reconstruct(hand):
|
|
"""Laeuft die HH-Aktionen durch, baut vor jeder Hero-Aktion den Wire-Spot und paart ihn
|
|
mit der naechsten geloggten Entscheidung. Gibt Liste von (spot_dict, decision) zurueck."""
|
|
seats, stacks = hand["seats"], hand["stacks"]
|
|
bb = hand["bb"]
|
|
hero_seat = seats[HERO]
|
|
lines = hand["hh"].splitlines()
|
|
street = "PREFLOP"
|
|
street_contrib = Counter()
|
|
cum = Counter()
|
|
folded = set()
|
|
history = []
|
|
decisions = iter(hand["decisions"])
|
|
out = []
|
|
|
|
req_quelle = QUELLE
|
|
|
|
def snapshot(dec):
|
|
"""Baut die Wire-Anfrage fuer die aktuelle Hero-Entscheidung."""
|
|
board = dec["board"]
|
|
to_call = dec["to_call"]
|
|
hero_stack = round(stacks[HERO] - cum[HERO], 4)
|
|
legal = (["FOLD", "CALL"] + (["RAISE"] if hero_stack > to_call else [])) if to_call > 0 \
|
|
else ["CHECK"] + (["RAISE"] if hero_stack > 0 else [])
|
|
vils = []
|
|
for name, seat in seats.items():
|
|
if name == HERO:
|
|
continue
|
|
v = {"seat": seat, "stack": round(stacks[name] - cum[name], 4),
|
|
"folded": seat in folded}
|
|
if name in hand["prof"]:
|
|
v["profile"] = dict(hand["prof"][name])
|
|
live = (GELOGGT or {}).get((str(hand["hid"]), dec["street"]), {}).get(str(seat))
|
|
if live:
|
|
v["profile"] = {k: x for k, x in live.items() if k not in ("folded", "marke")}
|
|
if live.get("marke"):
|
|
v["marke"] = live["marke"]
|
|
req_quelle["live"] += 1
|
|
vils.append(v)
|
|
req = {"variant": "NLHE", "bigBlind": bb, "seats": len(seats), "heroSeat": hero_seat,
|
|
"heroCards": _wire_cards(" ".join(hand["hero_cards"])),
|
|
"board": _board_dict(board), "street": dec["street"],
|
|
"pot": dec["pot"], "toCall": to_call, "heroStack": max(hero_stack, 0.0),
|
|
"legalActions": legal, "allowedSizes": [],
|
|
"villains": vils, "history": list(history),
|
|
"seed": (int(hand["hid"]) + STREETS.index(dec["street"]) * 7 + len(out)) & 0xFFFFFFFF}
|
|
if hand["button"]:
|
|
req["buttonSeat"] = hand["button"]
|
|
return req
|
|
|
|
for ln in lines:
|
|
if ln.startswith("*** FLOP"):
|
|
street = "FLOP"; street_contrib = Counter()
|
|
elif ln.startswith("*** TURN"):
|
|
street = "TURN"; street_contrib = Counter()
|
|
elif ln.startswith("*** RIVER"):
|
|
street = "RIVER"; street_contrib = Counter()
|
|
elif ln.startswith("*** SHOW DOWN") or ln.startswith("*** SUMMARY"):
|
|
break
|
|
m = ACT_RE.match(ln)
|
|
if not m:
|
|
continue
|
|
name, verb, amt, raise_to = m.group(1), m.group(2), m.group(3), m.group(4)
|
|
if name not in seats:
|
|
continue
|
|
seat = seats[name]
|
|
|
|
# Vor Heros Aktion: Spot bauen und mit der naechsten Entscheidung paaren
|
|
if name == HERO and verb in ("folds", "checks", "calls"):
|
|
dec = next(decisions, None)
|
|
if dec is not None and dec["street"] == street:
|
|
out.append((snapshot(dec), dec))
|
|
|
|
# Aktion auf den Zustand anwenden + history fortschreiben
|
|
if verb == "posts small blind":
|
|
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
|
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_SB", "amount": float(amt)})
|
|
elif verb == "posts big blind":
|
|
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
|
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_BB", "amount": float(amt)})
|
|
elif verb == "posts the ante":
|
|
cum[seat] += float(amt)
|
|
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_ANTE", "amount": float(amt)})
|
|
elif verb == "folds":
|
|
folded.add(seat)
|
|
history.append({"street": street, "seat": seat, "action": "FOLD"})
|
|
elif verb == "checks":
|
|
history.append({"street": street, "seat": seat, "action": "CHECK"})
|
|
elif verb == "bets":
|
|
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
|
history.append({"street": street, "seat": seat, "action": "BET", "amount": float(amt)})
|
|
elif verb == "calls":
|
|
street_contrib[seat] += float(amt); cum[seat] += float(amt)
|
|
history.append({"street": street, "seat": seat, "action": "CALL", "amount": round(street_contrib[seat], 4)})
|
|
elif verb == "raises":
|
|
add = float(raise_to) - street_contrib[seat]
|
|
street_contrib[seat] = float(raise_to); cum[seat] += add
|
|
history.append({"street": street, "seat": seat, "action": "RAISE", "amount": float(raise_to)})
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------- Benчmark
|
|
QUELLE = Counter()
|
|
|
|
|
|
def run(export_path):
|
|
global GELOGGT
|
|
GELOGGT = geloggte_gegner()
|
|
md = open(export_path, encoding="utf-8").read()
|
|
blocks = re.split(r'^### Hand ', md, flags=re.M)[1:]
|
|
hands = [h for h in (parse_hand(b) for b in blocks) if h]
|
|
|
|
spots = [] # (hand, spot_dict, logged_decision)
|
|
for h in hands:
|
|
for spot, dec in reconstruct(h):
|
|
spots.append((h, spot, dec))
|
|
|
|
requests = [json.dumps(s[1]) for s in spots]
|
|
answers = decide.entscheide(requests)
|
|
|
|
# --- Masse sammeln ---
|
|
treue = 0; treue_bet = 0; n_bet = 0
|
|
foldbet = Counter(); callbet = Counter()
|
|
mdf_rows = []
|
|
bias = []
|
|
overfold_loss = 0.0; overcall_loss = 0.0
|
|
overfolds = []
|
|
for (h, spot, dec), ans in zip(spots, answers):
|
|
re_act = ans.get("action", "ABSTAIN")
|
|
re_eq = ans.get("equity")
|
|
logged = dec["action"]
|
|
# ABSTAIN zaehlt fuer die Treue als die Linie, die live gespielt wurde (Aussetzen -> Log)
|
|
if re_act == logged:
|
|
treue += 1
|
|
facing = dec["street"] != "PREFLOP" and dec["to_call"] > 0
|
|
if facing:
|
|
n_bet += 1
|
|
if re_act == logged:
|
|
treue_bet += 1
|
|
if re_act == "FOLD":
|
|
foldbet[dec["street"]] += 1
|
|
elif re_act == "CALL":
|
|
callbet[dec["street"]] += 1
|
|
# Ground Truth: lebende Gegner, die ihre Karten zeigen
|
|
board = dec["board"]
|
|
live_shown = []
|
|
sn = _seat_name(h["seats"])
|
|
for name, cs in h["shown"].items():
|
|
if name == HERO:
|
|
continue
|
|
cc = karten(cs)
|
|
if all(c not in karten(board) and c not in karten(" ".join(h["hero_cards"])) for c in cc):
|
|
live_shown.append(cs)
|
|
if live_shown:
|
|
te = equity_vs(" ".join(h["hero_cards"]), board, live_shown)
|
|
be = dec["to_call"] / (dec["pot"] + dec["to_call"])
|
|
ev_call = te * (dec["pot"] + dec["to_call"]) - dec["to_call"]
|
|
if re_eq is not None:
|
|
bias.append(re_eq - te)
|
|
if re_act == "FOLD" and ev_call > 1e-9:
|
|
overfold_loss += ev_call
|
|
overfolds.append((h["hid"], dec["street"], " ".join(board), dec["pot"],
|
|
dec["to_call"], round(te, 3), round(be, 3), re_eq,
|
|
" / ".join(" ".join(cs) for cs in live_shown), ev_call))
|
|
elif re_act == "CALL" and ev_call < -1e-9:
|
|
overcall_loss += -ev_call
|
|
mdf_rows.append((dec["street"], dec["to_call"] / (dec["pot"] + dec["to_call"])))
|
|
|
|
bb = hands[0]["bb"] if hands else 0.02
|
|
import statistics
|
|
return {
|
|
"n_hands": len(hands), "n_spots": len(spots), "n_bet": n_bet,
|
|
"treue": treue / len(spots) if spots else 0,
|
|
"treue_bet": treue_bet / n_bet if n_bet else 0,
|
|
"foldbet": dict(foldbet), "callbet": dict(callbet),
|
|
"bias_mean": statistics.mean(bias) if bias else 0.0,
|
|
"bias_n": len(bias),
|
|
"overfold_bb": overfold_loss / bb, "overcall_bb": overcall_loss / bb,
|
|
"overfolds": sorted(overfolds, key=lambda x: -x[9]),
|
|
"bb": bb,
|
|
}
|
|
|
|
|
|
def write_baseline(r, path, export_name):
|
|
import subprocess
|
|
try:
|
|
sha = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=os.path.dirname(path) or ".",
|
|
capture_output=True, text=True).stdout.strip() or "?"
|
|
except Exception:
|
|
sha = "?"
|
|
lines = [f"label {sha}+lokal", f"export {export_name}",
|
|
f"hands {r['n_hands']}", f"spots {r['n_spots']}", f"facing_bet {r['n_bet']}",
|
|
f"faithfulness {r['treue']:.3f}", f"faithfulness_bet {r['treue_bet']:.3f}"]
|
|
for s in ["FLOP", "TURN", "RIVER"]:
|
|
lines.append(f"foldbet_{s.lower()} {r['foldbet'].get(s,0)} {r['callbet'].get(s,0)}")
|
|
lines += [f"equity_bias {r['bias_mean']:.3f} n={r['bias_n']}",
|
|
f"overfold_bb {r['overfold_bb']:.1f}", f"overcall_bb {r['overcall_bb']:.1f}"]
|
|
open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n")
|
|
|
|
|
|
def main():
|
|
path = os.environ.get("COINPOKER_EXPORT") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
|
if not path or not os.path.exists(path):
|
|
print(f"Export nicht gefunden: {path}\nSetze COINPOKER_EXPORT=/pfad/zur/session.md (oder als Argument)")
|
|
sys.exit(2)
|
|
r = run(path)
|
|
print(f"=== Replay-Benchmark ({os.path.basename(path)}) ===")
|
|
print(f"Haende {r['n_hands']} | Hero-Entscheidungen rekonstruiert {r['n_spots']} | davon gegen Bet {r['n_bet']}")
|
|
print(f"Gegnerprofile: {QUELLE['live']} aus dem Live-Zug-Log, sonst aus dem Export (nur VPIP)")
|
|
print(f"TREUE (Re-Decision == Log): gesamt {100*r['treue']:.0f}% | gegen Bet {100*r['treue_bet']:.0f}%")
|
|
print()
|
|
print("FOLD gegen Bet je Street (Re-Decision der aktuellen Engine):")
|
|
for s in ["FLOP", "TURN", "RIVER"]:
|
|
f, c = r["foldbet"].get(s, 0), r["callbet"].get(s, 0)
|
|
if f + c:
|
|
print(f" {s:5}: fold {f}, call {c} -> {100*f/(f+c):.0f}% Fold-to-bet")
|
|
print()
|
|
print(f"EQUITY-BIAS (Engine - wahr) ueber {r['bias_n']} Ground-Truth-Spots: {r['bias_mean']:+.3f}"
|
|
f" (negativ = unterschaetzt -> Overfold-Wurzel)")
|
|
print(f"EV-VERLUST belegt: Overfold {r['overfold_bb']:.1f} bb | Overcall {r['overcall_bb']:.1f} bb")
|
|
print()
|
|
print("Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV):")
|
|
for o in r["overfolds"][:12]:
|
|
hid, st, bd, pot, tc, te, be, eq, vil, ev = o
|
|
print(f" #{hid} {st:5} [{bd:14}] pot {pot:.2f} call {tc:.2f} | wahr {te:.2f} vs be {be:.2f} "
|
|
f"| Engine {eq} | Gegner {vil} | +EV weg {ev/r['bb']:.1f} bb")
|
|
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "benchmarks", "replay_baseline.txt")
|
|
ename = re.sub(r'_analyse\.md$|\.md$', '', os.path.basename(path))
|
|
write_baseline(r, base, ename)
|
|
print(f"\nBaseline geschrieben: {os.path.normpath(base)}")
|
|
return r
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|