File size: 11,095 Bytes
0c9afc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae5a2ac
 
 
 
 
 
 
 
 
0c9afc2
ae5a2ac
0c9afc2
 
 
 
 
 
ae5a2ac
 
 
0c9afc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
Use the trained poker AI.

  python play.py play --players 6 --stack 100        # you vs 5 AI players in the terminal
  python play.py advisor                              # AI suggests moves for a real table (any 2..23 players)

Python API:
  from play import PokerAI, Advisor
  adv = Advisor(PokerAI.load())                      # downloads model.pt from huggingface (Alisson990/poker)
  adv.new_hand(n=6, button=0, stacks=[100]*6, hero=3, hole="As Kd")
  adv.act(4, "call") ; adv.act(5, "raise", 3.5) ...  # amounts = total bet this street ("raise to"), in big blinds
  adv.board("Ah 7c 2d")
  print(adv.suggest())
"""
import argparse
import os
import random

import torch

from model import PokerNet
from poker_core import ACTION_NAMES, N_ACTIONS, NREV, HandEvaluator, PokerEnv

RANKS, SUITS = "23456789TJQKA", "cdhs"
SUIT_SYM = {"c": "♣", "d": "♦", "h": "♥", "s": "♠"}


def parse_card(s):
    s = s.strip()
    return RANKS.index(s[0].upper()) * 4 + SUITS.index(s[1].lower())


def card_str(c):
    return RANKS[c // 4] + SUITS[c % 4]


class PokerAI:
    def __init__(self, net, device="cpu"):
        self.net = net.eval()
        self.dev = device

    @staticmethod
    def load(path=None, device="cpu", repo="Alisson990/poker"):
        if path is None:
            from huggingface_hub import hf_hub_download
            path = hf_hub_download(repo, "model.pt")
        s = torch.load(path, map_location=device, weights_only=False)
        net = PokerNet(**s["cfg"]).to(device)
        net.load_state_dict(s["actor"])
        return PokerAI(net, device)

    @torch.no_grad()
    def probs(self, obs):
        return torch.softmax(self.net(obs).float(), -1)


class Advisor:
    """Tracks a real hand (any number of players 2..23) and asks the AI what to do."""

    def __init__(self, ai, eq_samples=256):
        self.ai = ai
        self.ev = HandEvaluator(ai.dev)
        self.K = eq_samples
        self.env = None

    def new_hand(self, n, button, stacks, hero, hole, sb=0.5, bb=1.0, ante=0.0):
        """stacks/blinds in any unit: everything is converted to big blinds internally."""
        self.unit = bb
        env = PokerEnv(1, max(n, 2), [0] * (n - 2) + [1], self.ai.dev, self.ev, eq_samples=self.K, ante_prob=0.0)
        st = torch.zeros(1, env.W)
        st[0, :n] = torch.tensor([float(s) / bb for s in stacks])
        env.reset(n_override=n, stacks_override=st)
        # rebuild blinds with the requested button / sizes
        env.button[0] = button
        env.stack[0, :n] = st[0, :n]
        env.bet.zero_(); env.contrib.zero_(); env.st_contrib.zero_()
        env.ante[0] = ante / bb
        if ante > 0:
            a = torch.minimum(torch.full((n,), ante / bb), env.stack[0, :n])
            env.stack[0, :n] -= a
            env.contrib[0, :n] += a
        sbs = button if n == 2 else (button + 1) % n
        bbs = (sbs + 1) % n
        for seat, amt in ((sbs, sb / bb), (bbs, 1.0)):
            a = min(amt, env.stack[0, seat].item())
            env.stack[0, seat] -= a
            env.bet[0, seat] += a
            env.contrib[0, seat] += a
            env.st_contrib[0, seat, 0] += a
        env.max_bet[0] = max(env.bet[0].max().item(), 1.0)
        env.allin[0] = env.present[0] & (env.stack[0] <= 1e-9)
        env.cur[0] = env._next_need(torch.tensor([bbs]), env._need())[0][0]
        cards = [parse_card(c) for c in hole.split()]
        used = set(cards)
        rest = [c for c in range(52) if c not in used]
        random.shuffle(rest)
        # opponents' (unknown) cards are irrelevant for the decision; fill them with dummy cards
        hole_t = torch.zeros(env.W, 2, dtype=torch.long)
        k = 0
        for s in range(env.W):
            if s == hero:
                hole_t[s] = torch.tensor(sorted(cards, reverse=True))
            else:
                hole_t[s] = torch.tensor(rest[k:k + 2])
                k += 2
        env.hole[0] = hole_t
        env.board[0] = torch.tensor(rest[k:k + 5])
        self.env, self.hero, self.n = env, hero, n
        self._used = used

    def board(self, cards):
        """Set the visible board (3, 4 or 5 cards)."""
        cs = [parse_card(c) for c in cards.split()]
        hero_cards = set(self.env.hole[0, self.hero].tolist())
        if len(set(cs)) != len(cs) or hero_cards & set(cs) or len(cs) > 5:
            raise ValueError("duplicate card (board repeats itself or your hole cards)")
        self.env.board[0, :len(cs)] = torch.tensor(cs)
        self._used |= set(cs)

    def to_act(self):
        return int(self.env.cur[0])

    def act(self, seat, kind, amount=None):
        """kind in fold/check/call/bet/raise/allin. amount = total bet on this street ("raise to"), same unit as stacks."""
        env = self.env
        if env.done[0]:
            raise RuntimeError("hand is over")
        if seat != self.to_act():
            raise ValueError(f"seat {self.to_act()} is to act, not {seat}")
        kind = kind.lower()
        custom = None
        if kind == "fold":
            a = 0 if env.legal()[0, 0] else 1
        elif kind in ("check", "call"):
            a = 1
        elif kind in ("allin", "all-in", "shove"):
            a = 9
        else:
            a = N_ACTIONS
            custom = torch.tensor([float(amount) / self.unit])
        fin, delta = env.step(torch.tensor([a]), custom_to=custom)
        return bool(fin[0])

    def suggest(self):
        env = self.env
        if self.to_act() != self.hero:
            raise ValueError(f"it is seat {self.to_act()}'s turn, not the hero's")
        o = env.obs()
        pr = self.ai.probs(o)[0]
        rt = env._raise_targets(env.cur)[0]
        bet_p = env.bet[0, self.hero].item()
        to_call = max(env.max_bet[0].item() - bet_p, 0.0)
        opts = []
        for i in pr.argsort(descending=True).tolist():
            if pr[i] < 0.01:
                continue
            if i == 0:
                desc = "fold"
            elif i == 1:
                desc = "check" if to_call <= 1e-9 else f"call {min(to_call, env.stack[0, self.hero].item()) * self.unit:g}"
            elif i == 9:
                desc = f"all-in ({(env.stack[0, self.hero].item() + bet_p) * self.unit:g})"
            else:
                desc = f"{'bet' if env.max_bet[0] <= 1e-9 else 'raise to'} {rt[i].item() * self.unit:.2f} ({ACTION_NAMES[i]})"
            opts.append((round(pr[i].item(), 3), desc, i))
        eq = o["glob"][0, 4 + 18].item()
        return dict(best=opts[0][1], options=opts, equity_vs_random=round(eq, 3))


# ------------------------------------------------------------------ terminal game

def show_table(env, hero, reveal=False):
    n = int(env.n[0])
    st = int(env.street[0])
    board = [card_str(c) for c in env.board[0, :NREV[st]].tolist()]
    print(f"\n  Board: {' '.join(board) or '--'}   Pot: {env.contrib[0].sum().item():.1f} bb")
    for s in range(n):
        tag = "YOU " if s == hero else f"AI{s:<2}"
        btn = "(D)" if s == int(env.button[0]) else "   "
        cards = " ".join(card_str(c) for c in env.hole[0, s].tolist()) if (s == hero or reveal) else "?? ??"
        state = "folded" if env.folded[0, s] else ("ALL-IN" if env.allin[0, s] else "")
        cur = "<-" if s == int(env.cur[0]) and not env.done[0] else ""
        print(f"  {btn} {tag} [{cards}] stack {env.stack[0, s].item():7.1f}  bet {env.bet[0, s].item():6.1f} {state} {cur}")


def play_cli(players, stack, model_path):
    ai = PokerAI.load(model_path)
    ev = HandEvaluator("cpu")
    hero = 0
    env = PokerEnv(1, players, [0] * (players - 2) + [1], "cpu", ev, eq_samples=64, ante_prob=0.0)
    stacks = torch.full((1, players), float(stack))
    total = 0.0
    hand = 0
    while True:
        hand += 1
        env.reset(n_override=players, stacks_override=stacks.clone())
        print(f"\n===== Hand {hand} =====  (your result so far: {total:+.1f} bb)")
        while not env.done[0]:
            p = int(env.cur[0])
            if p == hero:
                show_table(env, hero)
                L = env.legal()[0]
                to_call = (env.max_bet[0] - env.bet[0, hero]).item()
                print(f"  To call: {to_call:.1f}.  Options: f=fold, c=check/call, r <amount>=raise to, a=all-in, q=quit")
                cmd = input("  > ").strip().lower().split()
                if not cmd:
                    continue
                if cmd[0] == "q":
                    return
                custom = None
                if cmd[0] == "f":
                    a = 0 if L[0] else 1
                elif cmd[0] == "c":
                    a = 1
                elif cmd[0] == "a":
                    a = 9 if L[9] else 1
                elif cmd[0] == "r" and len(cmd) > 1 and L[9]:
                    a, custom = N_ACTIONS, torch.tensor([float(cmd[1])])
                else:
                    print("  invalid")
                    continue
                fin, delta = env.step(torch.tensor([a]), custom_to=custom)
            else:
                o = env.obs()
                a = torch.distributions.Categorical(probs=ai.probs(o)).sample()
                print(f"  AI{p} -> {ACTION_NAMES[a.item()]}")
                fin, delta = env.step(a)
        show_table(env, hero, reveal=True)
        d = delta[0, hero].item()
        total += d
        print(f"  Hand result: {d:+.1f} bb")


def advisor_cli(model_path):
    adv = Advisor(PokerAI.load(model_path))
    print("Poker AI advisor. Amounts in big blinds (or any unit if you pass --bb).")
    n = int(input("players at table: "))
    while True:
        button = int(input(f"button seat (0..{n-1}): "))
        hero = int(input("your seat: "))
        stacks = [float(x) for x in input(f"{n} stacks separated by space: ").split()]
        hole = input("your cards (e.g. As Kd): ")
        adv.new_hand(n, button, stacks, hero, hole)
        while not adv.env.done[0]:
            p = adv.to_act()
            st = int(adv.env.street[0])
            if p == hero:
                s = adv.suggest()
                print(f"  >>> AI suggests: {s['best']}   (all: {s['options']}, equity vs random {s['equity_vs_random']})")
            line = input(f"  seat {p} action (fold/check/call/raise X/allin) or 'board <cards>': ").split()
            if not line:
                continue
            if line[0] == "board":
                adv.board(" ".join(line[1:]))
                continue
            adv.act(p, line[0], float(line[1]) if len(line) > 1 else None)
            if int(adv.env.street[0]) != st and not adv.env.done[0]:
                print("  -- new street: type 'board <all visible cards>' --")
        print("hand over\n")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("mode", choices=["play", "advisor"])
    ap.add_argument("--players", type=int, default=6)
    ap.add_argument("--stack", type=float, default=100)
    ap.add_argument("--model", default=None, help="path to model.pt (default: download from HF)")
    a = ap.parse_args()
    if a.mode == "play":
        play_cli(a.players, a.stack, a.model)
    else:
        advisor_cli(a.model)