File size: 18,397 Bytes
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Self-play PPO training for multi-player No-Limit Hold'em (2..23 players)."""
import copy
import json
import math
import os
import random
import time

import torch
import torch.nn.functional as F

from model import PokerNet
from poker_core import BOT_KINDS, N_ACTIONS, HandEvaluator, PokerEnv

DEFAULT = dict(
    groups=[
        # n = 2..9 : heads-up heavy, full ring 9 included
        dict(W=9, B=32768, probs=[30, 9, 9, 10, 12, 10, 10, 10]),
        # n = 10..23 : big / crowded tables (generalisation to "any number of players")
        dict(W=23, B=8192, probs=[0] * 8 + [14, 14, 14, 12, 12, 12, 6, 4, 3, 3, 2, 2, 1, 1]),
    ],
    T_min=64,
    eq_samples=16,
    d=256, layers=4, heads=8,
    cd=192, clayers=3, cheads=6,
    lr=3e-4, lr_min=3e-5, epochs=2, minibatch=32768,
    clip=0.2, ent0=0.02, ent1=0.003, vf_coef=0.5, max_grad=1.0, target_kl=0.04,
    reward_scale=1 / 25.0,
    p_mixed=0.45, p_bot_opp=0.35, learner_seat_p=0.5,
    snapshot_every=20, max_snapshots=10,
    eval_every_min=25, ckpt_every_min=10, hf_every_min=20, hf_ckpt_every_min=60,
)


def sub(o, m):
    return {k: v[m] for k, v in o.items()}


def cat_obs(lst):
    return {k: torch.cat([o[k] for o in lst], 0) for k in lst[0]}


class Trainer:
    def __init__(self, cfg, device, out_dir, hf=None, log=print):
        self.cfg = cfg
        self.dev = device
        self.out = out_dir
        self.hf = hf
        self.log = log
        os.makedirs(out_dir, exist_ok=True)
        self.ev = HandEvaluator(device)
        self.envs = [PokerEnv(g["B"], g["W"], g["probs"], device, self.ev, eq_samples=cfg["eq_samples"])
                     for g in cfg["groups"]]
        self.actor = PokerNet(cfg["d"], cfg["layers"], cfg["heads"]).to(device)
        self.critic = PokerNet(cfg["cd"], cfg["clayers"], cfg["cheads"], critic=True).to(device)
        self.opt = torch.optim.AdamW(list(self.actor.parameters()) + list(self.critic.parameters()),
                                     lr=cfg["lr"], weight_decay=1e-4, eps=1e-6)
        self.actor_u, self.critic_u = self.actor, self.critic
        if cfg.get("compile"):
            self.actor_u = torch.compile(self.actor, dynamic=True)
            self.critic_u = torch.compile(self.critic, dynamic=True)
        self.snapshots = []  # list of (iter, state_dict)
        self.snap_nets = []
        self.it = 0
        self.decisions = 0
        self.hands = 0
        self.elapsed_prev = 0.0
        self.metrics_path = os.path.join(out_dir, "metrics.jsonl")

    # ------------------------------------------------------------ persistence
    def state(self):
        return dict(cfg=self.cfg, actor=self.actor.state_dict(), critic=self.critic.state_dict(),
                    opt=self.opt.state_dict(), snapshots=self.snapshots, it=self.it,
                    decisions=self.decisions, hands=self.hands, elapsed=self.elapsed_prev + self.elapsed())

    def load(self, path):
        s = torch.load(path, map_location=self.dev, weights_only=False)
        self.actor.load_state_dict(s["actor"])
        self.critic.load_state_dict(s["critic"])
        self.opt.load_state_dict(s["opt"])
        self.snapshots = s["snapshots"]
        self.it, self.decisions, self.hands = s["it"], s["decisions"], s["hands"]
        self.elapsed_prev = s.get("elapsed", 0.0)
        self._rebuild_snap_nets()
        self.log(f"resumed from {path} at iter {self.it}")

    def _rebuild_snap_nets(self):
        self.snap_nets = []
        for _, sd in self.snapshots:
            net = PokerNet(self.cfg["d"], self.cfg["layers"], self.cfg["heads"]).to(self.dev)
            net.load_state_dict(sd)
            net.eval()
            self.snap_nets.append(net)

    def save_ckpt(self):
        path = os.path.join(self.out, "ckpt.pt")
        torch.save(self.state(), path + ".tmp")
        os.replace(path + ".tmp", path)
        torch.save(dict(cfg=dict(d=self.cfg["d"], layers=self.cfg["layers"], heads=self.cfg["heads"]),
                        actor=self.actor.state_dict(), it=self.it, decisions=self.decisions, hands=self.hands),
                   os.path.join(self.out, "model.pt"))

    def elapsed(self):
        return time.time() - self.t0

    # ------------------------------------------------------------ league
    def n_opp_types(self):
        return len(BOT_KINDS) + len(self.snap_nets)

    def assign(self, env, ctrl, mask):
        B, W, dev = env.B, env.W, self.dev
        c = self.cfg
        mixed = torch.rand(B, device=dev) < (c["p_mixed"] if True else 0)
        nb, ns = len(BOT_KINDS), len(self.snap_nets)
        use_bot = (torch.rand(B, device=dev) < c["p_bot_opp"]) | (ns == 0)
        bot_id = torch.randint(0, nb, (B,), device=dev) + 1
        snap_id = (torch.randint(0, max(ns, 1), (B,), device=dev) + 1 + nb) if ns > 0 else bot_id
        # bias towards recent snapshots
        if ns > 0:
            recent = torch.rand(B, device=dev) < 0.5
            snap_id = torch.where(recent, torch.full_like(snap_id, nb + ns), snap_id)
        opp = torch.where(use_bot, bot_id, snap_id)
        learner = (torch.rand(B, W, device=dev) < c["learner_seat_p"]) | ~mixed[:, None]
        forced = F.one_hot((torch.rand(B, device=dev) * env.n).long().clamp(max=env.n - 1), W).bool()
        new = torch.where(learner | forced, torch.zeros_like(ctrl), opp[:, None].expand(-1, W))
        return torch.where(mask[:, None], new, ctrl)

    def opp_act(self, k, o):
        nb = len(BOT_KINDS)
        if k <= nb:
            return bot_action(BOT_KINDS[k - 1], o)
        net = self.snap_nets[k - nb - 1]
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.dev == "cuda"):
            logits = net(o)
        return torch.distributions.Categorical(logits=logits.float()).sample()

    # ------------------------------------------------------------ rollout
    @torch.no_grad()
    def rollout(self, env):
        dev, B = self.dev, env.B
        env.reset()
        ctrl = self.assign(env, torch.zeros(B, env.W, dtype=torch.long, device=dev),
                           torch.ones(B, dtype=torch.bool, device=dev))
        steps = []  # per step: dict(game, seat, obs, act, logp, val)
        ends = []  # per step: (finished mask, delta)
        t = 0
        T_min = self.cfg["T_min"]
        hands = 0
        while True:
            active = ~env.done
            if not active.any():
                break
            idx = active.nonzero().squeeze(1)
            o = env.obs(privileged=True, idx=idx)
            p = env.cur[idx]
            c = ctrl[idx, p]
            act = torch.ones(idx.shape[0], dtype=torch.long, device=dev)
            lm = c == 0
            rec = None
            if lm.any():
                ol = sub(o, lm)
                with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
                    logits = self.actor(ol)
                    val = self.critic(ol).float()
                dist = torch.distributions.Categorical(logits=logits.float())
                a = dist.sample()
                act[lm] = a
                rec = dict(game=idx[lm], seat=p[lm], obs=ol, act=a, logp=dist.log_prob(a), val=val)
            for k in torch.unique(c[~lm]).tolist() if (~lm).any() else []:
                m = c == k
                po = {kk: v for kk, v in sub(o, m).items() if kk not in ("all_hole", "full_board")}
                act[m] = self.opp_act(k, po)
            full = torch.ones(B, dtype=torch.long, device=dev)
            full[idx] = act
            fin, delta = env.step(full, mask=active)
            steps.append(rec)
            ends.append((fin, delta))
            hands += int(fin.sum())
            if t < T_min:
                rm = env.done.clone()
                if rm.any():
                    env.reset(rm)
                    ctrl = self.assign(env, ctrl, rm)
            t += 1
        # returns: walk backwards
        pending = torch.zeros(B, env.W, device=dev)
        rets = [None] * len(steps)
        for i in range(len(steps) - 1, -1, -1):
            fin, delta = ends[i]
            pending = torch.where(fin[:, None], delta, pending)
            r = steps[i]
            if r is not None:
                rets[i] = pending[r["game"], r["seat"]]
        recs = [(s, r) for s, r in zip(steps, rets) if s is not None]
        data = dict(obs=cat_obs([s["obs"] for s, _ in recs]),
                    act=torch.cat([s["act"] for s, _ in recs]),
                    logp=torch.cat([s["logp"] for s, _ in recs]),
                    val=torch.cat([s["val"] for s, _ in recs]),
                    ret=torch.cat([r for _, r in recs]))
        return data, hands, t

    # ------------------------------------------------------------ PPO
    def update(self, datas, frac):
        c = self.cfg
        lr = c["lr_min"] + (c["lr"] - c["lr_min"]) * 0.5 * (1 + math.cos(math.pi * min(frac, 1.0)))
        ent_coef = c["ent1"] + (c["ent0"] - c["ent1"]) * max(0.0, 1 - frac)
        for gpar in self.opt.param_groups:
            gpar["lr"] = lr
        prepared = []
        for d in datas:
            ret = d["ret"] * c["reward_scale"]
            adv = ret - d["val"]
            prepared.append((d, ret, adv))
        allv = torch.cat([a for _, _, a in prepared])
        mu, sd = allv.mean(), allv.std() + 1e-8
        stats = dict(pg=0.0, vf=0.0, ent=0.0, kl=0.0, clipfrac=0.0, n=0)
        stop = False
        for ep in range(c["epochs"]):
            batches = []
            for gi, (d, ret, adv) in enumerate(prepared):
                N = ret.shape[0]
                perm = torch.randperm(N, device=self.dev)
                for i in range(0, N, c["minibatch"]):
                    batches.append((gi, perm[i:i + c["minibatch"]]))
            random.shuffle(batches)
            kls = []
            for gi, mb in batches:
                d, ret, adv = prepared[gi]
                o = sub(d["obs"], mb)
                a = d["act"][mb]
                with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.dev == "cuda"):
                    logits = self.actor_u(o)
                    v = self.critic_u(o).float()
                logits = logits.float()
                logp_all = torch.log_softmax(logits, -1)
                logp = logp_all.gather(1, a[:, None]).squeeze(1)
                p_all = logp_all.exp()
                ent = -(p_all * logp_all.masked_fill(~o["legal"], 0)).sum(1).mean()
                ratio = torch.exp(logp - d["logp"][mb])
                A = (adv[mb] - mu) / sd
                pg = -torch.min(ratio * A, ratio.clamp(1 - c["clip"], 1 + c["clip"]) * A).mean()
                vf = F.mse_loss(v, ret[mb])
                loss = pg + c["vf_coef"] * vf - ent_coef * ent
                self.opt.zero_grad(set_to_none=True)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(list(self.actor.parameters()) + list(self.critic.parameters()),
                                               c["max_grad"])
                self.opt.step()
                with torch.no_grad():
                    kl = ((ratio - 1) - torch.log(ratio)).mean().item()
                kls.append(kl)
                stats["pg"] += pg.item()
                stats["vf"] += vf.item()
                stats["ent"] += ent.item()
                stats["kl"] += kl
                stats["clipfrac"] += ((ratio - 1).abs() > c["clip"]).float().mean().item()
                stats["n"] += 1
            if sum(kls) / len(kls) > c["target_kl"]:
                stop = True
                break
        n = max(stats.pop("n"), 1)
        stats = {k: v / n for k, v in stats.items()}
        stats.update(lr=lr, ent_coef=ent_coef, epochs_done=ep + 1, kl_stop=stop)
        return stats

    # ------------------------------------------------------------ evaluation
    @torch.no_grad()
    def evaluate(self, opp, n, min_hands=20000, B=4096):
        """Hero (current actor) in one seat vs n-1 copies of `opp` (bot name or net), 100bb stacks."""
        dev = self.dev
        env = PokerEnv(B, max(n, 2), [0] * (n - 2) + [1], dev, self.ev, eq_samples=self.cfg["eq_samples"],
                       fixed_stack=100.0, ante_prob=0.0)
        env.reset(n_override=n)
        hero = (torch.rand(B, device=dev) * n).long()
        tot, tot2, hands = 0.0, 0.0, 0
        steps = 0
        while hands < min_hands and steps < 4000:
            o = env.obs()
            p = env.cur
            hm = p == hero
            act = torch.ones(B, dtype=torch.long, device=dev)
            with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
                if hm.any():
                    act[hm] = torch.distributions.Categorical(logits=self.actor(sub(o, hm)).float()).sample()
                if (~hm).any():
                    oo = sub(o, ~hm)
                    if isinstance(opp, str):
                        act[~hm] = bot_action(opp, oo)
                    else:
                        act[~hm] = torch.distributions.Categorical(logits=opp(oo).float()).sample()
            fin, delta = env.step(act)
            if fin.any():
                r = delta[fin].gather(1, hero[fin][:, None]).squeeze(1)
                tot += r.sum().item()
                tot2 += (r ** 2).sum().item()
                hands += int(fin.sum())
                env.reset(fin)
                hero = torch.where(fin, (torch.rand(B, device=dev) * env.n).long(), hero)
            steps += 1
        mean = tot / max(hands, 1)
        var = tot2 / max(hands, 1) - mean ** 2
        return dict(bb100=100 * mean, se100=100 * math.sqrt(max(var, 0) / max(hands, 1)), hands=hands)

    def eval_suite(self):
        res = {}
        t = time.time()
        self.actor.eval()
        for n in (2, 6, 9, 15):
            for bot in ("call", "tag", "maniac", "rock", "random"):
                if n == 15 and bot in ("random", "rock"):
                    continue
                r = self.evaluate(bot, n, min_hands=int(self.cfg.get('eval_scale',1.0)*(12000 if n <= 6 else 8000)))
                res[f"n{n}_{bot}"] = round(r["bb100"], 1)
                res[f"n{n}_{bot}_se"] = round(r["se100"], 1)
        if self.snap_nets:
            old = self.snap_nets[0]
            for n in (2, 6):
                r = self.evaluate(old, n, min_hands=int(self.cfg.get('eval_scale',1.0)*20000))
                res[f"n{n}_vs_snap{self.snapshots[0][0]}"] = round(r["bb100"], 1)
                res[f"n{n}_vs_snap{self.snapshots[0][0]}_se"] = round(r["se100"], 1)
        self.actor.train()
        res["eval_sec"] = round(time.time() - t, 1)
        return res

    # ------------------------------------------------------------ main loop
    def write_metrics(self, m):
        with open(self.metrics_path, "a") as f:
            f.write(json.dumps(m) + "\n")

    def train(self, hours, stop_file=None):
        c = self.cfg
        self.t0 = time.time()
        budget = hours * 3600
        last = dict(eval=time.time(), ckpt=time.time(), hf=0.0, hfck=time.time())
        if self.it == 0:
            m = dict(it=0, kind="eval", **self.eval_suite())
            self.log(json.dumps(m))
            self.write_metrics(m)
        while self.elapsed_prev + self.elapsed() < budget:
            if stop_file and os.path.exists(stop_file):
                self.log("stop file found")
                break
            ti = time.time()
            datas, hands, steps = [], 0, []
            for env in self.envs:
                d, h, t = self.rollout(env)
                datas.append(d)
                hands += h
                steps.append(t)
            tr = time.time() - ti
            st = self.update(datas, (self.elapsed_prev + self.elapsed()) / budget)
            n_dec = sum(d["act"].shape[0] for d in datas)
            self.decisions += n_dec
            self.hands += hands
            self.it += 1
            acts = torch.cat([d["act"] for d in datas])
            hist = torch.bincount(acts, minlength=N_ACTIONS).float() / acts.shape[0]
            m = dict(it=self.it, kind="train", t=round((self.elapsed_prev + self.elapsed()) / 60, 1), dec=n_dec, hands=hands,
                     tot_hands=self.hands, steps=steps, t_roll=round(tr, 1), t_upd=round(time.time() - ti - tr, 1),
                     fold=round(hist[0].item(), 3), call=round(hist[1].item(), 3),
                     raise_=round(hist[2:9].sum().item(), 3), allin=round(hist[9].item(), 3),
                     **{k: (round(v, 5) if isinstance(v, float) else v) for k, v in st.items()})
            self.log(json.dumps(m))
            self.write_metrics(m)
            if self.it % c["snapshot_every"] == 0:
                self.snapshots.append((self.it, copy.deepcopy({k: v.detach().clone() for k, v in self.actor.state_dict().items()})))
                if len(self.snapshots) > c["max_snapshots"]:
                    # keep the oldest (anchor) and drop a random middle one
                    self.snapshots.pop(random.randint(1, len(self.snapshots) - 2))
                self._rebuild_snap_nets()
            now = time.time()
            if now - last["eval"] > c["eval_every_min"] * 60:
                m = dict(it=self.it, kind="eval", t=round(self.elapsed() / 60, 1), **self.eval_suite())
                self.log(json.dumps(m))
                self.write_metrics(m)
                last["eval"] = now
            if now - last["ckpt"] > c["ckpt_every_min"] * 60:
                self.save_ckpt()
                last["ckpt"] = now
            if self.hf and now - last["hf"] > c["hf_every_min"] * 60:
                self.save_ckpt()
                big = now - last["hfck"] > c["hf_ckpt_every_min"] * 60
                self.hf(self.out, self.it, big)
                last["hf"] = now
                if big:
                    last["hfck"] = now
        m = dict(it=self.it, kind="eval", final=True, **self.eval_suite())
        self.log(json.dumps(m))
        self.write_metrics(m)
        self.save_ckpt()
        if self.hf:
            self.hf(self.out, self.it, True)


from poker_core import bot_action  # noqa: E402