File size: 3,137 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
import torch
import torch.nn as nn

from poker_core import N_ACTIONS, MAX_SEATS, obs_dims


class PokerNet(nn.Module):
    """Set/sequence transformer over [global, 7 cards, seat tokens]. Works for any number of seats <= 23.
    critic=True adds privileged inputs (all hole cards + full board) and outputs a scalar value."""

    def __init__(self, d=256, layers=4, heads=8, critic=False):
        super().__init__()
        fg, fs = obs_dims()
        self.critic = critic
        self.cfg = dict(d=d, layers=layers, heads=heads, critic=critic)
        self.card = nn.Embedding(53, d)
        self.rank = nn.Embedding(14, d)
        self.suit = nn.Embedding(5, d)
        self.slot = nn.Embedding(7 + (5 if critic else 0), d)
        self.glob = nn.Sequential(nn.Linear(fg, d), nn.GELU(), nn.Linear(d, d))
        self.seat = nn.Sequential(nn.Linear(fs, d), nn.GELU(), nn.Linear(d, d))
        self.seat_pos = nn.Embedding(MAX_SEATS, d)
        self.btn_dist = nn.Embedding(MAX_SEATS, d)
        self.tok_type = nn.Embedding(4, d)
        if critic:
            self.hole_proj = nn.Linear(d, d)
        layer = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, activation="gelu",
                                           batch_first=True, norm_first=True)
        self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
        self.norm = nn.LayerNorm(d)
        out = 1 if critic else N_ACTIONS
        self.head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, out))
        if not critic:
            nn.init.zeros_(self.head[-1].weight)
            nn.init.zeros_(self.head[-1].bias)

    def card_emb(self, c):
        c = c.long()
        unk = c == 52
        r = torch.where(unk, torch.full_like(c, 13), c // 4)
        s = torch.where(unk, torch.full_like(c, 4), c % 4)
        return self.card(c) + self.rank(r) + self.suit(s)

    def forward(self, o):
        cards = o["cards"]
        b = cards.shape[0]
        dev = cards.device
        g = self.glob(o["glob"].float()).unsqueeze(1) + self.tok_type.weight[0]
        ce = self.card_emb(cards) + self.slot(torch.arange(7, device=dev))[None] + self.tok_type.weight[1]
        toks = [g, ce]
        st = (self.seat(o["seat"].float()) + self.seat_pos(o["seat_pos"]) + self.btn_dist(o["btn_dist"])
              + self.tok_type.weight[2])
        if self.critic:
            hs = self.card_emb(o["all_hole"]).sum(2)
            st = st + self.hole_proj(hs)
            fb = self.card_emb(o["full_board"]) + self.slot(torch.arange(7, 12, device=dev))[None] + self.tok_type.weight[3]
            toks.append(fb)
        toks.append(st)
        x = torch.cat(toks, 1)
        nfix = x.shape[1] - st.shape[1]
        pad = torch.cat([torch.zeros(b, nfix, dtype=torch.bool, device=dev), ~o["seat_mask"]], 1)
        x = self.enc(x, src_key_padding_mask=pad)
        x = self.norm(x)
        selfseat = x[:, nfix]  # seat token of the acting player
        h = torch.cat([x[:, 0], selfseat], 1)
        out = self.head(h)
        if self.critic:
            return out.squeeze(1)
        return out.float().masked_fill(~o["legal"], -1e9)