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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chess Transformer Model for the Chess Challenge.
|
| 3 |
+
|
| 4 |
+
This module provides a simple GPT-style transformer architecture
|
| 5 |
+
designed to fit within the 1M parameter constraint.
|
| 6 |
+
|
| 7 |
+
Key components:
|
| 8 |
+
- ChessConfig: Configuration class for model hyperparameters
|
| 9 |
+
- ChessForCausalLM: The main model class for next-move prediction
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 22 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RMSNorm(nn.Module):
|
| 26 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.eps = eps
|
| 29 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
|
| 33 |
+
|
| 34 |
+
class RotaryEmbedding(nn.Module):
|
| 35 |
+
def __init__(self, dim, max_seq_len=256):
|
| 36 |
+
super().__init__()
|
| 37 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
| 38 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 39 |
+
|
| 40 |
+
def forward(self, x, seq_len):
|
| 41 |
+
t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
|
| 42 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 43 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 44 |
+
return emb[None, :, None, :]
|
| 45 |
+
|
| 46 |
+
def apply_rotary_emb(q, k, freqs):
|
| 47 |
+
def rotate_half(x):
|
| 48 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 49 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 50 |
+
|
| 51 |
+
q_rot = (q * freqs.cos()) + (rotate_half(q) * freqs.sin())
|
| 52 |
+
k_rot = (k * freqs.cos()) + (rotate_half(k) * freqs.sin())
|
| 53 |
+
return q_rot, k_rot
|
| 54 |
+
|
| 55 |
+
class SwiGLU(nn.Module):
|
| 56 |
+
def __init__(self, dim: int, inner_dim: int, dropout: float):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.w1 = nn.Linear(dim, inner_dim, bias=False)
|
| 59 |
+
self.w2 = nn.Linear(inner_dim, dim, bias=False)
|
| 60 |
+
self.w3 = nn.Linear(dim, inner_dim, bias=False)
|
| 61 |
+
self.dropout = nn.Dropout(dropout)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
# L'essence de SwiGLU : (SiLU(W1x) * W3x) * W2
|
| 65 |
+
return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
|
| 66 |
+
|
| 67 |
+
class ModernAttention(nn.Module):
|
| 68 |
+
def __init__(self, config):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.n_head = config.n_head
|
| 71 |
+
self.head_dim = config.n_embd // config.n_head
|
| 72 |
+
|
| 73 |
+
self.wq = nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 74 |
+
self.wk = nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 75 |
+
self.wv = nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 76 |
+
self.wo = nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 77 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 78 |
+
|
| 79 |
+
def forward(self, x, freqs, mask=None):
|
| 80 |
+
bsz, seqlen, _ = x.shape
|
| 81 |
+
q, k, v = self.wq(x), self.wk(x), self.wv(x)
|
| 82 |
+
|
| 83 |
+
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 84 |
+
k = k.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 85 |
+
v = v.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 86 |
+
|
| 87 |
+
q, k = apply_rotary_emb(q, k, freqs)
|
| 88 |
+
|
| 89 |
+
scores = torch.matmul(q.transpose(1, 2), k.transpose(1, 2).transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 90 |
+
|
| 91 |
+
if mask is not None:
|
| 92 |
+
scores = scores + mask[:, :, :seqlen, :seqlen]
|
| 93 |
+
|
| 94 |
+
scores = F.softmax(scores.float(), dim=-1).type_as(q)
|
| 95 |
+
output = torch.matmul(scores, v.transpose(1, 2))
|
| 96 |
+
output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
|
| 97 |
+
return self.dropout(self.wo(output))
|
| 98 |
+
|
| 99 |
+
class ModernBlock(nn.Module):
|
| 100 |
+
def __init__(self, config):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.attention = ModernAttention(config)
|
| 103 |
+
self.feed_forward = SwiGLU(config.n_embd, config.n_inner, config.dropout)
|
| 104 |
+
self.attention_norm = RMSNorm(config.n_embd)
|
| 105 |
+
self.ffn_norm = RMSNorm(config.n_embd)
|
| 106 |
+
|
| 107 |
+
def forward(self, x, freqs, mask):
|
| 108 |
+
x = x + self.attention(self.attention_norm(x), freqs, mask)
|
| 109 |
+
x = x + self.feed_forward(self.ffn_norm(x))
|
| 110 |
+
return x
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class ChessConfig(PretrainedConfig):
|
| 117 |
+
"""
|
| 118 |
+
Configuration class for the Chess Transformer model.
|
| 119 |
+
|
| 120 |
+
This configuration is designed for a ~1M parameter model.
|
| 121 |
+
Students can adjust these values to explore different architectures.
|
| 122 |
+
|
| 123 |
+
Parameter budget breakdown (with default values):
|
| 124 |
+
- Embeddings (vocab): 1200 x 128 = 153,600
|
| 125 |
+
- Position Embeddings: 256 x 128 = 32,768
|
| 126 |
+
- Transformer Layers: 6 x ~120,000 = ~720,000
|
| 127 |
+
- LM Head (with weight tying): 0 (shared with embeddings)
|
| 128 |
+
- Total: ~906,000 parameters
|
| 129 |
+
|
| 130 |
+
Attributes:
|
| 131 |
+
vocab_size: Size of the vocabulary (number of unique moves).
|
| 132 |
+
n_embd: Embedding dimension (d_model).
|
| 133 |
+
n_layer: Number of transformer layers.
|
| 134 |
+
n_head: Number of attention heads.
|
| 135 |
+
n_ctx: Maximum sequence length (context window).
|
| 136 |
+
n_inner: Feed-forward inner dimension (default: 3 * n_embd).
|
| 137 |
+
dropout: Dropout probability.
|
| 138 |
+
layer_norm_epsilon: Epsilon for layer normalization.
|
| 139 |
+
tie_weights: Whether to tie embedding and output weights.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
model_type = "chess_transformer"
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
vocab_size: int = 1200,
|
| 147 |
+
n_embd: int = 128,
|
| 148 |
+
n_layer: int = 6,
|
| 149 |
+
n_head: int = 8,
|
| 150 |
+
n_ctx: int = 256,
|
| 151 |
+
n_inner: Optional[int] = None,
|
| 152 |
+
dropout: float = 0.1,
|
| 153 |
+
layer_norm_epsilon: float = 1e-5,
|
| 154 |
+
tie_weights: bool = True,
|
| 155 |
+
pad_token_id: int = 0,
|
| 156 |
+
bos_token_id: int = 1,
|
| 157 |
+
eos_token_id: int = 2,
|
| 158 |
+
**kwargs,
|
| 159 |
+
):
|
| 160 |
+
super().__init__(
|
| 161 |
+
pad_token_id=pad_token_id,
|
| 162 |
+
bos_token_id=bos_token_id,
|
| 163 |
+
eos_token_id=eos_token_id,
|
| 164 |
+
**kwargs,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
self.vocab_size = vocab_size
|
| 168 |
+
self.n_embd = n_embd
|
| 169 |
+
self.n_layer = n_layer
|
| 170 |
+
self.n_head = n_head
|
| 171 |
+
self.n_ctx = n_ctx
|
| 172 |
+
self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
|
| 173 |
+
self.dropout = dropout
|
| 174 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 175 |
+
self.tie_weights = tie_weights
|
| 176 |
+
# Inform HF base class about tying behavior
|
| 177 |
+
self.tie_word_embeddings = bool(tie_weights)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class MultiHeadAttention(nn.Module):
|
| 181 |
+
"""
|
| 182 |
+
Multi-head self-attention module.
|
| 183 |
+
|
| 184 |
+
This is a standard scaled dot-product attention implementation
|
| 185 |
+
with causal masking for autoregressive generation.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
def __init__(self, config: ChessConfig):
|
| 189 |
+
super().__init__()
|
| 190 |
+
|
| 191 |
+
assert config.n_embd % config.n_head == 0, \
|
| 192 |
+
f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
|
| 193 |
+
|
| 194 |
+
self.n_head = config.n_head
|
| 195 |
+
self.n_embd = config.n_embd
|
| 196 |
+
self.head_dim = config.n_embd // config.n_head
|
| 197 |
+
|
| 198 |
+
# Combined QKV projection for efficiency
|
| 199 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 200 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 201 |
+
|
| 202 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 203 |
+
|
| 204 |
+
# Causal mask (will be created on first forward pass)
|
| 205 |
+
self.register_buffer(
|
| 206 |
+
"bias",
|
| 207 |
+
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
|
| 208 |
+
1, 1, config.n_ctx, config.n_ctx
|
| 209 |
+
),
|
| 210 |
+
persistent=False,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def forward(
|
| 214 |
+
self,
|
| 215 |
+
x: torch.Tensor,
|
| 216 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 217 |
+
) -> torch.Tensor:
|
| 218 |
+
batch_size, seq_len, _ = x.size()
|
| 219 |
+
|
| 220 |
+
# Compute Q, K, V
|
| 221 |
+
qkv = self.c_attn(x)
|
| 222 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 223 |
+
|
| 224 |
+
# Reshape for multi-head attention
|
| 225 |
+
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 226 |
+
k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 227 |
+
v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 228 |
+
|
| 229 |
+
# Scaled dot-product attention
|
| 230 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 231 |
+
|
| 232 |
+
# Apply causal mask
|
| 233 |
+
causal_mask = self.bias[:, :, :seq_len, :seq_len]
|
| 234 |
+
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
|
| 235 |
+
|
| 236 |
+
# Apply attention mask (for padding)
|
| 237 |
+
if attention_mask is not None:
|
| 238 |
+
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
|
| 239 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 240 |
+
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
|
| 241 |
+
|
| 242 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 243 |
+
attn_weights = self.dropout(attn_weights)
|
| 244 |
+
|
| 245 |
+
# Apply attention to values
|
| 246 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 247 |
+
|
| 248 |
+
# Reshape back
|
| 249 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(
|
| 250 |
+
batch_size, seq_len, self.n_embd
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Output projection
|
| 254 |
+
attn_output = self.c_proj(attn_output)
|
| 255 |
+
|
| 256 |
+
return attn_output
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class FeedForward(nn.Module):
|
| 260 |
+
"""
|
| 261 |
+
Feed-forward network (MLP) module.
|
| 262 |
+
|
| 263 |
+
Standard two-layer MLP with GELU activation.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
def __init__(self, config: ChessConfig):
|
| 267 |
+
super().__init__()
|
| 268 |
+
|
| 269 |
+
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
|
| 270 |
+
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
|
| 271 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 272 |
+
|
| 273 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 274 |
+
x = self.c_fc(x)
|
| 275 |
+
x = F.gelu(x)
|
| 276 |
+
x = self.c_proj(x)
|
| 277 |
+
x = self.dropout(x)
|
| 278 |
+
return x
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class TransformerBlock(nn.Module):
|
| 282 |
+
"""
|
| 283 |
+
A single transformer block with attention and feed-forward layers.
|
| 284 |
+
|
| 285 |
+
Uses pre-normalization (LayerNorm before attention/FFN) for better
|
| 286 |
+
training stability.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
def __init__(self, config: ChessConfig):
|
| 290 |
+
super().__init__()
|
| 291 |
+
|
| 292 |
+
self.ln_1 = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 293 |
+
self.attn = MultiHeadAttention(config)
|
| 294 |
+
self.ln_2 = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 295 |
+
self.mlp = FeedForward(config)
|
| 296 |
+
|
| 297 |
+
def forward(
|
| 298 |
+
self,
|
| 299 |
+
x: torch.Tensor,
|
| 300 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 301 |
+
) -> torch.Tensor:
|
| 302 |
+
# Pre-norm attention
|
| 303 |
+
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
|
| 304 |
+
# Pre-norm FFN
|
| 305 |
+
x = x + self.mlp(self.ln_2(x))
|
| 306 |
+
return x
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class ChessForCausalLM(PreTrainedModel):
|
| 310 |
+
config_class = ChessConfig
|
| 311 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 312 |
+
|
| 313 |
+
def __init__(self, config: ChessConfig):
|
| 314 |
+
super().__init__(config)
|
| 315 |
+
|
| 316 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 317 |
+
|
| 318 |
+
self.rope = RotaryEmbedding(config.n_embd // config.n_head)
|
| 319 |
+
|
| 320 |
+
self.drop = nn.Dropout(config.dropout)
|
| 321 |
+
self.h = nn.ModuleList([ModernBlock(config) for _ in range(config.n_layer)])
|
| 322 |
+
self.ln_f = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 323 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 324 |
+
|
| 325 |
+
self.post_init()
|
| 326 |
+
if config.tie_weights:
|
| 327 |
+
self.tie_weights()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def forward(
|
| 331 |
+
self,
|
| 332 |
+
input_ids: torch.LongTensor,
|
| 333 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 334 |
+
labels: Optional[torch.LongTensor] = None,
|
| 335 |
+
return_dict: Optional[bool] = None,
|
| 336 |
+
**kwargs,
|
| 337 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 338 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 339 |
+
batch_size, seq_len = input_ids.size()
|
| 340 |
+
device = input_ids.device
|
| 341 |
+
|
| 342 |
+
freqs = self.rope(input_ids, seq_len)
|
| 343 |
+
|
| 344 |
+
mask = torch.full((seq_len, seq_len), float("-inf"), device=device)
|
| 345 |
+
mask = torch.triu(mask, diagonal=1)
|
| 346 |
+
mask = mask.view(1, 1, seq_len, seq_len)
|
| 347 |
+
|
| 348 |
+
hidden_states = self.drop(self.wte(input_ids))
|
| 349 |
+
|
| 350 |
+
for block in self.h:
|
| 351 |
+
hidden_states = block(hidden_states, freqs, mask)
|
| 352 |
+
|
| 353 |
+
hidden_states = self.ln_f(hidden_states)
|
| 354 |
+
logits = self.lm_head(hidden_states)
|
| 355 |
+
|
| 356 |
+
loss = None
|
| 357 |
+
if labels is not None:
|
| 358 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 359 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 360 |
+
loss = F.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
| 361 |
+
|
| 362 |
+
if not return_dict:
|
| 363 |
+
output = (logits,)
|
| 364 |
+
return ((loss,) + output) if loss is not None else output
|
| 365 |
+
|
| 366 |
+
return CausalLMOutputWithPast(
|
| 367 |
+
loss=loss,
|
| 368 |
+
logits=logits,
|
| 369 |
+
past_key_values=None,
|
| 370 |
+
hidden_states=None,
|
| 371 |
+
attentions=None,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
def get_input_embeddings(self):
|
| 375 |
+
return self.wte
|
| 376 |
+
|
| 377 |
+
def set_input_embeddings(self, value):
|
| 378 |
+
self.wte = value
|
| 379 |
+
|
| 380 |
+
def get_output_embeddings(self):
|
| 381 |
+
return self.lm_head
|
| 382 |
+
|
| 383 |
+
def set_output_embeddings(self, new_embeddings):
|
| 384 |
+
self.lm_head = new_embeddings
|
| 385 |
+
|
| 386 |
+
def tie_weights(self):
|
| 387 |
+
"""
|
| 388 |
+
C'est cette méthode que HF appelle automatiquement si
|
| 389 |
+
config.tie_word_embeddings est True.
|
| 390 |
+
"""
|
| 391 |
+
self._tie_or_clone_weights(self.lm_head, self.wte)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
# Register the model with Auto classes for easy loading
|
| 395 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 396 |
+
|
| 397 |
+
AutoConfig.register("chess_transformer", ChessConfig)
|
| 398 |
+
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
|