amer224 commited on
Commit
df8ea5d
·
verified ·
1 Parent(s): 07dc3fe

Add brains/sovereign-v3/search.py

Browse files
Files changed (1) hide show
  1. brains/sovereign-v3/search.py +282 -0
brains/sovereign-v3/search.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ search.py — MCTS planning for SOVEREIGN v3 (MuZero-lite).
3
+
4
+ At decision time the model can now THINK: it encodes the board into a
5
+ compressed latent, then runs PUCT tree search over the (kind, cell) action
6
+ space using the learned prediction/dynamics networks (see model.py's
7
+ `encode` / `prediction` / `dynamics`). This is AlphaZero-style planning
8
+ adapted to a 3x1024 discrete action space with a policy prior:
9
+
10
+ prior — from the real policy at the ROOT (legality already
11
+ folded in via the gate/mask), from the prediction net at
12
+ deeper nodes
13
+ value — win-probability head (the last-survivor objective itself)
14
+ dynamics — one-step latent transition trained on consecutive shard
15
+ frames (rgb_t, a_t -> rgb_{t+1}) plus the farmer reward
16
+
17
+ The search visits become policy-improvement targets for PPO (AlphaZero's
18
+ policy improvement operator, see train_notes.md Stage B).
19
+
20
+ Cost: 64 sims x depth 12 x (~27M-flop dynamics+prediction) ≈ 20-40ms on a
21
+ T4 in fp16 — well inside the 560ms tick budget. Honest simplifications
22
+ (documented, not hidden): (1) the rollout uses a fixed 25% troop commit
23
+ (the pct of the FINAL chosen action still comes from the full policy head
24
+ at that cell); (2) the latent is a vector (cortex pool + 8x8 compressed
25
+ map) — a MuZero-grade abstract state, not a pixel-perfect one.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ from dataclasses import dataclass, field
32
+ from typing import Dict, List, Optional, Tuple
33
+
34
+ import torch
35
+ import torch.nn.functional as F
36
+
37
+ EPS = 1e-6
38
+
39
+
40
+ @dataclass
41
+ class SearchResult:
42
+ kind: int
43
+ cell: int
44
+ pct: float
45
+ expected_win: float # mean Q of the visit distribution
46
+ q_chosen: float # Q of the chosen action
47
+ visits: torch.Tensor # (3*g*g,) visit counts
48
+ visit_probs: torch.Tensor # (3*g*g,) normalized visit distribution
49
+ max_depth_reached: int
50
+ log: dict = field(default_factory=dict)
51
+
52
+
53
+ class _Node:
54
+ __slots__ = ("z", "lp", "n", "w", "children", "depth")
55
+
56
+ def __init__(self, z: torch.Tensor, lp: float, depth: int):
57
+ self.z = z # latent state (1, latent_dim)
58
+ self.lp = lp # log-prob of this edge (prior)
59
+ self.n = 0 # visit count
60
+ self.w = 0.0 # accumulated value
61
+ self.children: Dict[int, _Node] = {}
62
+ self.depth = depth
63
+
64
+ @property
65
+ def q(self) -> float:
66
+ return self.w / max(self.n, 1)
67
+
68
+
69
+ class Searcher:
70
+ def __init__(self, model, sims: int = 64, max_depth: int = 12,
71
+ c_puct: float = 1.25, top_k: int = 16,
72
+ dirichlet_alpha: float = 0.3, dirichlet_frac: float = 0.25,
73
+ discount: float = 0.995, temperature: float = 1.0,
74
+ default_pct: float = 0.25, seed: Optional[int] = None):
75
+ self.model = model
76
+ self.sims = sims
77
+ self.max_depth = max_depth
78
+ self.c_puct = c_puct
79
+ self.top_k = top_k
80
+ self.dirichlet_alpha = dirichlet_alpha
81
+ self.dirichlet_frac = dirichlet_frac
82
+ self.discount = discount
83
+ self.temperature = temperature
84
+ self.default_pct = default_pct
85
+ self.rng = torch.Generator()
86
+ if seed is not None:
87
+ self.rng.manual_seed(seed)
88
+ self.grid = model.cfg.grid_default
89
+ self.num_actions = model.cfg.num_kinds * self.grid * self.grid
90
+
91
+ # -- action packing -----------------------------------------------------
92
+
93
+ def _kind_of(self, a: int) -> torch.Tensor:
94
+ return torch.tensor([a // (self.grid * self.grid)],
95
+ dtype=torch.long, device=self._device())
96
+
97
+ def _cell_of(self, a: int) -> torch.Tensor:
98
+ return torch.tensor([a % (self.grid * self.grid)],
99
+ dtype=torch.long, device=self._device())
100
+
101
+ def _device(self):
102
+ return next(self.model.parameters()).device
103
+
104
+ # -- main entry ---------------------------------------------------------
105
+
106
+ @torch.no_grad()
107
+ def search(self, rgb: torch.Tensor, nums: Optional[torch.Tensor] = None,
108
+ rtg: Optional[torch.Tensor] = None,
109
+ mask: Optional[torch.Tensor] = None,
110
+ deterministic: bool = False) -> SearchResult:
111
+ """Run MCTS from the current observation and return the chosen
112
+ action + visit statistics. rgb must be a single sample (B=1)."""
113
+ m = self.model
114
+ assert rgb.shape[0] == 1, "search operates on a single sample (B=1)"
115
+ device = rgb.device
116
+
117
+ # full policy pass at the root: legality already inside cell_logits
118
+ out = m(rgb, nums, rtg=rtg, mask=mask, grid=self.grid,
119
+ return_all=True)
120
+ root_logits = out["cell_logits"][0] # (3*g*g,)
121
+ z_root = m.encode(rgb, nums, rtg=rtg) # (1, latent_dim)
122
+
123
+ # root prior with Dirichlet exploration noise (global RNG: Dirichlet
124
+ # .sample() takes no generator arg)
125
+ lp_root = F.log_softmax(root_logits, dim=0)
126
+ if self.dirichlet_alpha > 0:
127
+ noise = torch.distributions.Dirichlet(
128
+ torch.full((self.num_actions,), self.dirichlet_alpha,
129
+ device=device)).sample()
130
+ lp_root = torch.log(
131
+ (1.0 - self.dirichlet_frac) * torch.exp(lp_root) +
132
+ self.dirichlet_frac * noise + EPS)
133
+
134
+ root = _Node(z_root, 0.0, 0) # lp unused at root
135
+ root.lp = 0.0
136
+ # store root log-probs for children priors
137
+ root_p = lp_root
138
+
139
+ max_depth_seen = 0
140
+ for _ in range(self.sims):
141
+ node = root
142
+ path: List[Tuple[_Node, int]] = []
143
+ depth = 0
144
+
145
+ # ---------- select ----------
146
+ while len(node.children) > 0 and depth < self.max_depth:
147
+ best_a, best_u = None, -float("inf")
148
+ tot_n = max(node.n, 1)
149
+ for a, ch in node.children.items():
150
+ u = ch.q + self.c_puct * math.exp(ch.lp) * \
151
+ math.sqrt(tot_n) / (1.0 + ch.n)
152
+ if u > best_u:
153
+ best_u, best_a = u, a
154
+ if best_a is None:
155
+ break
156
+ node = node.children[best_a]
157
+ path.append((node, best_a))
158
+ depth += 1
159
+ max_depth_seen = max(max_depth_seen, depth)
160
+
161
+ # ---------- expand + evaluate ----------
162
+ if depth < self.max_depth and node.depth < self.max_depth:
163
+ if node is root:
164
+ prior_lp = root_p
165
+ else:
166
+ prior_z, _, win_z = m.prediction(node.z)
167
+ prior_lp = F.log_softmax(prior_z[0], dim=0)
168
+ win_prob = torch.softmax(win_z, dim=1)[0, 1].item()
169
+ v = win_prob
170
+ if node is not root:
171
+ pass
172
+ else:
173
+ # root evaluation: policy win prob from the full model
174
+ v = out["win_prob"][0].item()
175
+ # children from top-k prior
176
+ k = min(self.top_k, self.num_actions)
177
+ top = torch.topk(prior_lp, k)
178
+ for a in top.indices.tolist():
179
+ a = int(a)
180
+ if a in node.children:
181
+ continue
182
+ z_next, _r = m.dynamics(
183
+ node.z, self._kind_of(a), self._cell_of(a),
184
+ torch.tensor([self.default_pct], device=device))
185
+ node.children[a] = _Node(z_next,
186
+ float(prior_lp[a]),
187
+ node.depth + 1)
188
+ # if no child was legal/creatable, evaluate the node itself
189
+ if not node.children:
190
+ _, _, win_z = m.prediction(node.z)
191
+ v = torch.softmax(win_z, dim=1)[0, 1].item()
192
+ else:
193
+ # depth limit: evaluate the leaf
194
+ _, _, win_z = m.prediction(node.z)
195
+ v = torch.softmax(win_z, dim=1)[0, 1].item()
196
+
197
+ # ---------- backprop ----------
198
+ for nd, _a in reversed(path):
199
+ nd.n += 1
200
+ nd.w += v
201
+ v *= self.discount
202
+ root.n += 1
203
+ root.w += v
204
+
205
+ # ---------- outcome ----------
206
+ visits = torch.zeros(self.num_actions, device=device)
207
+ for a, ch in root.children.items():
208
+ visits[a] = ch.n
209
+ if self.temperature <= 0 or deterministic:
210
+ chosen = int(torch.argmax(visits).item())
211
+ else:
212
+ p = torch.pow(visits.clamp_min(0.0), 1.0 / self.temperature)
213
+ s = p.sum()
214
+ if s <= EPS:
215
+ chosen = int(torch.argmax(root_p).item())
216
+ else:
217
+ chosen = int(torch.multinomial(
218
+ p / s, 1, generator=self.rng).item())
219
+ probs = visits / max(visits.sum().item(), EPS)
220
+
221
+ kind = chosen // (self.grid * self.grid)
222
+ cell = chosen % (self.grid * self.grid)
223
+
224
+ # final pct from the full policy head at the chosen cell
225
+ H = m.cfg.map_size
226
+ gd = self.grid
227
+ y = (cell // gd) * (H // gd) + (H // gd) // 2
228
+ xc = (cell % gd) * (H // gd) + (H // gd) // 2
229
+ yx = torch.stack([torch.tensor([y]), torch.tensor([xc])],
230
+ dim=0).unsqueeze(0).to(device)
231
+ pct_feat = m._gather(out["dec_feat"], yx)
232
+ ctx_full = m._ctx_full(nums if nums is not None else
233
+ torch.zeros(1, m.cfg.ctx_dim, device=device),
234
+ rtg)
235
+ kind_oh = F.one_hot(torch.tensor([kind], device=device),
236
+ m.cfg.num_kinds).float()
237
+ alpha, beta_p = m.pct_head(pct_feat, ctx_full, kind_oh)
238
+ pct = float((alpha / (alpha + beta_p))[0].item())
239
+
240
+ qs = torch.zeros(self.num_actions, device=device)
241
+ for a, ch in root.children.items():
242
+ qs[a] = ch.q
243
+ expected = float((qs * probs).sum().item())
244
+ q_chosen = float(qs[chosen].item())
245
+ ent = float(-(probs * torch.log(probs + EPS)).sum().item())
246
+
247
+ return SearchResult(
248
+ kind=kind, cell=cell, pct=pct,
249
+ expected_win=expected, q_chosen=q_chosen,
250
+ visits=visits, visit_probs=probs,
251
+ max_depth_reached=max_depth_seen,
252
+ log=dict(sims=self.sims, prior_entropy=ent,
253
+ mean_visits=visits.max().item()))
254
+
255
+
256
+ if __name__ == "__main__":
257
+ # CPU smoke test with a tiny config (full 256px needs a GPU for speed)
258
+ try:
259
+ from model import Sovereign, SovereignConfig, make_model
260
+ except ImportError:
261
+ from nn.model import Sovereign, SovereignConfig, make_model # noqa
262
+
263
+ cfg = SovereignConfig(map_size=64)
264
+ cfg.cortex_layers = 2
265
+ cfg.enc_ch = (32, 32, 64, 96, 160, 224)
266
+ cfg.enc_blocks = (1, 1, 1, 1, 1)
267
+ cfg.dec_plan = ((192, 160, 1), (128, 96, 1), (96, 64, 1),
268
+ (64, 32, 1), (48, None, 1), (32, None, 1))
269
+ cfg.dec_out_ch = 32
270
+ cfg.head_hidden = 512
271
+ cfg.cortex_d = 384
272
+ cfg.cortex_ffn = 1024
273
+ cfg.grid_default = 16
274
+ cfg.use_mem = False
275
+ m = make_model(cfg, seed=0)
276
+ s = Searcher(m, sims=4, max_depth=3, top_k=4)
277
+ rgb = torch.rand(1, 3, 64, 64)
278
+ res = s.search(rgb, torch.rand(1, 8))
279
+ print("search smoke:", res.kind, res.cell, round(res.pct, 3),
280
+ "expected_win", round(res.expected_win, 3),
281
+ "visits", res.visits.sum().item(), "depth", res.max_depth_reached)
282
+ print("search.py smoke OK")