SmileChou commited on
Commit
dc52c9a
·
verified ·
1 Parent(s): 488bf8c

Chess Challenge submission by SmileChou

Browse files
Files changed (9) hide show
  1. README.md +31 -0
  2. config.json +25 -0
  3. model.py +437 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +182 -0
  7. tokenizer_config.json +50 -0
  8. training_args.bin +3 -0
  9. vocab.json +150 -0
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # smile_chess_chanllenge_done
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [SmileChou](https://huggingface.co/SmileChou)
17
+ - **Parameters**: 997,964
18
+ - **Organization**: LLM-course
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ model = AutoModelForCausalLM.from_pretrained("LLM-course/smile_chess_chanllenge_done", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("LLM-course/smile_chess_chanllenge_done", trust_remote_code=True)
27
+ ```
28
+
29
+ ## Evaluation
30
+
31
+ This model is evaluated at the [Chess Challenge Arena](https://huggingface.co/spaces/LLM-course/Chess1MChallenge).
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "model.ChessConfig",
7
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
8
+ },
9
+
10
+ "bos_token_id": 1,
11
+ "dropout": 0.05,
12
+ "dtype": "float32",
13
+ "eos_token_id": 2,
14
+ "layer_norm_epsilon": 1e-05,
15
+ "model_type": "chess_transformer",
16
+ "n_ctx": 256,
17
+ "n_embd": 128,
18
+ "n_head": 8,
19
+ "n_inner": 354,
20
+ "n_layer": 6,
21
+ "pad_token_id": 0,
22
+ "tie_weights": true,
23
+ "transformers_version": "4.57.6",
24
+ "vocab_size": 148
25
+ }
model.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.05,
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 = loss_fct(
364
+ shift_logits.view(-1, shift_logits.size(-1)),
365
+ shift_labels.view(-1),
366
+ )
367
+
368
+ if not return_dict:
369
+ output = (logits,)
370
+ return ((loss,) + output) if loss is not None else output
371
+
372
+ return CausalLMOutputWithPast(
373
+ loss=loss,
374
+ logits=logits,
375
+ past_key_values=None,
376
+ hidden_states=None,
377
+ attentions=None,
378
+ )
379
+
380
+ @torch.no_grad()
381
+ def generate_move(
382
+ self,
383
+ input_ids: torch.LongTensor,
384
+ temperature: float = 1.0,
385
+ top_k: Optional[int] = None,
386
+ top_p: Optional[float] = None,
387
+ ) -> int:
388
+ """
389
+ Generate the next move given a sequence of moves.
390
+
391
+ Args:
392
+ input_ids: Token IDs of shape (1, seq_len).
393
+ temperature: Sampling temperature (1.0 = no change).
394
+ top_k: If set, only sample from top k tokens.
395
+ top_p: If set, use nucleus sampling with this threshold.
396
+
397
+ Returns:
398
+ The token ID of the predicted next move.
399
+ """
400
+ self.eval()
401
+
402
+ # Get logits for the last position
403
+ outputs = self(input_ids)
404
+ logits = outputs.logits[:, -1, :] / temperature
405
+
406
+ # Apply top-k filtering
407
+ if top_k is not None:
408
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
409
+ logits[indices_to_remove] = float("-inf")
410
+
411
+ # Apply top-p (nucleus) filtering
412
+ if top_p is not None:
413
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
414
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
415
+
416
+ # Remove tokens with cumulative probability above the threshold
417
+ sorted_indices_to_remove = cumulative_probs > top_p
418
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
419
+ sorted_indices_to_remove[..., 0] = 0
420
+
421
+ indices_to_remove = sorted_indices_to_remove.scatter(
422
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
423
+ )
424
+ logits[indices_to_remove] = float("-inf")
425
+
426
+ # Sample from the distribution
427
+ probs = F.softmax(logits, dim=-1)
428
+ next_token = torch.multinomial(probs, num_samples=1)
429
+
430
+ return next_token.item()
431
+
432
+
433
+ # Register the model with Auto classes for easy loading
434
+ from transformers import AutoConfig, AutoModelForCausalLM
435
+
436
+ AutoConfig.register("chess_transformer", ChessConfig)
437
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1b50a2c130d27f4770a8fc5c2ffe444f4610ad219da6d53e2e362319be33c57
3
+ size 3998304
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,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chess Tokenizer (Refactored).
3
+
4
+ Architecture:
5
+ - Splits chess moves into atomic component tokens.
6
+ - Structure: [Actor] -> [Source_Square] -> [Target_Square] -> [Promotion?]
7
+ - Output format: "WP", "e2_f", "e4_t"
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ from typing import Dict, List, Optional, Any, Tuple
16
+
17
+ from transformers import PreTrainedTokenizer
18
+
19
+
20
+ class ChessTokenizer(PreTrainedTokenizer):
21
+ """
22
+ A tokenizer that breaks chess moves into explicit actor and coordinate tokens.
23
+ Designed for high-precision state tracking.
24
+ """
25
+
26
+ model_input_names = ["input_ids", "attention_mask"]
27
+ vocab_files_names = {"vocab_file": "vocab.json"}
28
+
29
+ # --- Configuration Constants ---
30
+ TOKENS_SPECIAL = ["[PAD]", "[BOS]", "[EOS]", "[UNK]"]
31
+ CHARS_PIECE = "PNBRQK"
32
+ CHARS_COLOR = "WB"
33
+ CHARS_FILE = "abcdefgh"
34
+ CHARS_RANK = "12345678"
35
+ CHARS_PROMO = {"q", "r", "b", "n"}
36
+
37
+ # Regex to validate and parse standard Lichess moves (e.g., WPe2e4)
38
+ # Group 1: Color, 2: Piece, 3: Source, 4: Target, 5: Suffix
39
+ PATTERN_MOVE = re.compile(r"^([WB])([PNBRQK])([a-h][1-8])([a-h][1-8])(.*)$")
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_file: Optional[str] = None,
44
+ vocab: Optional[Dict[str, int]] = None,
45
+ **kwargs: Any,
46
+ ):
47
+ # Initialize special tokens for the parent class
48
+ self._pad_token = self.TOKENS_SPECIAL[0]
49
+ self._bos_token = self.TOKENS_SPECIAL[1]
50
+ self._eos_token = self.TOKENS_SPECIAL[2]
51
+ self._unk_token = self.TOKENS_SPECIAL[3]
52
+
53
+ # Clean kwargs to prevent collisions
54
+ for token_arg in ["pad_token", "bos_token", "eos_token", "unk_token"]:
55
+ kwargs.pop(token_arg, None)
56
+
57
+ # 1. Load Vocabulary
58
+ if vocab:
59
+ self._vocab = vocab
60
+ elif vocab_file and os.path.isfile(vocab_file):
61
+ with open(vocab_file, "r", encoding="utf-8") as f:
62
+ self._vocab = json.load(f)
63
+ else:
64
+ self._vocab = self._generate_vocabulary()
65
+
66
+ # 2. Build ID-to-Token Map
67
+ self._id_to_token = {v: k for k, v in self._vocab.items()}
68
+
69
+ super().__init__(
70
+ pad_token=self._pad_token,
71
+ bos_token=self._bos_token,
72
+ eos_token=self._eos_token,
73
+ unk_token=self._unk_token,
74
+ **kwargs,
75
+ )
76
+
77
+ def _generate_vocabulary(self) -> Dict[str, int]:
78
+ """Constructs the fixed dictionary of tokens."""
79
+ token_list = list(self.TOKENS_SPECIAL)
80
+
81
+ # A. Actor Tokens (e.g., WP, BN)
82
+ token_list.extend(
83
+ f"{c}{p}" for c in self.CHARS_COLOR for p in self.CHARS_PIECE
84
+ )
85
+
86
+ # B. Coordinate Tokens (Source & Target)
87
+ squares = [f"{f}{r}" for r in self.CHARS_RANK for f in self.CHARS_FILE]
88
+ token_list.extend(f"{sq}_f" for sq in squares) # From
89
+ token_list.extend(f"{sq}_t" for sq in squares) # To
90
+
91
+ # C. Promotion Tokens (Sorted for consistency)
92
+ token_list.extend(sorted(self.CHARS_PROMO))
93
+
94
+ return {token: idx for idx, token in enumerate(token_list)}
95
+
96
+ @property
97
+ def vocab_size(self) -> int:
98
+ return len(self._vocab)
99
+
100
+ def get_vocab(self) -> Dict[str, int]:
101
+ return self._vocab.copy()
102
+
103
+ def _tokenize(self, text: str) -> List[str]:
104
+ """
105
+ Parses a string of moves into atomic tokens.
106
+ Input: "WPe2e4 BNg8f6"
107
+ Output: ["WP", "e2_f", "e4_t", "BN", "g8_f", "f6_t"]
108
+ """
109
+ if not text:
110
+ return []
111
+
112
+ tokens = []
113
+ raw_items = text.strip().split()
114
+ special_set = set(self.TOKENS_SPECIAL)
115
+
116
+ for item in raw_items:
117
+ # Pass through special tokens immediately
118
+ if item in special_set:
119
+ tokens.append(item)
120
+ continue
121
+
122
+ # Parse move structure
123
+ match = self.PATTERN_MOVE.match(item)
124
+ if not match:
125
+ tokens.append(self.unk_token)
126
+ continue
127
+
128
+ # Deconstruct parts
129
+ color, piece, src, dst, suffix = match.groups()
130
+
131
+ # 1. Actor (Who)
132
+ tokens.append(f"{color}{piece}")
133
+
134
+ # 2. Origin (Where from)
135
+ tokens.append(f"{src}_f")
136
+
137
+ # 3. Destination (Where to)
138
+ tokens.append(f"{dst}_t")
139
+
140
+ # 4. Promotion (Transformation)
141
+ # Check for suffixes like "=Q" or trailing chars
142
+ if suffix:
143
+ if "=" in suffix:
144
+ # Look for the character immediately following '='
145
+ eq_idx = suffix.find("=")
146
+ if eq_idx + 1 < len(suffix):
147
+ promo_char = suffix[eq_idx + 1].lower()
148
+ if promo_char in self.CHARS_PROMO:
149
+ tokens.append(promo_char)
150
+
151
+ return tokens
152
+
153
+ def _convert_token_to_id(self, token: str) -> int:
154
+ return self._vocab.get(token, self.unk_token_id)
155
+
156
+ def _convert_id_to_token(self, index: int) -> str:
157
+ return self._id_to_token.get(index, self.unk_token)
158
+
159
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
160
+ """Joins tokens into a space-separated string, filtering out specials."""
161
+ special_set = set(self.TOKENS_SPECIAL)
162
+ return " ".join(t for t in tokens if t not in special_set)
163
+
164
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
165
+ if not os.path.exists(save_directory):
166
+ os.makedirs(save_directory, exist_ok=True)
167
+
168
+ filename = "vocab.json"
169
+ if filename_prefix:
170
+ filename = f"{filename_prefix}-{filename}"
171
+
172
+ full_path = os.path.join(save_directory, filename)
173
+
174
+ with open(full_path, "w", encoding="utf-8") as f:
175
+ json.dump(self._vocab, f, indent=2, ensure_ascii=False)
176
+
177
+ return (full_path,)
178
+
179
+ @classmethod
180
+ def build_vocab_from_dataset(cls, *args: Any, **kwargs: Any) -> "ChessTokenizer":
181
+ """Compatibility method for training pipelines."""
182
+ return cls()
tokenizer_config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[EOS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "bos_token": "[BOS]",
37
+ "auto_map": {
38
+ "AutoTokenizer": [
39
+ "tokenizer.ChessTokenizer",
40
+ null
41
+ ]
42
+ },
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
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0237f27c24fd35ae9075a49a691de6ee8b66113e3c207a0ec0847bcce221ccf5
3
+ size 5777
vocab.json ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "WP": 4,
7
+ "WN": 5,
8
+ "WB": 6,
9
+ "WR": 7,
10
+ "WQ": 8,
11
+ "WK": 9,
12
+ "BP": 10,
13
+ "BN": 11,
14
+ "BB": 12,
15
+ "BR": 13,
16
+ "BQ": 14,
17
+ "BK": 15,
18
+ "a1_f": 16,
19
+ "b1_f": 17,
20
+ "c1_f": 18,
21
+ "d1_f": 19,
22
+ "e1_f": 20,
23
+ "f1_f": 21,
24
+ "g1_f": 22,
25
+ "h1_f": 23,
26
+ "a2_f": 24,
27
+ "b2_f": 25,
28
+ "c2_f": 26,
29
+ "d2_f": 27,
30
+ "e2_f": 28,
31
+ "f2_f": 29,
32
+ "g2_f": 30,
33
+ "h2_f": 31,
34
+ "a3_f": 32,
35
+ "b3_f": 33,
36
+ "c3_f": 34,
37
+ "d3_f": 35,
38
+ "e3_f": 36,
39
+ "f3_f": 37,
40
+ "g3_f": 38,
41
+ "h3_f": 39,
42
+ "a4_f": 40,
43
+ "b4_f": 41,
44
+ "c4_f": 42,
45
+ "d4_f": 43,
46
+ "e4_f": 44,
47
+ "f4_f": 45,
48
+ "g4_f": 46,
49
+ "h4_f": 47,
50
+ "a5_f": 48,
51
+ "b5_f": 49,
52
+ "c5_f": 50,
53
+ "d5_f": 51,
54
+ "e5_f": 52,
55
+ "f5_f": 53,
56
+ "g5_f": 54,
57
+ "h5_f": 55,
58
+ "a6_f": 56,
59
+ "b6_f": 57,
60
+ "c6_f": 58,
61
+ "d6_f": 59,
62
+ "e6_f": 60,
63
+ "f6_f": 61,
64
+ "g6_f": 62,
65
+ "h6_f": 63,
66
+ "a7_f": 64,
67
+ "b7_f": 65,
68
+ "c7_f": 66,
69
+ "d7_f": 67,
70
+ "e7_f": 68,
71
+ "f7_f": 69,
72
+ "g7_f": 70,
73
+ "h7_f": 71,
74
+ "a8_f": 72,
75
+ "b8_f": 73,
76
+ "c8_f": 74,
77
+ "d8_f": 75,
78
+ "e8_f": 76,
79
+ "f8_f": 77,
80
+ "g8_f": 78,
81
+ "h8_f": 79,
82
+ "a1_t": 80,
83
+ "b1_t": 81,
84
+ "c1_t": 82,
85
+ "d1_t": 83,
86
+ "e1_t": 84,
87
+ "f1_t": 85,
88
+ "g1_t": 86,
89
+ "h1_t": 87,
90
+ "a2_t": 88,
91
+ "b2_t": 89,
92
+ "c2_t": 90,
93
+ "d2_t": 91,
94
+ "e2_t": 92,
95
+ "f2_t": 93,
96
+ "g2_t": 94,
97
+ "h2_t": 95,
98
+ "a3_t": 96,
99
+ "b3_t": 97,
100
+ "c3_t": 98,
101
+ "d3_t": 99,
102
+ "e3_t": 100,
103
+ "f3_t": 101,
104
+ "g3_t": 102,
105
+ "h3_t": 103,
106
+ "a4_t": 104,
107
+ "b4_t": 105,
108
+ "c4_t": 106,
109
+ "d4_t": 107,
110
+ "e4_t": 108,
111
+ "f4_t": 109,
112
+ "g4_t": 110,
113
+ "h4_t": 111,
114
+ "a5_t": 112,
115
+ "b5_t": 113,
116
+ "c5_t": 114,
117
+ "d5_t": 115,
118
+ "e5_t": 116,
119
+ "f5_t": 117,
120
+ "g5_t": 118,
121
+ "h5_t": 119,
122
+ "a6_t": 120,
123
+ "b6_t": 121,
124
+ "c6_t": 122,
125
+ "d6_t": 123,
126
+ "e6_t": 124,
127
+ "f6_t": 125,
128
+ "g6_t": 126,
129
+ "h6_t": 127,
130
+ "a7_t": 128,
131
+ "b7_t": 129,
132
+ "c7_t": 130,
133
+ "d7_t": 131,
134
+ "e7_t": 132,
135
+ "f7_t": 133,
136
+ "g7_t": 134,
137
+ "h7_t": 135,
138
+ "a8_t": 136,
139
+ "b8_t": 137,
140
+ "c8_t": 138,
141
+ "d8_t": 139,
142
+ "e8_t": 140,
143
+ "f8_t": 141,
144
+ "g8_t": 142,
145
+ "h8_t": 143,
146
+ "b": 144,
147
+ "n": 145,
148
+ "q": 146,
149
+ "r": 147
150
+ }