Valbad commited on
Commit
b77fee8
·
verified ·
1 Parent(s): a4f28c6

Chess Challenge submission by Valbad

Browse files
Files changed (1) hide show
  1. model.py +444 -0
model.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ChessConfig(PretrainedConfig):
26
+ """
27
+ Configuration class for the Chess Transformer model.
28
+
29
+ This configuration is designed for a ~1M parameter model.
30
+ Students can adjust these values to explore different architectures.
31
+
32
+ Parameter budget breakdown (with default values):
33
+ - Embeddings (vocab): 1200 x 128 = 153,600
34
+ - Position Embeddings: 256 x 128 = 32,768
35
+ - Transformer Layers: 6 x ~120,000 = ~720,000
36
+ - LM Head (with weight tying): 0 (shared with embeddings)
37
+ - Total: ~906,000 parameters
38
+
39
+ Attributes:
40
+ vocab_size: Size of the vocabulary (number of unique moves).
41
+ n_embd: Embedding dimension (d_model).
42
+ n_layer: Number of transformer layers.
43
+ n_head: Number of attention heads.
44
+ n_ctx: Maximum sequence length (context window).
45
+ n_inner: Feed-forward inner dimension (default: 3 * n_embd).
46
+ dropout: Dropout probability.
47
+ layer_norm_epsilon: Epsilon for layer normalization.
48
+ tie_weights: Whether to tie embedding and output weights.
49
+ """
50
+
51
+ model_type = "chess_transformer"
52
+
53
+ def __init__(
54
+ self,
55
+ vocab_size: int = 1200,
56
+ n_embd: int = 128,
57
+ n_layer: int = 6,
58
+ n_head: int = 4,
59
+ n_ctx: int = 256,
60
+ n_inner: Optional[int] = None,
61
+ dropout: float = 0.1,
62
+ layer_norm_epsilon: float = 1e-5,
63
+ tie_weights: bool = True,
64
+ pad_token_id: int = 0,
65
+ bos_token_id: int = 1,
66
+ eos_token_id: int = 2,
67
+ **kwargs,
68
+ ):
69
+ super().__init__(
70
+ pad_token_id=pad_token_id,
71
+ bos_token_id=bos_token_id,
72
+ eos_token_id=eos_token_id,
73
+ **kwargs,
74
+ )
75
+
76
+ self.vocab_size = vocab_size
77
+ self.n_embd = n_embd
78
+ self.n_layer = n_layer
79
+ self.n_head = n_head
80
+ self.n_ctx = n_ctx
81
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
82
+ self.dropout = dropout
83
+ self.layer_norm_epsilon = layer_norm_epsilon
84
+ self.tie_weights = tie_weights
85
+ # Inform HF base class about tying behavior
86
+ self.tie_word_embeddings = bool(tie_weights)
87
+
88
+
89
+ class MultiHeadAttention(nn.Module):
90
+ """
91
+ Multi-head self-attention module.
92
+
93
+ This is a standard scaled dot-product attention implementation
94
+ with causal masking for autoregressive generation.
95
+ """
96
+
97
+ def __init__(self, config: ChessConfig):
98
+ super().__init__()
99
+
100
+ assert config.n_embd % config.n_head == 0, \
101
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
102
+
103
+ self.n_head = config.n_head
104
+ self.n_embd = config.n_embd
105
+ self.head_dim = config.n_embd // config.n_head
106
+
107
+ # Combined QKV projection for efficiency
108
+ # self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd) # v0
109
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias = False) # v1
110
+ # self.c_proj = nn.Linear(config.n_embd, config.n_embd) # v0
111
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias = False) # v1
112
+
113
+ self.dropout = nn.Dropout(config.dropout) # v0&1
114
+ self.resid_dropout = nn.Dropout(config.dropout) # v1
115
+ # Causal mask (will be created on first forward pass)
116
+ self.register_buffer(
117
+ "bias",
118
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
119
+ 1, 1, config.n_ctx, config.n_ctx
120
+ ),
121
+ persistent=False,
122
+ )
123
+
124
+ def forward(
125
+ self,
126
+ x: torch.Tensor,
127
+ attention_mask: Optional[torch.Tensor] = None,
128
+ ) -> torch.Tensor:
129
+ batch_size, seq_len, _ = x.size()
130
+
131
+ # Compute Q, K, V
132
+ qkv = self.c_attn(x)
133
+ q, k, v = qkv.split(self.n_embd, dim=2)
134
+
135
+ # Reshape for multi-head attention
136
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
137
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
138
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
139
+
140
+ # Scaled dot-product attention
141
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
142
+
143
+ # Apply causal mask
144
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
145
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
146
+
147
+ # Apply attention mask (for padding)
148
+ if attention_mask is not None:
149
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
150
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
151
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
152
+
153
+ attn_weights = F.softmax(attn_weights, dim=-1)
154
+ attn_weights = self.dropout(attn_weights)
155
+
156
+ # Apply attention to values
157
+ attn_output = torch.matmul(attn_weights, v)
158
+
159
+ # Reshape back
160
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
161
+ batch_size, seq_len, self.n_embd
162
+ )
163
+
164
+ # Output projection
165
+ attn_output = self.c_proj(attn_output)
166
+ attn_output = self.resid_dropout(attn_output)
167
+
168
+ return attn_output
169
+
170
+
171
+ class FeedForward(nn.Module):
172
+ """
173
+ Feed-forward network (MLP) module.
174
+
175
+ Standard two-layer MLP with GELU activation.
176
+ """
177
+
178
+ def __init__(self, config: ChessConfig):
179
+ super().__init__()
180
+
181
+ # self.c_fc = nn.Linear(config.n_embd, config.n_inner) # v0
182
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner, bias = False) # v1
183
+ # self.c_proj = nn.Linear(config.n_inner, config.n_embd) # v0
184
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd, bias = False) # v1
185
+
186
+ self.dropout = nn.Dropout(config.dropout)
187
+
188
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
189
+ x = self.c_fc(x)
190
+ x = F.gelu(x)
191
+ x = self.c_proj(x)
192
+ x = self.dropout(x)
193
+ return x
194
+
195
+
196
+ class TransformerBlock(nn.Module):
197
+ """
198
+ A single transformer block with attention and feed-forward layers.
199
+
200
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
201
+ training stability.
202
+ """
203
+
204
+ def __init__(self, config: ChessConfig):
205
+ super().__init__()
206
+
207
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
208
+ self.attn = MultiHeadAttention(config)
209
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
210
+ self.mlp = FeedForward(config)
211
+
212
+ def forward(
213
+ self,
214
+ x: torch.Tensor,
215
+ attention_mask: Optional[torch.Tensor] = None,
216
+ ) -> torch.Tensor:
217
+ # Pre-norm attention
218
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
219
+ # Pre-norm FFN
220
+ x = x + self.mlp(self.ln_2(x))
221
+ return x
222
+
223
+
224
+ class ChessForCausalLM(PreTrainedModel):
225
+ """
226
+ Chess Transformer for Causal Language Modeling (next-move prediction).
227
+
228
+ This model is designed to predict the next chess move given a sequence
229
+ of previous moves. It uses a GPT-style architecture with:
230
+ - Token embeddings for chess moves
231
+ - Learned positional embeddings
232
+ - Stacked transformer blocks
233
+ - Linear head for next-token prediction
234
+
235
+ The model supports weight tying between the embedding layer and the
236
+ output projection to save parameters.
237
+
238
+ Example:
239
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
240
+ >>> model = ChessForCausalLM(config)
241
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
242
+ >>> outputs = model(**inputs)
243
+ >>> next_move_logits = outputs.logits[:, -1, :]
244
+ """
245
+
246
+ config_class = ChessConfig
247
+ base_model_prefix = "transformer"
248
+ supports_gradient_checkpointing = True
249
+ # Suppress missing-key warning for tied lm_head when loading
250
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
251
+
252
+ def __init__(self, config: ChessConfig):
253
+ super().__init__(config)
254
+
255
+ # Token and position embeddings
256
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
257
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
258
+
259
+ self.drop = nn.Dropout(config.dropout)
260
+
261
+ # Transformer blocks
262
+ self.h = nn.ModuleList([
263
+ TransformerBlock(config) for _ in range(config.n_layer)
264
+ ])
265
+
266
+ # Final layer norm
267
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
268
+
269
+ # Output head
270
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
271
+
272
+ # Declare tied weights for proper serialization
273
+ if config.tie_weights:
274
+ self._tied_weights_keys = ["lm_head.weight"]
275
+
276
+ # Initialize weights
277
+ self.post_init()
278
+
279
+ # Tie weights if configured
280
+ if config.tie_weights:
281
+ self.tie_weights()
282
+
283
+ def get_input_embeddings(self) -> nn.Module:
284
+ return self.wte
285
+
286
+ def set_input_embeddings(self, new_embeddings: nn.Module):
287
+ self.wte = new_embeddings
288
+ if getattr(self.config, "tie_weights", False):
289
+ self.tie_weights()
290
+
291
+ def get_output_embeddings(self) -> nn.Module:
292
+ return self.lm_head
293
+
294
+ def set_output_embeddings(self, new_embeddings: nn.Module):
295
+ self.lm_head = new_embeddings
296
+
297
+ def tie_weights(self):
298
+ # Use HF helper to tie or clone depending on config
299
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
300
+ self._tie_or_clone_weights(self.lm_head, self.wte)
301
+
302
+ def _init_weights(self, module: nn.Module):
303
+ """Initialize weights following GPT-2 style."""
304
+ if isinstance(module, nn.Linear):
305
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
306
+ if module.bias is not None:
307
+ torch.nn.init.zeros_(module.bias)
308
+ elif isinstance(module, nn.Embedding):
309
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
310
+ elif isinstance(module, nn.LayerNorm):
311
+ torch.nn.init.ones_(module.weight)
312
+ torch.nn.init.zeros_(module.bias)
313
+
314
+ def forward(
315
+ self,
316
+ input_ids: torch.LongTensor,
317
+ attention_mask: Optional[torch.Tensor] = None,
318
+ position_ids: Optional[torch.LongTensor] = None,
319
+ labels: Optional[torch.LongTensor] = None,
320
+ return_dict: Optional[bool] = None,
321
+ **kwargs,
322
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
323
+ """
324
+ Forward pass of the model.
325
+
326
+ Args:
327
+ input_ids: Token IDs of shape (batch_size, seq_len).
328
+ attention_mask: Attention mask of shape (batch_size, seq_len).
329
+ position_ids: Position IDs of shape (batch_size, seq_len).
330
+ labels: Labels for language modeling loss.
331
+ return_dict: Whether to return a ModelOutput object.
332
+
333
+ Returns:
334
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
335
+ """
336
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
337
+
338
+ batch_size, seq_len = input_ids.size()
339
+ device = input_ids.device
340
+
341
+ # Create position IDs if not provided
342
+ if position_ids is None:
343
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
344
+
345
+ # Get embeddings
346
+ token_embeds = self.wte(input_ids)
347
+ position_embeds = self.wpe(position_ids)
348
+ hidden_states = self.drop(token_embeds + position_embeds)
349
+
350
+ # Pass through transformer blocks
351
+ for block in self.h:
352
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
353
+
354
+ # Final layer norm
355
+ hidden_states = self.ln_f(hidden_states)
356
+
357
+ # Get logits
358
+ logits = self.lm_head(hidden_states)
359
+
360
+ # Compute loss if labels are provided
361
+ loss = None
362
+ if labels is not None:
363
+ # Shift logits and labels for next-token prediction
364
+ shift_logits = logits[..., :-1, :].contiguous()
365
+ shift_labels = labels[..., 1:].contiguous()
366
+
367
+ # Flatten for cross-entropy
368
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
369
+ # loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
370
+ loss = loss_fct(
371
+ shift_logits.view(-1, shift_logits.size(-1)),
372
+ shift_labels.view(-1),
373
+ )
374
+
375
+ if not return_dict:
376
+ output = (logits,)
377
+ return ((loss,) + output) if loss is not None else output
378
+
379
+ return CausalLMOutputWithPast(
380
+ loss=loss,
381
+ logits=logits,
382
+ past_key_values=None,
383
+ hidden_states=None,
384
+ attentions=None,
385
+ )
386
+
387
+ @torch.no_grad()
388
+ def generate_move(
389
+ self,
390
+ input_ids: torch.LongTensor,
391
+ temperature: float = 1.0,
392
+ top_k: Optional[int] = None,
393
+ top_p: Optional[float] = None,
394
+ ) -> int:
395
+ """
396
+ Generate the next move given a sequence of moves.
397
+
398
+ Args:
399
+ input_ids: Token IDs of shape (1, seq_len).
400
+ temperature: Sampling temperature (1.0 = no change).
401
+ top_k: If set, only sample from top k tokens.
402
+ top_p: If set, use nucleus sampling with this threshold.
403
+
404
+ Returns:
405
+ The token ID of the predicted next move.
406
+ """
407
+ self.eval()
408
+
409
+ # Get logits for the last position
410
+ outputs = self(input_ids)
411
+ logits = outputs.logits[:, -1, :] / temperature
412
+
413
+ # Apply top-k filtering
414
+ if top_k is not None:
415
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
416
+ logits[indices_to_remove] = float("-inf")
417
+
418
+ # Apply top-p (nucleus) filtering
419
+ if top_p is not None:
420
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
421
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
422
+
423
+ # Remove tokens with cumulative probability above the threshold
424
+ sorted_indices_to_remove = cumulative_probs > top_p
425
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
426
+ sorted_indices_to_remove[..., 0] = 0
427
+
428
+ indices_to_remove = sorted_indices_to_remove.scatter(
429
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
430
+ )
431
+ logits[indices_to_remove] = float("-inf")
432
+
433
+ # Sample from the distribution
434
+ probs = F.softmax(logits, dim=-1)
435
+ next_token = torch.multinomial(probs, num_samples=1)
436
+
437
+ return next_token.item()
438
+
439
+
440
+ # Register the model with Auto classes for easy loading
441
+ from transformers import AutoConfig, AutoModelForCausalLM
442
+
443
+ AutoConfig.register("chess_transformer", ChessConfig)
444
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)