eyaa99 commited on
Commit
2d23967
·
verified ·
1 Parent(s): 204bd32

Chess Challenge submission by eyaa99

Browse files
Files changed (9) hide show
  1. README.md +31 -0
  2. config.json +28 -0
  3. model.py +495 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +169 -0
  7. tokenizer_config.json +50 -0
  8. training_args.bin +3 -0
  9. vocab.json +91 -0
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # Chess-Eya
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [eyaa99](https://huggingface.co/eyaa99)
17
+ - **Parameters**: 957,600
18
+ - **Organization**: LLM-course
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ model = AutoModelForCausalLM.from_pretrained("LLM-course/Chess-Eya", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("LLM-course/Chess-Eya", trust_remote_code=True)
27
+ ```
28
+
29
+ ## Evaluation
30
+
31
+ This model is evaluated at the [Chess Challenge Arena](https://huggingface.co/spaces/LLM-course/Chess1MChallenge).
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "dropout": 0.05,
7
+ "dtype": "float32",
8
+ "eos_token_id": 2,
9
+ "layer_norm_epsilon": 1e-06,
10
+ "model_type": "chess_transformer",
11
+ "n_ctx": 256,
12
+ "n_embd": 112,
13
+ "n_head": 4,
14
+ "n_inner": 320,
15
+ "n_kv_head": 4,
16
+ "n_layer": 6,
17
+ "pad_token_id": 0,
18
+ "rms_norm_epsilon": 1e-06,
19
+ "rope_theta": 10000.0,
20
+ "tie_weights": true,
21
+ "transformers_version": "4.57.1",
22
+ "use_rope": true,
23
+ "vocab_size": 89,
24
+ "auto_map": {
25
+ "AutoConfig": "model.ChessConfig",
26
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
27
+ }
28
+ }
model.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from transformers import PretrainedConfig, PreTrainedModel
21
+ from transformers.modeling_outputs import CausalLMOutputWithPast
22
+
23
+
24
+ class ChessConfig(PretrainedConfig):
25
+ """
26
+ Configuration class for the Chess Transformer model.
27
+
28
+ This configuration is designed for a ~1M parameter model.
29
+ Students can adjust these values to explore different architectures.
30
+
31
+ Parameter budget breakdown (with default values):
32
+ - Embeddings (vocab): 1200 x 128 = 153,600
33
+ - Position Embeddings: 256 x 128 = 32,768
34
+ - Transformer Layers: 6 x ~120,000 = ~720,000
35
+ - LM Head (with weight tying): 0 (shared with embeddings)
36
+ - Total: ~906,000 parameters
37
+
38
+ Attributes:
39
+ vocab_size: Size of the vocabulary (number of unique moves).
40
+ n_embd: Embedding dimension (d_model).
41
+ n_layer: Number of transformer layers.
42
+ n_head: Number of attention heads.
43
+ n_ctx: Maximum sequence length (context window).
44
+ n_inner: Feed-forward inner dimension (default: 3 * n_embd).
45
+ dropout: Dropout probability.
46
+ layer_norm_epsilon: Epsilon for layer normalization.
47
+ tie_weights: Whether to tie embedding and output weights.
48
+ """
49
+
50
+ model_type = "chess_transformer"
51
+
52
+ def __init__(
53
+ self,
54
+ vocab_size: int = 1200,
55
+ n_embd: int = 128,
56
+ n_layer: int = 6,
57
+ n_head: int = 4,
58
+ n_kv_head: Optional[int] = None,
59
+ n_ctx: int = 256,
60
+ n_inner: Optional[int] = None,
61
+ dropout: float = 0.1,
62
+ rms_norm_epsilon: float = 1e-6,
63
+ tie_weights: bool = True,
64
+ use_rope: bool = True,
65
+ rope_theta: float = 10000.0,
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_kv_head = n_kv_head if n_kv_head is not None else n_head
83
+ self.n_ctx = n_ctx
84
+ # SwiGLU typically uses 2/3 * 4 * n_embd, rounded to multiple of 64
85
+ self.n_inner = n_inner if n_inner is not None else self._compute_swiglu_dim(n_embd)
86
+ self.dropout = dropout
87
+ self.rms_norm_epsilon = rms_norm_epsilon
88
+ self.tie_weights = tie_weights
89
+ self.tie_word_embeddings = bool(tie_weights)
90
+ self.use_rope = use_rope
91
+ self.rope_theta = rope_theta
92
+ # For compatibility with src/utils.py parameter estimation
93
+ self.layer_norm_epsilon = rms_norm_epsilon
94
+
95
+ @staticmethod
96
+ def _compute_swiglu_dim(n_embd: int) -> int:
97
+ """Compute SwiGLU hidden dimension (typically 8/3 * n_embd, rounded)."""
98
+ # Standard SwiGLU uses ~2.67x multiplier
99
+ hidden = int(8 * n_embd / 3)
100
+ # Round to multiple of 64 for efficiency (optional)
101
+ return ((hidden + 63) // 64) * 64
102
+
103
+
104
+ class RMSNorm(nn.Module):
105
+ """
106
+ Root Mean Square Layer Normalization.
107
+
108
+ Simpler and faster than LayerNorm - no mean centering, no bias.
109
+ """
110
+
111
+ def __init__(self, dim: int, eps: float = 1e-6):
112
+ super().__init__()
113
+ self.eps = eps
114
+ self.weight = nn.Parameter(torch.ones(dim))
115
+
116
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
117
+ # RMSNorm: x * weight / sqrt(mean(x^2) + eps)
118
+ norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
119
+ return x * norm * self.weight
120
+
121
+
122
+ class RotaryEmbedding(nn.Module):
123
+ """
124
+ Rotary Position Embeddings (RoPE).
125
+
126
+ Encodes position information directly into attention computation
127
+ without learnable parameters.
128
+ """
129
+
130
+ def __init__(self, dim: int, max_seq_len: int = 512, theta: float = 10000.0):
131
+ super().__init__()
132
+ self.dim = dim
133
+ self.max_seq_len = max_seq_len
134
+ self.theta = theta
135
+
136
+ # Precompute frequencies
137
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
138
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
139
+
140
+ # Precompute cos/sin cache
141
+ self._build_cache(max_seq_len)
142
+
143
+ def _build_cache(self, seq_len: int):
144
+ """Build cos/sin cache for positions."""
145
+ t = torch.arange(seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
146
+ freqs = torch.outer(t, self.inv_freq)
147
+ # Concatenate to get full dim
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
150
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
151
+
152
+ def forward(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
153
+ """Return cos and sin for the given sequence length."""
154
+ if seq_len > self.max_seq_len:
155
+ self._build_cache(seq_len)
156
+ self.max_seq_len = seq_len
157
+
158
+ return (
159
+ self.cos_cached[:seq_len].to(device),
160
+ self.sin_cached[:seq_len].to(device),
161
+ )
162
+
163
+
164
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
165
+ """Rotate half the hidden dims of the input."""
166
+ x1 = x[..., : x.shape[-1] // 2]
167
+ x2 = x[..., x.shape[-1] // 2 :]
168
+ return torch.cat((-x2, x1), dim=-1)
169
+
170
+
171
+ def apply_rotary_pos_emb(
172
+ q: torch.Tensor,
173
+ k: torch.Tensor,
174
+ cos: torch.Tensor,
175
+ sin: torch.Tensor,
176
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
177
+ """Apply rotary position embeddings to query and key tensors."""
178
+ # q, k: (batch, n_head, seq_len, head_dim)
179
+ # cos, sin: (seq_len, head_dim)
180
+ cos = cos.unsqueeze(0).unsqueeze(0) # (1, 1, seq_len, head_dim)
181
+ sin = sin.unsqueeze(0).unsqueeze(0)
182
+
183
+ q_embed = (q * cos) + (rotate_half(q) * sin)
184
+ k_embed = (k * cos) + (rotate_half(k) * sin)
185
+
186
+ return q_embed, k_embed
187
+
188
+
189
+ class MultiHeadAttention(nn.Module):
190
+ """
191
+ Multi-head self-attention with RoPE.
192
+
193
+ Supports Grouped Query Attention (GQA) when n_kv_head < n_head.
194
+ """
195
+
196
+ def __init__(self, config: ChessConfig):
197
+ super().__init__()
198
+
199
+ assert config.n_embd % config.n_head == 0
200
+
201
+ self.n_head = config.n_head
202
+ self.n_kv_head = config.n_kv_head
203
+ self.n_embd = config.n_embd
204
+ self.head_dim = config.n_embd // config.n_head
205
+ self.n_rep = config.n_head // config.n_kv_head # For GQA
206
+
207
+ # Separate Q, K, V projections for clarity with GQA
208
+ self.q_proj = nn.Linear(config.n_embd, config.n_head * self.head_dim, bias=False)
209
+ self.k_proj = nn.Linear(config.n_embd, config.n_kv_head * self.head_dim, bias=False)
210
+ self.v_proj = nn.Linear(config.n_embd, config.n_kv_head * self.head_dim, bias=False)
211
+ self.o_proj = nn.Linear(config.n_head * self.head_dim, config.n_embd, bias=False)
212
+
213
+ self.dropout = nn.Dropout(config.dropout)
214
+
215
+ # RoPE
216
+ self.rotary_emb = RotaryEmbedding(
217
+ self.head_dim,
218
+ max_seq_len=config.n_ctx,
219
+ theta=config.rope_theta,
220
+ )
221
+
222
+ # Causal mask
223
+ self.register_buffer(
224
+ "causal_mask",
225
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
226
+ 1, 1, config.n_ctx, config.n_ctx
227
+ ),
228
+ persistent=False,
229
+ )
230
+
231
+ def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
232
+ """Repeat KV heads for GQA."""
233
+ if self.n_rep == 1:
234
+ return x
235
+ batch, n_kv_head, seq_len, head_dim = x.shape
236
+ x = x[:, :, None, :, :].expand(batch, n_kv_head, self.n_rep, seq_len, head_dim)
237
+ return x.reshape(batch, n_kv_head * self.n_rep, seq_len, head_dim)
238
+
239
+ def forward(
240
+ self,
241
+ x: torch.Tensor,
242
+ attention_mask: Optional[torch.Tensor] = None,
243
+ ) -> torch.Tensor:
244
+ batch_size, seq_len, _ = x.size()
245
+
246
+ # Project Q, K, V
247
+ q = self.q_proj(x)
248
+ k = self.k_proj(x)
249
+ v = self.v_proj(x)
250
+
251
+ # Reshape for attention
252
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
253
+ k = k.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
254
+ v = v.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
255
+
256
+ # Apply RoPE
257
+ cos, sin = self.rotary_emb(seq_len, x.device)
258
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
259
+
260
+ # Repeat KV for GQA
261
+ k = self._repeat_kv(k)
262
+ v = self._repeat_kv(v)
263
+
264
+ # Scaled dot-product attention
265
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
266
+
267
+ # Apply causal mask
268
+ causal_mask = self.causal_mask[:, :, :seq_len, :seq_len]
269
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
270
+
271
+ # Apply padding mask
272
+ if attention_mask is not None:
273
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
274
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
275
+
276
+ attn_weights = F.softmax(attn_weights, dim=-1)
277
+ attn_weights = self.dropout(attn_weights)
278
+
279
+ # Apply attention to values
280
+ attn_output = torch.matmul(attn_weights, v)
281
+
282
+ # Reshape and project output
283
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
284
+ batch_size, seq_len, self.n_embd
285
+ )
286
+ attn_output = self.o_proj(attn_output)
287
+
288
+ return attn_output
289
+
290
+
291
+ class SwiGLU(nn.Module):
292
+ """
293
+ SwiGLU Feed-Forward Network.
294
+
295
+ SwiGLU(x) = (xW1 * SiLU(xW_gate)) @ W2
296
+
297
+ More expressive than standard FFN with similar parameter count.
298
+ """
299
+
300
+ def __init__(self, config: ChessConfig):
301
+ super().__init__()
302
+
303
+ hidden_dim = config.n_inner
304
+
305
+ # Gate and up projections (can be fused for efficiency)
306
+ self.gate_proj = nn.Linear(config.n_embd, hidden_dim, bias=False)
307
+ self.up_proj = nn.Linear(config.n_embd, hidden_dim, bias=False)
308
+ self.down_proj = nn.Linear(hidden_dim, config.n_embd, bias=False)
309
+ self.dropout = nn.Dropout(config.dropout)
310
+
311
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
312
+ # SwiGLU: SiLU(gate) * up, then down
313
+ gate = F.silu(self.gate_proj(x))
314
+ up = self.up_proj(x)
315
+ x = gate * up
316
+ x = self.down_proj(x)
317
+ x = self.dropout(x)
318
+ return x
319
+
320
+
321
+ class TransformerBlock(nn.Module):
322
+ """
323
+ Transformer block with RMSNorm, RoPE attention, and SwiGLU FFN.
324
+
325
+ Uses pre-normalization for training stability.
326
+ """
327
+
328
+ def __init__(self, config: ChessConfig):
329
+ super().__init__()
330
+
331
+ self.ln_1 = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
332
+ self.attn = MultiHeadAttention(config)
333
+ self.ln_2 = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
334
+ self.mlp = SwiGLU(config)
335
+
336
+ def forward(
337
+ self,
338
+ x: torch.Tensor,
339
+ attention_mask: Optional[torch.Tensor] = None,
340
+ ) -> torch.Tensor:
341
+ # Pre-norm attention with residual
342
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
343
+ # Pre-norm FFN with residual
344
+ x = x + self.mlp(self.ln_2(x))
345
+ return x
346
+
347
+
348
+ class ChessForCausalLM(PreTrainedModel):
349
+ """
350
+ Chess Transformer for Causal Language Modeling.
351
+
352
+ Modern architecture with RoPE, SwiGLU, and RMSNorm.
353
+ """
354
+
355
+ config_class = ChessConfig
356
+ base_model_prefix = "transformer"
357
+ supports_gradient_checkpointing = True
358
+ _tied_weights_keys = ["lm_head.weight"]
359
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
360
+
361
+ def __init__(self, config: ChessConfig):
362
+ super().__init__(config)
363
+
364
+ # Token embeddings (no position embeddings - using RoPE)
365
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
366
+
367
+ self.drop = nn.Dropout(config.dropout)
368
+
369
+ # Transformer blocks
370
+ self.h = nn.ModuleList([
371
+ TransformerBlock(config) for _ in range(config.n_layer)
372
+ ])
373
+
374
+ # Final RMSNorm
375
+ self.ln_f = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
376
+
377
+ # Output head
378
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
379
+
380
+ # Initialize weights
381
+ self.post_init()
382
+
383
+ # Tie weights if configured
384
+ if config.tie_weights:
385
+ self.tie_weights()
386
+
387
+ def get_input_embeddings(self) -> nn.Module:
388
+ return self.wte
389
+
390
+ def set_input_embeddings(self, new_embeddings: nn.Module):
391
+ self.wte = new_embeddings
392
+ if getattr(self.config, "tie_weights", False):
393
+ self.tie_weights()
394
+
395
+ def get_output_embeddings(self) -> nn.Module:
396
+ return self.lm_head
397
+
398
+ def set_output_embeddings(self, new_embeddings: nn.Module):
399
+ self.lm_head = new_embeddings
400
+
401
+ def tie_weights(self):
402
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
403
+ self._tie_or_clone_weights(self.lm_head, self.wte)
404
+
405
+ def _init_weights(self, module: nn.Module):
406
+ """Initialize weights."""
407
+ std = 0.02
408
+ if isinstance(module, nn.Linear):
409
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
410
+ if module.bias is not None:
411
+ torch.nn.init.zeros_(module.bias)
412
+ elif isinstance(module, nn.Embedding):
413
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
414
+ elif isinstance(module, RMSNorm):
415
+ torch.nn.init.ones_(module.weight)
416
+
417
+ def forward(
418
+ self,
419
+ input_ids: torch.LongTensor,
420
+ attention_mask: Optional[torch.Tensor] = None,
421
+ labels: Optional[torch.LongTensor] = None,
422
+ return_dict: Optional[bool] = None,
423
+ **kwargs,
424
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
425
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
426
+
427
+ # Get token embeddings (no position embeddings - RoPE handles position)
428
+ hidden_states = self.wte(input_ids)
429
+ hidden_states = self.drop(hidden_states)
430
+
431
+ # Pass through transformer blocks
432
+ for block in self.h:
433
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
434
+
435
+ # Final norm and head
436
+ hidden_states = self.ln_f(hidden_states)
437
+ logits = self.lm_head(hidden_states)
438
+
439
+ # Compute loss if labels provided
440
+ loss = None
441
+ if labels is not None:
442
+ shift_logits = logits[..., :-1, :].contiguous()
443
+ shift_labels = labels[..., 1:].contiguous()
444
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
445
+ loss = loss_fct(
446
+ shift_logits.view(-1, shift_logits.size(-1)),
447
+ shift_labels.view(-1),
448
+ )
449
+
450
+ if not return_dict:
451
+ output = (logits,)
452
+ return ((loss,) + output) if loss is not None else output
453
+
454
+ return CausalLMOutputWithPast(
455
+ loss=loss,
456
+ logits=logits,
457
+ past_key_values=None,
458
+ hidden_states=None,
459
+ attentions=None,
460
+ )
461
+
462
+ @torch.no_grad()
463
+ def generate_move(
464
+ self,
465
+ input_ids: torch.LongTensor,
466
+ temperature: float = 1.0,
467
+ top_k: Optional[int] = None,
468
+ top_p: Optional[float] = None,
469
+ ) -> int:
470
+ """Generate the next move token."""
471
+ self.eval()
472
+
473
+ outputs = self(input_ids)
474
+ logits = outputs.logits[:, -1, :] / temperature
475
+
476
+ if top_k is not None:
477
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
478
+ logits[indices_to_remove] = float("-inf")
479
+
480
+ if top_p is not None:
481
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
482
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
483
+ sorted_indices_to_remove = cumulative_probs > top_p
484
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
485
+ sorted_indices_to_remove[..., 0] = 0
486
+ indices_to_remove = sorted_indices_to_remove.scatter(
487
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
488
+ )
489
+ logits[indices_to_remove] = float("-inf")
490
+
491
+ probs = F.softmax(logits, dim=-1)
492
+ next_token = torch.multinomial(probs, num_samples=1)
493
+
494
+ return next_token.item()
495
+
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f204c0062e53e6692499f7fa2fef72320b32801ca4f62bd9a9e51f472628be25
3
+ size 3835416
special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[BOS]",
3
+ "eos_token": "[EOS]",
4
+ "pad_token": "[PAD]",
5
+ "unk_token": "[UNK]"
6
+ }
tokenizer.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, os, re
17
+ from typing import Dict, List, Optional
18
+ from transformers import PreTrainedTokenizer
19
+
20
+ _MOVE_RE = re.compile(r"^(?P<side>[WB])(?P<piece>[PNBRQK])(?P<src>[a-h][1-8])(?P<dst>[a-h][1-8])(?P<suffix>.*)$")
21
+ _PROMO_RE = re.compile(r"=([QRBNqrbn])")
22
+
23
+ def _parse_suffix(suffix: str):
24
+ s = (suffix or "").strip()
25
+ is_capture = "x" in s
26
+ is_check = "+" in s
27
+ is_mate = "*" in s
28
+ castle = "O-O-O" if "(O)" in s else ("O-O" if "(o)" in s else None)
29
+ promo = None
30
+ m = _PROMO_RE.search(s)
31
+ if m:
32
+ promo = m.group(1).lower()
33
+ return is_capture, is_check, is_mate, castle, promo
34
+
35
+ class ChessTokenizer(PreTrainedTokenizer):
36
+ """
37
+ A custom tokenizer for chess moves using extended UCI notation.
38
+
39
+ This tokenizer maps each possible chess move to a unique token ID.
40
+ The vocabulary is built from the training dataset to ensure all moves
41
+ encountered during training have a corresponding token.
42
+
43
+ Example:
44
+ >>> tokenizer = ChessTokenizer()
45
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
46
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
47
+ """
48
+
49
+ model_input_names = ["input_ids", "attention_mask"]
50
+ vocab_files_names = {"vocab_file": "vocab.json"}
51
+
52
+ PAD_TOKEN = "[PAD]"
53
+ BOS_TOKEN = "[BOS]"
54
+ EOS_TOKEN = "[EOS]"
55
+ UNK_TOKEN = "[UNK]"
56
+
57
+ def __init__(self, vocab_file: Optional[str] = None, vocab: Optional[Dict[str, int]] = None, **kwargs):
58
+ """
59
+ Initialize the chess tokenizer.
60
+
61
+ Args:
62
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
63
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
64
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
65
+ """
66
+ # Initialize special tokens
67
+ self._pad_token = self.PAD_TOKEN
68
+ self._bos_token = self.BOS_TOKEN
69
+ self._eos_token = self.EOS_TOKEN
70
+ self._unk_token = self.UNK_TOKEN
71
+
72
+ kwargs.pop("pad_token", None)
73
+ kwargs.pop("bos_token", None)
74
+ kwargs.pop("eos_token", None)
75
+ kwargs.pop("unk_token", None)
76
+
77
+ if vocab is not None:
78
+ self._vocab = vocab
79
+ elif vocab_file and os.path.exists(vocab_file):
80
+ with open(vocab_file, "r", encoding="utf-8") as f:
81
+ self._vocab = json.load(f)
82
+ else:
83
+ self._vocab = self._create_default_vocab()
84
+
85
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
86
+
87
+ super().__init__(
88
+ pad_token=self._pad_token,
89
+ bos_token=self._bos_token,
90
+ eos_token=self._eos_token,
91
+ unk_token=self._unk_token,
92
+ **kwargs,
93
+ )
94
+
95
+ @property
96
+ def vocab_size(self) -> int:
97
+ return len(self._vocab)
98
+
99
+ def get_vocab(self) -> Dict[str, int]:
100
+ return dict(self._vocab)
101
+
102
+ def _convert_token_to_id(self, token: str) -> int:
103
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
104
+
105
+ def _convert_id_to_token(self, index: int) -> str:
106
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
107
+
108
+ def _create_default_vocab(self) -> Dict[str, int]:
109
+ """
110
+ Create a minimal default vocabulary with just special tokens.
111
+
112
+ For the full vocabulary, use `build_vocab_from_dataset()`.
113
+ This minimal vocab is just a placeholder - you should build from data.
114
+ """
115
+ tokens: List[str] = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
116
+ tokens += [f"[W{p}]" for p in "PNBRQK"]
117
+ tokens += [f"[B{p}]" for p in "PNBRQK"]
118
+ tokens += [f"[{f}{r}]" for f in "abcdefgh" for r in "12345678"]
119
+ tokens += ["[x]", "[+]", "[#]", "[O-O]", "[O-O-O]"]
120
+ tokens += [f"[={p}]" for p in "qrbn"]
121
+ return {tok: i for i, tok in enumerate(tokens)}
122
+
123
+ def _tokenize(self, text: str) -> List[str]:
124
+ out: List[str] = []
125
+ for move in (text or "").strip().split():
126
+ # Raw UCI like e2e4 / e7e8q (no side/piece available)
127
+ if re.fullmatch(r"[a-h][1-8][a-h][1-8][qrbn]?", move):
128
+ src, dst = move[:2], move[2:4]
129
+ out += [f"[{src}]", f"[{dst}]"]
130
+ if len(move) == 5:
131
+ out += [f"[={move[4]}]"]
132
+ continue
133
+
134
+ m = _MOVE_RE.match(move)
135
+ if not m:
136
+ out.append(self.UNK_TOKEN)
137
+ continue
138
+
139
+ side = m.group("side") # "W" or "B"
140
+ piece = m.group("piece") # P/N/B/R/Q/K
141
+ src = f"[{m.group('src')}]"
142
+ dst = f"[{m.group('dst')}]"
143
+ is_cap, is_chk, is_mate, castle, promo = _parse_suffix(m.group("suffix") or "")
144
+
145
+ out += [f"[{side}{piece}]", src, dst]
146
+ if castle:
147
+ out.append(f"[{castle}]")
148
+ if is_cap:
149
+ out.append("[x]")
150
+ if is_mate:
151
+ out.append("[#]")
152
+ elif is_chk:
153
+ out.append("[+]")
154
+ if promo:
155
+ out.append(f"[={promo}]")
156
+ return out
157
+
158
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
159
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
160
+ return " ".join(t for t in tokens if t not in special)
161
+
162
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
163
+ if not os.path.isdir(save_directory):
164
+ os.makedirs(save_directory, exist_ok=True)
165
+ vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.json")
166
+ with open(vocab_file, "w", encoding="utf-8") as f:
167
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
168
+ return (vocab_file,)
169
+
tokenizer_config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[EOS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "bos_token": "[BOS]",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "[EOS]",
39
+ "extra_special_tokens": {},
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": "[PAD]",
42
+ "tokenizer_class": "ChessTokenizer",
43
+ "unk_token": "[UNK]",
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.ChessTokenizer",
47
+ null
48
+ ]
49
+ }
50
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e9055e4ced2ecd63bfa2c1d5a274a412bc1b275f8cb1ef8b380ad8dffd5d70c
3
+ size 5777
vocab.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[WP]": 4,
7
+ "[WN]": 5,
8
+ "[WB]": 6,
9
+ "[WR]": 7,
10
+ "[WQ]": 8,
11
+ "[WK]": 9,
12
+ "[BP]": 10,
13
+ "[BN]": 11,
14
+ "[BB]": 12,
15
+ "[BR]": 13,
16
+ "[BQ]": 14,
17
+ "[BK]": 15,
18
+ "[a1]": 16,
19
+ "[a2]": 17,
20
+ "[a3]": 18,
21
+ "[a4]": 19,
22
+ "[a5]": 20,
23
+ "[a6]": 21,
24
+ "[a7]": 22,
25
+ "[a8]": 23,
26
+ "[b1]": 24,
27
+ "[b2]": 25,
28
+ "[b3]": 26,
29
+ "[b4]": 27,
30
+ "[b5]": 28,
31
+ "[b6]": 29,
32
+ "[b7]": 30,
33
+ "[b8]": 31,
34
+ "[c1]": 32,
35
+ "[c2]": 33,
36
+ "[c3]": 34,
37
+ "[c4]": 35,
38
+ "[c5]": 36,
39
+ "[c6]": 37,
40
+ "[c7]": 38,
41
+ "[c8]": 39,
42
+ "[d1]": 40,
43
+ "[d2]": 41,
44
+ "[d3]": 42,
45
+ "[d4]": 43,
46
+ "[d5]": 44,
47
+ "[d6]": 45,
48
+ "[d7]": 46,
49
+ "[d8]": 47,
50
+ "[e1]": 48,
51
+ "[e2]": 49,
52
+ "[e3]": 50,
53
+ "[e4]": 51,
54
+ "[e5]": 52,
55
+ "[e6]": 53,
56
+ "[e7]": 54,
57
+ "[e8]": 55,
58
+ "[f1]": 56,
59
+ "[f2]": 57,
60
+ "[f3]": 58,
61
+ "[f4]": 59,
62
+ "[f5]": 60,
63
+ "[f6]": 61,
64
+ "[f7]": 62,
65
+ "[f8]": 63,
66
+ "[g1]": 64,
67
+ "[g2]": 65,
68
+ "[g3]": 66,
69
+ "[g4]": 67,
70
+ "[g5]": 68,
71
+ "[g6]": 69,
72
+ "[g7]": 70,
73
+ "[g8]": 71,
74
+ "[h1]": 72,
75
+ "[h2]": 73,
76
+ "[h3]": 74,
77
+ "[h4]": 75,
78
+ "[h5]": 76,
79
+ "[h6]": 77,
80
+ "[h7]": 78,
81
+ "[h8]": 79,
82
+ "[x]": 80,
83
+ "[+]": 81,
84
+ "[#]": 82,
85
+ "[O-O]": 83,
86
+ "[O-O-O]": 84,
87
+ "[=q]": 85,
88
+ "[=r]": 86,
89
+ "[=b]": 87,
90
+ "[=n]": 88
91
+ }