Valbad commited on
Commit
08d301d
·
verified ·
1 Parent(s): c885a1c

Chess Challenge submission by Valbad

Browse files
Files changed (8) hide show
  1. README.md +26 -0
  2. config.json +24 -0
  3. model.py +444 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +370 -0
  7. tokenizer_config.json +50 -0
  8. vocab.json +0 -0
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # model_valbad_v2
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Valbad](https://huggingface.co/Valbad)
17
+ - **Parameters**: 927,400
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 5000
24
+ - **Embedding dim**: 100
25
+ - **Layers**: 4
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "model.ChessConfig",
7
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "dropout": 0.1,
11
+ "dtype": "float32",
12
+ "eos_token_id": 2,
13
+ "layer_norm_epsilon": 1e-05,
14
+ "model_type": "chess_transformer",
15
+ "n_ctx": 256,
16
+ "n_embd": 100,
17
+ "n_head": 4,
18
+ "n_inner": 300,
19
+ "n_layer": 4,
20
+ "pad_token_id": 0,
21
+ "tie_weights": true,
22
+ "transformers_version": "4.57.3",
23
+ "vocab_size": 5000
24
+ }
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)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c5fb42a3306daa31da025719e74548d236b3f54d0d8999364d5ef20d597926d
3
+ size 3712640
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,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_iterator(
149
+ cls,
150
+ iterator,
151
+ vocab_size: int = 1200,
152
+ min_frequency: int = 1,
153
+ ) -> "ChessTokenizer":
154
+ """
155
+ Build a tokenizer vocabulary from an iterator of game strings.
156
+
157
+ - Controls final vocab size explicitly via vocab_size.
158
+ - Keeps the most frequent move tokens (best coverage).
159
+ - Uses min_frequency as a floor, but vocab_size is the main control.
160
+ """
161
+ from collections import Counter
162
+
163
+ token_counts = Counter()
164
+ for game in iterator:
165
+ moves = game.strip().split()
166
+ token_counts.update(moves)
167
+
168
+ # Filter by min_frequency first
169
+ items = [(tok, cnt) for tok, cnt in token_counts.items() if cnt >= min_frequency]
170
+
171
+ # Sort by frequency desc, then token for determinism
172
+ items.sort(key=lambda x: (-x[1], x[0]))
173
+
174
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
175
+ max_move_tokens = max(0, vocab_size - len(special_tokens))
176
+
177
+ move_tokens = [tok for tok, _ in items[:max_move_tokens]]
178
+ vocab = {token: idx for idx, token in enumerate(special_tokens + move_tokens)}
179
+
180
+ return cls(vocab=vocab)
181
+
182
+
183
+ # @classmethod
184
+ # def build_vocab_from_dataset(
185
+ # cls,
186
+ # dataset_name: str = "dlouapre/lichess_2025-01_1M",
187
+ # split: str = "train",
188
+ # column: str = "text",
189
+ # min_frequency: int = 500,
190
+ # max_samples: Optional[int] = 100000,
191
+ # ) -> "ChessTokenizer":
192
+ # """
193
+ # Build a tokenizer vocabulary from a Hugging Face dataset.
194
+
195
+ # Args:
196
+ # dataset_name: Name of the dataset on Hugging Face Hub.
197
+ # split: Dataset split to use.
198
+ # column: Column containing the game strings.
199
+ # min_frequency: Minimum frequency for a token to be included (default: 500).
200
+ # max_samples: Maximum number of samples to process (default: 100k).
201
+
202
+ # Returns:
203
+ # A ChessTokenizer with the built vocabulary.
204
+ # """
205
+ # from datasets import load_dataset
206
+
207
+ # dataset = load_dataset(dataset_name, split=split)
208
+
209
+ # if max_samples is not None:
210
+ # dataset = dataset.select(range(min(max_samples, len(dataset))))
211
+
212
+ # def game_iterator():
213
+ # for example in dataset:
214
+ # yield example[column]
215
+
216
+ # return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
217
+ @classmethod
218
+ def build_vocab_from_dataset(
219
+ cls,
220
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
221
+ split: str = "train",
222
+ column: str = "text",
223
+ vocab_size: int = 1200,
224
+ min_frequency: int = 1,
225
+ max_samples: Optional[int] = 200000,
226
+ ) -> "ChessTokenizer":
227
+ """
228
+ Build a tokenizer vocabulary from a Hugging Face dataset.
229
+
230
+ Args:
231
+ vocab_size: Final vocab size INCLUDING special tokens.
232
+ min_frequency: Minimum count to consider a move (usually 1 is fine).
233
+ max_samples: How many games to scan to build vocab.
234
+ """
235
+ from datasets import load_dataset
236
+
237
+ dataset = load_dataset(dataset_name, split=split)
238
+
239
+ # if max_samples is not None: # v0&1
240
+ # dataset = dataset.select(range(min(max_samples, len(dataset))))
241
+
242
+ if max_samples is not None: # v2
243
+ n = min(max_samples, len(dataset))
244
+ dataset = dataset.shuffle(seed=42).select(range(n))
245
+
246
+ def game_iterator():
247
+ for example in dataset:
248
+ yield example[column]
249
+
250
+ return cls.build_vocab_from_iterator(
251
+ game_iterator(),
252
+ vocab_size=vocab_size,
253
+ min_frequency=min_frequency,
254
+ )
255
+
256
+ @property
257
+ def vocab_size(self) -> int:
258
+ """Return the size of the vocabulary."""
259
+ return len(self._vocab)
260
+
261
+ def get_vocab(self) -> Dict[str, int]:
262
+ """Return the vocabulary as a dictionary."""
263
+ return dict(self._vocab)
264
+
265
+ def _tokenize(self, text: str) -> List[str]:
266
+ """
267
+ Tokenize a string of moves into a list of tokens.
268
+
269
+ Args:
270
+ text: A string of space-separated moves.
271
+
272
+ Returns:
273
+ List of move tokens.
274
+ """
275
+ return text.strip().split()
276
+
277
+ def _convert_token_to_id(self, token: str) -> int:
278
+ """Convert a token to its ID."""
279
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
280
+
281
+ def _convert_id_to_token(self, index: int) -> str:
282
+ """Convert an ID to its token."""
283
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
284
+
285
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
286
+ """Convert a list of tokens back to a string."""
287
+ # Filter out special tokens for cleaner output
288
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
289
+ return " ".join(t for t in tokens if t not in special)
290
+
291
+ def save_vocabulary(
292
+ self,
293
+ save_directory: str,
294
+ filename_prefix: Optional[str] = None,
295
+ ) -> tuple:
296
+ """
297
+ Save the vocabulary to a JSON file.
298
+
299
+ Args:
300
+ save_directory: Directory to save the vocabulary.
301
+ filename_prefix: Optional prefix for the filename.
302
+
303
+ Returns:
304
+ Tuple containing the path to the saved vocabulary file.
305
+ """
306
+ if not os.path.isdir(save_directory):
307
+ os.makedirs(save_directory, exist_ok=True)
308
+
309
+ vocab_file = os.path.join(
310
+ save_directory,
311
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
312
+ )
313
+
314
+ with open(vocab_file, "w", encoding="utf-8") as f:
315
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
316
+
317
+ return (vocab_file,)
318
+
319
+ # def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
320
+ # if token_ids_1 is not None:
321
+ # # Not expected here, but handle gracefully
322
+ # token_ids = token_ids_0 + token_ids_1
323
+ # else:
324
+ # token_ids = token_ids_0
325
+ # return [self.bos_token_id] + token_ids + [self.eos_token_id]
326
+
327
+ # def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
328
+ # if already_has_special_tokens:
329
+ # return [1 if t in (self.pad_token_id, self.bos_token_id, self.eos_token_id, self.unk_token_id) else 0 for t in token_ids_0]
330
+ # if token_ids_1 is not None:
331
+ # token_ids = token_ids_0 + token_ids_1
332
+ # else:
333
+ # token_ids = token_ids_0
334
+ # return [1] + [0] * len(token_ids) + [1]
335
+
336
+ def count_vocab_from_dataset(
337
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
338
+ split: str = "train",
339
+ column: str = "text",
340
+ max_samples: Optional[int] = 10000,
341
+ ) -> Dict[str, int]:
342
+ """
343
+ Count token frequencies in a dataset (useful for vocabulary analysis).
344
+
345
+ Args:
346
+ dataset_name: Name of the dataset on Hugging Face Hub.
347
+ split: Dataset split to use.
348
+ column: Column containing the game strings.
349
+ max_samples: Maximum number of samples to process.
350
+
351
+ Returns:
352
+ Dictionary mapping tokens to their frequencies.
353
+ """
354
+ from collections import Counter
355
+ from datasets import load_dataset
356
+
357
+ dataset = load_dataset(dataset_name, split=split)
358
+
359
+ if max_samples is not None:
360
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
361
+
362
+ token_counts = Counter()
363
+
364
+ for example in dataset:
365
+ moves = example[column].strip().split()
366
+ token_counts.update(moves)
367
+
368
+ return dict(token_counts)
369
+
370
+
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
+ "auto_map": {
37
+ "AutoTokenizer": [
38
+ "tokenizer.ChessTokenizer",
39
+ null
40
+ ]
41
+ },
42
+ "bos_token": "[BOS]",
43
+ "clean_up_tokenization_spaces": false,
44
+ "eos_token": "[EOS]",
45
+ "extra_special_tokens": {},
46
+ "model_max_length": 1000000000000000019884624838656,
47
+ "pad_token": "[PAD]",
48
+ "tokenizer_class": "ChessTokenizer",
49
+ "unk_token": "[UNK]"
50
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff