File size: 2,328 Bytes
d341ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compact ResNet policy/value network for the AChess distillation dataset."""

from __future__ import annotations

import torch
from torch import nn
from torch.nn import functional as F


class ResBlock(nn.Module):
    def __init__(self, channels: int):
        super().__init__()
        self.bn1 = nn.BatchNorm2d(channels)
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        nn.init.zeros_(self.bn2.weight)

    def forward(self, x):
        h = F.relu(self.bn1(x), inplace=True)
        h = self.conv1(h)
        h = self.bn2(h)
        h = self.conv2(h)
        return F.relu(x + h, inplace=True)


class ChessNet(nn.Module):
    def __init__(self, channels: int = 128, blocks: int = 10, planes: int = 20):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(planes, channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(channels),
            nn.ReLU(inplace=True),
        )
        self.body = nn.Sequential(*[ResBlock(channels) for _ in range(blocks)])
        # 64 output planes x 64 squares = 4096 (from * 64 + to).
        self.policy = nn.Conv2d(channels, 64, 1)
        self.value_conv = nn.Conv2d(channels, 1, 1)
        self.value_bn = nn.BatchNorm2d(1)
        self.value_fc = nn.Linear(64, 256)
        self.value_out = nn.Linear(256, 1)
        self.wdl_out = nn.Linear(256, 3)
        self._init_weights()

    def _init_weights(self):
        for module in self.modules():
            if isinstance(module, nn.Conv2d):
                nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
            elif isinstance(module, nn.Linear):
                nn.init.xavier_uniform_(module.weight)
                nn.init.zeros_(module.bias)

    def forward(self, x, legal_mask=None):
        h = self.body(self.stem(x))
        logits = self.policy(h).flatten(1)
        if legal_mask is not None:
            logits = logits.masked_fill(~legal_mask, -1e4)
        v = F.relu(self.value_bn(self.value_conv(h)), inplace=True).flatten(1)
        v = F.relu(self.value_fc(v), inplace=True)
        value = torch.tanh(self.value_out(v)).squeeze(-1)
        wdl = self.wdl_out(v)
        return logits, value, wdl