xLeverd commited on
Commit
d341ccf
·
verified ·
1 Parent(s): ac5beb8

Update code and baseline

Browse files
Files changed (1) hide show
  1. model.py +62 -0
model.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compact ResNet policy/value network for the AChess distillation dataset."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+
10
+ class ResBlock(nn.Module):
11
+ def __init__(self, channels: int):
12
+ super().__init__()
13
+ self.bn1 = nn.BatchNorm2d(channels)
14
+ self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
15
+ self.bn2 = nn.BatchNorm2d(channels)
16
+ self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
17
+ nn.init.zeros_(self.bn2.weight)
18
+
19
+ def forward(self, x):
20
+ h = F.relu(self.bn1(x), inplace=True)
21
+ h = self.conv1(h)
22
+ h = self.bn2(h)
23
+ h = self.conv2(h)
24
+ return F.relu(x + h, inplace=True)
25
+
26
+
27
+ class ChessNet(nn.Module):
28
+ def __init__(self, channels: int = 128, blocks: int = 10, planes: int = 20):
29
+ super().__init__()
30
+ self.stem = nn.Sequential(
31
+ nn.Conv2d(planes, channels, 3, padding=1, bias=False),
32
+ nn.BatchNorm2d(channels),
33
+ nn.ReLU(inplace=True),
34
+ )
35
+ self.body = nn.Sequential(*[ResBlock(channels) for _ in range(blocks)])
36
+ # 64 output planes x 64 squares = 4096 (from * 64 + to).
37
+ self.policy = nn.Conv2d(channels, 64, 1)
38
+ self.value_conv = nn.Conv2d(channels, 1, 1)
39
+ self.value_bn = nn.BatchNorm2d(1)
40
+ self.value_fc = nn.Linear(64, 256)
41
+ self.value_out = nn.Linear(256, 1)
42
+ self.wdl_out = nn.Linear(256, 3)
43
+ self._init_weights()
44
+
45
+ def _init_weights(self):
46
+ for module in self.modules():
47
+ if isinstance(module, nn.Conv2d):
48
+ nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
49
+ elif isinstance(module, nn.Linear):
50
+ nn.init.xavier_uniform_(module.weight)
51
+ nn.init.zeros_(module.bias)
52
+
53
+ def forward(self, x, legal_mask=None):
54
+ h = self.body(self.stem(x))
55
+ logits = self.policy(h).flatten(1)
56
+ if legal_mask is not None:
57
+ logits = logits.masked_fill(~legal_mask, -1e4)
58
+ v = F.relu(self.value_bn(self.value_conv(h)), inplace=True).flatten(1)
59
+ v = F.relu(self.value_fc(v), inplace=True)
60
+ value = torch.tanh(self.value_out(v)).squeeze(-1)
61
+ wdl = self.wdl_out(v)
62
+ return logits, value, wdl