Final README with results, play.py fixes
Browse files- README.md +82 -2
- modal_app.py +87 -0
- play.py +13 -3
README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
tags:
|
| 4 |
+
- poker
|
| 5 |
+
- reinforcement-learning
|
| 6 |
+
- self-play
|
| 7 |
+
- texas-holdem
|
| 8 |
+
---
|
| 9 |
|
| 10 |
+
# Poker AI — No-Limit Texas Hold'em para 2 a 23 jogadores
|
| 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 |
+
## Treino realizado
|
| 60 |
+
|
| 61 |
+
- 261 iterações PPO, **75,5 milhões de mãos** de self-play (≈600 milhões de decisões), 4,1 h numa NVIDIA B200.
|
| 62 |
+
- Estratégia final: ~40% fold, ~40% check/call, ~18% raises, ~2% all-in.
|
| 63 |
+
|
| 64 |
+
## Resultados finais (bb/100 da IA em 1 assento contra o resto da mesa, stacks 100bb, ± erro padrão)
|
| 65 |
+
|
| 66 |
+
| oponentes | heads-up | 6 jogadores | 9 jogadores | 15 jogadores |
|
| 67 |
+
|---|---|---|---|---|
|
| 68 |
+
| TAG (tight-aggressive por equidade) | +188 ± 18 | +112 ± 18 | +126 ± 19 | +87 ± 15 |
|
| 69 |
+
| Rock (super tight) | +117 ± 13 | +45 ± 12 | +40 ± 12 | — |
|
| 70 |
+
| Maniac (agressivo) | +476 ± 30 | +630 ± 81 | +859 ± 139 | +1100 ± 201 |
|
| 71 |
+
| Calling station | +1072 ± 32 | +4793 ± 149 | +5153 ± 243 | +6114 ± 345 |
|
| 72 |
+
| Aleatório | +340 ± 27 | +772 ± 64 | +776 ± 100 | — |
|
| 73 |
+
| Versão antiga dela mesma (iter. 20) | +187 ± 17 | +210 ± 28 | — | — |
|
| 74 |
+
|
| 75 |
+
No início do treino a IA perdia entre −900 e −1500 bb/100 para o bot TAG. Para comparação, um jogador profissional de cash game costuma ganhar entre +5 e +10 bb/100.
|
| 76 |
+
|
| 77 |
+
## Limitações (honestas)
|
| 78 |
+
|
| 79 |
+
**Não há garantia de que seja melhor que qualquer humano**: o orçamento total foi ~US$30 de GPU (≈4h de B200).
|
| 80 |
+
Bots sobre-humanos como Libratus e Pluribus usaram busca em tempo real e muito mais computação. Veja as avaliações em `metrics.jsonl`
|
| 81 |
+
(bb/100 contra cada bot, em mesas de 2, 6, 9 e 15 jogadores) para o nível real.
|
| 82 |
+
|
| 83 |
+
Uso educacional/pesquisa. Usar bots em sites de poker com dinheiro real normalmente viola os termos de uso desses sites.
|
modal_app.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
import modal
|
| 5 |
+
|
| 6 |
+
app = modal.App("poker-ai")
|
| 7 |
+
vol = modal.Volume.from_name("poker-vol", create_if_missing=True)
|
| 8 |
+
image = (
|
| 9 |
+
modal.Image.debian_slim(python_version="3.12")
|
| 10 |
+
.pip_install("torch==2.9.1", "numpy", "huggingface_hub>=0.34")
|
| 11 |
+
.add_local_python_source("poker_core", "model", "train")
|
| 12 |
+
.add_local_file("play.py", "/root/play.py")
|
| 13 |
+
.add_local_file("README.md", "/root/README.md")
|
| 14 |
+
)
|
| 15 |
+
REPO = "Alisson990/poker"
|
| 16 |
+
GPU = os.environ.get("POKER_GPU", "B200")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def hf_push(out_dir, it, big):
|
| 20 |
+
from huggingface_hub import CommitOperationAdd, HfApi
|
| 21 |
+
api = HfApi(token=os.environ["HF_TOKEN"])
|
| 22 |
+
ops = [CommitOperationAdd("model.pt", os.path.join(out_dir, "model.pt")),
|
| 23 |
+
CommitOperationAdd("metrics.jsonl", os.path.join(out_dir, "metrics.jsonl"))]
|
| 24 |
+
for f in ("poker_core.py", "model.py", "train.py"):
|
| 25 |
+
ops.append(CommitOperationAdd(f, f"/root/{f}"))
|
| 26 |
+
ops.append(CommitOperationAdd("play.py", "/root/play.py"))
|
| 27 |
+
if big:
|
| 28 |
+
ops.append(CommitOperationAdd(f"checkpoints/model_it{it:05d}.pt", os.path.join(out_dir, "model.pt")))
|
| 29 |
+
ops.append(CommitOperationAdd("training_state/ckpt.pt", os.path.join(out_dir, "ckpt.pt")))
|
| 30 |
+
for attempt in range(3):
|
| 31 |
+
try:
|
| 32 |
+
api.create_commit(REPO, ops, commit_message=f"iter {it}" + (" (checkpoint)" if big else ""))
|
| 33 |
+
print(f"[hf] pushed iter {it} big={big}", flush=True)
|
| 34 |
+
return
|
| 35 |
+
except Exception as e: # never crash training because of HF
|
| 36 |
+
print(f"[hf] push failed ({attempt}): {e}", flush=True)
|
| 37 |
+
time.sleep(10)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@app.function(image=image, gpu=GPU, timeout=24 * 3600, volumes={"/vol": vol}, secrets=[modal.Secret.from_name("hf-poker")],
|
| 41 |
+
cpu=4.0, memory=32768, retries=modal.Retries(max_retries=2, initial_delay=5.0))
|
| 42 |
+
def train_remote(hours: float, run: str = "main", overrides: dict = None, bench_iters: int = 0, push: bool = True):
|
| 43 |
+
import copy
|
| 44 |
+
import torch
|
| 45 |
+
from train import DEFAULT, Trainer
|
| 46 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 47 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 48 |
+
print(torch.cuda.get_device_name(0), flush=True)
|
| 49 |
+
cfg = copy.deepcopy(DEFAULT)
|
| 50 |
+
for k, v in (overrides or {}).items():
|
| 51 |
+
cfg[k] = v
|
| 52 |
+
out = f"/vol/{run}"
|
| 53 |
+
tr = Trainer(cfg, "cuda", out, hf=(hf_push if push else None), log=lambda s: print(s, flush=True))
|
| 54 |
+
orig = tr.save_ckpt
|
| 55 |
+
|
| 56 |
+
def save_and_commit():
|
| 57 |
+
orig()
|
| 58 |
+
vol.commit()
|
| 59 |
+
tr.save_ckpt = save_and_commit
|
| 60 |
+
if os.path.exists(os.path.join(out, "ckpt.pt")):
|
| 61 |
+
tr.load(os.path.join(out, "ckpt.pt"))
|
| 62 |
+
if bench_iters:
|
| 63 |
+
tr.t0 = time.time()
|
| 64 |
+
for i in range(bench_iters):
|
| 65 |
+
t = time.time()
|
| 66 |
+
datas = []
|
| 67 |
+
for env in tr.envs:
|
| 68 |
+
t1 = time.time()
|
| 69 |
+
d, h, s = tr.rollout(env)
|
| 70 |
+
torch.cuda.synchronize()
|
| 71 |
+
print(f" rollout W={env.W} B={env.B} dec={d['act'].shape[0]} hands={h} steps={s} {time.time()-t1:.2f}s", flush=True)
|
| 72 |
+
datas.append(d)
|
| 73 |
+
t2 = time.time()
|
| 74 |
+
st = tr.update(datas, 0.0)
|
| 75 |
+
torch.cuda.synchronize()
|
| 76 |
+
print(f"iter {i}: total {time.time()-t:.2f}s update {time.time()-t2:.2f}s mem {torch.cuda.max_memory_allocated()/1e9:.1f}GB {st}", flush=True)
|
| 77 |
+
t = time.time()
|
| 78 |
+
r = tr.evaluate("tag", 6, min_hands=12000)
|
| 79 |
+
print("eval tag6", r, f"{time.time()-t:.1f}s", flush=True)
|
| 80 |
+
return
|
| 81 |
+
tr.train(hours, stop_file=os.path.join(out, "STOP"))
|
| 82 |
+
vol.commit()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@app.local_entrypoint()
|
| 86 |
+
def main(hours: float = 0.1, run: str = "main", bench: int = 0, push: bool = True, mb: int = 32768, compile: bool = False):
|
| 87 |
+
train_remote.remote(hours, run, dict(minibatch=mb, compile=compile), bench, push)
|
play.py
CHANGED
|
@@ -94,16 +94,26 @@ class Advisor:
|
|
| 94 |
used = set(cards)
|
| 95 |
rest = [c for c in range(52) if c not in used]
|
| 96 |
random.shuffle(rest)
|
| 97 |
-
|
| 98 |
-
hole_t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
env.hole[0] = hole_t
|
| 100 |
-
env.board[0] = torch.tensor(rest[
|
| 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 |
|
|
|
|
| 94 |
used = set(cards)
|
| 95 |
rest = [c for c in range(52) if c not in used]
|
| 96 |
random.shuffle(rest)
|
| 97 |
+
# opponents' (unknown) cards are irrelevant for the decision; fill them with dummy cards
|
| 98 |
+
hole_t = torch.zeros(env.W, 2, dtype=torch.long)
|
| 99 |
+
k = 0
|
| 100 |
+
for s in range(env.W):
|
| 101 |
+
if s == hero:
|
| 102 |
+
hole_t[s] = torch.tensor(sorted(cards, reverse=True))
|
| 103 |
+
else:
|
| 104 |
+
hole_t[s] = torch.tensor(rest[k:k + 2])
|
| 105 |
+
k += 2
|
| 106 |
env.hole[0] = hole_t
|
| 107 |
+
env.board[0] = torch.tensor(rest[k:k + 5])
|
| 108 |
self.env, self.hero, self.n = env, hero, n
|
| 109 |
self._used = used
|
| 110 |
|
| 111 |
def board(self, cards):
|
| 112 |
"""Set the visible board (3, 4 or 5 cards)."""
|
| 113 |
cs = [parse_card(c) for c in cards.split()]
|
| 114 |
+
hero_cards = set(self.env.hole[0, self.hero].tolist())
|
| 115 |
+
if len(set(cs)) != len(cs) or hero_cards & set(cs) or len(cs) > 5:
|
| 116 |
+
raise ValueError("duplicate card (board repeats itself or your hole cards)")
|
| 117 |
self.env.board[0, :len(cs)] = torch.tensor(cs)
|
| 118 |
self._used |= set(cs)
|
| 119 |
|