iter 1
Browse files- README.md +2 -64
- metrics.jsonl +2 -0
- model.pt +3 -0
- model.py +69 -0
- play.py +262 -0
- poker_core.py +591 -0
- train.py +395 -0
README.md
CHANGED
|
@@ -1,65 +1,3 @@
|
|
| 1 |
-
-
|
| 2 |
-
license: mit
|
| 3 |
-
tags:
|
| 4 |
-
- poker
|
| 5 |
-
- reinforcement-learning
|
| 6 |
-
- self-play
|
| 7 |
-
- texas-holdem
|
| 8 |
-
---
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
Agente de No-Limit Hold'em treinado do zero por **self-play com reforço (PPO)**, inteiramente em GPU (NVIDIA B200 na Modal).
|
| 13 |
-
Uma única rede joga em **qualquer mesa de 2 até 23 jogadores** (heads-up, 6-max, full ring 9, 12, 15, 23...), com stacks diferentes por jogador e antes opcionais.
|
| 14 |
-
|
| 15 |
-
## Arquivos
|
| 16 |
-
|
| 17 |
-
| arquivo | conteúdo |
|
| 18 |
-
|---|---|
|
| 19 |
-
| `model.pt` | pesos mais recentes da política (rede ator) |
|
| 20 |
-
| `checkpoints/model_itXXXXX.pt` | snapshots a cada ~1h de treino |
|
| 21 |
-
| `training_state/ckpt.pt` | estado completo (ator + crítico + otimizador + liga) para continuar o treino |
|
| 22 |
-
| `metrics.jsonl` | métricas de treino e avaliações periódicas contra bots |
|
| 23 |
-
| `poker_core.py` | motor de NLHE vetorizado em PyTorch (regras completas, side pots, avaliador de mãos com lookup table) |
|
| 24 |
-
| `model.py` | rede Transformer |
|
| 25 |
-
| `train.py` | treino PPO self-play + liga de oponentes |
|
| 26 |
-
| `play.py` | jogar contra a IA no terminal / modo conselheiro para qualquer mesa |
|
| 27 |
-
|
| 28 |
-
## Como usar
|
| 29 |
-
|
| 30 |
-
```bash
|
| 31 |
-
pip install torch huggingface_hub
|
| 32 |
-
# baixe poker_core.py, model.py, play.py deste repositório
|
| 33 |
-
python play.py play --players 6 --stack 100 # você contra 5 IAs
|
| 34 |
-
python play.py play --players 2 # heads-up
|
| 35 |
-
python play.py advisor # a IA sugere jogadas numa mesa real (qualquer nº de jogadores)
|
| 36 |
-
```
|
| 37 |
-
|
| 38 |
-
API em Python:
|
| 39 |
-
|
| 40 |
-
```python
|
| 41 |
-
from play import PokerAI, Advisor
|
| 42 |
-
adv = Advisor(PokerAI.load()) # baixa model.pt do Hugging Face
|
| 43 |
-
adv.new_hand(n=9, button=0, stacks=[100]*9, hero=4, hole="Ah Kd")
|
| 44 |
-
adv.act(3, "raise", 3) # assento 3 aumenta para 3bb (valor = aposta total na rodada)
|
| 45 |
-
print(adv.suggest()) # {'best': 'raise to 10.00 (...)', 'options': [...], ...}
|
| 46 |
-
adv.act(4, "raise", 10); adv.act(5, "fold") ...
|
| 47 |
-
adv.board("Ah 7c 2d") # quando sair o flop/turn/river
|
| 48 |
-
```
|
| 49 |
-
|
| 50 |
-
## Como funciona
|
| 51 |
-
|
| 52 |
-
- **Motor**: dezenas de milhares de mesas simuladas em paralelo na GPU, com regras completas de NLHE: blinds, antes, min-raise, all-in incompleto (não reabre a ação), side pots múltiplos e split pots.
|
| 53 |
-
- **Ações**: fold, check/call, min-raise, raise de 33%/50%/75%/100%/150%/250% do pote, all-in. Ações de oponentes de qualquer tamanho são aceitas (modo conselheiro).
|
| 54 |
-
- **Rede (ator)**: Transformer (d=256, 4 camadas) sobre tokens [estado global, 7 cartas, 1 token por assento]. Como os assentos são tokens, a mesma rede serve para qualquer número de jogadores. Recebe também equidade Monte Carlo (vs 1 mão aleatória e vs todos os oponentes vivos) e a categoria da mão feita.
|
| 55 |
-
- **Crítico privilegiado**: durante o treino a função valor vê as cartas de todos e o board completo (reduz muito a variância; não é usado para jogar).
|
| 56 |
-
- **Liga**: além de self-play puro, parte das mesas tem versões antigas da rede e bots heurísticos (calling station, TAG, rock, maniac, aleatório, equity-caller), para evitar estratégias que só funcionam contra si mesma.
|
| 57 |
-
- **Distribuição das mesas**: 2–9 jogadores (heads-up mais frequente) e 10–23 jogadores; stacks de 3 a 300 BB.
|
| 58 |
-
|
| 59 |
-
## Limitações (honestas)
|
| 60 |
-
|
| 61 |
-
**Não há garantia de que seja melhor que qualquer humano**: o orçamento total foi ~US$30 de GPU (≈4h de B200).
|
| 62 |
-
Bots sobre-humanos como Libratus e Pluribus usaram busca em tempo real e muito mais computação. Veja as avaliações em `metrics.jsonl`
|
| 63 |
-
(bb/100 contra cada bot, em mesas de 2, 6, 9 e 15 jogadores) para o nível real.
|
| 64 |
-
|
| 65 |
-
Uso educacional/pesquisa. Usar bots em sites de poker com dinheiro real normalmente viola os termos de uso desses sites.
|
|
|
|
| 1 |
+
# Poker AI — No-Limit Texas Hold'em, 2 a 23 jogadores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
Treinamento em andamento (self-play PPO em GPU na Modal). Veja `metrics.jsonl` para o progresso.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
metrics.jsonl
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"it": 0, "kind": "eval", "n2_call": -30.5, "n2_call_se": 62.5, "n2_tag": -899.9, "n2_tag_se": 41.8, "n2_maniac": -908.9, "n2_maniac_se": 66.1, "n2_rock": -368.8, "n2_rock_se": 27.2, "n2_random": -6.6, "n2_random_se": 51.3, "n6_call": 18.5, "n6_call_se": 159.6, "n6_tag": -1373.7, "n6_tag_se": 49.1, "n6_maniac": -680.5, "n6_maniac_se": 140.2, "n6_rock": -732.6, "n6_rock_se": 33.8, "n6_random": -79.6, "n6_random_se": 112.7, "n9_call": 359.7, "n9_call_se": 258.3, "n9_tag": -1354.0, "n9_tag_se": 62.3, "n9_maniac": -106.2, "n9_maniac_se": 223.0, "n9_rock": -696.0, "n9_rock_se": 41.0, "n9_random": -29.5, "n9_random_se": 171.8, "n15_call": -319.5, "n15_call_se": 326.9, "n15_tag": -1543.9, "n15_tag_se": 63.3, "n15_maniac": -574.3, "n15_maniac_se": 276.1, "eval_sec": 29.8}
|
| 2 |
+
{"it": 1, "kind": "train", "t": 1.4, "dec": 2316391, "hands": 299457, "tot_hands": 299457, "steps": [118, 142], "t_roll": 13.9, "t_upd": 38.4, "fold": 0.282, "call": 0.295, "raise_": 0.323, "allin": 0.1, "pg": -0.0092, "vf": 25.3458, "ent": 1.43813, "kl": 0.01398, "clipfrac": 0.16829, "lr": 0.0003, "ent_coef": 0.01995, "epochs_done": 2, "kl_stop": false}
|
model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:28dc22211f6b4bdafa816c981c918703e7f253e929c8e5f1875a56b5d73c3de8
|
| 3 |
+
size 13926206
|
model.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from poker_core import N_ACTIONS, MAX_SEATS, obs_dims
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PokerNet(nn.Module):
|
| 8 |
+
"""Set/sequence transformer over [global, 7 cards, seat tokens]. Works for any number of seats <= 23.
|
| 9 |
+
critic=True adds privileged inputs (all hole cards + full board) and outputs a scalar value."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, d=256, layers=4, heads=8, critic=False):
|
| 12 |
+
super().__init__()
|
| 13 |
+
fg, fs = obs_dims()
|
| 14 |
+
self.critic = critic
|
| 15 |
+
self.cfg = dict(d=d, layers=layers, heads=heads, critic=critic)
|
| 16 |
+
self.card = nn.Embedding(53, d)
|
| 17 |
+
self.rank = nn.Embedding(14, d)
|
| 18 |
+
self.suit = nn.Embedding(5, d)
|
| 19 |
+
self.slot = nn.Embedding(7 + (5 if critic else 0), d)
|
| 20 |
+
self.glob = nn.Sequential(nn.Linear(fg, d), nn.GELU(), nn.Linear(d, d))
|
| 21 |
+
self.seat = nn.Sequential(nn.Linear(fs, d), nn.GELU(), nn.Linear(d, d))
|
| 22 |
+
self.seat_pos = nn.Embedding(MAX_SEATS, d)
|
| 23 |
+
self.btn_dist = nn.Embedding(MAX_SEATS, d)
|
| 24 |
+
self.tok_type = nn.Embedding(4, d)
|
| 25 |
+
if critic:
|
| 26 |
+
self.hole_proj = nn.Linear(d, d)
|
| 27 |
+
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, activation="gelu",
|
| 28 |
+
batch_first=True, norm_first=True)
|
| 29 |
+
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
| 30 |
+
self.norm = nn.LayerNorm(d)
|
| 31 |
+
out = 1 if critic else N_ACTIONS
|
| 32 |
+
self.head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, out))
|
| 33 |
+
if not critic:
|
| 34 |
+
nn.init.zeros_(self.head[-1].weight)
|
| 35 |
+
nn.init.zeros_(self.head[-1].bias)
|
| 36 |
+
|
| 37 |
+
def card_emb(self, c):
|
| 38 |
+
c = c.long()
|
| 39 |
+
unk = c == 52
|
| 40 |
+
r = torch.where(unk, torch.full_like(c, 13), c // 4)
|
| 41 |
+
s = torch.where(unk, torch.full_like(c, 4), c % 4)
|
| 42 |
+
return self.card(c) + self.rank(r) + self.suit(s)
|
| 43 |
+
|
| 44 |
+
def forward(self, o):
|
| 45 |
+
cards = o["cards"]
|
| 46 |
+
b = cards.shape[0]
|
| 47 |
+
dev = cards.device
|
| 48 |
+
g = self.glob(o["glob"].float()).unsqueeze(1) + self.tok_type.weight[0]
|
| 49 |
+
ce = self.card_emb(cards) + self.slot(torch.arange(7, device=dev))[None] + self.tok_type.weight[1]
|
| 50 |
+
toks = [g, ce]
|
| 51 |
+
st = (self.seat(o["seat"].float()) + self.seat_pos(o["seat_pos"]) + self.btn_dist(o["btn_dist"])
|
| 52 |
+
+ self.tok_type.weight[2])
|
| 53 |
+
if self.critic:
|
| 54 |
+
hs = self.card_emb(o["all_hole"]).sum(2)
|
| 55 |
+
st = st + self.hole_proj(hs)
|
| 56 |
+
fb = self.card_emb(o["full_board"]) + self.slot(torch.arange(7, 12, device=dev))[None] + self.tok_type.weight[3]
|
| 57 |
+
toks.append(fb)
|
| 58 |
+
toks.append(st)
|
| 59 |
+
x = torch.cat(toks, 1)
|
| 60 |
+
nfix = x.shape[1] - st.shape[1]
|
| 61 |
+
pad = torch.cat([torch.zeros(b, nfix, dtype=torch.bool, device=dev), ~o["seat_mask"]], 1)
|
| 62 |
+
x = self.enc(x, src_key_padding_mask=pad)
|
| 63 |
+
x = self.norm(x)
|
| 64 |
+
selfseat = x[:, nfix] # seat token of the acting player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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Use the trained poker AI.
|
| 3 |
+
|
| 4 |
+
python play.py play --players 6 --stack 100 # you vs 5 AI players in the terminal
|
| 5 |
+
python play.py advisor # AI suggests moves for a real table (any 2..23 players)
|
| 6 |
+
|
| 7 |
+
Python API:
|
| 8 |
+
from play import PokerAI, Advisor
|
| 9 |
+
adv = Advisor(PokerAI.load()) # downloads model.pt from huggingface (Alisson990/poker)
|
| 10 |
+
adv.new_hand(n=6, button=0, stacks=[100]*6, hero=3, hole="As Kd")
|
| 11 |
+
adv.act(4, "call") ; adv.act(5, "raise", 3.5) ... # amounts = total bet this street ("raise to"), in big blinds
|
| 12 |
+
adv.board("Ah 7c 2d")
|
| 13 |
+
print(adv.suggest())
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from model import PokerNet
|
| 22 |
+
from poker_core import ACTION_NAMES, N_ACTIONS, NREV, HandEvaluator, PokerEnv
|
| 23 |
+
|
| 24 |
+
RANKS, SUITS = "23456789TJQKA", "cdhs"
|
| 25 |
+
SUIT_SYM = {"c": "♣", "d": "♦", "h": "♥", "s": "♠"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_card(s):
|
| 29 |
+
s = s.strip()
|
| 30 |
+
return RANKS.index(s[0].upper()) * 4 + SUITS.index(s[1].lower())
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def card_str(c):
|
| 34 |
+
return RANKS[c // 4] + SUITS[c % 4]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PokerAI:
|
| 38 |
+
def __init__(self, net, device="cpu"):
|
| 39 |
+
self.net = net.eval()
|
| 40 |
+
self.dev = device
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def load(path=None, device="cpu", repo="Alisson990/poker"):
|
| 44 |
+
if path is None:
|
| 45 |
+
from huggingface_hub import hf_hub_download
|
| 46 |
+
path = hf_hub_download(repo, "model.pt")
|
| 47 |
+
s = torch.load(path, map_location=device, weights_only=False)
|
| 48 |
+
net = PokerNet(**s["cfg"]).to(device)
|
| 49 |
+
net.load_state_dict(s["actor"])
|
| 50 |
+
return PokerAI(net, device)
|
| 51 |
+
|
| 52 |
+
@torch.no_grad()
|
| 53 |
+
def probs(self, obs):
|
| 54 |
+
return torch.softmax(self.net(obs).float(), -1)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class Advisor:
|
| 58 |
+
"""Tracks a real hand (any number of players 2..23) and asks the AI what to do."""
|
| 59 |
+
|
| 60 |
+
def __init__(self, ai, eq_samples=256):
|
| 61 |
+
self.ai = ai
|
| 62 |
+
self.ev = HandEvaluator(ai.dev)
|
| 63 |
+
self.K = eq_samples
|
| 64 |
+
self.env = None
|
| 65 |
+
|
| 66 |
+
def new_hand(self, n, button, stacks, hero, hole, sb=0.5, bb=1.0, ante=0.0):
|
| 67 |
+
"""stacks/blinds in any unit: everything is converted to big blinds internally."""
|
| 68 |
+
self.unit = bb
|
| 69 |
+
env = PokerEnv(1, max(n, 2), [0] * (n - 2) + [1], self.ai.dev, self.ev, eq_samples=self.K, ante_prob=0.0)
|
| 70 |
+
st = torch.zeros(1, env.W)
|
| 71 |
+
st[0, :n] = torch.tensor([float(s) / bb for s in stacks])
|
| 72 |
+
env.reset(n_override=n, stacks_override=st)
|
| 73 |
+
# rebuild blinds with the requested button / sizes
|
| 74 |
+
env.button[0] = button
|
| 75 |
+
env.stack[0, :n] = st[0, :n]
|
| 76 |
+
env.bet.zero_(); env.contrib.zero_(); env.st_contrib.zero_()
|
| 77 |
+
env.ante[0] = ante / bb
|
| 78 |
+
if ante > 0:
|
| 79 |
+
a = torch.minimum(torch.full((n,), ante / bb), env.stack[0, :n])
|
| 80 |
+
env.stack[0, :n] -= a
|
| 81 |
+
env.contrib[0, :n] += a
|
| 82 |
+
sbs = button if n == 2 else (button + 1) % n
|
| 83 |
+
bbs = (sbs + 1) % n
|
| 84 |
+
for seat, amt in ((sbs, sb / bb), (bbs, 1.0)):
|
| 85 |
+
a = min(amt, env.stack[0, seat].item())
|
| 86 |
+
env.stack[0, seat] -= a
|
| 87 |
+
env.bet[0, seat] += a
|
| 88 |
+
env.contrib[0, seat] += a
|
| 89 |
+
env.st_contrib[0, seat, 0] += a
|
| 90 |
+
env.max_bet[0] = max(env.bet[0].max().item(), 1.0)
|
| 91 |
+
env.allin[0] = env.present[0] & (env.stack[0] <= 1e-9)
|
| 92 |
+
env.cur[0] = env._next_need(torch.tensor([bbs]), env._need())[0][0]
|
| 93 |
+
cards = [parse_card(c) for c in hole.split()]
|
| 94 |
+
used = set(cards)
|
| 95 |
+
rest = [c for c in range(52) if c not in used]
|
| 96 |
+
random.shuffle(rest)
|
| 97 |
+
hole_t = torch.tensor(rest[:2 * env.W]).reshape(env.W, 2)
|
| 98 |
+
hole_t[hero] = torch.tensor(sorted(cards, reverse=True))
|
| 99 |
+
env.hole[0] = hole_t
|
| 100 |
+
env.board[0] = torch.tensor(rest[2 * env.W:2 * env.W + 5])
|
| 101 |
+
self.env, self.hero, self.n = env, hero, n
|
| 102 |
+
self._used = used
|
| 103 |
+
|
| 104 |
+
def board(self, cards):
|
| 105 |
+
"""Set the visible board (3, 4 or 5 cards)."""
|
| 106 |
+
cs = [parse_card(c) for c in cards.split()]
|
| 107 |
+
self.env.board[0, :len(cs)] = torch.tensor(cs)
|
| 108 |
+
self._used |= set(cs)
|
| 109 |
+
|
| 110 |
+
def to_act(self):
|
| 111 |
+
return int(self.env.cur[0])
|
| 112 |
+
|
| 113 |
+
def act(self, seat, kind, amount=None):
|
| 114 |
+
"""kind in fold/check/call/bet/raise/allin. amount = total bet on this street ("raise to"), same unit as stacks."""
|
| 115 |
+
env = self.env
|
| 116 |
+
if env.done[0]:
|
| 117 |
+
raise RuntimeError("hand is over")
|
| 118 |
+
if seat != self.to_act():
|
| 119 |
+
raise ValueError(f"seat {self.to_act()} is to act, not {seat}")
|
| 120 |
+
kind = kind.lower()
|
| 121 |
+
custom = None
|
| 122 |
+
if kind == "fold":
|
| 123 |
+
a = 0 if env.legal()[0, 0] else 1
|
| 124 |
+
elif kind in ("check", "call"):
|
| 125 |
+
a = 1
|
| 126 |
+
elif kind in ("allin", "all-in", "shove"):
|
| 127 |
+
a = 9
|
| 128 |
+
else:
|
| 129 |
+
a = N_ACTIONS
|
| 130 |
+
custom = torch.tensor([float(amount) / self.unit])
|
| 131 |
+
fin, delta = env.step(torch.tensor([a]), custom_to=custom)
|
| 132 |
+
return bool(fin[0])
|
| 133 |
+
|
| 134 |
+
def suggest(self):
|
| 135 |
+
env = self.env
|
| 136 |
+
if self.to_act() != self.hero:
|
| 137 |
+
raise ValueError(f"it is seat {self.to_act()}'s turn, not the hero's")
|
| 138 |
+
o = env.obs()
|
| 139 |
+
pr = self.ai.probs(o)[0]
|
| 140 |
+
rt = env._raise_targets(env.cur)[0]
|
| 141 |
+
bet_p = env.bet[0, self.hero].item()
|
| 142 |
+
to_call = max(env.max_bet[0].item() - bet_p, 0.0)
|
| 143 |
+
opts = []
|
| 144 |
+
for i in pr.argsort(descending=True).tolist():
|
| 145 |
+
if pr[i] < 0.01:
|
| 146 |
+
continue
|
| 147 |
+
if i == 0:
|
| 148 |
+
desc = "fold"
|
| 149 |
+
elif i == 1:
|
| 150 |
+
desc = "check" if to_call <= 1e-9 else f"call {min(to_call, env.stack[0, self.hero].item()) * self.unit:g}"
|
| 151 |
+
elif i == 9:
|
| 152 |
+
desc = f"all-in ({(env.stack[0, self.hero].item() + bet_p) * self.unit:g})"
|
| 153 |
+
else:
|
| 154 |
+
desc = f"{'bet' if env.max_bet[0] <= 1e-9 else 'raise to'} {rt[i].item() * self.unit:.2f} ({ACTION_NAMES[i]})"
|
| 155 |
+
opts.append((round(pr[i].item(), 3), desc, i))
|
| 156 |
+
eq = o["glob"][0, 4 + 18].item()
|
| 157 |
+
return dict(best=opts[0][1], options=opts, equity_vs_random=round(eq, 3))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ------------------------------------------------------------------ terminal game
|
| 161 |
+
|
| 162 |
+
def show_table(env, hero, reveal=False):
|
| 163 |
+
n = int(env.n[0])
|
| 164 |
+
st = int(env.street[0])
|
| 165 |
+
board = [card_str(c) for c in env.board[0, :NREV[st]].tolist()]
|
| 166 |
+
print(f"\n Board: {' '.join(board) or '--'} Pot: {env.contrib[0].sum().item():.1f} bb")
|
| 167 |
+
for s in range(n):
|
| 168 |
+
tag = "YOU " if s == hero else f"AI{s:<2}"
|
| 169 |
+
btn = "(D)" if s == int(env.button[0]) else " "
|
| 170 |
+
cards = " ".join(card_str(c) for c in env.hole[0, s].tolist()) if (s == hero or reveal) else "?? ??"
|
| 171 |
+
state = "folded" if env.folded[0, s] else ("ALL-IN" if env.allin[0, s] else "")
|
| 172 |
+
cur = "<-" if s == int(env.cur[0]) and not env.done[0] else ""
|
| 173 |
+
print(f" {btn} {tag} [{cards}] stack {env.stack[0, s].item():7.1f} bet {env.bet[0, s].item():6.1f} {state} {cur}")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def play_cli(players, stack, model_path):
|
| 177 |
+
ai = PokerAI.load(model_path)
|
| 178 |
+
ev = HandEvaluator("cpu")
|
| 179 |
+
hero = 0
|
| 180 |
+
env = PokerEnv(1, players, [0] * (players - 2) + [1], "cpu", ev, eq_samples=64, ante_prob=0.0)
|
| 181 |
+
stacks = torch.full((1, players), float(stack))
|
| 182 |
+
total = 0.0
|
| 183 |
+
hand = 0
|
| 184 |
+
while True:
|
| 185 |
+
hand += 1
|
| 186 |
+
env.reset(n_override=players, stacks_override=stacks.clone())
|
| 187 |
+
print(f"\n===== Hand {hand} ===== (your result so far: {total:+.1f} bb)")
|
| 188 |
+
while not env.done[0]:
|
| 189 |
+
p = int(env.cur[0])
|
| 190 |
+
if p == hero:
|
| 191 |
+
show_table(env, hero)
|
| 192 |
+
L = env.legal()[0]
|
| 193 |
+
to_call = (env.max_bet[0] - env.bet[0, hero]).item()
|
| 194 |
+
print(f" To call: {to_call:.1f}. Options: f=fold, c=check/call, r <amount>=raise to, a=all-in, q=quit")
|
| 195 |
+
cmd = input(" > ").strip().lower().split()
|
| 196 |
+
if not cmd:
|
| 197 |
+
continue
|
| 198 |
+
if cmd[0] == "q":
|
| 199 |
+
return
|
| 200 |
+
custom = None
|
| 201 |
+
if cmd[0] == "f":
|
| 202 |
+
a = 0 if L[0] else 1
|
| 203 |
+
elif cmd[0] == "c":
|
| 204 |
+
a = 1
|
| 205 |
+
elif cmd[0] == "a":
|
| 206 |
+
a = 9 if L[9] else 1
|
| 207 |
+
elif cmd[0] == "r" and len(cmd) > 1 and L[9]:
|
| 208 |
+
a, custom = N_ACTIONS, torch.tensor([float(cmd[1])])
|
| 209 |
+
else:
|
| 210 |
+
print(" invalid")
|
| 211 |
+
continue
|
| 212 |
+
fin, delta = env.step(torch.tensor([a]), custom_to=custom)
|
| 213 |
+
else:
|
| 214 |
+
o = env.obs()
|
| 215 |
+
a = torch.distributions.Categorical(probs=ai.probs(o)).sample()
|
| 216 |
+
print(f" AI{p} -> {ACTION_NAMES[a.item()]}")
|
| 217 |
+
fin, delta = env.step(a)
|
| 218 |
+
show_table(env, hero, reveal=True)
|
| 219 |
+
d = delta[0, hero].item()
|
| 220 |
+
total += d
|
| 221 |
+
print(f" Hand result: {d:+.1f} bb")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def advisor_cli(model_path):
|
| 225 |
+
adv = Advisor(PokerAI.load(model_path))
|
| 226 |
+
print("Poker AI advisor. Amounts in big blinds (or any unit if you pass --bb).")
|
| 227 |
+
n = int(input("players at table: "))
|
| 228 |
+
while True:
|
| 229 |
+
button = int(input(f"button seat (0..{n-1}): "))
|
| 230 |
+
hero = int(input("your seat: "))
|
| 231 |
+
stacks = [float(x) for x in input(f"{n} stacks separated by space: ").split()]
|
| 232 |
+
hole = input("your cards (e.g. As Kd): ")
|
| 233 |
+
adv.new_hand(n, button, stacks, hero, hole)
|
| 234 |
+
while not adv.env.done[0]:
|
| 235 |
+
p = adv.to_act()
|
| 236 |
+
st = int(adv.env.street[0])
|
| 237 |
+
if p == hero:
|
| 238 |
+
s = adv.suggest()
|
| 239 |
+
print(f" >>> AI suggests: {s['best']} (all: {s['options']}, equity vs random {s['equity_vs_random']})")
|
| 240 |
+
line = input(f" seat {p} action (fold/check/call/raise X/allin) or 'board <cards>': ").split()
|
| 241 |
+
if not line:
|
| 242 |
+
continue
|
| 243 |
+
if line[0] == "board":
|
| 244 |
+
adv.board(" ".join(line[1:]))
|
| 245 |
+
continue
|
| 246 |
+
adv.act(p, line[0], float(line[1]) if len(line) > 1 else None)
|
| 247 |
+
if int(adv.env.street[0]) != st and not adv.env.done[0]:
|
| 248 |
+
print(" -- new street: type 'board <all visible cards>' --")
|
| 249 |
+
print("hand over\n")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
ap = argparse.ArgumentParser()
|
| 254 |
+
ap.add_argument("mode", choices=["play", "advisor"])
|
| 255 |
+
ap.add_argument("--players", type=int, default=6)
|
| 256 |
+
ap.add_argument("--stack", type=float, default=100)
|
| 257 |
+
ap.add_argument("--model", default=None, help="path to model.pt (default: download from HF)")
|
| 258 |
+
a = ap.parse_args()
|
| 259 |
+
if a.mode == "play":
|
| 260 |
+
play_cli(a.players, a.stack, a.model)
|
| 261 |
+
else:
|
| 262 |
+
advisor_cli(a.model)
|
poker_core.py
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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in parallel, each with 2..W players (W <= 23).
|
| 5 |
+
- Arbitrary per-player stacks, blinds 0.5/1 (all amounts in big blinds), optional antes.
|
| 6 |
+
- Full NLHE rules: min-raise, incomplete all-in raises (no reopen), side pots, split pots.
|
| 7 |
+
- Hand evaluator: 5-card lookup table (C(52,5) entries) + best-of-21 for 7 cards.
|
| 8 |
+
"""
|
| 9 |
+
import math
|
| 10 |
+
from itertools import combinations
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
N_ACTIONS = 10
|
| 16 |
+
# 0 fold, 1 check/call, 2 min-raise, 3..8 pot-fraction raises, 9 all-in
|
| 17 |
+
RAISE_FRACS = [None, None, 0.0, 0.33, 0.5, 0.75, 1.0, 1.5, 2.5, None]
|
| 18 |
+
ACTION_NAMES = ["fold", "check/call", "min-raise", "raise 33%", "raise 50%", "raise 75%",
|
| 19 |
+
"raise 100%", "raise 150%", "raise 250%", "all-in"]
|
| 20 |
+
MAX_SEATS = 23
|
| 21 |
+
NREV = [0, 3, 4, 5] # board cards revealed per street
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------- hand evaluation
|
| 24 |
+
|
| 25 |
+
def _eval5_direct(c):
|
| 26 |
+
"""c: (N,5) int64 cards 0..51 (rank = c//4, suit = c%4). Returns int64 score (higher is better)."""
|
| 27 |
+
r = c // 4
|
| 28 |
+
s = c % 4
|
| 29 |
+
rs, _ = r.sort(dim=1, descending=True)
|
| 30 |
+
flush = (s == s[:, :1]).all(1)
|
| 31 |
+
oh = F.one_hot(r, 13).sum(1) # (N,13)
|
| 32 |
+
cnt = oh.gather(1, rs)
|
| 33 |
+
key = cnt * 16 + rs
|
| 34 |
+
ks, _ = key.sort(dim=1, descending=True)
|
| 35 |
+
kr = ks % 16
|
| 36 |
+
kc = ks // 16
|
| 37 |
+
distinct = (oh > 0).sum(1)
|
| 38 |
+
wheel = (distinct == 5) & (rs[:, 0] == 12) & (rs[:, 1] == 3)
|
| 39 |
+
straight = ((distinct == 5) & (rs[:, 0] - rs[:, 4] == 4)) | wheel
|
| 40 |
+
c0 = kc[:, 0]
|
| 41 |
+
cat = torch.zeros_like(c0)
|
| 42 |
+
cat[c0 == 2] = 1
|
| 43 |
+
cat[(c0 == 2) & (kc[:, 2] == 2)] = 2
|
| 44 |
+
cat[c0 == 3] = 3
|
| 45 |
+
cat[straight] = 4
|
| 46 |
+
cat[flush] = 5
|
| 47 |
+
cat[(c0 == 3) & (kc[:, 3] == 2)] = 6
|
| 48 |
+
cat[c0 == 4] = 7
|
| 49 |
+
cat[straight & flush] = 8
|
| 50 |
+
tie = kr[:, 0] * 16 ** 4 + kr[:, 1] * 16 ** 3 + kr[:, 2] * 16 ** 2 + kr[:, 3] * 16 + kr[:, 4]
|
| 51 |
+
high = torch.where(wheel, torch.full_like(rs[:, 0], 3), rs[:, 0])
|
| 52 |
+
tie = torch.where(straight, high * 16 ** 4, tie)
|
| 53 |
+
return cat * 16 ** 5 + tie
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class HandEvaluator:
|
| 57 |
+
def __init__(self, device):
|
| 58 |
+
self.device = device
|
| 59 |
+
binom = torch.zeros(53, 6, dtype=torch.long)
|
| 60 |
+
for n in range(53):
|
| 61 |
+
for k in range(6):
|
| 62 |
+
binom[n, k] = math.comb(n, k)
|
| 63 |
+
self.binom = binom.to(device)
|
| 64 |
+
combos = torch.tensor(list(combinations(range(52), 5)), dtype=torch.long)
|
| 65 |
+
lut = torch.zeros(len(combos), dtype=torch.int32)
|
| 66 |
+
for i in range(0, len(combos), 400_000):
|
| 67 |
+
c = combos[i:i + 400_000]
|
| 68 |
+
idx = self._index_cpu(c, binom)
|
| 69 |
+
lut[idx] = _eval5_direct(c).to(torch.int32)
|
| 70 |
+
self.lut = lut.to(device)
|
| 71 |
+
self.comb = {k: torch.tensor(list(combinations(range(k), 5)), dtype=torch.long, device=device)
|
| 72 |
+
for k in (5, 6, 7)}
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def _index_cpu(c, binom):
|
| 76 |
+
return (binom[c[:, 0], 1] + binom[c[:, 1], 2] + binom[c[:, 2], 3] +
|
| 77 |
+
binom[c[:, 3], 4] + binom[c[:, 4], 5])
|
| 78 |
+
|
| 79 |
+
def eval_k(self, cards):
|
| 80 |
+
"""cards (..., k) with k in 5,6,7, all valid & distinct. Returns int32 best-5 score."""
|
| 81 |
+
k = cards.shape[-1]
|
| 82 |
+
sh = cards.shape[:-1]
|
| 83 |
+
c = cards.reshape(-1, k).long().sort(dim=1).values
|
| 84 |
+
sub = c[:, self.comb[k]] # (M, C, 5) ascending
|
| 85 |
+
b = self.binom
|
| 86 |
+
idx = (b[sub[..., 0], 1] + b[sub[..., 1], 2] + b[sub[..., 2], 3] +
|
| 87 |
+
b[sub[..., 3], 4] + b[sub[..., 4], 5])
|
| 88 |
+
return self.lut[idx].max(dim=-1).values.reshape(sh)
|
| 89 |
+
|
| 90 |
+
def eval7_chunked(self, cards, chunk=1 << 20):
|
| 91 |
+
sh = cards.shape[:-1]
|
| 92 |
+
flat = cards.reshape(-1, 7)
|
| 93 |
+
out = torch.empty(flat.shape[0], dtype=torch.int32, device=flat.device)
|
| 94 |
+
for i in range(0, flat.shape[0], chunk):
|
| 95 |
+
out[i:i + chunk] = self.eval_k(flat[i:i + chunk])
|
| 96 |
+
return out.reshape(sh)
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def category(score):
|
| 100 |
+
return (score.long() // (16 ** 5)).clamp(0, 8)
|
| 101 |
+
|
| 102 |
+
def equity(self, hole, board, nrev, n_opp, K=16, chunk=2048):
|
| 103 |
+
"""Monte-Carlo equity vs uniformly random hands.
|
| 104 |
+
hole (N,2), board (N,5) (only first nrev valid), nrev (N,), n_opp (N,) >=1.
|
| 105 |
+
Returns eq1 (vs 1 random hand) and eqM (vs n_opp random hands)."""
|
| 106 |
+
N = hole.shape[0]
|
| 107 |
+
dev = hole.device
|
| 108 |
+
eq1 = torch.empty(N, device=dev)
|
| 109 |
+
eqm = torch.empty(N, device=dev)
|
| 110 |
+
for i in range(0, N, chunk):
|
| 111 |
+
h = hole[i:i + chunk]
|
| 112 |
+
bd = board[i:i + chunk]
|
| 113 |
+
nr = nrev[i:i + chunk]
|
| 114 |
+
no = n_opp[i:i + chunk]
|
| 115 |
+
n = h.shape[0]
|
| 116 |
+
O = int(no.max().item()) if n > 0 else 1
|
| 117 |
+
O = max(O, 1)
|
| 118 |
+
known = torch.zeros(n, 52, dtype=torch.bool, device=dev)
|
| 119 |
+
known.scatter_(1, h.long(), True)
|
| 120 |
+
slot = torch.arange(5, device=dev)
|
| 121 |
+
bvalid = slot[None] < nr[:, None]
|
| 122 |
+
bk = torch.where(bvalid, bd.long(), h[:, :1].long().expand(-1, 5))
|
| 123 |
+
known.scatter_(1, bk, True)
|
| 124 |
+
keys = torch.rand(n, K, 52, device=dev)
|
| 125 |
+
keys = keys.masked_fill(known[:, None, :], 2.0)
|
| 126 |
+
M = 5 + 2 * O
|
| 127 |
+
samp = keys.topk(M, dim=2, largest=False).indices # (n,K,M) random unknown cards
|
| 128 |
+
# opponents take samp[:2O]; unrevealed board slot i takes samp[2O + i - nrev]
|
| 129 |
+
bsel = (2 * O + (slot[None] - nr[:, None]).clamp(min=0)).clamp(max=M - 1)
|
| 130 |
+
bfill = samp.gather(2, bsel[:, None, :].expand(-1, K, -1))
|
| 131 |
+
board_s = torch.where(bvalid[:, None, :], bd.long()[:, None, :].expand(-1, K, -1), bfill)
|
| 132 |
+
hero7 = torch.cat([h.long()[:, None, :].expand(-1, K, -1), board_s], dim=2)
|
| 133 |
+
hs = self.eval_k(hero7) # (n,K)
|
| 134 |
+
opp_h = samp[:, :, :2 * O].reshape(n, K, O, 2)
|
| 135 |
+
opp7 = torch.cat([opp_h, board_s[:, :, None, :].expand(-1, -1, O, -1)], dim=3)
|
| 136 |
+
os_ = self.eval_k(opp7) # (n,K,O)
|
| 137 |
+
omask = torch.arange(O, device=dev)[None, None, :] < no[:, None, None]
|
| 138 |
+
os_ = torch.where(omask, os_, torch.full_like(os_, -1))
|
| 139 |
+
o0 = os_[:, :, 0]
|
| 140 |
+
e1 = (hs > o0).float() + 0.5 * (hs == o0).float()
|
| 141 |
+
mx = os_.max(dim=2).values
|
| 142 |
+
ties = (os_ == hs[:, :, None]).sum(2).float()
|
| 143 |
+
em = (hs > mx).float() + (hs == mx).float() / (1.0 + ties)
|
| 144 |
+
eq1[i:i + chunk] = e1.mean(1)
|
| 145 |
+
eqm[i:i + chunk] = em.mean(1)
|
| 146 |
+
return eq1, eqm
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ---------------------------------------------------------------- environment
|
| 150 |
+
|
| 151 |
+
class PokerEnv:
|
| 152 |
+
"""Batch of NLHE games. Every non-finished game always has exactly one player to act (self.cur)."""
|
| 153 |
+
|
| 154 |
+
FG = None # set after first obs
|
| 155 |
+
FS = None
|
| 156 |
+
|
| 157 |
+
def __init__(self, B, W, n_probs, device, evaluator, eq_samples=16, fixed_stack=None, ante_prob=0.2):
|
| 158 |
+
assert 2 <= W <= MAX_SEATS
|
| 159 |
+
self.B, self.W, self.dev = B, W, device
|
| 160 |
+
self.ev = evaluator
|
| 161 |
+
self.K = eq_samples
|
| 162 |
+
p = torch.tensor(n_probs, dtype=torch.float, device=device) # probs over n = 2..len+1
|
| 163 |
+
self.n_probs = p / p.sum()
|
| 164 |
+
self.fixed_stack = fixed_stack
|
| 165 |
+
self.ante_prob = ante_prob
|
| 166 |
+
z = lambda *s, dt=torch.float: torch.zeros(*s, dtype=dt, device=device)
|
| 167 |
+
self.n = z(B, dt=torch.long)
|
| 168 |
+
self.button = z(B, dt=torch.long)
|
| 169 |
+
self.stack = z(B, W)
|
| 170 |
+
self.start_stack = z(B, W)
|
| 171 |
+
self.bet = z(B, W)
|
| 172 |
+
self.contrib = z(B, W)
|
| 173 |
+
self.st_contrib = z(B, W, 4)
|
| 174 |
+
self.st_aggr = z(B, W, 4)
|
| 175 |
+
self.last_act = z(B, W, dt=torch.long)
|
| 176 |
+
self.folded = z(B, W, dt=torch.bool)
|
| 177 |
+
self.allin = z(B, W, dt=torch.bool)
|
| 178 |
+
self.present = z(B, W, dt=torch.bool)
|
| 179 |
+
self.acted = z(B, W, dt=torch.bool)
|
| 180 |
+
self.can_raise = z(B, W, dt=torch.bool)
|
| 181 |
+
self.max_bet = z(B)
|
| 182 |
+
self.min_raise = z(B)
|
| 183 |
+
self.ante = z(B)
|
| 184 |
+
self.street = z(B, dt=torch.long)
|
| 185 |
+
self.cur = z(B, dt=torch.long)
|
| 186 |
+
self.hole = z(B, W, 2, dt=torch.long)
|
| 187 |
+
self.board = z(B, 5, dt=torch.long)
|
| 188 |
+
self.done = torch.ones(B, dtype=torch.bool, device=device)
|
| 189 |
+
self.ar = torch.arange(B, device=device)
|
| 190 |
+
self.seats = torch.arange(W, device=device)
|
| 191 |
+
|
| 192 |
+
# ------------------------------------------------------------ helpers
|
| 193 |
+
def _next_need(self, frm, need):
|
| 194 |
+
offs = torch.arange(1, self.W + 1, device=self.dev)
|
| 195 |
+
idx = (frm[:, None] + offs[None, :]) % self.n[:, None]
|
| 196 |
+
g = need.gather(1, idx)
|
| 197 |
+
first = g.float().argmax(1)
|
| 198 |
+
return idx.gather(1, first[:, None]).squeeze(1), g.any(1)
|
| 199 |
+
|
| 200 |
+
def _need(self):
|
| 201 |
+
return (self.present & ~self.folded & ~self.allin &
|
| 202 |
+
(~self.acted | (self.bet < self.max_bet[:, None] - 1e-6)))
|
| 203 |
+
|
| 204 |
+
# ------------------------------------------------------------ reset
|
| 205 |
+
def reset(self, mask=None, n_override=None, stacks_override=None):
|
| 206 |
+
B, W, dev = self.B, self.W, self.dev
|
| 207 |
+
if mask is None:
|
| 208 |
+
mask = torch.ones(B, dtype=torch.bool, device=dev)
|
| 209 |
+
if not mask.any():
|
| 210 |
+
return
|
| 211 |
+
m = mask
|
| 212 |
+
m2 = m[:, None]
|
| 213 |
+
if n_override is not None:
|
| 214 |
+
n = torch.full((B,), n_override, dtype=torch.long, device=dev) if isinstance(n_override, int) else n_override
|
| 215 |
+
else:
|
| 216 |
+
n = torch.multinomial(self.n_probs, B, replacement=True) + 2
|
| 217 |
+
present = self.seats[None] < n[:, None]
|
| 218 |
+
button = (torch.rand(B, device=dev) * n).long().clamp(max=n - 1)
|
| 219 |
+
# stacks
|
| 220 |
+
if stacks_override is not None:
|
| 221 |
+
stk = stacks_override
|
| 222 |
+
elif self.fixed_stack is not None:
|
| 223 |
+
stk = torch.full((B, W), float(self.fixed_stack), device=dev)
|
| 224 |
+
else:
|
| 225 |
+
u = torch.rand(B, device=dev)
|
| 226 |
+
common = torch.exp(torch.empty(B, device=dev).uniform_(math.log(10), math.log(250)))
|
| 227 |
+
common = torch.where(u < 0.4, torch.full_like(common, 100.0), common)
|
| 228 |
+
indiv = torch.exp(torch.empty(B, W, device=dev).uniform_(math.log(3), math.log(300)))
|
| 229 |
+
stk = torch.where((u < 0.7)[:, None], common[:, None].expand(-1, W), indiv)
|
| 230 |
+
stk = (stk * 2).round() / 2
|
| 231 |
+
stk = torch.where(present, stk.clamp(min=2.0), torch.zeros_like(stk))
|
| 232 |
+
ante = torch.where(torch.rand(B, device=dev) < self.ante_prob,
|
| 233 |
+
torch.empty(B, device=dev).uniform_(0.05, 0.25), torch.zeros(B, device=dev))
|
| 234 |
+
ante = (ante * 20).round() / 20
|
| 235 |
+
if stacks_override is not None or self.fixed_stack is not None:
|
| 236 |
+
ante = torch.zeros(B, device=dev)
|
| 237 |
+
# deck
|
| 238 |
+
perm = torch.rand(B, 52, device=dev).argsort(1)
|
| 239 |
+
hole = perm[:, :2 * W].reshape(B, W, 2)
|
| 240 |
+
hole = hole.sort(dim=2, descending=True).values
|
| 241 |
+
board = perm[:, 46:51] if W == 23 else perm[:, 2 * W:2 * W + 5]
|
| 242 |
+
# blinds
|
| 243 |
+
sb = torch.where(n == 2, button, (button + 1) % n)
|
| 244 |
+
bb = (sb + 1) % n
|
| 245 |
+
contrib = torch.where(present, torch.minimum(ante[:, None].expand(-1, W), stk), torch.zeros_like(stk))
|
| 246 |
+
stack = stk - contrib
|
| 247 |
+
bet = torch.zeros(B, W, device=dev)
|
| 248 |
+
sbamt = torch.minimum(stack[self.ar, sb], torch.full((B,), 0.5, device=dev))
|
| 249 |
+
bet[self.ar, sb] = sbamt
|
| 250 |
+
stack[self.ar, sb] -= sbamt
|
| 251 |
+
bbamt = torch.minimum(stack[self.ar, bb], torch.full((B,), 1.0, device=dev))
|
| 252 |
+
bet[self.ar, bb] = bbamt
|
| 253 |
+
stack[self.ar, bb] -= bbamt
|
| 254 |
+
contrib = contrib + bet
|
| 255 |
+
stc = torch.zeros(B, W, 4, device=dev)
|
| 256 |
+
stc[:, :, 0] = bet
|
| 257 |
+
|
| 258 |
+
def put(name, val):
|
| 259 |
+
cur = getattr(self, name)
|
| 260 |
+
mm = m.view(B, *([1] * (cur.dim() - 1)))
|
| 261 |
+
setattr(self, name, torch.where(mm, val, cur))
|
| 262 |
+
|
| 263 |
+
put("n", n)
|
| 264 |
+
put("button", button)
|
| 265 |
+
put("present", present)
|
| 266 |
+
put("start_stack", stk)
|
| 267 |
+
put("stack", stack)
|
| 268 |
+
put("bet", bet)
|
| 269 |
+
put("contrib", contrib)
|
| 270 |
+
put("st_contrib", stc)
|
| 271 |
+
put("st_aggr", torch.zeros(B, W, 4, device=dev))
|
| 272 |
+
put("last_act", torch.zeros(B, W, dtype=torch.long, device=dev))
|
| 273 |
+
put("folded", ~present)
|
| 274 |
+
put("allin", present & (stack <= 1e-9))
|
| 275 |
+
put("acted", torch.zeros(B, W, dtype=torch.bool, device=dev))
|
| 276 |
+
put("can_raise", present.clone())
|
| 277 |
+
put("max_bet", bet.max(1).values.clamp(min=1.0))
|
| 278 |
+
put("min_raise", torch.ones(B, device=dev))
|
| 279 |
+
put("ante", ante)
|
| 280 |
+
put("street", torch.zeros(B, dtype=torch.long, device=dev))
|
| 281 |
+
put("hole", hole)
|
| 282 |
+
put("board", board)
|
| 283 |
+
put("done", torch.zeros(B, dtype=torch.bool, device=dev))
|
| 284 |
+
cur, ok = self._next_need(bb, self._need())
|
| 285 |
+
put("cur", cur)
|
| 286 |
+
|
| 287 |
+
# ------------------------------------------------------------ raise targets / legality
|
| 288 |
+
def _raise_targets(self, p):
|
| 289 |
+
"""Returns (B, N_ACTIONS) raise-to amounts (uncapped) for raise actions."""
|
| 290 |
+
bet_p = self.bet[self.ar, p]
|
| 291 |
+
to_call = (self.max_bet - bet_p).clamp(min=0)
|
| 292 |
+
pot = self.contrib.sum(1)
|
| 293 |
+
pac = pot + to_call
|
| 294 |
+
minr = self.max_bet + self.min_raise
|
| 295 |
+
rt = torch.zeros(self.B, N_ACTIONS, device=self.dev)
|
| 296 |
+
for a in range(2, 9):
|
| 297 |
+
f = RAISE_FRACS[a]
|
| 298 |
+
rt[:, a] = torch.maximum(self.max_bet + f * pac, minr)
|
| 299 |
+
rt[:, 9] = bet_p + self.stack[self.ar, p]
|
| 300 |
+
return rt
|
| 301 |
+
|
| 302 |
+
def legal(self, p=None):
|
| 303 |
+
if p is None:
|
| 304 |
+
p = self.cur
|
| 305 |
+
bet_p = self.bet[self.ar, p]
|
| 306 |
+
stk = self.stack[self.ar, p]
|
| 307 |
+
to_call = (self.max_bet - bet_p).clamp(min=0)
|
| 308 |
+
rt = self._raise_targets(p)
|
| 309 |
+
raise_ok = self.can_raise[self.ar, p] & (stk > to_call + 1e-9)
|
| 310 |
+
L = torch.zeros(self.B, N_ACTIONS, dtype=torch.bool, device=self.dev)
|
| 311 |
+
L[:, 0] = to_call > 1e-9
|
| 312 |
+
L[:, 1] = True
|
| 313 |
+
L[:, 2:9] = raise_ok[:, None] & ((rt[:, 2:9] - bet_p[:, None]) < stk[:, None] - 1e-9)
|
| 314 |
+
L[:, 9] = raise_ok
|
| 315 |
+
return L
|
| 316 |
+
|
| 317 |
+
# ------------------------------------------------------------ step
|
| 318 |
+
def step(self, action, mask=None, custom_to=None):
|
| 319 |
+
"""Apply `action` (B,) for current players of games in mask (default: all not done).
|
| 320 |
+
Action == N_ACTIONS means "raise to custom_to[b]" (arbitrary amount, used by play.py).
|
| 321 |
+
Returns (hand_finished (B,) bool, delta (B,W) chip result for finished hands)."""
|
| 322 |
+
B, W, dev, ar = self.B, self.W, self.dev, self.ar
|
| 323 |
+
if mask is None:
|
| 324 |
+
mask = ~self.done
|
| 325 |
+
mask = mask & ~self.done
|
| 326 |
+
p = self.cur
|
| 327 |
+
bet_p = self.bet[ar, p]
|
| 328 |
+
stk = self.stack[ar, p]
|
| 329 |
+
to_call = (self.max_bet - bet_p).clamp(min=0)
|
| 330 |
+
rt = self._raise_targets(p)
|
| 331 |
+
a = action.long()
|
| 332 |
+
is_fold = (a == 0) & mask
|
| 333 |
+
is_call = (a == 1) & mask
|
| 334 |
+
is_raise = (a >= 2) & mask
|
| 335 |
+
r_to = rt.gather(1, a.clamp(max=N_ACTIONS - 1)[:, None]).squeeze(1)
|
| 336 |
+
if custom_to is not None:
|
| 337 |
+
r_to = torch.where(a == N_ACTIONS, torch.maximum(custom_to, self.max_bet + self.min_raise), r_to)
|
| 338 |
+
r_to = torch.minimum(r_to, bet_p + stk)
|
| 339 |
+
amt = torch.where(is_call, torch.minimum(to_call, stk), torch.zeros_like(stk))
|
| 340 |
+
amt = torch.where(is_raise, (r_to - bet_p).clamp(min=0), amt)
|
| 341 |
+
amt = torch.minimum(amt, stk)
|
| 342 |
+
onehot_p = F.one_hot(p, W).bool() & mask[:, None]
|
| 343 |
+
add = onehot_p.float() * amt[:, None]
|
| 344 |
+
self.stack = self.stack - add
|
| 345 |
+
self.bet = self.bet + add
|
| 346 |
+
self.contrib = self.contrib + add
|
| 347 |
+
st_oh = F.one_hot(self.street, 4).float()
|
| 348 |
+
self.st_contrib = self.st_contrib + add[:, :, None] * st_oh[:, None, :]
|
| 349 |
+
self.folded = self.folded | (onehot_p & is_fold[:, None])
|
| 350 |
+
new_bet = bet_p + amt
|
| 351 |
+
raised = mask & (new_bet > self.max_bet + 1e-9)
|
| 352 |
+
inc = new_bet - self.max_bet
|
| 353 |
+
full = raised & (inc >= self.min_raise - 1e-9)
|
| 354 |
+
others = self.present & ~self.folded & ~self.allin & ~onehot_p
|
| 355 |
+
self.can_raise = self.can_raise | (others & full[:, None])
|
| 356 |
+
self.min_raise = torch.where(full, inc, self.min_raise)
|
| 357 |
+
self.max_bet = torch.where(raised, new_bet, self.max_bet)
|
| 358 |
+
self.st_aggr = self.st_aggr + (onehot_p & raised[:, None]).float()[:, :, None] * st_oh[:, None, :]
|
| 359 |
+
self.acted = self.acted | onehot_p
|
| 360 |
+
self.can_raise = self.can_raise & ~onehot_p
|
| 361 |
+
went_allin = onehot_p & (self.stack <= 1e-9) & self.present & ~self.folded
|
| 362 |
+
self.allin = self.allin | went_allin
|
| 363 |
+
code = torch.where(is_fold, 1, torch.where(raised, 4, torch.where(amt > 1e-9, 3, 2)))
|
| 364 |
+
code = torch.where(went_allin.any(1) & (amt > 1e-9), 5, code)
|
| 365 |
+
self.last_act = torch.where(onehot_p, code[:, None], self.last_act)
|
| 366 |
+
|
| 367 |
+
# ---- resolve
|
| 368 |
+
live = self.present & ~self.folded
|
| 369 |
+
n_live = live.sum(1)
|
| 370 |
+
one_left = mask & (n_live == 1)
|
| 371 |
+
need = self._need()
|
| 372 |
+
round_done = mask & ~need.any(1) & ~one_left
|
| 373 |
+
can_act = live & ~self.allin
|
| 374 |
+
n_can = can_act.sum(1)
|
| 375 |
+
showdown = round_done & ((self.street == 3) | (n_can <= 1))
|
| 376 |
+
advance = round_done & ~showdown
|
| 377 |
+
cont = mask & ~one_left & ~round_done
|
| 378 |
+
|
| 379 |
+
# continue in same round
|
| 380 |
+
nxt, _ = self._next_need(p, need)
|
| 381 |
+
self.cur = torch.where(cont, nxt, self.cur)
|
| 382 |
+
|
| 383 |
+
# advance street
|
| 384 |
+
if advance.any():
|
| 385 |
+
a2 = advance[:, None]
|
| 386 |
+
self.street = torch.where(advance, self.street + 1, self.street)
|
| 387 |
+
self.bet = torch.where(a2, torch.zeros_like(self.bet), self.bet)
|
| 388 |
+
self.max_bet = torch.where(advance, torch.zeros_like(self.max_bet), self.max_bet)
|
| 389 |
+
self.min_raise = torch.where(advance, torch.ones_like(self.min_raise), self.min_raise)
|
| 390 |
+
self.acted = self.acted & ~a2
|
| 391 |
+
self.can_raise = torch.where(a2, can_act, self.can_raise)
|
| 392 |
+
nxt2, _ = self._next_need(self.button, self._need())
|
| 393 |
+
self.cur = torch.where(advance, nxt2, self.cur)
|
| 394 |
+
|
| 395 |
+
# payouts
|
| 396 |
+
win = torch.zeros(B, W, device=dev)
|
| 397 |
+
pot = self.contrib.sum(1)
|
| 398 |
+
win = win + (live & one_left[:, None]).float() * pot[:, None]
|
| 399 |
+
if showdown.any():
|
| 400 |
+
idx = showdown.nonzero().squeeze(1)
|
| 401 |
+
win[idx] = self._showdown(idx)
|
| 402 |
+
finished = one_left | showdown
|
| 403 |
+
self.stack = self.stack + win
|
| 404 |
+
self.done = self.done | finished
|
| 405 |
+
delta = torch.where(finished[:, None], self.stack - self.start_stack, torch.zeros_like(self.stack))
|
| 406 |
+
return finished, delta
|
| 407 |
+
|
| 408 |
+
def _showdown(self, idx):
|
| 409 |
+
hole = self.hole[idx] # (b,W,2)
|
| 410 |
+
board = self.board[idx] # (b,5)
|
| 411 |
+
b = idx.shape[0]
|
| 412 |
+
W = self.W
|
| 413 |
+
cards7 = torch.cat([hole, board[:, None, :].expand(-1, W, -1)], dim=2)
|
| 414 |
+
live = self.present[idx] & ~self.folded[idx]
|
| 415 |
+
score = self.ev.eval7_chunked(cards7).long()
|
| 416 |
+
score = torch.where(live, score, torch.full_like(score, -1))
|
| 417 |
+
c = self.contrib[idx]
|
| 418 |
+
lv = c.sort(1).values
|
| 419 |
+
prev = torch.zeros(b, device=self.dev)
|
| 420 |
+
win = torch.zeros(b, W, device=self.dev)
|
| 421 |
+
for k in range(W):
|
| 422 |
+
L = lv[:, k]
|
| 423 |
+
layer = (torch.minimum(c, L[:, None]) - torch.minimum(c, prev[:, None])).sum(1)
|
| 424 |
+
elig = live & (c >= L[:, None] - 1e-6)
|
| 425 |
+
none = ~elig.any(1)
|
| 426 |
+
elig = torch.where(none[:, None], live, elig)
|
| 427 |
+
sc = torch.where(elig, score, torch.full_like(score, -2))
|
| 428 |
+
best = sc.max(1).values
|
| 429 |
+
winners = elig & (sc == best[:, None])
|
| 430 |
+
share = layer / winners.sum(1).clamp(min=1)
|
| 431 |
+
win = win + winners.float() * share[:, None]
|
| 432 |
+
prev = L
|
| 433 |
+
return win
|
| 434 |
+
|
| 435 |
+
# ------------------------------------------------------------ observation
|
| 436 |
+
def obs(self, privileged=False, idx=None):
|
| 437 |
+
"""Observation for the current player of each game (or subset idx)."""
|
| 438 |
+
if idx is None:
|
| 439 |
+
idx = self.ar
|
| 440 |
+
b = idx.shape[0]
|
| 441 |
+
W, dev = self.W, self.dev
|
| 442 |
+
p = self.cur[idx]
|
| 443 |
+
n = self.n[idx]
|
| 444 |
+
btn = self.button[idx]
|
| 445 |
+
street = self.street[idx]
|
| 446 |
+
present = self.present[idx]
|
| 447 |
+
folded = self.folded[idx]
|
| 448 |
+
allin = self.allin[idx]
|
| 449 |
+
stack = self.stack[idx]
|
| 450 |
+
bet = self.bet[idx]
|
| 451 |
+
contrib = self.contrib[idx]
|
| 452 |
+
maxb = self.max_bet[idx]
|
| 453 |
+
minr = self.min_raise[idx]
|
| 454 |
+
ar = torch.arange(b, device=dev)
|
| 455 |
+
live = present & ~folded
|
| 456 |
+
n_live = live.sum(1)
|
| 457 |
+
can_act = live & ~allin
|
| 458 |
+
pot = contrib.sum(1)
|
| 459 |
+
bet_p = bet[ar, p]
|
| 460 |
+
stk_p = stack[ar, p]
|
| 461 |
+
to_call = (maxb - bet_p).clamp(min=0)
|
| 462 |
+
others_live = live.clone()
|
| 463 |
+
others_live[ar, p] = False
|
| 464 |
+
max_other = torch.where(others_live, stack + bet, torch.zeros_like(stack)).max(1).values
|
| 465 |
+
eff = torch.minimum(stk_p + bet_p, max_other)
|
| 466 |
+
nrev = torch.tensor(NREV, device=dev)[street]
|
| 467 |
+
hole_p = self.hole[idx, p] # (b,2)
|
| 468 |
+
board = self.board[idx]
|
| 469 |
+
# equity features
|
| 470 |
+
n_opp = (n_live - 1).clamp(min=1)
|
| 471 |
+
eq1, eqm = self.ev.equity(hole_p, board, nrev, n_opp, K=self.K)
|
| 472 |
+
# made-hand category
|
| 473 |
+
cat = torch.zeros(b, dtype=torch.long, device=dev)
|
| 474 |
+
cat = torch.where(street == 0, (hole_p[:, 0] // 4 == hole_p[:, 1] // 4).long(), cat)
|
| 475 |
+
for s, k in ((1, 5), (2, 6), (3, 7)):
|
| 476 |
+
m = street == s
|
| 477 |
+
if m.any():
|
| 478 |
+
cc = torch.cat([hole_p[m], board[m, :k - 2]], 1)
|
| 479 |
+
cat[m] = self.ev.category(self.ev.eval_k(cc))
|
| 480 |
+
need = (present & ~folded & ~allin & (~self.acted[idx] | (bet < maxb[:, None] - 1e-6)))
|
| 481 |
+
n_need_others = need.sum(1) - need[ar, p].long()
|
| 482 |
+
postpos = ((p - btn - 1) % n).float() / (n - 1).clamp(min=1).float()
|
| 483 |
+
g = [
|
| 484 |
+
F.one_hot(street, 4).float(),
|
| 485 |
+
torch.stack([
|
| 486 |
+
n.float() / 10, n_live.float() / 10, can_act.sum(1).float() / 10,
|
| 487 |
+
pot / 100, torch.log1p(pot) / 5,
|
| 488 |
+
to_call / 100, torch.log1p(to_call) / 5, to_call / (pot + to_call).clamp(min=1e-6),
|
| 489 |
+
stk_p / 100, torch.log1p(stk_p) / 5, (stk_p / pot.clamp(min=1e-6)).clamp(max=20) / 20,
|
| 490 |
+
eff / 100, torch.log1p(eff) / 5,
|
| 491 |
+
maxb / 100, minr / 100, bet_p / 100, contrib[ar, p] / 100,
|
| 492 |
+
eq1, eqm, eq1 ** n_opp.float(),
|
| 493 |
+
(p == btn).float(), postpos, self.ante[idx],
|
| 494 |
+
self.st_aggr[idx, :, :].gather(2, street[:, None, None].expand(-1, W, 1)).sum((1, 2)) / 5,
|
| 495 |
+
(live & allin).sum(1).float() / 10, n_need_others.float() / 10,
|
| 496 |
+
], 1),
|
| 497 |
+
F.one_hot(cat, 9).float(),
|
| 498 |
+
]
|
| 499 |
+
glob = torch.cat(g, 1)
|
| 500 |
+
# seat tokens in order relative to acting player
|
| 501 |
+
t = torch.arange(W, device=dev)
|
| 502 |
+
smask = t[None] < n[:, None]
|
| 503 |
+
sidx = torch.where(smask, (p[:, None] + t[None]) % n[:, None], t[None].expand(b, -1))
|
| 504 |
+
gat = lambda x: x.gather(1, sidx)
|
| 505 |
+
sb = torch.where(n == 2, btn, (btn + 1) % n)
|
| 506 |
+
bbs = (sb + 1) % n
|
| 507 |
+
s_stack = gat(stack)
|
| 508 |
+
s_bet = gat(bet)
|
| 509 |
+
s_con = gat(contrib)
|
| 510 |
+
stc = self.st_contrib[idx].gather(1, sidx[:, :, None].expand(-1, -1, 4))
|
| 511 |
+
sta = self.st_aggr[idx].gather(1, sidx[:, :, None].expand(-1, -1, 4))
|
| 512 |
+
la = F.one_hot(gat(self.last_act[idx]), 6).float()
|
| 513 |
+
seat = torch.cat([
|
| 514 |
+
torch.stack([
|
| 515 |
+
gat(present).float(), gat(folded).float(), gat(allin).float(), (t[None] == 0).float().expand(b, -1),
|
| 516 |
+
s_stack / 100, torch.log1p(s_stack) / 5, s_bet / 100, torch.log1p(s_bet) / 5,
|
| 517 |
+
s_con / 100, torch.log1p(s_con) / 5,
|
| 518 |
+
gat(self.acted[idx]).float(), gat(self.can_raise[idx]).float(),
|
| 519 |
+
(sidx == btn[:, None]).float(), (sidx == sb[:, None]).float(), (sidx == bbs[:, None]).float(),
|
| 520 |
+
gat(need).float(), gat(self.start_stack[idx]) / 100,
|
| 521 |
+
], 2),
|
| 522 |
+
stc / 100, sta / 3, la,
|
| 523 |
+
], 2) * smask[:, :, None].float()
|
| 524 |
+
btn_dist = torch.where(smask, (sidx - btn[:, None]) % n[:, None], torch.zeros_like(sidx))
|
| 525 |
+
board_vis = torch.where(torch.arange(5, device=dev)[None] < nrev[:, None], board, torch.full_like(board, 52))
|
| 526 |
+
cards = torch.cat([hole_p, board_vis], 1)
|
| 527 |
+
legal = self.legal()[idx] if idx is not self.ar else self.legal()
|
| 528 |
+
o = dict(cards=cards, glob=glob, seat=seat, seat_pos=t[None].expand(b, -1).contiguous(),
|
| 529 |
+
btn_dist=btn_dist, seat_mask=smask, legal=legal)
|
| 530 |
+
if privileged:
|
| 531 |
+
ah = self.hole[idx].gather(1, sidx[:, :, None].expand(-1, -1, 2))
|
| 532 |
+
ah = torch.where(smask[:, :, None], ah, torch.full_like(ah, 52))
|
| 533 |
+
o["all_hole"] = ah
|
| 534 |
+
o["full_board"] = board
|
| 535 |
+
PokerEnv.FG = glob.shape[1]
|
| 536 |
+
PokerEnv.FS = seat.shape[2]
|
| 537 |
+
return o
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def obs_dims():
|
| 541 |
+
return 4 + 26 + 9, 17 + 4 + 4 + 6
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
# ---------------------------------------------------------------- heuristic opponents
|
| 545 |
+
|
| 546 |
+
def bot_action(kind, obs, gen=None):
|
| 547 |
+
"""Simple rule-based bots for league diversity and evaluation."""
|
| 548 |
+
g = obs["glob"]
|
| 549 |
+
L = obs["legal"]
|
| 550 |
+
b = g.shape[0]
|
| 551 |
+
dev = g.device
|
| 552 |
+
eqm = g[:, 4 + 18]
|
| 553 |
+
eq1 = g[:, 4 + 17]
|
| 554 |
+
pot_odds = g[:, 4 + 7]
|
| 555 |
+
to_call_pos = L[:, 0]
|
| 556 |
+
act = torch.ones(b, dtype=torch.long, device=dev) # call/check
|
| 557 |
+
|
| 558 |
+
def pick_raise(pref):
|
| 559 |
+
a = torch.full((b,), pref, dtype=torch.long, device=dev)
|
| 560 |
+
ok = L.gather(1, a[:, None]).squeeze(1)
|
| 561 |
+
a = torch.where(ok, a, torch.where(L[:, 9], torch.full_like(a, 9), torch.ones_like(a)))
|
| 562 |
+
return a
|
| 563 |
+
|
| 564 |
+
fold_or_check = torch.where(to_call_pos, torch.zeros_like(act), torch.ones_like(act))
|
| 565 |
+
if kind == "call":
|
| 566 |
+
return act
|
| 567 |
+
if kind == "random":
|
| 568 |
+
logits = torch.where(L, torch.zeros(b, N_ACTIONS, device=dev), torch.full((b, N_ACTIONS), -1e9, device=dev))
|
| 569 |
+
return torch.distributions.Categorical(logits=logits).sample()
|
| 570 |
+
if kind == "tag":
|
| 571 |
+
a = torch.where(eqm >= pot_odds + 0.04, act, fold_or_check)
|
| 572 |
+
a = torch.where((eqm > 0.55) & ~to_call_pos, pick_raise(4), a)
|
| 573 |
+
a = torch.where(eqm > 0.72, pick_raise(6), a)
|
| 574 |
+
return a
|
| 575 |
+
if kind == "rock":
|
| 576 |
+
a = torch.where(eqm >= pot_odds + 0.15, act, fold_or_check)
|
| 577 |
+
a = torch.where(eqm > 0.82, pick_raise(5), a)
|
| 578 |
+
return a
|
| 579 |
+
if kind == "maniac":
|
| 580 |
+
r = torch.rand(b, device=dev)
|
| 581 |
+
size = torch.randint(3, 10, (b,), device=dev)
|
| 582 |
+
rs = torch.where(L.gather(1, size[:, None]).squeeze(1), size, torch.where(L[:, 9], 9, 1))
|
| 583 |
+
a = torch.where(r < 0.55, rs, act)
|
| 584 |
+
a = torch.where((eq1 < 0.3) & (r > 0.85) & to_call_pos, torch.zeros_like(a), a)
|
| 585 |
+
return a
|
| 586 |
+
if kind == "eqcaller":
|
| 587 |
+
return torch.where(eq1 >= pot_odds, act, fold_or_check)
|
| 588 |
+
raise ValueError(kind)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
BOT_KINDS = ["call", "random", "tag", "rock", "maniac", "eqcaller"]
|
train.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-play PPO training for multi-player No-Limit Hold'em (2..23 players)."""
|
| 2 |
+
import copy
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from model import PokerNet
|
| 13 |
+
from poker_core import BOT_KINDS, N_ACTIONS, HandEvaluator, PokerEnv
|
| 14 |
+
|
| 15 |
+
DEFAULT = dict(
|
| 16 |
+
groups=[
|
| 17 |
+
# n = 2..9 : heads-up heavy, full ring 9 included
|
| 18 |
+
dict(W=9, B=32768, probs=[30, 9, 9, 10, 12, 10, 10, 10]),
|
| 19 |
+
# n = 10..23 : big / crowded tables (generalisation to "any number of players")
|
| 20 |
+
dict(W=23, B=8192, probs=[0] * 8 + [14, 14, 14, 12, 12, 12, 6, 4, 3, 3, 2, 2, 1, 1]),
|
| 21 |
+
],
|
| 22 |
+
T_min=64,
|
| 23 |
+
eq_samples=16,
|
| 24 |
+
d=256, layers=4, heads=8,
|
| 25 |
+
cd=192, clayers=3, cheads=6,
|
| 26 |
+
lr=3e-4, lr_min=3e-5, epochs=2, minibatch=32768,
|
| 27 |
+
clip=0.2, ent0=0.02, ent1=0.003, vf_coef=0.5, max_grad=1.0, target_kl=0.04,
|
| 28 |
+
reward_scale=1 / 25.0,
|
| 29 |
+
p_mixed=0.45, p_bot_opp=0.35, learner_seat_p=0.5,
|
| 30 |
+
snapshot_every=20, max_snapshots=10,
|
| 31 |
+
eval_every_min=25, ckpt_every_min=10, hf_every_min=20, hf_ckpt_every_min=60,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def sub(o, m):
|
| 36 |
+
return {k: v[m] for k, v in o.items()}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def cat_obs(lst):
|
| 40 |
+
return {k: torch.cat([o[k] for o in lst], 0) for k in lst[0]}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Trainer:
|
| 44 |
+
def __init__(self, cfg, device, out_dir, hf=None, log=print):
|
| 45 |
+
self.cfg = cfg
|
| 46 |
+
self.dev = device
|
| 47 |
+
self.out = out_dir
|
| 48 |
+
self.hf = hf
|
| 49 |
+
self.log = log
|
| 50 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 51 |
+
self.ev = HandEvaluator(device)
|
| 52 |
+
self.envs = [PokerEnv(g["B"], g["W"], g["probs"], device, self.ev, eq_samples=cfg["eq_samples"])
|
| 53 |
+
for g in cfg["groups"]]
|
| 54 |
+
self.actor = PokerNet(cfg["d"], cfg["layers"], cfg["heads"]).to(device)
|
| 55 |
+
self.critic = PokerNet(cfg["cd"], cfg["clayers"], cfg["cheads"], critic=True).to(device)
|
| 56 |
+
self.opt = torch.optim.AdamW(list(self.actor.parameters()) + list(self.critic.parameters()),
|
| 57 |
+
lr=cfg["lr"], weight_decay=1e-4, eps=1e-6)
|
| 58 |
+
self.actor_u, self.critic_u = self.actor, self.critic
|
| 59 |
+
if cfg.get("compile"):
|
| 60 |
+
self.actor_u = torch.compile(self.actor, dynamic=True)
|
| 61 |
+
self.critic_u = torch.compile(self.critic, dynamic=True)
|
| 62 |
+
self.snapshots = [] # list of (iter, state_dict)
|
| 63 |
+
self.snap_nets = []
|
| 64 |
+
self.it = 0
|
| 65 |
+
self.decisions = 0
|
| 66 |
+
self.hands = 0
|
| 67 |
+
self.elapsed_prev = 0.0
|
| 68 |
+
self.metrics_path = os.path.join(out_dir, "metrics.jsonl")
|
| 69 |
+
|
| 70 |
+
# ------------------------------------------------------------ persistence
|
| 71 |
+
def state(self):
|
| 72 |
+
return dict(cfg=self.cfg, actor=self.actor.state_dict(), critic=self.critic.state_dict(),
|
| 73 |
+
opt=self.opt.state_dict(), snapshots=self.snapshots, it=self.it,
|
| 74 |
+
decisions=self.decisions, hands=self.hands, elapsed=self.elapsed_prev + self.elapsed())
|
| 75 |
+
|
| 76 |
+
def load(self, path):
|
| 77 |
+
s = torch.load(path, map_location=self.dev, weights_only=False)
|
| 78 |
+
self.actor.load_state_dict(s["actor"])
|
| 79 |
+
self.critic.load_state_dict(s["critic"])
|
| 80 |
+
self.opt.load_state_dict(s["opt"])
|
| 81 |
+
self.snapshots = s["snapshots"]
|
| 82 |
+
self.it, self.decisions, self.hands = s["it"], s["decisions"], s["hands"]
|
| 83 |
+
self.elapsed_prev = s.get("elapsed", 0.0)
|
| 84 |
+
self._rebuild_snap_nets()
|
| 85 |
+
self.log(f"resumed from {path} at iter {self.it}")
|
| 86 |
+
|
| 87 |
+
def _rebuild_snap_nets(self):
|
| 88 |
+
self.snap_nets = []
|
| 89 |
+
for _, sd in self.snapshots:
|
| 90 |
+
net = PokerNet(self.cfg["d"], self.cfg["layers"], self.cfg["heads"]).to(self.dev)
|
| 91 |
+
net.load_state_dict(sd)
|
| 92 |
+
net.eval()
|
| 93 |
+
self.snap_nets.append(net)
|
| 94 |
+
|
| 95 |
+
def save_ckpt(self):
|
| 96 |
+
path = os.path.join(self.out, "ckpt.pt")
|
| 97 |
+
torch.save(self.state(), path + ".tmp")
|
| 98 |
+
os.replace(path + ".tmp", path)
|
| 99 |
+
torch.save(dict(cfg=dict(d=self.cfg["d"], layers=self.cfg["layers"], heads=self.cfg["heads"]),
|
| 100 |
+
actor=self.actor.state_dict(), it=self.it, decisions=self.decisions, hands=self.hands),
|
| 101 |
+
os.path.join(self.out, "model.pt"))
|
| 102 |
+
|
| 103 |
+
def elapsed(self):
|
| 104 |
+
return time.time() - self.t0
|
| 105 |
+
|
| 106 |
+
# ------------------------------------------------------------ league
|
| 107 |
+
def n_opp_types(self):
|
| 108 |
+
return len(BOT_KINDS) + len(self.snap_nets)
|
| 109 |
+
|
| 110 |
+
def assign(self, env, ctrl, mask):
|
| 111 |
+
B, W, dev = env.B, env.W, self.dev
|
| 112 |
+
c = self.cfg
|
| 113 |
+
mixed = torch.rand(B, device=dev) < (c["p_mixed"] if True else 0)
|
| 114 |
+
nb, ns = len(BOT_KINDS), len(self.snap_nets)
|
| 115 |
+
use_bot = (torch.rand(B, device=dev) < c["p_bot_opp"]) | (ns == 0)
|
| 116 |
+
bot_id = torch.randint(0, nb, (B,), device=dev) + 1
|
| 117 |
+
snap_id = (torch.randint(0, max(ns, 1), (B,), device=dev) + 1 + nb) if ns > 0 else bot_id
|
| 118 |
+
# bias towards recent snapshots
|
| 119 |
+
if ns > 0:
|
| 120 |
+
recent = torch.rand(B, device=dev) < 0.5
|
| 121 |
+
snap_id = torch.where(recent, torch.full_like(snap_id, nb + ns), snap_id)
|
| 122 |
+
opp = torch.where(use_bot, bot_id, snap_id)
|
| 123 |
+
learner = (torch.rand(B, W, device=dev) < c["learner_seat_p"]) | ~mixed[:, None]
|
| 124 |
+
forced = F.one_hot((torch.rand(B, device=dev) * env.n).long().clamp(max=env.n - 1), W).bool()
|
| 125 |
+
new = torch.where(learner | forced, torch.zeros_like(ctrl), opp[:, None].expand(-1, W))
|
| 126 |
+
return torch.where(mask[:, None], new, ctrl)
|
| 127 |
+
|
| 128 |
+
def opp_act(self, k, o):
|
| 129 |
+
nb = len(BOT_KINDS)
|
| 130 |
+
if k <= nb:
|
| 131 |
+
return bot_action(BOT_KINDS[k - 1], o)
|
| 132 |
+
net = self.snap_nets[k - nb - 1]
|
| 133 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.dev == "cuda"):
|
| 134 |
+
logits = net(o)
|
| 135 |
+
return torch.distributions.Categorical(logits=logits.float()).sample()
|
| 136 |
+
|
| 137 |
+
# ------------------------------------------------------------ rollout
|
| 138 |
+
@torch.no_grad()
|
| 139 |
+
def rollout(self, env):
|
| 140 |
+
dev, B = self.dev, env.B
|
| 141 |
+
env.reset()
|
| 142 |
+
ctrl = self.assign(env, torch.zeros(B, env.W, dtype=torch.long, device=dev),
|
| 143 |
+
torch.ones(B, dtype=torch.bool, device=dev))
|
| 144 |
+
steps = [] # per step: dict(game, seat, obs, act, logp, val)
|
| 145 |
+
ends = [] # per step: (finished mask, delta)
|
| 146 |
+
t = 0
|
| 147 |
+
T_min = self.cfg["T_min"]
|
| 148 |
+
hands = 0
|
| 149 |
+
while True:
|
| 150 |
+
active = ~env.done
|
| 151 |
+
if not active.any():
|
| 152 |
+
break
|
| 153 |
+
idx = active.nonzero().squeeze(1)
|
| 154 |
+
o = env.obs(privileged=True, idx=idx)
|
| 155 |
+
p = env.cur[idx]
|
| 156 |
+
c = ctrl[idx, p]
|
| 157 |
+
act = torch.ones(idx.shape[0], dtype=torch.long, device=dev)
|
| 158 |
+
lm = c == 0
|
| 159 |
+
rec = None
|
| 160 |
+
if lm.any():
|
| 161 |
+
ol = sub(o, lm)
|
| 162 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
|
| 163 |
+
logits = self.actor(ol)
|
| 164 |
+
val = self.critic(ol).float()
|
| 165 |
+
dist = torch.distributions.Categorical(logits=logits.float())
|
| 166 |
+
a = dist.sample()
|
| 167 |
+
act[lm] = a
|
| 168 |
+
rec = dict(game=idx[lm], seat=p[lm], obs=ol, act=a, logp=dist.log_prob(a), val=val)
|
| 169 |
+
for k in torch.unique(c[~lm]).tolist() if (~lm).any() else []:
|
| 170 |
+
m = c == k
|
| 171 |
+
po = {kk: v for kk, v in sub(o, m).items() if kk not in ("all_hole", "full_board")}
|
| 172 |
+
act[m] = self.opp_act(k, po)
|
| 173 |
+
full = torch.ones(B, dtype=torch.long, device=dev)
|
| 174 |
+
full[idx] = act
|
| 175 |
+
fin, delta = env.step(full, mask=active)
|
| 176 |
+
steps.append(rec)
|
| 177 |
+
ends.append((fin, delta))
|
| 178 |
+
hands += int(fin.sum())
|
| 179 |
+
if t < T_min:
|
| 180 |
+
rm = env.done.clone()
|
| 181 |
+
if rm.any():
|
| 182 |
+
env.reset(rm)
|
| 183 |
+
ctrl = self.assign(env, ctrl, rm)
|
| 184 |
+
t += 1
|
| 185 |
+
# returns: walk backwards
|
| 186 |
+
pending = torch.zeros(B, env.W, device=dev)
|
| 187 |
+
rets = [None] * len(steps)
|
| 188 |
+
for i in range(len(steps) - 1, -1, -1):
|
| 189 |
+
fin, delta = ends[i]
|
| 190 |
+
pending = torch.where(fin[:, None], delta, pending)
|
| 191 |
+
r = steps[i]
|
| 192 |
+
if r is not None:
|
| 193 |
+
rets[i] = pending[r["game"], r["seat"]]
|
| 194 |
+
recs = [(s, r) for s, r in zip(steps, rets) if s is not None]
|
| 195 |
+
data = dict(obs=cat_obs([s["obs"] for s, _ in recs]),
|
| 196 |
+
act=torch.cat([s["act"] for s, _ in recs]),
|
| 197 |
+
logp=torch.cat([s["logp"] for s, _ in recs]),
|
| 198 |
+
val=torch.cat([s["val"] for s, _ in recs]),
|
| 199 |
+
ret=torch.cat([r for _, r in recs]))
|
| 200 |
+
return data, hands, t
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------ PPO
|
| 203 |
+
def update(self, datas, frac):
|
| 204 |
+
c = self.cfg
|
| 205 |
+
lr = c["lr_min"] + (c["lr"] - c["lr_min"]) * 0.5 * (1 + math.cos(math.pi * min(frac, 1.0)))
|
| 206 |
+
ent_coef = c["ent1"] + (c["ent0"] - c["ent1"]) * max(0.0, 1 - frac)
|
| 207 |
+
for gpar in self.opt.param_groups:
|
| 208 |
+
gpar["lr"] = lr
|
| 209 |
+
prepared = []
|
| 210 |
+
for d in datas:
|
| 211 |
+
ret = d["ret"] * c["reward_scale"]
|
| 212 |
+
adv = ret - d["val"]
|
| 213 |
+
prepared.append((d, ret, adv))
|
| 214 |
+
allv = torch.cat([a for _, _, a in prepared])
|
| 215 |
+
mu, sd = allv.mean(), allv.std() + 1e-8
|
| 216 |
+
stats = dict(pg=0.0, vf=0.0, ent=0.0, kl=0.0, clipfrac=0.0, n=0)
|
| 217 |
+
stop = False
|
| 218 |
+
for ep in range(c["epochs"]):
|
| 219 |
+
batches = []
|
| 220 |
+
for gi, (d, ret, adv) in enumerate(prepared):
|
| 221 |
+
N = ret.shape[0]
|
| 222 |
+
perm = torch.randperm(N, device=self.dev)
|
| 223 |
+
for i in range(0, N, c["minibatch"]):
|
| 224 |
+
batches.append((gi, perm[i:i + c["minibatch"]]))
|
| 225 |
+
random.shuffle(batches)
|
| 226 |
+
kls = []
|
| 227 |
+
for gi, mb in batches:
|
| 228 |
+
d, ret, adv = prepared[gi]
|
| 229 |
+
o = sub(d["obs"], mb)
|
| 230 |
+
a = d["act"][mb]
|
| 231 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.dev == "cuda"):
|
| 232 |
+
logits = self.actor_u(o)
|
| 233 |
+
v = self.critic_u(o).float()
|
| 234 |
+
logits = logits.float()
|
| 235 |
+
logp_all = torch.log_softmax(logits, -1)
|
| 236 |
+
logp = logp_all.gather(1, a[:, None]).squeeze(1)
|
| 237 |
+
p_all = logp_all.exp()
|
| 238 |
+
ent = -(p_all * logp_all.masked_fill(~o["legal"], 0)).sum(1).mean()
|
| 239 |
+
ratio = torch.exp(logp - d["logp"][mb])
|
| 240 |
+
A = (adv[mb] - mu) / sd
|
| 241 |
+
pg = -torch.min(ratio * A, ratio.clamp(1 - c["clip"], 1 + c["clip"]) * A).mean()
|
| 242 |
+
vf = F.mse_loss(v, ret[mb])
|
| 243 |
+
loss = pg + c["vf_coef"] * vf - ent_coef * ent
|
| 244 |
+
self.opt.zero_grad(set_to_none=True)
|
| 245 |
+
loss.backward()
|
| 246 |
+
torch.nn.utils.clip_grad_norm_(list(self.actor.parameters()) + list(self.critic.parameters()),
|
| 247 |
+
c["max_grad"])
|
| 248 |
+
self.opt.step()
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
kl = ((ratio - 1) - torch.log(ratio)).mean().item()
|
| 251 |
+
kls.append(kl)
|
| 252 |
+
stats["pg"] += pg.item()
|
| 253 |
+
stats["vf"] += vf.item()
|
| 254 |
+
stats["ent"] += ent.item()
|
| 255 |
+
stats["kl"] += kl
|
| 256 |
+
stats["clipfrac"] += ((ratio - 1).abs() > c["clip"]).float().mean().item()
|
| 257 |
+
stats["n"] += 1
|
| 258 |
+
if sum(kls) / len(kls) > c["target_kl"]:
|
| 259 |
+
stop = True
|
| 260 |
+
break
|
| 261 |
+
n = max(stats.pop("n"), 1)
|
| 262 |
+
stats = {k: v / n for k, v in stats.items()}
|
| 263 |
+
stats.update(lr=lr, ent_coef=ent_coef, epochs_done=ep + 1, kl_stop=stop)
|
| 264 |
+
return stats
|
| 265 |
+
|
| 266 |
+
# ------------------------------------------------------------ evaluation
|
| 267 |
+
@torch.no_grad()
|
| 268 |
+
def evaluate(self, opp, n, min_hands=20000, B=4096):
|
| 269 |
+
"""Hero (current actor) in one seat vs n-1 copies of `opp` (bot name or net), 100bb stacks."""
|
| 270 |
+
dev = self.dev
|
| 271 |
+
env = PokerEnv(B, max(n, 2), [0] * (n - 2) + [1], dev, self.ev, eq_samples=self.cfg["eq_samples"],
|
| 272 |
+
fixed_stack=100.0, ante_prob=0.0)
|
| 273 |
+
env.reset(n_override=n)
|
| 274 |
+
hero = (torch.rand(B, device=dev) * n).long()
|
| 275 |
+
tot, tot2, hands = 0.0, 0.0, 0
|
| 276 |
+
steps = 0
|
| 277 |
+
while hands < min_hands and steps < 4000:
|
| 278 |
+
o = env.obs()
|
| 279 |
+
p = env.cur
|
| 280 |
+
hm = p == hero
|
| 281 |
+
act = torch.ones(B, dtype=torch.long, device=dev)
|
| 282 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
|
| 283 |
+
if hm.any():
|
| 284 |
+
act[hm] = torch.distributions.Categorical(logits=self.actor(sub(o, hm)).float()).sample()
|
| 285 |
+
if (~hm).any():
|
| 286 |
+
oo = sub(o, ~hm)
|
| 287 |
+
if isinstance(opp, str):
|
| 288 |
+
act[~hm] = bot_action(opp, oo)
|
| 289 |
+
else:
|
| 290 |
+
act[~hm] = torch.distributions.Categorical(logits=opp(oo).float()).sample()
|
| 291 |
+
fin, delta = env.step(act)
|
| 292 |
+
if fin.any():
|
| 293 |
+
r = delta[fin].gather(1, hero[fin][:, None]).squeeze(1)
|
| 294 |
+
tot += r.sum().item()
|
| 295 |
+
tot2 += (r ** 2).sum().item()
|
| 296 |
+
hands += int(fin.sum())
|
| 297 |
+
env.reset(fin)
|
| 298 |
+
hero = torch.where(fin, (torch.rand(B, device=dev) * env.n).long(), hero)
|
| 299 |
+
steps += 1
|
| 300 |
+
mean = tot / max(hands, 1)
|
| 301 |
+
var = tot2 / max(hands, 1) - mean ** 2
|
| 302 |
+
return dict(bb100=100 * mean, se100=100 * math.sqrt(max(var, 0) / max(hands, 1)), hands=hands)
|
| 303 |
+
|
| 304 |
+
def eval_suite(self):
|
| 305 |
+
res = {}
|
| 306 |
+
t = time.time()
|
| 307 |
+
self.actor.eval()
|
| 308 |
+
for n in (2, 6, 9, 15):
|
| 309 |
+
for bot in ("call", "tag", "maniac", "rock", "random"):
|
| 310 |
+
if n == 15 and bot in ("random", "rock"):
|
| 311 |
+
continue
|
| 312 |
+
r = self.evaluate(bot, n, min_hands=int(self.cfg.get('eval_scale',1.0)*(12000 if n <= 6 else 8000)))
|
| 313 |
+
res[f"n{n}_{bot}"] = round(r["bb100"], 1)
|
| 314 |
+
res[f"n{n}_{bot}_se"] = round(r["se100"], 1)
|
| 315 |
+
if self.snap_nets:
|
| 316 |
+
old = self.snap_nets[0]
|
| 317 |
+
for n in (2, 6):
|
| 318 |
+
r = self.evaluate(old, n, min_hands=int(self.cfg.get('eval_scale',1.0)*20000))
|
| 319 |
+
res[f"n{n}_vs_snap{self.snapshots[0][0]}"] = round(r["bb100"], 1)
|
| 320 |
+
res[f"n{n}_vs_snap{self.snapshots[0][0]}_se"] = round(r["se100"], 1)
|
| 321 |
+
self.actor.train()
|
| 322 |
+
res["eval_sec"] = round(time.time() - t, 1)
|
| 323 |
+
return res
|
| 324 |
+
|
| 325 |
+
# ------------------------------------------------------------ main loop
|
| 326 |
+
def write_metrics(self, m):
|
| 327 |
+
with open(self.metrics_path, "a") as f:
|
| 328 |
+
f.write(json.dumps(m) + "\n")
|
| 329 |
+
|
| 330 |
+
def train(self, hours, stop_file=None):
|
| 331 |
+
c = self.cfg
|
| 332 |
+
self.t0 = time.time()
|
| 333 |
+
budget = hours * 3600
|
| 334 |
+
last = dict(eval=time.time(), ckpt=time.time(), hf=0.0, hfck=time.time())
|
| 335 |
+
if self.it == 0:
|
| 336 |
+
m = dict(it=0, kind="eval", **self.eval_suite())
|
| 337 |
+
self.log(json.dumps(m))
|
| 338 |
+
self.write_metrics(m)
|
| 339 |
+
while self.elapsed_prev + self.elapsed() < budget:
|
| 340 |
+
if stop_file and os.path.exists(stop_file):
|
| 341 |
+
self.log("stop file found")
|
| 342 |
+
break
|
| 343 |
+
ti = time.time()
|
| 344 |
+
datas, hands, steps = [], 0, []
|
| 345 |
+
for env in self.envs:
|
| 346 |
+
d, h, t = self.rollout(env)
|
| 347 |
+
datas.append(d)
|
| 348 |
+
hands += h
|
| 349 |
+
steps.append(t)
|
| 350 |
+
tr = time.time() - ti
|
| 351 |
+
st = self.update(datas, (self.elapsed_prev + self.elapsed()) / budget)
|
| 352 |
+
n_dec = sum(d["act"].shape[0] for d in datas)
|
| 353 |
+
self.decisions += n_dec
|
| 354 |
+
self.hands += hands
|
| 355 |
+
self.it += 1
|
| 356 |
+
acts = torch.cat([d["act"] for d in datas])
|
| 357 |
+
hist = torch.bincount(acts, minlength=N_ACTIONS).float() / acts.shape[0]
|
| 358 |
+
m = dict(it=self.it, kind="train", t=round((self.elapsed_prev + self.elapsed()) / 60, 1), dec=n_dec, hands=hands,
|
| 359 |
+
tot_hands=self.hands, steps=steps, t_roll=round(tr, 1), t_upd=round(time.time() - ti - tr, 1),
|
| 360 |
+
fold=round(hist[0].item(), 3), call=round(hist[1].item(), 3),
|
| 361 |
+
raise_=round(hist[2:9].sum().item(), 3), allin=round(hist[9].item(), 3),
|
| 362 |
+
**{k: (round(v, 5) if isinstance(v, float) else v) for k, v in st.items()})
|
| 363 |
+
self.log(json.dumps(m))
|
| 364 |
+
self.write_metrics(m)
|
| 365 |
+
if self.it % c["snapshot_every"] == 0:
|
| 366 |
+
self.snapshots.append((self.it, copy.deepcopy({k: v.detach().clone() for k, v in self.actor.state_dict().items()})))
|
| 367 |
+
if len(self.snapshots) > c["max_snapshots"]:
|
| 368 |
+
# keep the oldest (anchor) and drop a random middle one
|
| 369 |
+
self.snapshots.pop(random.randint(1, len(self.snapshots) - 2))
|
| 370 |
+
self._rebuild_snap_nets()
|
| 371 |
+
now = time.time()
|
| 372 |
+
if now - last["eval"] > c["eval_every_min"] * 60:
|
| 373 |
+
m = dict(it=self.it, kind="eval", t=round(self.elapsed() / 60, 1), **self.eval_suite())
|
| 374 |
+
self.log(json.dumps(m))
|
| 375 |
+
self.write_metrics(m)
|
| 376 |
+
last["eval"] = now
|
| 377 |
+
if now - last["ckpt"] > c["ckpt_every_min"] * 60:
|
| 378 |
+
self.save_ckpt()
|
| 379 |
+
last["ckpt"] = now
|
| 380 |
+
if self.hf and now - last["hf"] > c["hf_every_min"] * 60:
|
| 381 |
+
self.save_ckpt()
|
| 382 |
+
big = now - last["hfck"] > c["hf_ckpt_every_min"] * 60
|
| 383 |
+
self.hf(self.out, self.it, big)
|
| 384 |
+
last["hf"] = now
|
| 385 |
+
if big:
|
| 386 |
+
last["hfck"] = now
|
| 387 |
+
m = dict(it=self.it, kind="eval", final=True, **self.eval_suite())
|
| 388 |
+
self.log(json.dumps(m))
|
| 389 |
+
self.write_metrics(m)
|
| 390 |
+
self.save_ckpt()
|
| 391 |
+
if self.hf:
|
| 392 |
+
self.hf(self.out, self.it, True)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
from poker_core import bot_action # noqa: E402
|