File size: 9,137 Bytes
38fef7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""dag.py: DAgger positions for training OUR net (diloco2.py, env DAG=1, needs TEACHER).

The data holds positions from human / Stockfish lines. In play our search keeps evaluating positions after moves that
nobody in the data chose (autopsy of the gauntlet games: ~2/3 of the lost games start with one blunder in moves 40-80).
So every round, with the current net, the GPU plays our OWN policy (sampled at temperature `temp`) from random data
positions for `L` plies (fastgen: legal moves + make move, all rows at once) and keeps every position it reaches.
The Lc0 teacher labels them for free (policy over the legal moves + value), and a position is drawn into training in
proportion to how wrong our net is on it: |our value - teacher value| + the total variation distance of the two
policies (+ a small floor), i.e. the training goes where the learner's own states are not yet understood.
python dag.py (on a box): smoke test with a small random net and a random "teacher"."""
import torch

from chessnet import planes
from fastgen import FastGen


class Dag:
    def __init__(self, passes=32, R=2048, L=12, temp=0.8, floor=0.02, dev="cuda"):
        self.passes, self.R, self.L, self.temp, self.floor, self.dev = passes, R, L, temp, floor, dev
        self.fg = FastGen()
        self.w = torch.tensor([1 << i for i in range(63)] + [-(1 << 63)], dtype=torch.long, device=dev)
        self.us = self.th = self.fl = self.pr = None
        self.par = torch.arange(R, device=dev)
        self.scr = torch.full((R,), R, dtype=torch.long, device=dev)

    @torch.no_grad()
    def harvest(self, net, roots, teach):
        """roots(n) -> (planes [n, 17, 8, 8], flags [n]) random data positions; teach(x, fl) -> (slots, p, v) as teacher.py.
        Fills the position store (bitboards + flags + draw probabilities); returns (positions, mean score, share of
        positions where the policies differ by >= 0.3 total variation)."""
        was = net.training
        net.eval()
        U, T, F, S = [], [], [], []
        R = self.R
        for _ in range(self.passes):
            x, fl = roots(R)
            bb = (x[:, :12].reshape(R, 12, 64).round().long() * self.w).sum(2)
            us, th, f = bb[:, :6].contiguous(), bb[:, 6:].contiguous(), (fl.long() & 255).contiguous()
            alive = torch.ones(R, dtype=torch.bool, device=self.dev)
            for ply in range(self.L + 1):
                xc = planes(torch.cat([us, th], 1), f).to(memory_format=torch.channels_last)
                with torch.autocast("cuda", torch.bfloat16):
                    pol, val = net(xc)[:2]
                mv, li, nl, _ = self.fg.legal(us, th, f, 128)
                alive &= nl > 0
                lg = pol.float().gather(1, li.clamp(min=0)).masked_fill(mv < 0, -1e9)
                if ply >= 1:                                     # the root is in the data already
                    tli, tp, tv = teach(xc, f)
                    po = torch.softmax(lg, 1)
                    score = (torch.sigmoid(val.float()) - tv).abs() + 0.5 * (po - tp).abs().sum(1) * 0.5
                    ok = alive & (nl > 0)
                    U.append(us[ok]); T.append(th[ok]); F.append(f[ok]); S.append(score[ok])
                if ply == self.L:
                    break
                pi = torch.softmax(lg / self.temp, 1)
                idx = torch.multinomial(pi.nan_to_num(nan=0.0).clamp_min(0) + 1e-12, 1)
                cm = mv.gather(1, idx).squeeze(1).clamp(min=0)
                cu, ct, cf = self.fg.play(torch.cat([us, us[:1]]), torch.cat([th, th[:1]]), torch.cat([f, f[:1]]),
                                          torch.stack([self.par, cm, self.scr]).contiguous(), R)
                us, th, f = cu, ct, cf & 255
        net.train(was)
        self.us, self.th, self.fl, sc = torch.cat(U), torch.cat(T), torch.cat(F), torch.cat(S)
        self.pr = (sc + self.floor)
        self.pr = self.pr / self.pr.sum()
        return len(sc), float(sc.mean()), float((sc >= 0.3).float().mean())

    def draw(self, n):
        """n positions drawn in proportion to the score -> (planes [n, 17, 8, 8], flags [n])."""
        i = torch.multinomial(self.pr, n, replacement=True)
        f = self.fl[i]
        return planes(torch.cat([self.us[i], self.th[i]], 1), f).to(memory_format=torch.channels_last), f


def wait_shards(maxwait, log=print, out="/marimo/chess/dag6", repo="Asilarkness/chess-nets"):
    """dist6: wait (<= maxwait s) for this box's treegen.py to finish, stop it (STOP file: it ends its current root, flushes its
    shard), fetch the shards of the other workers from HF dag6/ -> sorted list of shard files."""
    import glob, os, time
    t0 = time.time()
    while not os.path.exists(f"{out}/DONE") and time.time() - t0 < maxwait:
        time.sleep(15)
    open(f"{out}/STOP", "w").close()
    t1 = time.time()
    while not os.path.exists(f"{out}/DONE") and time.time() - t1 < 180:
        time.sleep(3)
    from huggingface_hub import HfApi, hf_hub_download
    for f in HfApi().list_repo_files(repo):
        if f.startswith("dag6/t") and f.endswith(".pt") and not os.path.exists(f"{out}/{os.path.basename(f)}"):
            os.replace(hf_hub_download(repo, f, local_dir="/marimo/chess/hf"), f"{out}/{os.path.basename(f)}")
    fs = sorted(glob.glob(f"{out}/t*_*.pt"))
    log(f"dag6 shards: {len(fs)} ({time.time() - t0:.0f} s)")
    assert fs, "no treegen shards"
    return fs


class TreeStore:
    """dist6: the rows of treegen.py shards (nodes of Lc0-teacher search trees on positions of our games), kept on the CPU.
    draw(n) -> (planes [n, 17, 8, 8], flags, q [n] subtree expected score, pol [n, 128] visit distribution in fastgen slot order,
    has [n] bool: the node has a visit distribution); rows are drawn in proportion to sqrt(visits)."""

    def __init__(self, files, dev="cuda"):
        parts = [torch.load(f) for f in files]
        off, pp = 0, []
        for p in parts:
            x = p["ppos"].clone()
            x[x >= 0] += off
            pp.append(x)
            off += len(p["pol"])
        cat = lambda k: torch.cat([p[k] for p in parts])
        self.us, self.th, self.fl, self.q = cat("us"), cat("th"), cat("fl").long(), cat("q")
        self.pol, self.ppos, self.dev = cat("pol"), torch.cat(pp).long(), dev
        self.cdf = torch.cumsum(cat("N").double().sqrt(), 0)

    def draw(self, n):
        i = torch.searchsorted(self.cdf, torch.rand(n, dtype=torch.float64) * self.cdf[-1]).clamp(max=len(self.q) - 1)
        us, th, f = self.us[i].to(self.dev), self.th[i].to(self.dev), self.fl[i].to(self.dev)
        pp = self.ppos[i]
        has = (pp >= 0).to(self.dev)
        pol = self.pol[pp.clamp(min=0)].float().to(self.dev) * has[:, None]
        return (planes(torch.cat([us, th], 1), f).to(memory_format=torch.channels_last), f, self.q[i].to(self.dev), pol, has)


if __name__ == "__main__":
    import random
    import time
    import chess
    import gpuchess as G
    from chessnet import Net
    torch.manual_seed(0)
    net = Net(64, 2, 1, 1, 1).cuda().to(memory_format=torch.channels_last)
    rng, bs = random.Random(2), []
    while len(bs) < 4096:
        b = chess.Board()
        for _ in range(rng.randint(4, 60)):
            ms = list(b.legal_moves)
            if not ms:
                break
            b.push(rng.choice(ms))
        if not b.is_game_over():
            bs.append(b)
    u, t_, f = zip(*[G.from_board(b, "cuda") for b in bs])
    X = planes(torch.cat([torch.cat(u), torch.cat(t_)], 1), torch.cat(f)).to(memory_format=torch.channels_last)
    FL = torch.cat(f) & 255
    dag = Dag(passes=4, R=2048, L=8)
    roots = lambda n: (X[:n], FL[:n])

    def teach(x, fl):                                            # a random "teacher" with legal-move probabilities
        n = x.shape[0]
        us2 = (x[:, :12].reshape(n, 12, 64).round().long() * dag.w).sum(2)
        mv, li, nl, _ = dag.fg.legal(us2[:, :6].contiguous(), us2[:, 6:].contiguous(), (fl.long() & 255).contiguous(), 128)
        p = torch.softmax(torch.randn(n, 128, device="cuda").masked_fill(mv < 0, -1e9), 1)
        return li.clamp(min=0), p, torch.rand(n, device="cuda")
    t0 = time.perf_counter()
    n, ms, hi = dag.harvest(net, roots, teach)
    torch.cuda.synchronize()
    print(f"harvested {n} positions in {time.perf_counter() - t0:.1f} s, mean score {ms:.3f}, share >= 0.3: {hi:.2f}")
    assert net.training, "net mode not restored"
    ku = (dag.us[:, 5] != 0).all() and (dag.th[:, 5] != 0).all()
    mv, li, nl, _ = dag.fg.legal(dag.us, dag.th, dag.fl, 128)
    print("both kings on the board:", bool(ku), " positions with a legal move:", bool((nl > 0).all()),
          " distinct:", len(set(map(tuple, torch.cat([dag.us, dag.th], 1)[:5000].tolist()))), "/ 5000 sampled")
    # the sampled positions must be reachable: replay a few of them with python-chess is not possible (the rows are not
    # tracked), so check the planes round trip instead
    x2, f2 = dag.draw(1024)
    bb = (x2[:, :12].reshape(1024, 12, 64).round().long() * dag.w).sum(2)
    print("planes round trip ok:", bool((bb[:, :6] != 0).any()), "x2", tuple(x2.shape))
    print("DAG_OK")