GKlajer commited on
Commit
69ca48f
·
verified ·
1 Parent(s): 46873db

Chess Challenge submission by GKlajer

Browse files
Files changed (8) hide show
  1. README.md +26 -0
  2. config.json +25 -0
  3. model.py +438 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +294 -0
  7. tokenizer_config.json +50 -0
  8. vocab.json +87 -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
+ # chess-gm02
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [GKlajer](https://huggingface.co/GKlajer)
17
+ - **Parameters**: 881,664
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 85
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 5
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 128,
17
+ "n_head": 4,
18
+ "n_inner": 384,
19
+ "n_layer": 5,
20
+ "pad_token_id": 0,
21
+ "tie_weights": false,
22
+ "tie_word_embeddings": false,
23
+ "transformers_version": "4.57.5",
24
+ "vocab_size": 85
25
+ }
model.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
104
+ self.n_head = config.n_head
105
+ self.n_embd = config.n_embd
106
+ self.head_dim = config.n_embd // config.n_head
107
+
108
+ # Combined QKV projection for efficiency
109
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
110
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
111
+
112
+ self.dropout = nn.Dropout(config.dropout)
113
+
114
+ # Causal mask (will be created on first forward pass)
115
+ self.register_buffer(
116
+ "bias",
117
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
118
+ 1, 1, config.n_ctx, config.n_ctx
119
+ ),
120
+ persistent=False,
121
+ )
122
+
123
+ def forward(
124
+ self,
125
+ x: torch.Tensor,
126
+ attention_mask: Optional[torch.Tensor] = None,
127
+ ) -> torch.Tensor:
128
+ batch_size, seq_len, _ = x.size()
129
+
130
+ # Compute Q, K, V
131
+ qkv = self.c_attn(x)
132
+ q, k, v = qkv.split(self.n_embd, dim=2)
133
+
134
+ # Reshape for multi-head attention
135
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
136
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
137
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
138
+
139
+ # Scaled dot-product attention
140
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
141
+
142
+ # Apply causal mask
143
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
144
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
145
+
146
+ # Apply attention mask (for padding)
147
+ if attention_mask is not None:
148
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
149
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
150
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
151
+
152
+ attn_weights = F.softmax(attn_weights, dim=-1)
153
+ attn_weights = self.dropout(attn_weights)
154
+
155
+ # Apply attention to values
156
+ attn_output = torch.matmul(attn_weights, v)
157
+
158
+ # Reshape back
159
+ attn_output = (
160
+ attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.n_embd)
161
+ )
162
+
163
+ # Output projection
164
+ attn_output = self.c_proj(attn_output)
165
+
166
+ return attn_output
167
+
168
+
169
+ class FeedForward(nn.Module):
170
+ """
171
+ Feed-forward network (MLP) module.
172
+
173
+ Standard two-layer MLP with GELU activation.
174
+ """
175
+
176
+ def __init__(self, config: ChessConfig):
177
+ super().__init__()
178
+
179
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner)
180
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
181
+ self.dropout = nn.Dropout(config.dropout)
182
+
183
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
184
+ x = self.c_fc(x)
185
+ x = F.gelu(x)
186
+ x = self.c_proj(x)
187
+ x = self.dropout(x)
188
+ return x
189
+
190
+
191
+ class TransformerBlock(nn.Module):
192
+ """
193
+ A single transformer block with attention and feed-forward layers.
194
+
195
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
196
+ training stability.
197
+ """
198
+
199
+ def __init__(self, config: ChessConfig):
200
+ super().__init__()
201
+
202
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
203
+ self.attn = MultiHeadAttention(config)
204
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
205
+ self.mlp = FeedForward(config)
206
+
207
+ def forward(
208
+ self,
209
+ x: torch.Tensor,
210
+ attention_mask: Optional[torch.Tensor] = None,
211
+ ) -> torch.Tensor:
212
+ # Pre-norm attention
213
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
214
+ # Pre-norm FFN
215
+ x = x + self.mlp(self.ln_2(x))
216
+ return x
217
+
218
+
219
+ class ChessForCausalLM(PreTrainedModel):
220
+ """
221
+ Chess Transformer for Causal Language Modeling (next-move prediction).
222
+
223
+ This model is designed to predict the next chess move given a sequence
224
+ of previous moves. It uses a GPT-style architecture with:
225
+ - Token embeddings for chess moves
226
+ - Learned positional embeddings
227
+ - Stacked transformer blocks
228
+ - Linear head for next-token prediction
229
+
230
+ The model supports weight tying between the embedding layer and the
231
+ output projection to save parameters.
232
+
233
+ Example:
234
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
235
+ >>> model = ChessForCausalLM(config)
236
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
237
+ >>> outputs = model(**inputs)
238
+ >>> next_move_logits = outputs.logits[:, -1, :]
239
+ """
240
+
241
+ config_class = ChessConfig
242
+ base_model_prefix = "transformer"
243
+ supports_gradient_checkpointing = True
244
+ # Suppress missing-key warning for tied lm_head when loading
245
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
246
+
247
+ def __init__(self, config: ChessConfig):
248
+ super().__init__(config)
249
+
250
+ # Token and position embeddings
251
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
252
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
253
+
254
+ self.drop = nn.Dropout(config.dropout)
255
+
256
+ # Transformer blocks
257
+ self.h = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layer)])
258
+
259
+ # Final layer norm
260
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
261
+
262
+ # Output head
263
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
264
+
265
+ # Declare tied weights for proper serialization
266
+ if config.tie_weights:
267
+ self._tied_weights_keys = ["lm_head.weight"]
268
+
269
+ # Initialize weights
270
+ self.post_init()
271
+
272
+ # Tie weights if configured
273
+ if config.tie_weights:
274
+ self.tie_weights()
275
+
276
+ def get_input_embeddings(self) -> nn.Module:
277
+ return self.wte
278
+
279
+ def set_input_embeddings(self, new_embeddings: nn.Module):
280
+ self.wte = new_embeddings
281
+ if getattr(self.config, "tie_weights", False):
282
+ self.tie_weights()
283
+
284
+ def get_output_embeddings(self) -> nn.Module:
285
+ return self.lm_head
286
+
287
+ def set_output_embeddings(self, new_embeddings: nn.Module):
288
+ self.lm_head = new_embeddings
289
+
290
+ def tie_weights(self):
291
+ # Use HF helper to tie or clone depending on config
292
+ if getattr(self.config, "tie_weights", False) or getattr(
293
+ self.config, "tie_word_embeddings", False
294
+ ):
295
+ self._tie_or_clone_weights(self.lm_head, self.wte)
296
+
297
+ def _init_weights(self, module: nn.Module):
298
+ """Initialize weights following GPT-2 style."""
299
+ if isinstance(module, nn.Linear):
300
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
301
+ if module.bias is not None:
302
+ torch.nn.init.zeros_(module.bias)
303
+ elif isinstance(module, nn.Embedding):
304
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
305
+ elif isinstance(module, nn.LayerNorm):
306
+ torch.nn.init.ones_(module.weight)
307
+ torch.nn.init.zeros_(module.bias)
308
+
309
+ def forward(
310
+ self,
311
+ input_ids: torch.LongTensor,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ position_ids: Optional[torch.LongTensor] = None,
314
+ labels: Optional[torch.LongTensor] = None,
315
+ return_dict: Optional[bool] = None,
316
+ **kwargs,
317
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
318
+ """
319
+ Forward pass of the model.
320
+
321
+ Args:
322
+ input_ids: Token IDs of shape (batch_size, seq_len).
323
+ attention_mask: Attention mask of shape (batch_size, seq_len).
324
+ position_ids: Position IDs of shape (batch_size, seq_len).
325
+ labels: Labels for language modeling loss.
326
+ return_dict: Whether to return a ModelOutput object.
327
+
328
+ Returns:
329
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
330
+ """
331
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
332
+
333
+ batch_size, seq_len = input_ids.size()
334
+ device = input_ids.device
335
+
336
+ # Create position IDs if not provided
337
+ if position_ids is None:
338
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
339
+
340
+ # Get embeddings
341
+ token_embeds = self.wte(input_ids)
342
+ position_embeds = self.wpe(position_ids)
343
+ hidden_states = self.drop(token_embeds + position_embeds)
344
+
345
+ # Pass through transformer blocks
346
+ for block in self.h:
347
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
348
+
349
+ # Final layer norm
350
+ hidden_states = self.ln_f(hidden_states)
351
+
352
+ # Get logits
353
+ logits = self.lm_head(hidden_states)
354
+
355
+ # Compute loss if labels are provided
356
+ loss = None
357
+ if labels is not None:
358
+ # Shift logits and labels for next-token prediction
359
+ shift_logits = logits[..., :-1, :].contiguous()
360
+ shift_labels = labels[..., 1:].contiguous()
361
+
362
+ # Flatten for cross-entropy
363
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
364
+ loss = loss_fct(
365
+ shift_logits.view(-1, shift_logits.size(-1)),
366
+ shift_labels.view(-1),
367
+ )
368
+
369
+ if not return_dict:
370
+ output = (logits,)
371
+ return ((loss,) + output) if loss is not None else output
372
+
373
+ return CausalLMOutputWithPast(
374
+ loss=loss,
375
+ logits=logits,
376
+ past_key_values=None,
377
+ hidden_states=None,
378
+ attentions=None,
379
+ )
380
+
381
+ @torch.no_grad()
382
+ def generate_move(
383
+ self,
384
+ input_ids: torch.LongTensor,
385
+ temperature: float = 1.0,
386
+ top_k: Optional[int] = None,
387
+ top_p: Optional[float] = None,
388
+ ) -> int:
389
+ """
390
+ Generate the next move given a sequence of moves.
391
+
392
+ Args:
393
+ input_ids: Token IDs of shape (1, seq_len).
394
+ temperature: Sampling temperature (1.0 = no change).
395
+ top_k: If set, only sample from top k tokens.
396
+ top_p: If set, use nucleus sampling with this threshold.
397
+
398
+ Returns:
399
+ The token ID of the predicted next move.
400
+ """
401
+ self.eval()
402
+
403
+ # Get logits for the last position
404
+ outputs = self(input_ids)
405
+ logits = outputs.logits[:, -1, :] / temperature
406
+
407
+ # Apply top-k filtering
408
+ if top_k is not None:
409
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
410
+ logits[indices_to_remove] = float("-inf")
411
+
412
+ # Apply top-p (nucleus) filtering
413
+ if top_p is not None:
414
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
415
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
416
+
417
+ # Remove tokens with cumulative probability above the threshold
418
+ sorted_indices_to_remove = cumulative_probs > top_p
419
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
420
+ sorted_indices_to_remove[..., 0] = 0
421
+
422
+ indices_to_remove = sorted_indices_to_remove.scatter(
423
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
424
+ )
425
+ logits[indices_to_remove] = float("-inf")
426
+
427
+ # Sample from the distribution
428
+ probs = F.softmax(logits, dim=-1)
429
+ next_token = torch.multinomial(probs, num_samples=1)
430
+
431
+ return next_token.item()
432
+
433
+
434
+ # Register the model with Auto classes for easy loading
435
+ from transformers import AutoConfig, AutoModelForCausalLM
436
+
437
+ AutoConfig.register("chess_transformer", ChessConfig)
438
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:685800553e898e35235d74f16c692440a19fdf9c67e16a791b9daa4fdf6660f9
3
+ size 3532160
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,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+ This tokenizer treats each move as a single token using the extended UCI notation
4
+ from the Lichess dataset (e.g., WPe2e4, BNg8f6).
5
+ The dataset format uses:
6
+ - W/B prefix for White/Black
7
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
8
+ - Source and destination squares (e.g., e2e4)
9
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
10
+ """
11
+ from __future__ import annotations
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ from typing import Dict, List, Optional
16
+ import re
17
+ from transformers import PreTrainedTokenizer
18
+
19
+ MOVE_RE = re.compile(
20
+ r"^(?P<side>[WB])"
21
+ r"(?P<piece>[PNBRQK])"
22
+ r"(?P<src>[a-h][1-8])"
23
+ r"(?P<dst>[a-h][1-8])"
24
+ r"(?P<suffix>.*)$"
25
+ )
26
+
27
+
28
+ class ChessTokenizer(PreTrainedTokenizer):
29
+ """
30
+ A custom tokenizer for chess moves using extended UCI notation.
31
+
32
+ This tokenizer maps each possible chess move to a unique token ID.
33
+ The vocabulary is built from the training dataset to ensure all moves
34
+ encountered during training have a corresponding token.
35
+
36
+ Example:
37
+ >>> tokenizer = ChessTokenizer()
38
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
39
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
40
+ """
41
+
42
+ model_input_names = ["input_ids", "attention_mask"]
43
+ vocab_files_names = {"vocab_file": "vocab.json"}
44
+
45
+ # Special tokens
46
+ PAD_TOKEN = "[PAD]"
47
+ BOS_TOKEN = "[BOS]"
48
+ EOS_TOKEN = "[EOS]"
49
+ UNK_TOKEN = "[UNK]"
50
+
51
+ def __init__(
52
+ self,
53
+ vocab_file: Optional[str] = None,
54
+ vocab: Optional[Dict[str, int]] = None,
55
+ **kwargs,
56
+ ):
57
+ """
58
+ Initialize the chess tokenizer.
59
+
60
+ Args:
61
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
62
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
63
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
64
+ """
65
+ # Initialize special tokens
66
+ self._pad_token = self.PAD_TOKEN
67
+ self._bos_token = self.BOS_TOKEN
68
+ self._eos_token = self.EOS_TOKEN
69
+ self._unk_token = self.UNK_TOKEN
70
+ # Remove any duplicate special-token entries passed through kwargs
71
+ # to avoid "multiple values for keyword" errors when loading from disk.
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
+ # Load or create vocabulary
78
+ if vocab is not None:
79
+ self._vocab = vocab
80
+ elif vocab_file is not None and os.path.exists(vocab_file):
81
+ with open(vocab_file, "r", encoding="utf-8") as f:
82
+ self._vocab = json.load(f)
83
+ else:
84
+ # Create a minimal vocabulary with just special tokens
85
+ # The full vocabulary should be built from the dataset
86
+ self._vocab = self._create_default_vocab()
87
+
88
+ # Create reverse mapping
89
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
90
+
91
+ # Call parent init AFTER setting up vocab
92
+ super().__init__(
93
+ pad_token=self._pad_token,
94
+ bos_token=self._bos_token,
95
+ eos_token=self._eos_token,
96
+ unk_token=self._unk_token,
97
+ **kwargs,
98
+ )
99
+
100
+ def _create_default_vocab(self) -> Dict[str, int]:
101
+ """
102
+ Create a minimal default vocabulary with just special tokens.
103
+
104
+ For the full vocabulary, use `build_vocab_from_dataset()`.
105
+ This minimal vocab is just a placeholder - you should build from data.
106
+ """
107
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
108
+ side_tokens = ["[W]", "[B]"]
109
+ piece_tokens = ["[P]", "[N]", "[BISHOP]", "[R]", "[Q]", "[K]"]
110
+ square_tokens = [f"[{file}{rank}]" for rank in "12345678" for file in "abcdefgh"]
111
+ suffix_tokens = ["[x]", "[+]", "[#]", "[O-O]", "[O-O-O]", "[prom_Q]", "[prom_R]", "[prom_B]", "[prom_N]"]
112
+ vocab_list = special_tokens + side_tokens + piece_tokens + square_tokens + suffix_tokens
113
+ vocab = {token: idx for idx, token in enumerate(vocab_list)}
114
+ return vocab
115
+
116
+ @classmethod
117
+ def build_vocab_from_iterator(
118
+ cls,
119
+ iterator,
120
+ min_frequency: int = 1,
121
+ ) -> "ChessTokenizer":
122
+ """
123
+ Build a tokenizer vocabulary from an iterator of game strings.
124
+
125
+ Args:
126
+ iterator: An iterator yielding game strings (space-separated moves).
127
+ min_frequency: Minimum frequency for a token to be included.
128
+
129
+ Returns:
130
+ A ChessTokenizer with the built vocabulary.
131
+ """
132
+ return cls()
133
+
134
+ @classmethod
135
+ def build_vocab_from_dataset(
136
+ cls,
137
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
138
+ split: str = "train",
139
+ column: str = "text",
140
+ min_frequency: int = 500,
141
+ max_samples: Optional[int] = 100000,
142
+ ) -> "ChessTokenizer":
143
+ """
144
+ Build a tokenizer vocabulary from a Hugging Face dataset.
145
+
146
+ Args:
147
+ dataset_name: Name of the dataset on Hugging Face Hub.
148
+ split: Dataset split to use.
149
+ column: Column containing the game strings.
150
+ min_frequency: Minimum frequency for a token to be included (default: 500).
151
+ max_samples: Maximum number of samples to process (default: 100k).
152
+
153
+ Returns:
154
+ A ChessTokenizer with the built vocabulary.
155
+ """
156
+ return cls()
157
+
158
+ @property
159
+ def vocab_size(self) -> int:
160
+ """Return the size of the vocabulary."""
161
+ return len(self._vocab)
162
+
163
+ def get_vocab(self) -> Dict[str, int]:
164
+ """Return the vocabulary as a dictionary."""
165
+ return dict(self._vocab)
166
+
167
+ def _tokenize(self, text: str) -> List[str]:
168
+ """
169
+ Tokenize a string of moves into a list of tokens.
170
+
171
+ Args:
172
+ text: A string of space-separated moves.
173
+
174
+ Returns:
175
+ List of move tokens.
176
+ """
177
+ tokens: List[str] = []
178
+ moves = text.strip().split()
179
+ for move in moves:
180
+ if "O-O-O" in move:
181
+ side = "[W]" if move.startswith("W") else "[B]"
182
+ tokens.append(side)
183
+ tokens.append("[O-O-O]")
184
+ continue
185
+ if "O-O" in move:
186
+ side = "[W]" if move.startswith("W") else "[B]"
187
+ tokens.append(side)
188
+ tokens.append("[O-O]")
189
+ continue
190
+ m = MOVE_RE.match(move)
191
+ if not m:
192
+ tokens.append(self.UNK_TOKEN)
193
+ continue
194
+ side = "[W]" if m.group("side") == "W" else "[B]"
195
+ piece = m.group("piece")
196
+ src = m.group("src")
197
+ dst = m.group("dst")
198
+ suffix = m.group("suffix") or ""
199
+ tokens.append(side)
200
+ if piece == "B":
201
+ tokens.append("[BISHOP]")
202
+ else:
203
+ tokens.append(f"[{piece}]")
204
+ tokens.append(f"[{src}]")
205
+ tokens.append(f"[{dst}]")
206
+ if "x" in suffix:
207
+ tokens.append("[x]")
208
+ if "*" in suffix:
209
+ tokens.append("[#]")
210
+ elif "+" in suffix:
211
+ tokens.append("[+]")
212
+ if "=" in suffix:
213
+ i = suffix.find("=")
214
+ if i != -1 and i + 1 < len(suffix):
215
+ promo = suffix[i + 1].upper()
216
+ if promo in ("Q", "R", "B", "N"):
217
+ tokens.append(f"[prom_{promo}]")
218
+ return tokens
219
+
220
+ def _convert_token_to_id(self, token: str) -> int:
221
+ """Convert a token to its ID."""
222
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
223
+
224
+ def _convert_id_to_token(self, index: int) -> str:
225
+ """Convert an ID to its token."""
226
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
227
+
228
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
229
+ """Convert a list of tokens back to a string."""
230
+ # Filter out special tokens for cleaner output
231
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
232
+ return " ".join(t for t in tokens if t not in special)
233
+
234
+ def save_vocabulary(
235
+ self,
236
+ save_directory: str,
237
+ filename_prefix: Optional[str] = None,
238
+ ) -> tuple:
239
+ """
240
+ Save the vocabulary to a JSON file.
241
+
242
+ Args:
243
+ save_directory: Directory to save the vocabulary.
244
+ filename_prefix: Optional prefix for the filename.
245
+
246
+ Returns:
247
+ Tuple containing the path to the saved vocabulary file.
248
+ """
249
+ if not os.path.isdir(save_directory):
250
+ os.makedirs(save_directory, exist_ok=True)
251
+
252
+ vocab_file = os.path.join(
253
+ save_directory,
254
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
255
+ )
256
+
257
+ with open(vocab_file, "w", encoding="utf-8") as f:
258
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
259
+
260
+ return (vocab_file,)
261
+
262
+ def count_vocab_from_dataset(
263
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
264
+ split: str = "train",
265
+ column: str = "text",
266
+ max_samples: Optional[int] = 10000,
267
+ ) -> Dict[str, int]:
268
+ """
269
+ Count token frequencies in a dataset (useful for vocabulary analysis).
270
+
271
+ Args:
272
+ dataset_name: Name of the dataset on Hugging Face Hub.
273
+ split: Dataset split to use.
274
+ column: Column containing the game strings.
275
+ max_samples: Maximum number of samples to process.
276
+
277
+ Returns:
278
+ Dictionary mapping tokens to their frequencies.
279
+ """
280
+ from collections import Counter
281
+ from datasets import load_dataset
282
+
283
+ dataset = load_dataset(dataset_name, split=split)
284
+
285
+ if max_samples is not None:
286
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
287
+
288
+ tokenizer = ChessTokenizer()
289
+ token_counts = Counter()
290
+
291
+ for example in dataset:
292
+ token_counts.update(tokenizer._tokenize(example[column]))
293
+
294
+ return dict(token_counts)
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
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[W]": 4,
7
+ "[B]": 5,
8
+ "[P]": 6,
9
+ "[N]": 7,
10
+ "[BISHOP]": 8,
11
+ "[R]": 9,
12
+ "[Q]": 10,
13
+ "[K]": 11,
14
+ "[a1]": 12,
15
+ "[b1]": 13,
16
+ "[c1]": 14,
17
+ "[d1]": 15,
18
+ "[e1]": 16,
19
+ "[f1]": 17,
20
+ "[g1]": 18,
21
+ "[h1]": 19,
22
+ "[a2]": 20,
23
+ "[b2]": 21,
24
+ "[c2]": 22,
25
+ "[d2]": 23,
26
+ "[e2]": 24,
27
+ "[f2]": 25,
28
+ "[g2]": 26,
29
+ "[h2]": 27,
30
+ "[a3]": 28,
31
+ "[b3]": 29,
32
+ "[c3]": 30,
33
+ "[d3]": 31,
34
+ "[e3]": 32,
35
+ "[f3]": 33,
36
+ "[g3]": 34,
37
+ "[h3]": 35,
38
+ "[a4]": 36,
39
+ "[b4]": 37,
40
+ "[c4]": 38,
41
+ "[d4]": 39,
42
+ "[e4]": 40,
43
+ "[f4]": 41,
44
+ "[g4]": 42,
45
+ "[h4]": 43,
46
+ "[a5]": 44,
47
+ "[b5]": 45,
48
+ "[c5]": 46,
49
+ "[d5]": 47,
50
+ "[e5]": 48,
51
+ "[f5]": 49,
52
+ "[g5]": 50,
53
+ "[h5]": 51,
54
+ "[a6]": 52,
55
+ "[b6]": 53,
56
+ "[c6]": 54,
57
+ "[d6]": 55,
58
+ "[e6]": 56,
59
+ "[f6]": 57,
60
+ "[g6]": 58,
61
+ "[h6]": 59,
62
+ "[a7]": 60,
63
+ "[b7]": 61,
64
+ "[c7]": 62,
65
+ "[d7]": 63,
66
+ "[e7]": 64,
67
+ "[f7]": 65,
68
+ "[g7]": 66,
69
+ "[h7]": 67,
70
+ "[a8]": 68,
71
+ "[b8]": 69,
72
+ "[c8]": 70,
73
+ "[d8]": 71,
74
+ "[e8]": 72,
75
+ "[f8]": 73,
76
+ "[g8]": 74,
77
+ "[h8]": 75,
78
+ "[x]": 76,
79
+ "[+]": 77,
80
+ "[#]": 78,
81
+ "[O-O]": 79,
82
+ "[O-O-O]": 80,
83
+ "[prom_Q]": 81,
84
+ "[prom_R]": 82,
85
+ "[prom_B]": 83,
86
+ "[prom_N]": 84
87
+ }