hamonk commited on
Commit
8d63e7e
·
verified ·
1 Parent(s): f2e802d

Chess Challenge submission by hamonk

Browse files
Files changed (7) hide show
  1. README.md +26 -0
  2. config.json +24 -0
  3. model.py +438 -0
  4. model.safetensors +3 -0
  5. tokenizer.py +427 -0
  6. tokenizer_config.json +8 -0
  7. vocab.json +115 -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-hamonk-v7
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [hamonk](https://huggingface.co/hamonk)
17
+ - **Parameters**: 874,368
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 113
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 5
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": 128,
17
+ "n_head": 4,
18
+ "n_inner": 384,
19
+ "n_layer": 5,
20
+ "pad_token_id": 0,
21
+ "tie_weights": true,
22
+ "transformers_version": "4.57.6",
23
+ "vocab_size": 113
24
+ }
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
+ 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)
109
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
110
+
111
+ self.dropout = nn.Dropout(config.dropout)
112
+
113
+ # Causal mask (will be created on first forward pass)
114
+ self.register_buffer(
115
+ "bias",
116
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
117
+ 1, 1, config.n_ctx, config.n_ctx
118
+ ),
119
+ persistent=False,
120
+ )
121
+
122
+ def forward(
123
+ self,
124
+ x: torch.Tensor,
125
+ attention_mask: Optional[torch.Tensor] = None,
126
+ ) -> torch.Tensor:
127
+ batch_size, seq_len, _ = x.size()
128
+
129
+ # Compute Q, K, V
130
+ qkv = self.c_attn(x)
131
+ q, k, v = qkv.split(self.n_embd, dim=2)
132
+
133
+ # Reshape for multi-head attention
134
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
135
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
136
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
137
+
138
+ # Scaled dot-product attention
139
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
140
+
141
+ # Apply causal mask
142
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
143
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
144
+
145
+ # Apply attention mask (for padding)
146
+ if attention_mask is not None:
147
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
148
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
149
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
150
+
151
+ attn_weights = F.softmax(attn_weights, dim=-1)
152
+ attn_weights = self.dropout(attn_weights)
153
+
154
+ # Apply attention to values
155
+ attn_output = torch.matmul(attn_weights, v)
156
+
157
+ # Reshape back
158
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
159
+ batch_size, seq_len, self.n_embd
160
+ )
161
+
162
+ # Output projection
163
+ attn_output = self.c_proj(attn_output)
164
+
165
+ return attn_output
166
+
167
+
168
+ class FeedForward(nn.Module):
169
+ """
170
+ Feed-forward network (MLP) module.
171
+
172
+ Standard two-layer MLP with GELU activation.
173
+ """
174
+
175
+ def __init__(self, config: ChessConfig):
176
+ super().__init__()
177
+
178
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner)
179
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
180
+ self.dropout = nn.Dropout(config.dropout)
181
+
182
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
183
+ x = self.c_fc(x)
184
+ x = F.gelu(x)
185
+ x = self.c_proj(x)
186
+ x = self.dropout(x)
187
+ return x
188
+
189
+
190
+ class TransformerBlock(nn.Module):
191
+ """
192
+ A single transformer block with attention and feed-forward layers.
193
+
194
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
195
+ training stability.
196
+ """
197
+
198
+ def __init__(self, config: ChessConfig):
199
+ super().__init__()
200
+
201
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
202
+ self.attn = MultiHeadAttention(config)
203
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
204
+ self.mlp = FeedForward(config)
205
+
206
+ def forward(
207
+ self,
208
+ x: torch.Tensor,
209
+ attention_mask: Optional[torch.Tensor] = None,
210
+ ) -> torch.Tensor:
211
+ # Pre-norm attention
212
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
213
+ # Pre-norm FFN
214
+ x = x + self.mlp(self.ln_2(x))
215
+ return x
216
+
217
+
218
+ class ChessForCausalLM(PreTrainedModel):
219
+ """
220
+ Chess Transformer for Causal Language Modeling (next-move prediction).
221
+
222
+ This model is designed to predict the next chess move given a sequence
223
+ of previous moves. It uses a GPT-style architecture with:
224
+ - Token embeddings for chess moves
225
+ - Learned positional embeddings
226
+ - Stacked transformer blocks
227
+ - Linear head for next-token prediction
228
+
229
+ The model supports weight tying between the embedding layer and the
230
+ output projection to save parameters.
231
+
232
+ Example:
233
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
234
+ >>> model = ChessForCausalLM(config)
235
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
236
+ >>> outputs = model(**inputs)
237
+ >>> next_move_logits = outputs.logits[:, -1, :]
238
+ """
239
+
240
+ config_class = ChessConfig
241
+ base_model_prefix = "transformer"
242
+ supports_gradient_checkpointing = True
243
+ # Suppress missing-key warning for tied lm_head when loading
244
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
245
+
246
+ def __init__(self, config: ChessConfig):
247
+ super().__init__(config)
248
+
249
+ # Token and position embeddings
250
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
251
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
252
+
253
+ self.drop = nn.Dropout(config.dropout)
254
+
255
+ # Transformer blocks
256
+ self.h = nn.ModuleList([
257
+ TransformerBlock(config) for _ in range(config.n_layer)
258
+ ])
259
+
260
+ # Final layer norm
261
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
262
+
263
+ # Output head
264
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
265
+
266
+ # Declare tied weights for proper serialization
267
+ if config.tie_weights:
268
+ self._tied_weights_keys = ["lm_head.weight"]
269
+
270
+ # Initialize weights
271
+ self.post_init()
272
+
273
+ # Tie weights if configured
274
+ if config.tie_weights:
275
+ self.tie_weights()
276
+
277
+ def get_input_embeddings(self) -> nn.Module:
278
+ return self.wte
279
+
280
+ def set_input_embeddings(self, new_embeddings: nn.Module):
281
+ self.wte = new_embeddings
282
+ if getattr(self.config, "tie_weights", False):
283
+ self.tie_weights()
284
+
285
+ def get_output_embeddings(self) -> nn.Module:
286
+ return self.lm_head
287
+
288
+ def set_output_embeddings(self, new_embeddings: nn.Module):
289
+ self.lm_head = new_embeddings
290
+
291
+ def tie_weights(self):
292
+ # Use HF helper to tie or clone depending on config
293
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
294
+ self._tie_or_clone_weights(self.lm_head, self.wte)
295
+
296
+ def _init_weights(self, module: nn.Module):
297
+ """Initialize weights following GPT-2 style."""
298
+ if isinstance(module, nn.Linear):
299
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
300
+ if module.bias is not None:
301
+ torch.nn.init.zeros_(module.bias)
302
+ elif isinstance(module, nn.Embedding):
303
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
304
+ elif isinstance(module, nn.LayerNorm):
305
+ torch.nn.init.ones_(module.weight)
306
+ torch.nn.init.zeros_(module.bias)
307
+
308
+ def forward(
309
+ self,
310
+ input_ids: torch.LongTensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ labels: Optional[torch.LongTensor] = None,
314
+ return_dict: Optional[bool] = None,
315
+ **kwargs,
316
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
317
+ """
318
+ Forward pass of the model.
319
+
320
+ Args:
321
+ input_ids: Token IDs of shape (batch_size, seq_len).
322
+ attention_mask: Attention mask of shape (batch_size, seq_len).
323
+ position_ids: Position IDs of shape (batch_size, seq_len).
324
+ labels: Labels for language modeling loss.
325
+ return_dict: Whether to return a ModelOutput object.
326
+
327
+ Returns:
328
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
329
+ """
330
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
331
+
332
+ batch_size, seq_len = input_ids.size()
333
+ device = input_ids.device
334
+
335
+ # Create position IDs if not provided
336
+ if position_ids is None:
337
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
338
+
339
+ # Get embeddings
340
+ token_embeds = self.wte(input_ids)
341
+ position_embeds = self.wpe(position_ids)
342
+ hidden_states = self.drop(token_embeds + position_embeds)
343
+
344
+ # Pass through transformer blocks
345
+ for block in self.h:
346
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
347
+
348
+ # Final layer norm
349
+ hidden_states = self.ln_f(hidden_states)
350
+
351
+ # Get logits
352
+ logits = self.lm_head(hidden_states)
353
+
354
+ # Compute loss if labels are provided
355
+ loss = None
356
+ if labels is not None:
357
+ # Shift logits and labels for next-token prediction
358
+ shift_logits = logits[..., :-1, :].contiguous()
359
+ shift_labels = labels[..., 1:].contiguous()
360
+
361
+ # Flatten for cross-entropy
362
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
363
+ # loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
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:85661e063f9a78f1b8b9b45f6bfa9c3111fcec969624fa53a1852df311d26ac3
3
+ size 3502896
tokenizer.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ We build a vocabulary with:
5
+ - W/B prefix for White/Black
6
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
7
+ - Source and rank and file: e.g e 2
8
+ - Destination and rank and file: e.g e 4
9
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
10
+
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ import shutil
19
+ import inspect
20
+ from typing import Dict, List, Optional
21
+
22
+ from transformers import PreTrainedTokenizer
23
+
24
+
25
+ class ChessTokenizer(PreTrainedTokenizer):
26
+ """
27
+ A custom tokenizer for chess moves.
28
+
29
+ Example:
30
+ >>> tokenizer = ChessTokenizer()
31
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
32
+ # [BOS, W, P, e, 2, e, 4, B, P, e, 7, e, 5, EOS]
33
+ """
34
+
35
+ model_input_names = ["input_ids", "attention_mask"]
36
+ vocab_files_names = {"vocab_file": "vocab.json"}
37
+
38
+ # Special tokens
39
+ PAD_TOKEN = "[PAD]"
40
+ BOS_TOKEN = "[BOS]"
41
+ EOS_TOKEN = "[EOS]"
42
+ UNK_TOKEN = "[UNK]"
43
+ SEP_TOKEN = "[SEP]"
44
+
45
+ def __init__(
46
+ self,
47
+ vocab_file: Optional[str] = None,
48
+ vocab: Optional[Dict[str, int]] = None,
49
+ **kwargs,
50
+ ):
51
+ """
52
+ Initialize the chess tokenizer.
53
+
54
+ Args:
55
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
56
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
57
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
58
+ """
59
+ # Initialize special tokens
60
+ self._pad_token = self.PAD_TOKEN
61
+ self._bos_token = self.BOS_TOKEN
62
+ self._eos_token = self.EOS_TOKEN
63
+ self._unk_token = self.UNK_TOKEN
64
+ self._sep_token = self.SEP_TOKEN
65
+
66
+ # Remove any duplicate special-token entries passed through kwargs
67
+ # to avoid "multiple values for keyword" errors when loading from disk.
68
+ kwargs.pop("pad_token", None)
69
+ kwargs.pop("bos_token", None)
70
+ kwargs.pop("eos_token", None)
71
+ kwargs.pop("unk_token", None)
72
+ kwargs.pop("sep_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
+ sep_token=self._sep_token,
95
+ **kwargs,
96
+ )
97
+
98
+ def _create_default_vocab(self) -> Dict[str, int]:
99
+ """
100
+ Create a minimal default vocabulary with just special tokens.
101
+
102
+ For the full vocabulary, use `build_vocab_from_dataset()`.
103
+ This minimal vocab is just a placeholder - you should build from data.
104
+ """
105
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.SEP_TOKEN]
106
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
107
+ return vocab
108
+
109
+
110
+ @classmethod
111
+ def build_vocab_from_dataset(
112
+ cls,
113
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
114
+ split: str = "train",
115
+ column: str = "text",
116
+ save_path: Optional[str] = None,
117
+ ) -> "ChessTokenizer":
118
+ """
119
+ Build a tokenizer vocabulary from a Hugging Face dataset.
120
+
121
+ Args:
122
+ dataset_name: Name of the dataset on Hugging Face Hub.
123
+ split: Dataset split to use.
124
+ column: Column containing the game strings.
125
+
126
+ Returns:
127
+ A ChessTokenizer with the built vocabulary.
128
+
129
+ Args:
130
+ save_path: Optional path to write the generated vocab JSON. If not
131
+ provided, the vocab will be saved to ``./chess_tokenizer_vocab.json``.
132
+ """
133
+ from datasets import load_dataset
134
+
135
+ # If a saved vocab exists at `save_path`, load it and return a tokenizer
136
+ if save_path is None:
137
+ cwd = os.getcwd()
138
+ save_path = os.path.join(cwd, "chess_tokenizer_vocab.json")
139
+
140
+ if os.path.exists(save_path):
141
+ try:
142
+ with open(save_path, "r", encoding="utf-8") as f:
143
+ print("Loading existing tokenizer vocab from", save_path)
144
+ vocab = json.load(f)
145
+ return cls(vocab=vocab)
146
+ except Exception:
147
+ # If loading fails, fall through to rebuild the vocab.
148
+ pass
149
+
150
+ dataset = load_dataset(dataset_name, split=split)
151
+
152
+ # Iterator over games (respect max_samples if provided)
153
+ samples = dataset[column]
154
+
155
+ tokens = set()
156
+
157
+ for game in samples:
158
+ if not isinstance(game, str):
159
+ continue
160
+ moves = game.strip().split()
161
+ for move in moves:
162
+ # Basic parsing of move token components
163
+ if len(move) < 2:
164
+ continue
165
+ color = move[0]
166
+ piece = move[1]
167
+ from_square = move[2:4] if len(move) >= 4 else ''
168
+ to_square = move[4:6] if len(move) >= 6 else ''
169
+ suffix = move[6:] if len(move) > 6 else ''
170
+
171
+ tokens.add(color)
172
+ tokens.add(piece)
173
+ tokens.add(from_square)
174
+ tokens.add(to_square)
175
+ if suffix:
176
+ tokens.add(suffix)
177
+
178
+ # Sort tokens
179
+ tokens = sorted(tokens)
180
+
181
+ # Ensure special tokens are present at fixed ids
182
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN, cls.SEP_TOKEN]
183
+
184
+ # Build vocab mapping: special tokens first, then tokens
185
+ vocab: Dict[str, int] = {}
186
+ idx = 0
187
+ for st in special_tokens:
188
+ vocab[st] = idx
189
+ idx += 1
190
+
191
+ for t in tokens:
192
+ if t in vocab:
193
+ continue
194
+ vocab[t] = idx
195
+ idx += 1
196
+
197
+ # Create tokenizer instance with this vocab
198
+ tokenizer = cls(vocab=vocab)
199
+
200
+ # Save vocab to disk. Use provided `save_path` or default file name.
201
+ try:
202
+ if save_path is None:
203
+ cwd = os.getcwd()
204
+ save_path = os.path.join(cwd, "chess_tokenizer_vocab.json")
205
+
206
+ # Write to a temporary file first and atomically replace final file.
207
+ tmp_path = save_path + ".tmp"
208
+ with open(tmp_path, "w", encoding="utf-8") as f:
209
+ json.dump(vocab, f, ensure_ascii=False, indent=2)
210
+ os.replace(tmp_path, save_path)
211
+ except Exception:
212
+ # Non-fatal: ignore save errors but don't leave temp files behind.
213
+ try:
214
+ if 'tmp_path' in locals() and os.path.exists(tmp_path):
215
+ os.remove(tmp_path)
216
+ except Exception:
217
+ pass
218
+
219
+ return tokenizer
220
+
221
+ @property
222
+ def vocab_size(self) -> int:
223
+ """Return the size of the vocabulary."""
224
+ return len(self._vocab)
225
+
226
+ def get_vocab(self) -> Dict[str, int]:
227
+ """Return the vocabulary as a dictionary."""
228
+ return dict(self._vocab)
229
+
230
+ def _tokenize(self, text: str) -> List[str]:
231
+ """
232
+ Tokenize a string of moves into a list of tokens.
233
+
234
+ Args:
235
+ text: A string of space-separated moves.
236
+
237
+ Returns:
238
+ List of move tokens.
239
+ """
240
+ tokens: List[str] = []
241
+ for move in text.strip().split():
242
+ if len(move) < 2:
243
+ continue
244
+ color, piece, from_square, to_square, suffix = self._decompose_move(move)
245
+ tokens.append(color)
246
+ tokens.append(piece)
247
+ tokens.append(from_square)
248
+ tokens.append(to_square)
249
+ if suffix:
250
+ tokens.append(suffix)
251
+
252
+ tokens.append(self._sep_token)
253
+
254
+ return tokens[:-1] # Remove last SEP token
255
+
256
+ @staticmethod
257
+ def _decompose_move(move: str):
258
+ """Decompose a move string into components: color, piece, from_square, to_square, suffix.
259
+
260
+ Returns a 5-tuple of strings (empty strings for missing parts).
261
+ """
262
+ color = move[0]
263
+ piece = move[1] if len(move) >= 2 else ''
264
+ from_square = move[2:4] if len(move) >= 4 else ''
265
+ to_square = move[4:6] if len(move) >= 6 else ''
266
+ suffix = move[6:] if len(move) > 6 else ''
267
+ return color, piece, from_square, to_square, suffix
268
+
269
+ def _convert_token_to_id(self, token: str) -> int:
270
+ """Convert a token to its ID."""
271
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
272
+
273
+ def _convert_id_to_token(self, index: int) -> str:
274
+ """Convert an ID to its token."""
275
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
276
+
277
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
278
+ """Convert a list of tokens back to a string."""
279
+ # Filter out special tokens for cleaner output
280
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
281
+ return " ".join(t for t in tokens if t not in special)
282
+
283
+ def decode(self, token_ids: List[int], skip_special_tokens: bool = True) -> str:
284
+ """Decode a list of token IDs back to a string."""
285
+ tokens = [self._convert_id_to_token(int(tid)) for tid in token_ids]
286
+ if skip_special_tokens:
287
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
288
+ # SEP token should be replace by space
289
+ tokens = [t if t != self.SEP_TOKEN else " " for t in tokens if t not in special]
290
+ return "".join(tokens)
291
+
292
+ def save_vocabulary(
293
+ self,
294
+ save_directory: str,
295
+ filename_prefix: Optional[str] = None,
296
+ ) -> tuple:
297
+ """
298
+ Save the vocabulary to a JSON file.
299
+
300
+ Args:
301
+ save_directory: Directory to save the vocabulary.
302
+ filename_prefix: Optional prefix for the filename.
303
+
304
+ Returns:
305
+ Tuple containing the path to the saved vocabulary file.
306
+ """
307
+ if not os.path.isdir(save_directory):
308
+ os.makedirs(save_directory, exist_ok=True)
309
+
310
+ vocab_file = os.path.join(
311
+ save_directory,
312
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
313
+ )
314
+
315
+ with open(vocab_file, "w", encoding="utf-8") as f:
316
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
317
+
318
+ return (vocab_file,)
319
+
320
+ def save_pretrained(
321
+ self,
322
+ save_directory: str,
323
+ filename_prefix: Optional[str] = None,
324
+ save_tokenizer_code: bool = True,
325
+ ) -> None:
326
+ """Save tokenizer files to a directory in a HF-compatible layout.
327
+
328
+ This writes the vocab JSON (via `save_vocabulary`), a small
329
+ `tokenizer_config.json` describing special tokens and the vocab
330
+ filename, and optionally copies the tokenizer module source file
331
+ into the directory so others can import the implementation.
332
+ """
333
+ if not os.path.isdir(save_directory):
334
+ os.makedirs(save_directory, exist_ok=True)
335
+
336
+ # Save the vocabulary file
337
+ vocab_file_tuple = self.save_vocabulary(save_directory, filename_prefix)
338
+ vocab_file = vocab_file_tuple[0]
339
+
340
+ # Write a minimal tokenizer config
341
+ config = {
342
+ "tokenizer_class": self.__class__.__name__,
343
+ "vocab_file": os.path.basename(vocab_file),
344
+ "pad_token": self.PAD_TOKEN,
345
+ "bos_token": self.BOS_TOKEN,
346
+ "eos_token": self.EOS_TOKEN,
347
+ "unk_token": self.UNK_TOKEN,
348
+ }
349
+ config_path = os.path.join(save_directory, "tokenizer_config.json")
350
+ with open(config_path, "w", encoding="utf-8") as f:
351
+ json.dump(config, f, ensure_ascii=False, indent=2)
352
+
353
+ # Optionally copy this module file so the tokenizer class implementation
354
+ # is available alongside the saved vocab/config. This helps when
355
+ # transferring the saved tokenizer to another environment.
356
+ if save_tokenizer_code:
357
+ try:
358
+ src_file = Path(inspect.getsourcefile(self.__class__))
359
+ dst_file = Path(save_directory) / src_file.name
360
+ shutil.copy2(src_file, dst_file)
361
+ except Exception:
362
+ # Non-fatal; we still saved vocab and config
363
+ pass
364
+
365
+ @classmethod
366
+ def from_pretrained(cls, load_directory: str) -> "ChessTokenizer":
367
+ """Load tokenizer from a directory previously written with `save_pretrained`.
368
+
369
+ This primarily reads the vocab file and constructs the tokenizer.
370
+ If a `tokenizer_config.json` exists it will be consulted for the
371
+ vocab filename and special tokens (but we still instantiate using
372
+ the provided class).
373
+ """
374
+ config_path = os.path.join(load_directory, "tokenizer_config.json")
375
+ vocab_file = None
376
+ if os.path.exists(config_path):
377
+ try:
378
+ with open(config_path, "r", encoding="utf-8") as f:
379
+ cfg = json.load(f)
380
+ vocab_file = os.path.join(load_directory, cfg.get("vocab_file", "vocab.json"))
381
+ except Exception:
382
+ pass
383
+
384
+ if vocab_file is None:
385
+ # Fallback: look for a vocab file in the directory
386
+ candidates = [p for p in os.listdir(load_directory) if p.endswith("vocab.json")]
387
+ if candidates:
388
+ vocab_file = os.path.join(load_directory, candidates[0])
389
+
390
+ if vocab_file is None or not os.path.exists(vocab_file):
391
+ raise FileNotFoundError(f"No vocab file found in {load_directory}")
392
+
393
+ return cls(vocab_file=vocab_file)
394
+
395
+ def count_vocab_from_dataset(
396
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
397
+ split: str = "train",
398
+ column: str = "text",
399
+ max_samples: Optional[int] = 10000,
400
+ ) -> Dict[str, int]:
401
+ """
402
+ Count token frequencies in a dataset (useful for vocabulary analysis).
403
+
404
+ Args:
405
+ dataset_name: Name of the dataset on Hugging Face Hub.
406
+ split: Dataset split to use.
407
+ column: Column containing the game strings.
408
+ max_samples: Maximum number of samples to process.
409
+
410
+ Returns:
411
+ Dictionary mapping tokens to their frequencies.
412
+ """
413
+ from collections import Counter
414
+ from datasets import load_dataset
415
+
416
+ dataset = load_dataset(dataset_name, split=split)
417
+
418
+ if max_samples is not None:
419
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
420
+
421
+ tokenizer = ChessTokenizer()
422
+ token_counts = Counter()
423
+
424
+ for example in dataset:
425
+ token_counts.update(tokenizer._tokenize(example[column]))
426
+
427
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "ChessTokenizer",
3
+ "vocab_file": "vocab.json",
4
+ "pad_token": "[PAD]",
5
+ "bos_token": "[BOS]",
6
+ "eos_token": "[EOS]",
7
+ "unk_token": "[UNK]"
8
+ }
vocab.json ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[SEP]": 4,
7
+ "(+)": 5,
8
+ "(+*)": 6,
9
+ "(+*B)": 7,
10
+ "(+*N)": 8,
11
+ "(+*Q)": 9,
12
+ "(+*R)": 10,
13
+ "(+B)": 11,
14
+ "(+N)": 12,
15
+ "(+Q)": 13,
16
+ "(+R)": 14,
17
+ "(B)": 15,
18
+ "(N)": 16,
19
+ "(O)": 17,
20
+ "(O+)": 18,
21
+ "(O+*)": 19,
22
+ "(Q)": 20,
23
+ "(R)": 21,
24
+ "(o)": 22,
25
+ "(o+)": 23,
26
+ "(o+*)": 24,
27
+ "(x)": 25,
28
+ "(x+)": 26,
29
+ "(x+*)": 27,
30
+ "(x+*B)": 28,
31
+ "(x+*Q)": 29,
32
+ "(x+*R)": 30,
33
+ "(x+B)": 31,
34
+ "(x+N)": 32,
35
+ "(x+Q)": 33,
36
+ "(x+R)": 34,
37
+ "(xB)": 35,
38
+ "(xE)": 36,
39
+ "(xE+)": 37,
40
+ "(xE+*)": 38,
41
+ "(xN)": 39,
42
+ "(xQ)": 40,
43
+ "(xR)": 41,
44
+ "B": 42,
45
+ "K": 43,
46
+ "N": 44,
47
+ "P": 45,
48
+ "Q": 46,
49
+ "R": 47,
50
+ "W": 48,
51
+ "a1": 49,
52
+ "a2": 50,
53
+ "a3": 51,
54
+ "a4": 52,
55
+ "a5": 53,
56
+ "a6": 54,
57
+ "a7": 55,
58
+ "a8": 56,
59
+ "b1": 57,
60
+ "b2": 58,
61
+ "b3": 59,
62
+ "b4": 60,
63
+ "b5": 61,
64
+ "b6": 62,
65
+ "b7": 63,
66
+ "b8": 64,
67
+ "c1": 65,
68
+ "c2": 66,
69
+ "c3": 67,
70
+ "c4": 68,
71
+ "c5": 69,
72
+ "c6": 70,
73
+ "c7": 71,
74
+ "c8": 72,
75
+ "d1": 73,
76
+ "d2": 74,
77
+ "d3": 75,
78
+ "d4": 76,
79
+ "d5": 77,
80
+ "d6": 78,
81
+ "d7": 79,
82
+ "d8": 80,
83
+ "e1": 81,
84
+ "e2": 82,
85
+ "e3": 83,
86
+ "e4": 84,
87
+ "e5": 85,
88
+ "e6": 86,
89
+ "e7": 87,
90
+ "e8": 88,
91
+ "f1": 89,
92
+ "f2": 90,
93
+ "f3": 91,
94
+ "f4": 92,
95
+ "f5": 93,
96
+ "f6": 94,
97
+ "f7": 95,
98
+ "f8": 96,
99
+ "g1": 97,
100
+ "g2": 98,
101
+ "g3": 99,
102
+ "g4": 100,
103
+ "g5": 101,
104
+ "g6": 102,
105
+ "g7": 103,
106
+ "g8": 104,
107
+ "h1": 105,
108
+ "h2": 106,
109
+ "h3": 107,
110
+ "h4": 108,
111
+ "h5": 109,
112
+ "h6": 110,
113
+ "h7": 111,
114
+ "h8": 112
115
+ }