amer224 commited on
Commit
3219a42
·
verified ·
1 Parent(s): d36c2de

Add brains/sovereign-v3/distill.py

Browse files
Files changed (1) hide show
  1. brains/sovereign-v3/distill.py +141 -0
brains/sovereign-v3/distill.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ distill.py — wake-sleep distillation: big SOVEREIGN -> small student.
3
+
4
+ The 290M teacher trains slowly; the league + rollout loop wants speed.
5
+ The wake-sleep loop (train_notes.md Stage C):
6
+
7
+ SLEEP big teacher PPO-trains (wake: search + league rollouts)
8
+ WAKE distill teacher -> ~30-40M student (KL on kind/cell heatmaps,
9
+ MSE on value/pct params)
10
+ ROLL student runs the rollouts 2-3x faster, generating richer
11
+ league self-play data for the teacher
12
+
13
+ Also used to distill MCTS visit targets into the policy (pass
14
+ `search_targets` = (3*g*g,) visit-prob vectors per batch — the AlphaZero
15
+ policy-improvement operator).
16
+
17
+ torch only. Batches must be dicts with at least:
18
+ rgb (B,3,H,W) · nums (B,8) · rtg (B,1) · cell (B,)
19
+ optional: pct (B,), search_targets (B,3*g*g)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Iterator, Optional
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+
29
+
30
+ def small_config():
31
+ """~35M dense student — same contract, same heads, thinner everything."""
32
+ from model import SovereignConfig # deferred import: model is big
33
+ c = SovereignConfig()
34
+ c.enc_ch = (48, 48, 80, 144, 256, 416)
35
+ c.enc_blocks = (1, 2, 2, 2, 2)
36
+ c.cortex_d = 512
37
+ c.cortex_ffn = 2048
38
+ c.cortex_layers = 2
39
+ c.dec_plan = ((512, 256, 1), (256, 144, 1), (144, 80, 1),
40
+ (80, 48, 1), (48, None, 1), (32, None, 1))
41
+ c.dec_out_ch = 32
42
+ c.head_hidden = 1024
43
+ c.heat_hidden = 64
44
+ c.tower_hidden = 96
45
+ c.pct_hidden = 256
46
+ c.mem_hidden = 256
47
+ c.use_mem = False
48
+ return c
49
+
50
+
51
+ def _to(batch: dict, device: torch.device) -> dict:
52
+ out = {}
53
+ for k in ("rgb", "nums", "rtg", "cell", "pct", "search_targets"):
54
+ if k in batch:
55
+ out[k] = batch[k].to(device)
56
+ return out
57
+
58
+
59
+ def distill(teacher, student, batches: Iterator[dict], epochs: int = 1,
60
+ lr: float = 3e-4, kl_cell: float = 1.0, kl_kind: float = 1.0,
61
+ mse_val: float = 1.0, mse_pct: float = 0.5,
62
+ ce_cell: float = 0.25, search_w: float = 0.5,
63
+ device: str = "cuda") -> None:
64
+ """KL on the per-kind heatmaps + hard-cell CE + value/pct regression +
65
+ optional search-target distillation."""
66
+ teacher.to(device).eval()
67
+ student.to(device).train()
68
+ opt = torch.optim.AdamW(student.parameters(), lr=lr)
69
+ dev = torch.device(device)
70
+
71
+ for ep in range(epochs):
72
+ tot, nb = 0.0, 0
73
+ for raw in batches:
74
+ b = _to(raw, dev)
75
+ rgb, nums = b["rgb"], b["nums"]
76
+ rtg = b["rtg"] if "rtg" in b else torch.zeros(
77
+ nums.shape[0], 1, device=dev)
78
+ cell = b["cell"]
79
+ with torch.no_grad():
80
+ to = teacher(rgb, nums, rtg=rtg, cell=cell,
81
+ return_all=True)
82
+ so = student(rgb, nums, rtg=rtg, cell=cell, return_all=True)
83
+
84
+ loss = 0.0
85
+ loss = loss + kl_cell * F.kl_div(
86
+ F.log_softmax(so["cell_logits"], 1),
87
+ F.softmax(to["cell_logits"], 1), reduction="batchmean")
88
+ loss = loss + kl_kind * F.kl_div(
89
+ F.log_softmax(so["kind_logits"], 1),
90
+ F.softmax(to["kind_logits"], 1), reduction="batchmean")
91
+ loss = loss + mse_val * F.mse_loss(so["value"], to["value"])
92
+ loss = loss + mse_pct * (
93
+ F.mse_loss(so["pct_params"][0], to["pct_params"][0]) +
94
+ F.mse_loss(so["pct_params"][1], to["pct_params"][1]))
95
+ loss = loss + ce_cell * F.cross_entropy(so["cell_logits"], cell)
96
+ if "search_targets" in b:
97
+ loss = loss + search_w * F.kl_div(
98
+ F.log_softmax(so["cell_logits"], 1),
99
+ b["search_targets"].clamp_min(1e-6), reduction="batchmean")
100
+
101
+ opt.zero_grad()
102
+ loss.backward()
103
+ opt.step()
104
+ tot += loss.item()
105
+ nb += 1
106
+ print(f"distill ep {ep+1}: loss={tot/max(nb,1):.4f}", flush=True)
107
+
108
+
109
+ def save_student(student, path: str) -> None:
110
+ torch.save({"config": student.cfg, "state_dict": student.state_dict()},
111
+ path)
112
+ print(f"[distill] saved {path}")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ # smoke: teacher = small model, student = even smaller, one fake batch
117
+ from model import Sovereign, SovereignConfig, count_params
118
+
119
+ cfg = small_config()
120
+ cfg.map_size = 64
121
+ cfg.grid_default = 16
122
+ cfg.use_search = False
123
+ cfg.use_gate = False
124
+ cfg.use_dynamics = False
125
+ teacher = Sovereign(cfg)
126
+ cfg2 = SovereignConfig(map_size=64, grid_default=16, use_search=False,
127
+ use_gate=False, use_dynamics=False)
128
+ cfg2.cortex_d = 256
129
+ cfg2.cortex_ffn = 1024
130
+ cfg2.enc_ch = (24, 24, 48, 72, 128, 160)
131
+ cfg2.dec_plan = ((128, 128, 1), (96, 72, 1), (72, 48, 1),
132
+ (48, 24, 1), (32, None, 1), (24, None, 1))
133
+ cfg2.dec_out_ch = 24
134
+ student = Sovereign(cfg2)
135
+ print("teacher", count_params(teacher) / 1e6, "M | student",
136
+ count_params(student) / 1e6, "M")
137
+ batch = [dict(rgb=torch.rand(2, 3, 64, 64), nums=torch.rand(2, 8),
138
+ rtg=torch.rand(2, 1),
139
+ cell=torch.tensor([10, 40]))]
140
+ distill(teacher, student, iter(batch), epochs=1, device="cpu")
141
+ print("distill.py smoke OK")