Willy Vo commited on
Commit
6ee5e27
·
1 Parent(s): f1dac5e

add model and tokenizer

Browse files
Files changed (2) hide show
  1. model.py +439 -0
  2. tokenizer.py +340 -0
model.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 86,
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
+
363
+ #loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id) # MODIF
364
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
365
+ loss = loss_fct(
366
+ shift_logits.view(-1, shift_logits.size(-1)),
367
+ shift_labels.view(-1),
368
+ )
369
+
370
+ if not return_dict:
371
+ output = (logits,)
372
+ return ((loss,) + output) if loss is not None else output
373
+
374
+ return CausalLMOutputWithPast(
375
+ loss=loss,
376
+ logits=logits,
377
+ past_key_values=None,
378
+ hidden_states=None,
379
+ attentions=None,
380
+ )
381
+
382
+ @torch.no_grad()
383
+ def generate_move(
384
+ self,
385
+ input_ids: torch.LongTensor,
386
+ temperature: float = 1.0,
387
+ top_k: Optional[int] = None,
388
+ top_p: Optional[float] = None,
389
+ ) -> int:
390
+ """
391
+ Generate the next move given a sequence of moves.
392
+
393
+ Args:
394
+ input_ids: Token IDs of shape (1, seq_len).
395
+ temperature: Sampling temperature (1.0 = no change).
396
+ top_k: If set, only sample from top k tokens.
397
+ top_p: If set, use nucleus sampling with this threshold.
398
+
399
+ Returns:
400
+ The token ID of the predicted next move.
401
+ """
402
+ self.eval()
403
+
404
+ # Get logits for the last position
405
+ outputs = self(input_ids)
406
+ logits = outputs.logits[:, -1, :] / temperature
407
+
408
+ # Apply top-k filtering
409
+ if top_k is not None:
410
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
411
+ logits[indices_to_remove] = float("-inf")
412
+
413
+ # Apply top-p (nucleus) filtering
414
+ if top_p is not None:
415
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
416
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
417
+
418
+ # Remove tokens with cumulative probability above the threshold
419
+ sorted_indices_to_remove = cumulative_probs > top_p
420
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
421
+ sorted_indices_to_remove[..., 0] = 0
422
+
423
+ indices_to_remove = sorted_indices_to_remove.scatter(
424
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
425
+ )
426
+ logits[indices_to_remove] = float("-inf")
427
+
428
+ # Sample from the distribution
429
+ probs = F.softmax(logits, dim=-1)
430
+ next_token = torch.multinomial(probs, num_samples=1)
431
+
432
+ return next_token.item()
433
+
434
+
435
+ # Register the model with Auto classes for easy loading
436
+ from transformers import AutoConfig, AutoModelForCausalLM
437
+
438
+ AutoConfig.register("chess_transformer", ChessConfig)
439
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
tokenizer.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fixed structured vocabulary (no dataset-dependent move tokens).
100
+
101
+ Tokens:
102
+ - Special: [PAD], [BOS], [EOS], [UNK]
103
+ - Color: [W], [B]
104
+ - Pieces: [P], [N], [BISHOP], [R], [Q], [K]
105
+ - Squares: [a1]..[h8]
106
+ - Suffixes: [x], [+], [#]
107
+ - Castling: [O-O], [O-O-O]
108
+ - Promotions: [prom_Q], [prom_R], [prom_B], [prom_N]
109
+ - Move separator: [MOVE_END]
110
+ """
111
+ special = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
112
+ colors = ["[W]", "[B]"]
113
+ pieces = ["[P]", "[N]", "[BISHOP]", "[R]", "[Q]", "[K]"]
114
+
115
+ files = "abcdefgh"
116
+ ranks = "12345678"
117
+ squares = [f"[{f}{r}]" for r in ranks for f in files] # a1..h8
118
+
119
+ suffixes = ["[x]", "[+]", "[#]"]
120
+ castling = ["[O-O]", "[O-O-O]"]
121
+ promotions = ["[prom_Q]", "[prom_R]", "[prom_B]", "[prom_N]"]
122
+ move_end = ["[MOVE_END]"]
123
+
124
+ tokens = special + colors + pieces + squares + suffixes + castling + promotions + move_end
125
+ return {tok: i for i, tok in enumerate(tokens)}
126
+
127
+ @classmethod
128
+ def build_vocab_from_iterator(cls, iterator, min_frequency: int = 1) -> "ChessTokenizer":
129
+ # Structured tokenizer uses a fixed vocab; iterator is unused.
130
+ return cls(vocab=cls().get_vocab())
131
+
132
+ # @classmethod
133
+ # def build_vocab_from_dataset(
134
+ # cls,
135
+ # dataset_name: str = "dlouapre/lichess_2025-01_1M",
136
+ # split: str = "train",
137
+ # column: str = "text",
138
+ # min_frequency: int = 500,
139
+ # max_samples: Optional[int] = 100000,
140
+ # ) -> "ChessTokenizer":
141
+ # """
142
+ # Build a tokenizer vocabulary from a Hugging Face dataset.
143
+
144
+ # Args:
145
+ # dataset_name: Name of the dataset on Hugging Face Hub.
146
+ # split: Dataset split to use.
147
+ # column: Column containing the game strings.
148
+ # min_frequency: Minimum frequency for a token to be included (default: 500).
149
+ # max_samples: Maximum number of samples to process (default: 100k).
150
+
151
+ # Returns:
152
+ # A ChessTokenizer with the built vocabulary.
153
+ # """
154
+ # from datasets import load_dataset
155
+
156
+ # dataset = load_dataset(dataset_name, split=split)
157
+
158
+ # if max_samples is not None:
159
+ # dataset = dataset.select(range(min(max_samples, len(dataset))))
160
+
161
+ # def game_iterator():
162
+ # for example in dataset:
163
+ # yield example[column]
164
+
165
+ # return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
166
+
167
+ @classmethod
168
+ def build_vocab_from_dataset(cls,dataset_name: str = "dlouapre/lichess_2025-01_1M",split: str = "train",column: str = "text",min_frequency: int = 500,max_samples: Optional[int] = 100000,) -> "ChessTokenizer":
169
+ # Structured tokenizer uses a fixed vocab; dataset params are unused.
170
+ return cls(vocab=cls().get_vocab())
171
+
172
+ @property
173
+ def vocab_size(self) -> int:
174
+ """Return the size of the vocabulary."""
175
+ return len(self._vocab)
176
+
177
+ def get_vocab(self) -> Dict[str, int]:
178
+ """Return the vocabulary as a dictionary."""
179
+ return dict(self._vocab)
180
+
181
+ def _move_to_tokens(self, move: str) -> List[str]:
182
+ """
183
+ Convert one extended-UCI move string to structured tokens.
184
+
185
+ Examples:
186
+ "WPe2e4" -> ["[W]","[P]","[e2]","[e4]"]
187
+ "WBb5c6(x+)" -> ["[W]","[BISHOP]","[b5]","[c6]","[x]","[+]"]
188
+ "BKe8g8(o)" -> ["[B]","[O-O]"]
189
+ "WPa7a8(Q)" -> ["[W]","[P]","[a7]","[a8]","[prom_Q]"]
190
+ """
191
+ toks: List[str] = []
192
+
193
+ if not move:
194
+ return [self.UNK_TOKEN]
195
+
196
+ # Color
197
+ color = move[0]
198
+ toks.append("[W]" if color == "W" else "[B]")
199
+
200
+ # Basic fields
201
+ # move[1] is piece letter in dataset (P,N,B,R,Q,K)
202
+ piece_char = move[1] if len(move) > 1 else ""
203
+ piece_map = {"P": "[P]", "N": "[N]", "B": "[BISHOP]", "R": "[R]", "Q": "[Q]", "K": "[K]"}
204
+ toks.append(piece_map.get(piece_char, self.UNK_TOKEN))
205
+
206
+ # Source and destination squares assumed at positions 2:4 and 4:6
207
+ # e.g. WPe2e4 -> from=e2 to=e4
208
+ if len(move) >= 6:
209
+ from_sq = move[2:4]
210
+ to_sq = move[4:6]
211
+ toks.append(f"[{from_sq}]")
212
+ toks.append(f"[{to_sq}]")
213
+ else:
214
+ # malformed
215
+ toks.append(self.UNK_TOKEN)
216
+ toks.append(self.UNK_TOKEN)
217
+
218
+ # --- Castling ---
219
+ # Dataset mentions (o)/(O)=castling, sometimes attached to king moves.
220
+ # We'll map based on king destination:
221
+ if "(o)" in move or "(O)" in move:
222
+ # King ends on g-file => O-O ; on c-file => O-O-O
223
+ if len(move) >= 6:
224
+ to_sq = move[4:6]
225
+ if to_sq[0] == "g":
226
+ return [toks[0], "[O-O]"]
227
+ if to_sq[0] == "c":
228
+ return [toks[0], "[O-O-O]"]
229
+
230
+ # --- Promotion ---
231
+ if "(Q)" in move:
232
+ toks.append("[prom_Q]")
233
+ elif "(R)" in move:
234
+ toks.append("[prom_R]")
235
+ elif "(B)" in move:
236
+ toks.append("[prom_B]")
237
+ elif "(N)" in move:
238
+ toks.append("[prom_N]")
239
+
240
+ # --- Capture / check / mate ---
241
+ # Capture patterns: "(x)" "(x+)" "(x+*)" etc.
242
+ if "(x" in move:
243
+ toks.append("[x]")
244
+
245
+ # Checkmate sometimes written (+*) or similar
246
+ if "(+*)" in move:
247
+ toks.append("[#]")
248
+ elif "(+)" in move or "(x+)" in move:
249
+ toks.append("[+]")
250
+
251
+ return toks
252
+
253
+ def _tokenize(self, text: str) -> List[str]:
254
+ """
255
+ Tokenize a game string into structured tokens.
256
+
257
+ Each move becomes:
258
+ [W]/[B], [PIECE], [from], [to], optional flags, then [MOVE_END]
259
+ """
260
+ moves = text.strip().split()
261
+ out: List[str] = []
262
+ for mv in moves:
263
+ out.extend(self._move_to_tokens(mv))
264
+ out.append("[MOVE_END]")
265
+ return out
266
+
267
+ def _convert_token_to_id(self, token: str) -> int:
268
+ """Convert a token to its ID."""
269
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
270
+
271
+ def _convert_id_to_token(self, index: int) -> str:
272
+ """Convert an ID to its token."""
273
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
274
+
275
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
276
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
277
+ return " ".join(t for t in tokens if (t not in special and t != "[MOVE_END]"))
278
+
279
+ def save_vocabulary(
280
+ self,
281
+ save_directory: str,
282
+ filename_prefix: Optional[str] = None,
283
+ ) -> tuple:
284
+ """
285
+ Save the vocabulary to a JSON file.
286
+
287
+ Args:
288
+ save_directory: Directory to save the vocabulary.
289
+ filename_prefix: Optional prefix for the filename.
290
+
291
+ Returns:
292
+ Tuple containing the path to the saved vocabulary file.
293
+ """
294
+ if not os.path.isdir(save_directory):
295
+ os.makedirs(save_directory, exist_ok=True)
296
+
297
+ vocab_file = os.path.join(
298
+ save_directory,
299
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
300
+ )
301
+
302
+ with open(vocab_file, "w", encoding="utf-8") as f:
303
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
304
+
305
+ return (vocab_file,)
306
+
307
+
308
+ def count_vocab_from_dataset(
309
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
310
+ split: str = "train",
311
+ column: str = "text",
312
+ max_samples: Optional[int] = 10000,
313
+ ) -> Dict[str, int]:
314
+ """
315
+ Count token frequencies in a dataset (useful for vocabulary analysis).
316
+
317
+ Args:
318
+ dataset_name: Name of the dataset on Hugging Face Hub.
319
+ split: Dataset split to use.
320
+ column: Column containing the game strings.
321
+ max_samples: Maximum number of samples to process.
322
+
323
+ Returns:
324
+ Dictionary mapping tokens to their frequencies.
325
+ """
326
+ from collections import Counter
327
+ from datasets import load_dataset
328
+
329
+ dataset = load_dataset(dataset_name, split=split)
330
+
331
+ if max_samples is not None:
332
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
333
+
334
+ token_counts = Counter()
335
+
336
+ for example in dataset:
337
+ moves = example[column].strip().split()
338
+ token_counts.update(moves)
339
+
340
+ return dict(token_counts)