Leonardo16AM commited on
Commit
9b02e5a
·
verified ·
1 Parent(s): 143f438

Chess Challenge submission by Leonardo16AM

Browse files
Files changed (2) hide show
  1. model.py +614 -0
  2. tokenizer.py +278 -0
model.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 8,
58
+ n_head: int = 6,
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
+ kv_lora_rank: int = 32,
65
+ q_lora_rank: Optional[int] = None,
66
+ pad_token_id: int = 0,
67
+ bos_token_id: int = 1,
68
+ eos_token_id: int = 2,
69
+ **kwargs,
70
+ ):
71
+ super().__init__(
72
+ pad_token_id=pad_token_id,
73
+ bos_token_id=bos_token_id,
74
+ eos_token_id=eos_token_id,
75
+ **kwargs,
76
+ )
77
+
78
+ self.vocab_size = vocab_size
79
+ self.n_embd = n_embd
80
+ self.n_layer = n_layer
81
+ self.n_head = n_head
82
+ self.n_ctx = n_ctx
83
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
84
+ self.dropout = dropout
85
+ self.layer_norm_epsilon = layer_norm_epsilon
86
+ self.tie_weights = tie_weights
87
+ # Inform HF base class about tying behavior
88
+ self.tie_word_embeddings = bool(tie_weights)
89
+
90
+ self.kv_lora_rank = kv_lora_rank
91
+ self.q_lora_rank = q_lora_rank
92
+
93
+
94
+ class RMSNorm(nn.Module):
95
+ def __init__(self, dim: int, eps: float = 1e-6):
96
+ super().__init__()
97
+ self.eps = eps
98
+ self.weight = nn.Parameter(torch.ones(dim))
99
+
100
+ def forward(self, x):
101
+ var = torch.mean(x ** 2, dim=-1, keepdim=True)
102
+ return x * torch.rsqrt(var + self.eps) * self.weight
103
+
104
+ def apply_rotary_pos_emb(q, k, cos, sin):
105
+ # Aplica rotación solo a las dimensiones correspondientes
106
+ # Asume q, k shape: (batch, head, seq_len, head_dim)
107
+ # cos, sin shape: (1, 1, seq_len, head_dim)
108
+
109
+ # Divide q y k en partes real e imaginaria simuladas para rotación
110
+ q_embed = (q * cos) + (rotate_half(q) * sin)
111
+ k_embed = (k * cos) + (rotate_half(k) * sin)
112
+ return q_embed, k_embed
113
+
114
+ def rotate_half(x):
115
+ x1 = x[..., : x.shape[-1] // 2]
116
+ x2 = x[..., x.shape[-1] // 2 :]
117
+ return torch.cat((-x2, x1), dim=-1)
118
+
119
+
120
+ class MultiHeadLatentAttention(nn.Module):
121
+ """
122
+ Multi-Head Latent Attention (MLA).
123
+
124
+ Implementa la compresión Low-Rank Key-Value (KV).
125
+ En lugar de almacenar cabezas KV completas, proyectamos a un espacio latente
126
+ y luego generamos las cabezas sobre la marcha.
127
+ """
128
+
129
+ def __init__(self, config: ChessConfig):
130
+ super().__init__()
131
+
132
+ assert config.n_embd % config.n_head == 0, \
133
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
134
+
135
+ self.n_head = config.n_head
136
+ self.n_embd = config.n_embd
137
+ self.head_dim = config.n_embd // config.n_head
138
+ self.kv_lora_rank = config.kv_lora_rank
139
+
140
+ # --- Query Projection ---
141
+ # Si q_lora_rank está definido, también comprimimos Q (opcional),
142
+ # si no, usamos proyección estándar.
143
+ if config.q_lora_rank is not None:
144
+ self.q_down_proj = nn.Linear(config.n_embd, config.q_lora_rank, bias=False)
145
+ self.q_ln = nn.LayerNorm(config.q_lora_rank, eps=config.layer_norm_epsilon)
146
+ self.q_up_proj = nn.Linear(config.q_lora_rank, config.n_embd, bias=False)
147
+ self.use_q_lora = True
148
+ else:
149
+ self.q_proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
150
+ self.use_q_lora = False
151
+
152
+ # --- KV Latent Compression (El núcleo de MLA) ---
153
+ # 1. Down Projection: Comprime la dimensión oculta a una dimensión latente pequeña
154
+ self.kv_down_proj = nn.Linear(config.n_embd, config.kv_lora_rank, bias=False)
155
+
156
+ # 2. Normalization: Importante para la estabilidad en el espacio latente
157
+ self.kv_ln = nn.LayerNorm(config.kv_lora_rank, eps=config.layer_norm_epsilon)
158
+
159
+ # 3. Up Projection: Genera K y V desde el vector latente
160
+ # Salida: 2 * n_embd (porque necesitamos Keys y Values completos)
161
+ self.kv_up_proj = nn.Linear(config.kv_lora_rank, 2 * config.n_embd, bias=False)
162
+
163
+ # Output projection
164
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
165
+ self.dropout = nn.Dropout(config.dropout)
166
+
167
+ # Causal mask
168
+ self.register_buffer(
169
+ "bias",
170
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
171
+ 1, 1, config.n_ctx, config.n_ctx
172
+ ),
173
+ persistent=False,
174
+ )
175
+
176
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, self.head_dim, 2).float() / self.head_dim))
177
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
178
+
179
+ self.q_norm = RMSNorm(self.head_dim, eps=config.layer_norm_epsilon)
180
+ self.k_norm = RMSNorm(self.head_dim, eps=config.layer_norm_epsilon)
181
+
182
+ def forward(
183
+ self,
184
+ x: torch.Tensor,
185
+ attention_mask: Optional[torch.Tensor] = None,
186
+ ) -> torch.Tensor:
187
+ batch_size, seq_len, _ = x.size()
188
+
189
+ if self.use_q_lora:
190
+ q = self.q_down_proj(x)
191
+ q = self.q_ln(q)
192
+ q = self.q_up_proj(q)
193
+ else:
194
+ q = self.q_proj(x)
195
+
196
+ # 2. Generar Latent KV y luego K, V
197
+ # Compresión
198
+ latent_kv = self.kv_down_proj(x)
199
+ latent_kv = self.kv_ln(latent_kv)
200
+
201
+ # Descompresión a cabezas
202
+ kv = self.kv_up_proj(latent_kv)
203
+ k, v = kv.split(self.n_embd, dim=2)
204
+
205
+ # 3. Reshape para Multi-Head Attention standard
206
+ # (B, L, D) -> (B, L, H, HeadDim) -> (B, H, L, HeadDim)
207
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
208
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
209
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
210
+
211
+ q = self.q_norm(q)
212
+ k = self.k_norm(k)
213
+
214
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
215
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
216
+ emb = torch.cat((freqs, freqs), dim=-1)
217
+ cos = emb.cos()[None, None, :, :]
218
+ sin = emb.sin()[None, None, :, :]
219
+
220
+ # Aplicar RoPE a Q y K (K viene de tu up-projection)
221
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
222
+
223
+ # 4. Scaled Dot-Product Attention (Igual que antes)
224
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
225
+
226
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
227
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
228
+
229
+ if attention_mask is not None:
230
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
231
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
232
+
233
+ attn_weights = F.softmax(attn_weights, dim=-1)
234
+ attn_weights = self.dropout(attn_weights)
235
+
236
+ attn_output = torch.matmul(attn_weights, v)
237
+
238
+ # 5. Output Projection
239
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
240
+ batch_size, seq_len, self.n_embd
241
+ )
242
+ attn_output = self.c_proj(attn_output)
243
+
244
+ return attn_output
245
+
246
+
247
+ class MultiHeadAttention(nn.Module):
248
+ """
249
+ Multi-head self-attention module.
250
+
251
+ This is a standard scaled dot-product attention implementation
252
+ with causal masking for autoregressive generation.
253
+ """
254
+
255
+ def __init__(self, config: ChessConfig):
256
+ super().__init__()
257
+
258
+ assert config.n_embd % config.n_head == 0, \
259
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
260
+
261
+ self.n_head = config.n_head
262
+ self.n_embd = config.n_embd
263
+ self.head_dim = config.n_embd // config.n_head
264
+
265
+ # Combined QKV projection for efficiency
266
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
267
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
268
+
269
+ self.dropout = nn.Dropout(config.dropout)
270
+
271
+ # Causal mask (will be created on first forward pass)
272
+ self.register_buffer(
273
+ "bias",
274
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
275
+ 1, 1, config.n_ctx, config.n_ctx
276
+ ),
277
+ persistent=False,
278
+ )
279
+
280
+ def forward(
281
+ self,
282
+ x: torch.Tensor,
283
+ attention_mask: Optional[torch.Tensor] = None,
284
+ ) -> torch.Tensor:
285
+ batch_size, seq_len, _ = x.size()
286
+
287
+ # Compute Q, K, V
288
+ qkv = self.c_attn(x)
289
+ q, k, v = qkv.split(self.n_embd, dim=2)
290
+
291
+ # Reshape for multi-head attention
292
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
293
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
294
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
295
+
296
+ # Scaled dot-product attention
297
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
298
+
299
+ # Apply causal mask
300
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
301
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
302
+
303
+ # Apply attention mask (for padding)
304
+ if attention_mask is not None:
305
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
306
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
307
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
308
+
309
+ attn_weights = F.softmax(attn_weights, dim=-1)
310
+ attn_weights = self.dropout(attn_weights)
311
+
312
+ # Apply attention to values
313
+ attn_output = torch.matmul(attn_weights, v)
314
+
315
+ # Reshape back
316
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
317
+ batch_size, seq_len, self.n_embd
318
+ )
319
+
320
+ # Output projection
321
+ attn_output = self.c_proj(attn_output)
322
+
323
+ return attn_output
324
+
325
+
326
+ # class FeedForward(nn.Module):
327
+ # """
328
+ # Feed-forward network (MLP) module.
329
+
330
+ # Standard two-layer MLP with GELU activation.
331
+ # """
332
+
333
+ # def __init__(self, config: ChessConfig):
334
+ # super().__init__()
335
+
336
+ # self.c_fc = nn.Linear(config.n_embd, config.n_inner)
337
+ # self.c_proj = nn.Linear(config.n_inner, config.n_embd)
338
+ # self.dropout = nn.Dropout(config.dropout)
339
+
340
+ # def forward(self, x: torch.Tensor) -> torch.Tensor:
341
+ # x = self.c_fc(x)
342
+ # x = F.gelu(x)
343
+ # x = self.c_proj(x)
344
+ # x = self.dropout(x)
345
+ # return x
346
+
347
+ class FeedForward(nn.Module):
348
+ """
349
+ SwiGLU Feed-forward network.
350
+ """
351
+ def __init__(self, config: ChessConfig):
352
+ super().__init__()
353
+ self.w1 = nn.Linear(config.n_embd, config.n_inner, bias=False)
354
+ self.w3 = nn.Linear(config.n_embd, config.n_inner, bias=False)
355
+ self.w2 = nn.Linear(config.n_inner, config.n_embd, bias=False)
356
+
357
+ self.dropout = nn.Dropout(config.dropout)
358
+
359
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
360
+ return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
361
+
362
+
363
+ class TransformerBlock(nn.Module):
364
+ """
365
+ A single transformer block with attention and feed-forward layers.
366
+
367
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
368
+ training stability.
369
+ """
370
+
371
+ def __init__(self, config: ChessConfig):
372
+ super().__init__()
373
+
374
+ # self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
375
+ self.ln_1 = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
376
+ self.attn = MultiHeadLatentAttention(config)
377
+ # self.attn = MultiHeadAttention(config)
378
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
379
+ self.mlp = FeedForward(config)
380
+
381
+ def forward(
382
+ self,
383
+ x: torch.Tensor,
384
+ attention_mask: Optional[torch.Tensor] = None,
385
+ ) -> torch.Tensor:
386
+ # Pre-norm attention
387
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
388
+ # Pre-norm FFN
389
+ x = x + self.mlp(self.ln_2(x))
390
+ return x
391
+
392
+
393
+ class ChessForCausalLM(PreTrainedModel):
394
+ """
395
+ Chess Transformer for Causal Language Modeling (next-move prediction).
396
+
397
+ This model is designed to predict the next chess move given a sequence
398
+ of previous moves. It uses a GPT-style architecture with:
399
+ - Token embeddings for chess moves
400
+ - Learned positional embeddings
401
+ - Stacked transformer blocks
402
+ - Linear head for next-token prediction
403
+
404
+ The model supports weight tying between the embedding layer and the
405
+ output projection to save parameters.
406
+
407
+ Example:
408
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
409
+ >>> model = ChessForCausalLM(config)
410
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
411
+ >>> outputs = model(**inputs)
412
+ >>> next_move_logits = outputs.logits[:, -1, :]
413
+ """
414
+
415
+ config_class = ChessConfig
416
+ base_model_prefix = "transformer"
417
+ supports_gradient_checkpointing = True
418
+ # Suppress missing-key warning for tied lm_head when loading
419
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
420
+
421
+ def __init__(self, config: ChessConfig):
422
+ super().__init__(config)
423
+
424
+ # Token and position embeddings
425
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
426
+ # self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
427
+
428
+ self.drop = nn.Dropout(config.dropout)
429
+
430
+ # Transformer blocks
431
+ self.h = nn.ModuleList([
432
+ TransformerBlock(config) for _ in range(config.n_layer)
433
+ ])
434
+
435
+ # Final layer norm
436
+ # self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
437
+ self.ln_f = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
438
+
439
+ # Output head
440
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
441
+
442
+ # Declare tied weights for proper serialization
443
+ if config.tie_weights:
444
+ self._tied_weights_keys = ["lm_head.weight"]
445
+
446
+ # Initialize weights
447
+ self.post_init()
448
+
449
+ # Tie weights if configured
450
+ if config.tie_weights:
451
+ self.tie_weights()
452
+
453
+ def get_input_embeddings(self) -> nn.Module:
454
+ return self.wte
455
+
456
+ def set_input_embeddings(self, new_embeddings: nn.Module):
457
+ self.wte = new_embeddings
458
+ if getattr(self.config, "tie_weights", False):
459
+ self.tie_weights()
460
+
461
+ def get_output_embeddings(self) -> nn.Module:
462
+ return self.lm_head
463
+
464
+ def set_output_embeddings(self, new_embeddings: nn.Module):
465
+ self.lm_head = new_embeddings
466
+
467
+ def tie_weights(self):
468
+ # Use HF helper to tie or clone depending on config
469
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
470
+ self._tie_or_clone_weights(self.lm_head, self.wte)
471
+
472
+ def _init_weights(self, module: nn.Module):
473
+ """Initialize weights following GPT-2 style."""
474
+ if isinstance(module, nn.Linear):
475
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
476
+ if module.bias is not None:
477
+ torch.nn.init.zeros_(module.bias)
478
+ elif isinstance(module, nn.Embedding):
479
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
480
+ elif isinstance(module, nn.LayerNorm):
481
+ torch.nn.init.ones_(module.weight)
482
+ torch.nn.init.zeros_(module.bias)
483
+
484
+ def forward(
485
+ self,
486
+ input_ids: torch.LongTensor,
487
+ attention_mask: Optional[torch.Tensor] = None,
488
+ position_ids: Optional[torch.LongTensor] = None,
489
+ labels: Optional[torch.LongTensor] = None,
490
+ return_dict: Optional[bool] = None,
491
+ **kwargs,
492
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
493
+ """
494
+ Forward pass of the model.
495
+
496
+ Args:
497
+ input_ids: Token IDs of shape (batch_size, seq_len).
498
+ attention_mask: Attention mask of shape (batch_size, seq_len).
499
+ position_ids: Position IDs of shape (batch_size, seq_len).
500
+ labels: Labels for language modeling loss.
501
+ return_dict: Whether to return a ModelOutput object.
502
+
503
+ Returns:
504
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
505
+ """
506
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
507
+
508
+ batch_size, seq_len = input_ids.size()
509
+ device = input_ids.device
510
+
511
+ # Create position IDs if not provided
512
+ if position_ids is None:
513
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
514
+
515
+ # Get embeddings
516
+ token_embeds = self.wte(input_ids)
517
+ # position_embeds = self.wpe(position_ids)
518
+ # hidden_states = self.drop(token_embeds + position_embeds)
519
+ hidden_states = self.drop(token_embeds)
520
+
521
+ # Pass through transformer blocks
522
+ for block in self.h:
523
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
524
+
525
+ # Final layer norm
526
+ hidden_states = self.ln_f(hidden_states)
527
+
528
+ # Get logits
529
+ logits = self.lm_head(hidden_states)
530
+
531
+ # Compute loss if labels are provided
532
+ loss = None
533
+ if labels is not None:
534
+ # Shift logits and labels for next-token prediction
535
+ shift_logits = logits[..., :-1, :].contiguous()
536
+ shift_labels = labels[..., 1:].contiguous()
537
+
538
+ # Flatten for cross-entropy
539
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
540
+ loss = loss_fct(
541
+ shift_logits.view(-1, shift_logits.size(-1)),
542
+ shift_labels.view(-1),
543
+ )
544
+
545
+ if not return_dict:
546
+ output = (logits,)
547
+ return ((loss,) + output) if loss is not None else output
548
+
549
+ return CausalLMOutputWithPast(
550
+ loss=loss,
551
+ logits=logits,
552
+ past_key_values=None,
553
+ hidden_states=None,
554
+ attentions=None,
555
+ )
556
+
557
+ @torch.no_grad()
558
+ def generate_move(
559
+ self,
560
+ input_ids: torch.LongTensor,
561
+ temperature: float = 1.0,
562
+ top_k: Optional[int] = None,
563
+ top_p: Optional[float] = None,
564
+ ) -> int:
565
+ """
566
+ Generate the next move given a sequence of moves.
567
+
568
+ Args:
569
+ input_ids: Token IDs of shape (1, seq_len).
570
+ temperature: Sampling temperature (1.0 = no change).
571
+ top_k: If set, only sample from top k tokens.
572
+ top_p: If set, use nucleus sampling with this threshold.
573
+
574
+ Returns:
575
+ The token ID of the predicted next move.
576
+ """
577
+ self.eval()
578
+
579
+ # Get logits for the last position
580
+ outputs = self(input_ids)
581
+ logits = outputs.logits[:, -1, :] / temperature
582
+
583
+ # Apply top-k filtering
584
+ if top_k is not None:
585
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
586
+ logits[indices_to_remove] = float("-inf")
587
+
588
+ # Apply top-p (nucleus) filtering
589
+ if top_p is not None:
590
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
591
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
592
+
593
+ # Remove tokens with cumulative probability above the threshold
594
+ sorted_indices_to_remove = cumulative_probs > top_p
595
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
596
+ sorted_indices_to_remove[..., 0] = 0
597
+
598
+ indices_to_remove = sorted_indices_to_remove.scatter(
599
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
600
+ )
601
+ logits[indices_to_remove] = float("-inf")
602
+
603
+ # Sample from the distribution
604
+ probs = F.softmax(logits, dim=-1)
605
+ next_token = torch.multinomial(probs, num_samples=1)
606
+
607
+ return next_token.item()
608
+
609
+
610
+ # Register the model with Auto classes for easy loading
611
+ from transformers import AutoConfig, AutoModelForCausalLM
612
+
613
+ AutoConfig.register("chess_transformer", ChessConfig)
614
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
tokenizer.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ This tokenizer treats each move as a single token using the extended UCI notation
5
+ from the Lichess dataset (e.g., WPe2e4, BNg8f6).
6
+
7
+ The dataset format uses:
8
+ - W/B prefix for White/Black
9
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
10
+ - Source and destination squares (e.g., e2e4)
11
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Dict, List, Optional
20
+
21
+ from transformers import PreTrainedTokenizer
22
+
23
+
24
+ class ChessTokenizer(PreTrainedTokenizer):
25
+ """
26
+ A custom tokenizer for chess moves using extended UCI notation.
27
+
28
+ This tokenizer maps each possible chess move to a unique token ID.
29
+ The vocabulary is built from the training dataset to ensure all moves
30
+ encountered during training have a corresponding token.
31
+
32
+ Example:
33
+ >>> tokenizer = ChessTokenizer()
34
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
35
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
36
+ """
37
+
38
+ model_input_names = ["input_ids", "attention_mask"]
39
+ vocab_files_names = {"vocab_file": "vocab.json"}
40
+
41
+ # Special tokens
42
+ PAD_TOKEN = "[PAD]"
43
+ BOS_TOKEN = "[BOS]"
44
+ EOS_TOKEN = "[EOS]"
45
+ UNK_TOKEN = "[UNK]"
46
+
47
+ def __init__(
48
+ self,
49
+ vocab_file: Optional[str] = None,
50
+ vocab: Optional[Dict[str, int]] = None,
51
+ **kwargs,
52
+ ):
53
+ """
54
+ Initialize the chess tokenizer.
55
+
56
+ Args:
57
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
58
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
59
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
60
+ """
61
+ # Initialize special tokens
62
+ self._pad_token = self.PAD_TOKEN
63
+ self._bos_token = self.BOS_TOKEN
64
+ self._eos_token = self.EOS_TOKEN
65
+ self._unk_token = self.UNK_TOKEN
66
+
67
+ # Remove any duplicate special-token entries passed through kwargs
68
+ # to avoid "multiple values for keyword" errors when loading from disk.
69
+ kwargs.pop("pad_token", None)
70
+ kwargs.pop("bos_token", None)
71
+ kwargs.pop("eos_token", None)
72
+ kwargs.pop("unk_token", None)
73
+
74
+ # Load or create vocabulary
75
+ if vocab is not None:
76
+ self._vocab = vocab
77
+ elif vocab_file is not None and os.path.exists(vocab_file):
78
+ with open(vocab_file, "r", encoding="utf-8") as f:
79
+ self._vocab = json.load(f)
80
+ else:
81
+ # Create a minimal vocabulary with just special tokens
82
+ # The full vocabulary should be built from the dataset
83
+ self._vocab = self._create_default_vocab()
84
+
85
+ # Create reverse mapping
86
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
87
+
88
+ # Call parent init AFTER setting up vocab
89
+ super().__init__(
90
+ pad_token=self._pad_token,
91
+ bos_token=self._bos_token,
92
+ eos_token=self._eos_token,
93
+ unk_token=self._unk_token,
94
+ **kwargs,
95
+ )
96
+
97
+ def _create_default_vocab(self) -> Dict[str, int]:
98
+ """
99
+ Create a minimal default vocabulary with just special tokens.
100
+
101
+ For the full vocabulary, use `build_vocab_from_dataset()`.
102
+ This minimal vocab is just a placeholder - you should build from data.
103
+ """
104
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
105
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
106
+ return vocab
107
+
108
+ @classmethod
109
+ def build_vocab_from_iterator(
110
+ cls,
111
+ iterator,
112
+ min_frequency: int = 1,
113
+ ) -> "ChessTokenizer":
114
+ """
115
+ Build a tokenizer vocabulary from an iterator of game strings.
116
+
117
+ Args:
118
+ iterator: An iterator yielding game strings (space-separated moves).
119
+ min_frequency: Minimum frequency for a token to be included.
120
+
121
+ Returns:
122
+ A ChessTokenizer with the built vocabulary.
123
+ """
124
+ from collections import Counter
125
+
126
+ token_counts = Counter()
127
+
128
+ for game in iterator:
129
+ moves = game.strip().split()
130
+ token_counts.update(moves)
131
+
132
+ # Filter by frequency
133
+ tokens = [
134
+ token for token, count in token_counts.items()
135
+ if count >= min_frequency
136
+ ]
137
+
138
+ # Sort for reproducibility
139
+ tokens = sorted(tokens)
140
+
141
+ # Build vocabulary
142
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
143
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
144
+
145
+ return cls(vocab=vocab)
146
+
147
+ @classmethod
148
+ def build_vocab_from_dataset(
149
+ cls,
150
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
151
+ split: str = "train",
152
+ column: str = "text",
153
+ min_frequency: int = 500,
154
+ max_samples: Optional[int] = 100000,
155
+ ) -> "ChessTokenizer":
156
+ """
157
+ Build a tokenizer vocabulary from a Hugging Face dataset.
158
+
159
+ Args:
160
+ dataset_name: Name of the dataset on Hugging Face Hub.
161
+ split: Dataset split to use.
162
+ column: Column containing the game strings.
163
+ min_frequency: Minimum frequency for a token to be included (default: 500).
164
+ max_samples: Maximum number of samples to process (default: 100k).
165
+
166
+ Returns:
167
+ A ChessTokenizer with the built vocabulary.
168
+ """
169
+ from datasets import load_dataset
170
+
171
+ dataset = load_dataset(dataset_name, split=split)
172
+
173
+ if max_samples is not None:
174
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
175
+
176
+ def game_iterator():
177
+ for example in dataset:
178
+ yield example[column]
179
+
180
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
181
+
182
+ @property
183
+ def vocab_size(self) -> int:
184
+ """Return the size of the vocabulary."""
185
+ return len(self._vocab)
186
+
187
+ def get_vocab(self) -> Dict[str, int]:
188
+ """Return the vocabulary as a dictionary."""
189
+ return dict(self._vocab)
190
+
191
+ def _tokenize(self, text: str) -> List[str]:
192
+ """
193
+ Tokenize a string of moves into a list of tokens.
194
+
195
+ Args:
196
+ text: A string of space-separated moves.
197
+
198
+ Returns:
199
+ List of move tokens.
200
+ """
201
+ return text.strip().split()
202
+
203
+ def _convert_token_to_id(self, token: str) -> int:
204
+ """Convert a token to its ID."""
205
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
206
+
207
+ def _convert_id_to_token(self, index: int) -> str:
208
+ """Convert an ID to its token."""
209
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
210
+
211
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
212
+ """Convert a list of tokens back to a string."""
213
+ # Filter out special tokens for cleaner output
214
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
215
+ return " ".join(t for t in tokens if t not in special)
216
+
217
+ def save_vocabulary(
218
+ self,
219
+ save_directory: str,
220
+ filename_prefix: Optional[str] = None,
221
+ ) -> tuple:
222
+ """
223
+ Save the vocabulary to a JSON file.
224
+
225
+ Args:
226
+ save_directory: Directory to save the vocabulary.
227
+ filename_prefix: Optional prefix for the filename.
228
+
229
+ Returns:
230
+ Tuple containing the path to the saved vocabulary file.
231
+ """
232
+ if not os.path.isdir(save_directory):
233
+ os.makedirs(save_directory, exist_ok=True)
234
+
235
+ vocab_file = os.path.join(
236
+ save_directory,
237
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
238
+ )
239
+
240
+ with open(vocab_file, "w", encoding="utf-8") as f:
241
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
242
+
243
+ return (vocab_file,)
244
+
245
+
246
+ def count_vocab_from_dataset(
247
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
248
+ split: str = "train",
249
+ column: str = "text",
250
+ max_samples: Optional[int] = 10000,
251
+ ) -> Dict[str, int]:
252
+ """
253
+ Count token frequencies in a dataset (useful for vocabulary analysis).
254
+
255
+ Args:
256
+ dataset_name: Name of the dataset on Hugging Face Hub.
257
+ split: Dataset split to use.
258
+ column: Column containing the game strings.
259
+ max_samples: Maximum number of samples to process.
260
+
261
+ Returns:
262
+ Dictionary mapping tokens to their frequencies.
263
+ """
264
+ from collections import Counter
265
+ from datasets import load_dataset
266
+
267
+ dataset = load_dataset(dataset_name, split=split)
268
+
269
+ if max_samples is not None:
270
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
271
+
272
+ token_counts = Counter()
273
+
274
+ for example in dataset:
275
+ moves = example[column].strip().split()
276
+ token_counts.update(moves)
277
+
278
+ return dict(token_counts)