""" Vectorized No-Limit Texas Hold'em engine (PyTorch, runs on GPU or CPU). - B games simulated in parallel, each with 2..W players (W <= 23). - Arbitrary per-player stacks, blinds 0.5/1 (all amounts in big blinds), optional antes. - Full NLHE rules: min-raise, incomplete all-in raises (no reopen), side pots, split pots. - Hand evaluator: 5-card lookup table (C(52,5) entries) + best-of-21 for 7 cards. """ import math from itertools import combinations import torch import torch.nn.functional as F N_ACTIONS = 10 # 0 fold, 1 check/call, 2 min-raise, 3..8 pot-fraction raises, 9 all-in RAISE_FRACS = [None, None, 0.0, 0.33, 0.5, 0.75, 1.0, 1.5, 2.5, None] ACTION_NAMES = ["fold", "check/call", "min-raise", "raise 33%", "raise 50%", "raise 75%", "raise 100%", "raise 150%", "raise 250%", "all-in"] MAX_SEATS = 23 NREV = [0, 3, 4, 5] # board cards revealed per street # ---------------------------------------------------------------- hand evaluation def _eval5_direct(c): """c: (N,5) int64 cards 0..51 (rank = c//4, suit = c%4). Returns int64 score (higher is better).""" r = c // 4 s = c % 4 rs, _ = r.sort(dim=1, descending=True) flush = (s == s[:, :1]).all(1) oh = F.one_hot(r, 13).sum(1) # (N,13) cnt = oh.gather(1, rs) key = cnt * 16 + rs ks, _ = key.sort(dim=1, descending=True) kr = ks % 16 kc = ks // 16 distinct = (oh > 0).sum(1) wheel = (distinct == 5) & (rs[:, 0] == 12) & (rs[:, 1] == 3) straight = ((distinct == 5) & (rs[:, 0] - rs[:, 4] == 4)) | wheel c0 = kc[:, 0] cat = torch.zeros_like(c0) cat[c0 == 2] = 1 cat[(c0 == 2) & (kc[:, 2] == 2)] = 2 cat[c0 == 3] = 3 cat[straight] = 4 cat[flush] = 5 cat[(c0 == 3) & (kc[:, 3] == 2)] = 6 cat[c0 == 4] = 7 cat[straight & flush] = 8 tie = kr[:, 0] * 16 ** 4 + kr[:, 1] * 16 ** 3 + kr[:, 2] * 16 ** 2 + kr[:, 3] * 16 + kr[:, 4] high = torch.where(wheel, torch.full_like(rs[:, 0], 3), rs[:, 0]) tie = torch.where(straight, high * 16 ** 4, tie) return cat * 16 ** 5 + tie class HandEvaluator: def __init__(self, device): self.device = device binom = torch.zeros(53, 6, dtype=torch.long) for n in range(53): for k in range(6): binom[n, k] = math.comb(n, k) self.binom = binom.to(device) combos = torch.tensor(list(combinations(range(52), 5)), dtype=torch.long) lut = torch.zeros(len(combos), dtype=torch.int32) for i in range(0, len(combos), 400_000): c = combos[i:i + 400_000] idx = self._index_cpu(c, binom) lut[idx] = _eval5_direct(c).to(torch.int32) self.lut = lut.to(device) self.comb = {k: torch.tensor(list(combinations(range(k), 5)), dtype=torch.long, device=device) for k in (5, 6, 7)} @staticmethod def _index_cpu(c, binom): return (binom[c[:, 0], 1] + binom[c[:, 1], 2] + binom[c[:, 2], 3] + binom[c[:, 3], 4] + binom[c[:, 4], 5]) def eval_k(self, cards): """cards (..., k) with k in 5,6,7, all valid & distinct. Returns int32 best-5 score.""" k = cards.shape[-1] sh = cards.shape[:-1] c = cards.reshape(-1, k).long().sort(dim=1).values sub = c[:, self.comb[k]] # (M, C, 5) ascending b = self.binom idx = (b[sub[..., 0], 1] + b[sub[..., 1], 2] + b[sub[..., 2], 3] + b[sub[..., 3], 4] + b[sub[..., 4], 5]) return self.lut[idx].max(dim=-1).values.reshape(sh) def eval7_chunked(self, cards, chunk=1 << 20): sh = cards.shape[:-1] flat = cards.reshape(-1, 7) out = torch.empty(flat.shape[0], dtype=torch.int32, device=flat.device) for i in range(0, flat.shape[0], chunk): out[i:i + chunk] = self.eval_k(flat[i:i + chunk]) return out.reshape(sh) @staticmethod def category(score): return (score.long() // (16 ** 5)).clamp(0, 8) def equity(self, hole, board, nrev, n_opp, K=16, chunk=2048): """Monte-Carlo equity vs uniformly random hands. hole (N,2), board (N,5) (only first nrev valid), nrev (N,), n_opp (N,) >=1. Returns eq1 (vs 1 random hand) and eqM (vs n_opp random hands).""" N = hole.shape[0] dev = hole.device eq1 = torch.empty(N, device=dev) eqm = torch.empty(N, device=dev) for i in range(0, N, chunk): h = hole[i:i + chunk] bd = board[i:i + chunk] nr = nrev[i:i + chunk] no = n_opp[i:i + chunk] n = h.shape[0] O = int(no.max().item()) if n > 0 else 1 O = max(O, 1) known = torch.zeros(n, 52, dtype=torch.bool, device=dev) known.scatter_(1, h.long(), True) slot = torch.arange(5, device=dev) bvalid = slot[None] < nr[:, None] bk = torch.where(bvalid, bd.long(), h[:, :1].long().expand(-1, 5)) known.scatter_(1, bk, True) keys = torch.rand(n, K, 52, device=dev) keys = keys.masked_fill(known[:, None, :], 2.0) M = 5 + 2 * O samp = keys.topk(M, dim=2, largest=False).indices # (n,K,M) random unknown cards # opponents take samp[:2O]; unrevealed board slot i takes samp[2O + i - nrev] bsel = (2 * O + (slot[None] - nr[:, None]).clamp(min=0)).clamp(max=M - 1) bfill = samp.gather(2, bsel[:, None, :].expand(-1, K, -1)) board_s = torch.where(bvalid[:, None, :], bd.long()[:, None, :].expand(-1, K, -1), bfill) hero7 = torch.cat([h.long()[:, None, :].expand(-1, K, -1), board_s], dim=2) hs = self.eval_k(hero7) # (n,K) opp_h = samp[:, :, :2 * O].reshape(n, K, O, 2) opp7 = torch.cat([opp_h, board_s[:, :, None, :].expand(-1, -1, O, -1)], dim=3) os_ = self.eval_k(opp7) # (n,K,O) omask = torch.arange(O, device=dev)[None, None, :] < no[:, None, None] os_ = torch.where(omask, os_, torch.full_like(os_, -1)) o0 = os_[:, :, 0] e1 = (hs > o0).float() + 0.5 * (hs == o0).float() mx = os_.max(dim=2).values ties = (os_ == hs[:, :, None]).sum(2).float() em = (hs > mx).float() + (hs == mx).float() / (1.0 + ties) eq1[i:i + chunk] = e1.mean(1) eqm[i:i + chunk] = em.mean(1) return eq1, eqm # ---------------------------------------------------------------- environment class PokerEnv: """Batch of NLHE games. Every non-finished game always has exactly one player to act (self.cur).""" FG = None # set after first obs FS = None def __init__(self, B, W, n_probs, device, evaluator, eq_samples=16, fixed_stack=None, ante_prob=0.2): assert 2 <= W <= MAX_SEATS self.B, self.W, self.dev = B, W, device self.ev = evaluator self.K = eq_samples p = torch.tensor(n_probs, dtype=torch.float, device=device) # probs over n = 2..len+1 self.n_probs = p / p.sum() self.fixed_stack = fixed_stack self.ante_prob = ante_prob z = lambda *s, dt=torch.float: torch.zeros(*s, dtype=dt, device=device) self.n = z(B, dt=torch.long) self.button = z(B, dt=torch.long) self.stack = z(B, W) self.start_stack = z(B, W) self.bet = z(B, W) self.contrib = z(B, W) self.st_contrib = z(B, W, 4) self.st_aggr = z(B, W, 4) self.last_act = z(B, W, dt=torch.long) self.folded = z(B, W, dt=torch.bool) self.allin = z(B, W, dt=torch.bool) self.present = z(B, W, dt=torch.bool) self.acted = z(B, W, dt=torch.bool) self.can_raise = z(B, W, dt=torch.bool) self.max_bet = z(B) self.min_raise = z(B) self.ante = z(B) self.street = z(B, dt=torch.long) self.cur = z(B, dt=torch.long) self.hole = z(B, W, 2, dt=torch.long) self.board = z(B, 5, dt=torch.long) self.done = torch.ones(B, dtype=torch.bool, device=device) self.ar = torch.arange(B, device=device) self.seats = torch.arange(W, device=device) # ------------------------------------------------------------ helpers def _next_need(self, frm, need): offs = torch.arange(1, self.W + 1, device=self.dev) idx = (frm[:, None] + offs[None, :]) % self.n[:, None] g = need.gather(1, idx) first = g.float().argmax(1) return idx.gather(1, first[:, None]).squeeze(1), g.any(1) def _need(self): return (self.present & ~self.folded & ~self.allin & (~self.acted | (self.bet < self.max_bet[:, None] - 1e-6))) # ------------------------------------------------------------ reset def reset(self, mask=None, n_override=None, stacks_override=None): B, W, dev = self.B, self.W, self.dev if mask is None: mask = torch.ones(B, dtype=torch.bool, device=dev) if not mask.any(): return m = mask m2 = m[:, None] if n_override is not None: n = torch.full((B,), n_override, dtype=torch.long, device=dev) if isinstance(n_override, int) else n_override else: n = torch.multinomial(self.n_probs, B, replacement=True) + 2 present = self.seats[None] < n[:, None] button = (torch.rand(B, device=dev) * n).long().clamp(max=n - 1) # stacks if stacks_override is not None: stk = stacks_override elif self.fixed_stack is not None: stk = torch.full((B, W), float(self.fixed_stack), device=dev) else: u = torch.rand(B, device=dev) common = torch.exp(torch.empty(B, device=dev).uniform_(math.log(10), math.log(250))) common = torch.where(u < 0.4, torch.full_like(common, 100.0), common) indiv = torch.exp(torch.empty(B, W, device=dev).uniform_(math.log(3), math.log(300))) stk = torch.where((u < 0.7)[:, None], common[:, None].expand(-1, W), indiv) stk = (stk * 2).round() / 2 stk = torch.where(present, stk.clamp(min=2.0), torch.zeros_like(stk)) ante = torch.where(torch.rand(B, device=dev) < self.ante_prob, torch.empty(B, device=dev).uniform_(0.05, 0.25), torch.zeros(B, device=dev)) ante = (ante * 20).round() / 20 if stacks_override is not None or self.fixed_stack is not None: ante = torch.zeros(B, device=dev) # deck perm = torch.rand(B, 52, device=dev).argsort(1) hole = perm[:, :2 * W].reshape(B, W, 2) hole = hole.sort(dim=2, descending=True).values board = perm[:, 46:51] if W == 23 else perm[:, 2 * W:2 * W + 5] # blinds sb = torch.where(n == 2, button, (button + 1) % n) bb = (sb + 1) % n contrib = torch.where(present, torch.minimum(ante[:, None].expand(-1, W), stk), torch.zeros_like(stk)) stack = stk - contrib bet = torch.zeros(B, W, device=dev) sbamt = torch.minimum(stack[self.ar, sb], torch.full((B,), 0.5, device=dev)) bet[self.ar, sb] = sbamt stack[self.ar, sb] -= sbamt bbamt = torch.minimum(stack[self.ar, bb], torch.full((B,), 1.0, device=dev)) bet[self.ar, bb] = bbamt stack[self.ar, bb] -= bbamt contrib = contrib + bet stc = torch.zeros(B, W, 4, device=dev) stc[:, :, 0] = bet def put(name, val): cur = getattr(self, name) mm = m.view(B, *([1] * (cur.dim() - 1))) setattr(self, name, torch.where(mm, val, cur)) put("n", n) put("button", button) put("present", present) put("start_stack", stk) put("stack", stack) put("bet", bet) put("contrib", contrib) put("st_contrib", stc) put("st_aggr", torch.zeros(B, W, 4, device=dev)) put("last_act", torch.zeros(B, W, dtype=torch.long, device=dev)) put("folded", ~present) put("allin", present & (stack <= 1e-9)) put("acted", torch.zeros(B, W, dtype=torch.bool, device=dev)) put("can_raise", present.clone()) put("max_bet", bet.max(1).values.clamp(min=1.0)) put("min_raise", torch.ones(B, device=dev)) put("ante", ante) put("street", torch.zeros(B, dtype=torch.long, device=dev)) put("hole", hole) put("board", board) put("done", torch.zeros(B, dtype=torch.bool, device=dev)) cur, ok = self._next_need(bb, self._need()) put("cur", cur) # ------------------------------------------------------------ raise targets / legality def _raise_targets(self, p): """Returns (B, N_ACTIONS) raise-to amounts (uncapped) for raise actions.""" bet_p = self.bet[self.ar, p] to_call = (self.max_bet - bet_p).clamp(min=0) pot = self.contrib.sum(1) pac = pot + to_call minr = self.max_bet + self.min_raise rt = torch.zeros(self.B, N_ACTIONS, device=self.dev) for a in range(2, 9): f = RAISE_FRACS[a] rt[:, a] = torch.maximum(self.max_bet + f * pac, minr) rt[:, 9] = bet_p + self.stack[self.ar, p] return rt def legal(self, p=None): if p is None: p = self.cur bet_p = self.bet[self.ar, p] stk = self.stack[self.ar, p] to_call = (self.max_bet - bet_p).clamp(min=0) rt = self._raise_targets(p) raise_ok = self.can_raise[self.ar, p] & (stk > to_call + 1e-9) L = torch.zeros(self.B, N_ACTIONS, dtype=torch.bool, device=self.dev) L[:, 0] = to_call > 1e-9 L[:, 1] = True L[:, 2:9] = raise_ok[:, None] & ((rt[:, 2:9] - bet_p[:, None]) < stk[:, None] - 1e-9) L[:, 9] = raise_ok return L # ------------------------------------------------------------ step def step(self, action, mask=None, custom_to=None): """Apply `action` (B,) for current players of games in mask (default: all not done). Action == N_ACTIONS means "raise to custom_to[b]" (arbitrary amount, used by play.py). Returns (hand_finished (B,) bool, delta (B,W) chip result for finished hands).""" B, W, dev, ar = self.B, self.W, self.dev, self.ar if mask is None: mask = ~self.done mask = mask & ~self.done p = self.cur bet_p = self.bet[ar, p] stk = self.stack[ar, p] to_call = (self.max_bet - bet_p).clamp(min=0) rt = self._raise_targets(p) a = action.long() is_fold = (a == 0) & mask is_call = (a == 1) & mask is_raise = (a >= 2) & mask r_to = rt.gather(1, a.clamp(max=N_ACTIONS - 1)[:, None]).squeeze(1) if custom_to is not None: r_to = torch.where(a == N_ACTIONS, torch.maximum(custom_to, self.max_bet + self.min_raise), r_to) r_to = torch.minimum(r_to, bet_p + stk) amt = torch.where(is_call, torch.minimum(to_call, stk), torch.zeros_like(stk)) amt = torch.where(is_raise, (r_to - bet_p).clamp(min=0), amt) amt = torch.minimum(amt, stk) onehot_p = F.one_hot(p, W).bool() & mask[:, None] add = onehot_p.float() * amt[:, None] self.stack = self.stack - add self.bet = self.bet + add self.contrib = self.contrib + add st_oh = F.one_hot(self.street, 4).float() self.st_contrib = self.st_contrib + add[:, :, None] * st_oh[:, None, :] self.folded = self.folded | (onehot_p & is_fold[:, None]) new_bet = bet_p + amt raised = mask & (new_bet > self.max_bet + 1e-9) inc = new_bet - self.max_bet full = raised & (inc >= self.min_raise - 1e-9) others = self.present & ~self.folded & ~self.allin & ~onehot_p self.can_raise = self.can_raise | (others & full[:, None]) self.min_raise = torch.where(full, inc, self.min_raise) self.max_bet = torch.where(raised, new_bet, self.max_bet) self.st_aggr = self.st_aggr + (onehot_p & raised[:, None]).float()[:, :, None] * st_oh[:, None, :] self.acted = self.acted | onehot_p self.can_raise = self.can_raise & ~onehot_p went_allin = onehot_p & (self.stack <= 1e-9) & self.present & ~self.folded self.allin = self.allin | went_allin code = torch.where(is_fold, 1, torch.where(raised, 4, torch.where(amt > 1e-9, 3, 2))) code = torch.where(went_allin.any(1) & (amt > 1e-9), 5, code) self.last_act = torch.where(onehot_p, code[:, None], self.last_act) # ---- resolve live = self.present & ~self.folded n_live = live.sum(1) one_left = mask & (n_live == 1) need = self._need() round_done = mask & ~need.any(1) & ~one_left can_act = live & ~self.allin n_can = can_act.sum(1) showdown = round_done & ((self.street == 3) | (n_can <= 1)) advance = round_done & ~showdown cont = mask & ~one_left & ~round_done # continue in same round nxt, _ = self._next_need(p, need) self.cur = torch.where(cont, nxt, self.cur) # advance street if advance.any(): a2 = advance[:, None] self.street = torch.where(advance, self.street + 1, self.street) self.bet = torch.where(a2, torch.zeros_like(self.bet), self.bet) self.max_bet = torch.where(advance, torch.zeros_like(self.max_bet), self.max_bet) self.min_raise = torch.where(advance, torch.ones_like(self.min_raise), self.min_raise) self.acted = self.acted & ~a2 self.can_raise = torch.where(a2, can_act, self.can_raise) nxt2, _ = self._next_need(self.button, self._need()) self.cur = torch.where(advance, nxt2, self.cur) # payouts win = torch.zeros(B, W, device=dev) pot = self.contrib.sum(1) win = win + (live & one_left[:, None]).float() * pot[:, None] if showdown.any(): idx = showdown.nonzero().squeeze(1) win[idx] = self._showdown(idx) finished = one_left | showdown self.stack = self.stack + win self.done = self.done | finished delta = torch.where(finished[:, None], self.stack - self.start_stack, torch.zeros_like(self.stack)) return finished, delta def _showdown(self, idx): hole = self.hole[idx] # (b,W,2) board = self.board[idx] # (b,5) b = idx.shape[0] W = self.W cards7 = torch.cat([hole, board[:, None, :].expand(-1, W, -1)], dim=2) live = self.present[idx] & ~self.folded[idx] score = self.ev.eval7_chunked(cards7).long() score = torch.where(live, score, torch.full_like(score, -1)) c = self.contrib[idx] lv = c.sort(1).values prev = torch.zeros(b, device=self.dev) win = torch.zeros(b, W, device=self.dev) for k in range(W): L = lv[:, k] layer = (torch.minimum(c, L[:, None]) - torch.minimum(c, prev[:, None])).sum(1) elig = live & (c >= L[:, None] - 1e-6) none = ~elig.any(1) elig = torch.where(none[:, None], live, elig) sc = torch.where(elig, score, torch.full_like(score, -2)) best = sc.max(1).values winners = elig & (sc == best[:, None]) share = layer / winners.sum(1).clamp(min=1) win = win + winners.float() * share[:, None] prev = L return win # ------------------------------------------------------------ observation def obs(self, privileged=False, idx=None): """Observation for the current player of each game (or subset idx).""" if idx is None: idx = self.ar b = idx.shape[0] W, dev = self.W, self.dev p = self.cur[idx] n = self.n[idx] btn = self.button[idx] street = self.street[idx] present = self.present[idx] folded = self.folded[idx] allin = self.allin[idx] stack = self.stack[idx] bet = self.bet[idx] contrib = self.contrib[idx] maxb = self.max_bet[idx] minr = self.min_raise[idx] ar = torch.arange(b, device=dev) live = present & ~folded n_live = live.sum(1) can_act = live & ~allin pot = contrib.sum(1) bet_p = bet[ar, p] stk_p = stack[ar, p] to_call = (maxb - bet_p).clamp(min=0) others_live = live.clone() others_live[ar, p] = False max_other = torch.where(others_live, stack + bet, torch.zeros_like(stack)).max(1).values eff = torch.minimum(stk_p + bet_p, max_other) nrev = torch.tensor(NREV, device=dev)[street] hole_p = self.hole[idx, p] # (b,2) board = self.board[idx] # equity features n_opp = (n_live - 1).clamp(min=1) eq1, eqm = self.ev.equity(hole_p, board, nrev, n_opp, K=self.K) # made-hand category cat = torch.zeros(b, dtype=torch.long, device=dev) cat = torch.where(street == 0, (hole_p[:, 0] // 4 == hole_p[:, 1] // 4).long(), cat) for s, k in ((1, 5), (2, 6), (3, 7)): m = street == s if m.any(): cc = torch.cat([hole_p[m], board[m, :k - 2]], 1) cat[m] = self.ev.category(self.ev.eval_k(cc)) need = (present & ~folded & ~allin & (~self.acted[idx] | (bet < maxb[:, None] - 1e-6))) n_need_others = need.sum(1) - need[ar, p].long() postpos = ((p - btn - 1) % n).float() / (n - 1).clamp(min=1).float() g = [ F.one_hot(street, 4).float(), torch.stack([ n.float() / 10, n_live.float() / 10, can_act.sum(1).float() / 10, pot / 100, torch.log1p(pot) / 5, to_call / 100, torch.log1p(to_call) / 5, to_call / (pot + to_call).clamp(min=1e-6), stk_p / 100, torch.log1p(stk_p) / 5, (stk_p / pot.clamp(min=1e-6)).clamp(max=20) / 20, eff / 100, torch.log1p(eff) / 5, maxb / 100, minr / 100, bet_p / 100, contrib[ar, p] / 100, eq1, eqm, eq1 ** n_opp.float(), (p == btn).float(), postpos, self.ante[idx], self.st_aggr[idx, :, :].gather(2, street[:, None, None].expand(-1, W, 1)).sum((1, 2)) / 5, (live & allin).sum(1).float() / 10, n_need_others.float() / 10, ], 1), F.one_hot(cat, 9).float(), ] glob = torch.cat(g, 1) # seat tokens in order relative to acting player t = torch.arange(W, device=dev) smask = t[None] < n[:, None] sidx = torch.where(smask, (p[:, None] + t[None]) % n[:, None], t[None].expand(b, -1)) gat = lambda x: x.gather(1, sidx) sb = torch.where(n == 2, btn, (btn + 1) % n) bbs = (sb + 1) % n s_stack = gat(stack) s_bet = gat(bet) s_con = gat(contrib) stc = self.st_contrib[idx].gather(1, sidx[:, :, None].expand(-1, -1, 4)) sta = self.st_aggr[idx].gather(1, sidx[:, :, None].expand(-1, -1, 4)) la = F.one_hot(gat(self.last_act[idx]), 6).float() seat = torch.cat([ torch.stack([ gat(present).float(), gat(folded).float(), gat(allin).float(), (t[None] == 0).float().expand(b, -1), s_stack / 100, torch.log1p(s_stack) / 5, s_bet / 100, torch.log1p(s_bet) / 5, s_con / 100, torch.log1p(s_con) / 5, gat(self.acted[idx]).float(), gat(self.can_raise[idx]).float(), (sidx == btn[:, None]).float(), (sidx == sb[:, None]).float(), (sidx == bbs[:, None]).float(), gat(need).float(), gat(self.start_stack[idx]) / 100, ], 2), stc / 100, sta / 3, la, ], 2) * smask[:, :, None].float() btn_dist = torch.where(smask, (sidx - btn[:, None]) % n[:, None], torch.zeros_like(sidx)) board_vis = torch.where(torch.arange(5, device=dev)[None] < nrev[:, None], board, torch.full_like(board, 52)) cards = torch.cat([hole_p, board_vis], 1) legal = self.legal()[idx] if idx is not self.ar else self.legal() o = dict(cards=cards, glob=glob, seat=seat, seat_pos=t[None].expand(b, -1).contiguous(), btn_dist=btn_dist, seat_mask=smask, legal=legal) if privileged: ah = self.hole[idx].gather(1, sidx[:, :, None].expand(-1, -1, 2)) ah = torch.where(smask[:, :, None], ah, torch.full_like(ah, 52)) o["all_hole"] = ah o["full_board"] = board PokerEnv.FG = glob.shape[1] PokerEnv.FS = seat.shape[2] return o def obs_dims(): return 4 + 26 + 9, 17 + 4 + 4 + 6 # ---------------------------------------------------------------- heuristic opponents def bot_action(kind, obs, gen=None): """Simple rule-based bots for league diversity and evaluation.""" g = obs["glob"] L = obs["legal"] b = g.shape[0] dev = g.device eqm = g[:, 4 + 18] eq1 = g[:, 4 + 17] pot_odds = g[:, 4 + 7] to_call_pos = L[:, 0] act = torch.ones(b, dtype=torch.long, device=dev) # call/check def pick_raise(pref): a = torch.full((b,), pref, dtype=torch.long, device=dev) ok = L.gather(1, a[:, None]).squeeze(1) a = torch.where(ok, a, torch.where(L[:, 9], torch.full_like(a, 9), torch.ones_like(a))) return a fold_or_check = torch.where(to_call_pos, torch.zeros_like(act), torch.ones_like(act)) if kind == "call": return act if kind == "random": logits = torch.where(L, torch.zeros(b, N_ACTIONS, device=dev), torch.full((b, N_ACTIONS), -1e9, device=dev)) return torch.distributions.Categorical(logits=logits).sample() if kind == "tag": a = torch.where(eqm >= pot_odds + 0.04, act, fold_or_check) a = torch.where((eqm > 0.55) & ~to_call_pos, pick_raise(4), a) a = torch.where(eqm > 0.72, pick_raise(6), a) return a if kind == "rock": a = torch.where(eqm >= pot_odds + 0.15, act, fold_or_check) a = torch.where(eqm > 0.82, pick_raise(5), a) return a if kind == "maniac": r = torch.rand(b, device=dev) size = torch.randint(3, 10, (b,), device=dev) rs = torch.where(L.gather(1, size[:, None]).squeeze(1), size, torch.where(L[:, 9], 9, 1)) a = torch.where(r < 0.55, rs, act) a = torch.where((eq1 < 0.3) & (r > 0.85) & to_call_pos, torch.zeros_like(a), a) return a if kind == "eqcaller": return torch.where(eq1 >= pot_odds, act, fold_or_check) raise ValueError(kind) BOT_KINDS = ["call", "random", "tag", "rock", "maniac", "eqcaller"]