Gusthavok commited on
Commit
779a83f
·
verified ·
1 Parent(s): 19380dd

Chess Challenge submission by Gusthavok

Browse files
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
+ # chess_model_khg
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Gusthavok](https://huggingface.co/Gusthavok)
17
+ - **Parameters**: 871,808
18
+ - **Organization**: LLM-course
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ model = AutoModelForCausalLM.from_pretrained("LLM-course/chess_model_khg", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("LLM-course/chess_model_khg", 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).
__pycache__/tokenizer.cpython-313.pyc ADDED
Binary file (22.5 kB). View file
 
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "dropout": 0.1,
7
+ "dtype": "float32",
8
+ "eos_token_id": 2,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "model_type": "chess_transformer",
11
+ "n_ctx": 256,
12
+ "n_embd": 128,
13
+ "n_head": 4,
14
+ "n_inner": 384,
15
+ "n_layer": 5,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.56.2",
19
+ "vocab_size": 93,
20
+ "auto_map": {
21
+ "AutoConfig": "model.ChessConfig",
22
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
23
+ }
24
+ }
model.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Structured generation support
278
+ self.vocab_masks = None
279
+ self.tokenizer_ref = None
280
+ self._auto_prepare_attempted = False
281
+
282
+ # Enable constrained decoding during inference (disabled in training)
283
+ self.use_constrained_decoding = False
284
+
285
+ def _setup_token_type_indices(self, device):
286
+ """Setup indices for different token types for constrained generation. Lazy initialization."""
287
+ if self._token_indices_initialized:
288
+ return
289
+
290
+ # Color+piece tokens (WP, WN, WB, WR, WQ, WK, BP, BN, BB, BR, BQ, BK)
291
+ piece_tokens = ["WP", "WN", "WB", "WR", "WQ", "WK", "BP", "BN", "BB", "BR", "BQ", "BK"]
292
+
293
+ # Position tokens (a1-h8)
294
+ files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
295
+ ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
296
+ square_tokens = [f + r for f in files for r in ranks]
297
+
298
+ # Suffix tokens
299
+ suffix_tokens = ["(x)", "(+)", "(x+)", "(+*)", "(x+*)", "(o)", "(O)", "(xE)", "=Q", "=R", "=B", "=N"]
300
+
301
+ # Special tokens
302
+ special_tokens = ["[PAD]", "[BOS]", "[EOS]", "[UNK]"]
303
+
304
+ # Create vocab to index mapping (build a simple vocab dict)
305
+ # Assuming tokenizer uses this order: special tokens, pieces, squares, suffixes
306
+ vocab = {}
307
+ idx = 0
308
+ for token in special_tokens + piece_tokens + square_tokens + suffix_tokens:
309
+ vocab[token] = idx
310
+ idx += 1
311
+
312
+ # Store indices on the correct device
313
+ self.piece_token_ids = torch.tensor([vocab[t] for t in piece_tokens if t in vocab], device=device)
314
+ self.square_token_ids = torch.tensor([vocab[t] for t in square_tokens if t in vocab], device=device)
315
+ self.suffix_token_ids = torch.tensor([vocab[t] for t in suffix_tokens if t in vocab], device=device)
316
+ self.special_token_ids = torch.tensor([vocab[t] for t in special_tokens if t in vocab], device=device)
317
+
318
+ self._token_indices_initialized = True
319
+
320
+ def get_constrained_logits_mask(self, input_ids: torch.LongTensor) -> torch.Tensor:
321
+ """
322
+ Create a mask for constrained decoding based on the move pattern.
323
+
324
+ Pattern: [Piece] [Square] [Square] [Optional Suffix]
325
+
326
+ Args:
327
+ input_ids: Input token IDs of shape (batch_size, seq_len)
328
+
329
+ Returns:
330
+ Mask of shape (batch_size, vocab_size) where 1 = allowed, 0 = forbidden
331
+ """
332
+ batch_size, seq_len = input_ids.size()
333
+ device = input_ids.device
334
+ vocab_size = self.config.vocab_size
335
+
336
+
337
+ # Lazy initialization of token indices on the correct device
338
+ self._setup_token_type_indices(device)
339
+
340
+ # Initialize mask (all tokens forbidden by default)
341
+ mask = torch.zeros(batch_size, vocab_size, device=device)
342
+
343
+ # Token indices are already on the correct device
344
+ piece_ids = self.piece_token_ids
345
+ square_ids = self.square_token_ids
346
+ suffix_ids = self.suffix_token_ids
347
+ special_ids = self.special_token_ids
348
+ # Move indices to device
349
+ piece_ids = self.piece_token_ids.to(device)
350
+ square_ids = self.square_token_ids.to(device)
351
+ suffix_ids = self.suffix_token_ids.to(device)
352
+ special_ids = self.special_token_ids.to(device)
353
+
354
+ for b in range(batch_size):
355
+ # Get recent tokens (look at last few to determine pattern position)
356
+ # Count backwards from the last piece token to determine position in move
357
+ recent_tokens = input_ids[b, max(0, seq_len-10):seq_len]
358
+
359
+ # Find the last occurrence of a piece token
360
+ piece_mask = torch.isin(recent_tokens, piece_ids)
361
+ if piece_mask.any():
362
+ last_piece_idx = torch.where(piece_mask)[0][-1].item()
363
+ tokens_since_piece = len(recent_tokens) - last_piece_idx - 1
364
+
365
+ if tokens_since_piece == 0:
366
+ # Just saw piece → expect square (from_square)
367
+ mask[b, square_ids] = 1
368
+ elif tokens_since_piece == 1:
369
+ # Just saw from_square → expect square (to_square)
370
+ mask[b, square_ids] = 1
371
+ elif tokens_since_piece == 2:
372
+ # Just saw to_square → expect suffix OR new piece
373
+ mask[b, suffix_ids] = 1
374
+ mask[b, piece_ids] = 1
375
+ else:
376
+ # After suffix or multiple tokens → expect new piece
377
+ mask[b, piece_ids] = 1
378
+ else:
379
+ # No piece seen yet → expect piece (start of sequence/game)
380
+ mask[b, piece_ids] = 1
381
+ mask[b, special_ids] = 1 # Allow special tokens
382
+
383
+ return mask
384
+
385
+ def get_input_embeddings(self) -> nn.Module:
386
+ return self.wte
387
+
388
+ def set_input_embeddings(self, new_embeddings: nn.Module):
389
+ self.wte = new_embeddings
390
+ if getattr(self.config, "tie_weights", False):
391
+ self.tie_weights()
392
+
393
+ def get_output_embeddings(self) -> nn.Module:
394
+ return self.lm_head
395
+
396
+ def set_output_embeddings(self, new_embeddings: nn.Module):
397
+ self.lm_head = new_embeddings
398
+
399
+ def tie_weights(self):
400
+ # Use HF helper to tie or clone depending on config
401
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
402
+ self._tie_or_clone_weights(self.lm_head, self.wte)
403
+
404
+ def _init_weights(self, module: nn.Module):
405
+ """Initialize weights following GPT-2 style."""
406
+ if isinstance(module, nn.Linear):
407
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
408
+ if module.bias is not None:
409
+ torch.nn.init.zeros_(module.bias)
410
+ elif isinstance(module, nn.Embedding):
411
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
412
+ elif isinstance(module, nn.LayerNorm):
413
+ torch.nn.init.ones_(module.weight)
414
+ torch.nn.init.zeros_(module.bias)
415
+
416
+ def prepare_for_structured_generation(self, tokenizer):
417
+ """Prepare the model for structured generation with a tokenizer.
418
+
419
+ This builds vocabulary masks and stores tokenizer reference for state analysis.
420
+ Call this before generation to enable structured move generation.
421
+
422
+ Args:
423
+ tokenizer: ChessTokenizer instance with build_vocabulary_masks method.
424
+ """
425
+ self.tokenizer_ref = tokenizer
426
+ self.vocab_masks = tokenizer.build_vocabulary_masks()
427
+ # Move masks to same device as model
428
+ device = next(self.parameters()).device
429
+ self.vocab_masks = {k: v.to(device) for k, v in self.vocab_masks.items()}
430
+ self.use_constrained_decoding = True
431
+ print(f"Structured generation enabled with {len(self.vocab_masks)} mask types")
432
+
433
+ def _get_allowed_tokens_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
434
+ """Get a mask of allowed tokens based on current generation state.
435
+
436
+ Args:
437
+ input_ids: Tensor of shape (batch_size, seq_len).
438
+
439
+ Returns:
440
+ Boolean tensor of shape (batch_size, vocab_size) where True = allowed.
441
+ """
442
+ # Auto-prepare if not already done (for compatibility with evaluate.py)
443
+ if self.vocab_masks is None and self.tokenizer_ref is None:
444
+ # Try to auto-prepare using component mode tokenizer
445
+ try:
446
+ from tokenizer import ChessTokenizer
447
+ tokenizer = ChessTokenizer.build_vocab_more_detailed()
448
+ self.prepare_for_structured_generation(tokenizer)
449
+ except:
450
+ # If auto-prepare fails, allow all tokens (no constraints)
451
+ device = input_ids.device
452
+ return torch.ones((input_ids.shape[0], self.config.vocab_size), dtype=torch.bool, device=device)
453
+
454
+ if self.vocab_masks is None or self.tokenizer_ref is None:
455
+ # Still not prepared, allow all tokens
456
+ device = input_ids.device
457
+ return torch.ones((input_ids.shape[0], self.config.vocab_size), dtype=torch.bool, device=device)
458
+
459
+ batch_size = input_ids.shape[0]
460
+ vocab_size = self.config.vocab_size
461
+ device = input_ids.device
462
+
463
+ # Analyze generation state
464
+ state = self.tokenizer_ref.analyze_generation_state(input_ids)
465
+
466
+ # Handle single batch (state is dict) vs multi-batch (state is list)
467
+ if isinstance(state, dict):
468
+ states = [state]
469
+ else:
470
+ states = state
471
+
472
+ # Build mask for each batch element
473
+ masks = []
474
+ for s in states:
475
+ position = s['position']
476
+ expected_color = s['expected_color']
477
+
478
+ # Initialize mask (all False)
479
+ mask = torch.zeros(vocab_size, dtype=torch.bool, device=device)
480
+
481
+ if position == 0:
482
+ # Expect piece token with correct color
483
+ if expected_color == 'W':
484
+ mask = self.vocab_masks['white_piece'].clone()
485
+ else:
486
+ mask = self.vocab_masks['black_piece'].clone()
487
+ elif position == 1:
488
+ # Expect from_square
489
+ mask = self.vocab_masks['square'].clone()
490
+ elif position == 2:
491
+ # Expect to_square
492
+ mask = self.vocab_masks['square'].clone()
493
+ else: # position == 3
494
+ # Expect suffix or [EOM]
495
+ mask = self.vocab_masks['suffix'] | self.vocab_masks['eom']
496
+
497
+ masks.append(mask)
498
+
499
+ # Stack into (batch_size, vocab_size)
500
+ return torch.stack(masks, dim=0)
501
+
502
+ def forward(
503
+ self,
504
+ input_ids: torch.LongTensor,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ labels: Optional[torch.LongTensor] = None,
508
+ return_dict: Optional[bool] = None,
509
+ **kwargs,
510
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
511
+ """
512
+ Forward pass of the model.
513
+
514
+ Args:
515
+ input_ids: Token IDs of shape (batch_size, seq_len).
516
+ attention_mask: Attention mask of shape (batch_size, seq_len).
517
+ position_ids: Position IDs of shape (batch_size, seq_len).
518
+ labels: Labels for language modeling loss.
519
+ return_dict: Whether to return a ModelOutput object.
520
+
521
+ Returns:
522
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
523
+ """
524
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
525
+
526
+ batch_size, seq_len = input_ids.size()
527
+ device = input_ids.device
528
+
529
+ # Create position IDs if not provided
530
+ if position_ids is None:
531
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
532
+
533
+ # Get embeddings
534
+ token_embeds = self.wte(input_ids)
535
+ position_embeds = self.wpe(position_ids)
536
+ hidden_states = self.drop(token_embeds + position_embeds)
537
+
538
+ # Pass through transformer blocks
539
+ for block in self.h:
540
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
541
+
542
+ # Final layer norm
543
+ hidden_states = self.ln_f(hidden_states)
544
+
545
+ # Get logits
546
+ logits = self.lm_head(hidden_states)
547
+
548
+ # Apply structured generation mask during inference (eval mode without labels)
549
+ if not self.training and labels is None and hasattr(self, 'use_constrained_decoding') and self.use_constrained_decoding:
550
+ # Get mask for valid next tokens based on generation state
551
+ allowed_mask = self._get_allowed_tokens_mask(input_ids) # (batch_size, vocab_size)
552
+ # Apply mask to last position logits only (where we're generating)
553
+ last_logits = logits[:, -1, :] # (batch_size, vocab_size)
554
+ # Set disallowed tokens to -inf
555
+ last_logits = last_logits.masked_fill(~allowed_mask, float('-inf'))
556
+ # Update logits
557
+ logits[:, -1, :] = last_logits
558
+
559
+ # Compute loss if labels are provided
560
+ loss = None
561
+ if labels is not None:
562
+ # Shift logits and labels for next-token prediction
563
+ shift_logits = logits[..., :-1, :].contiguous()
564
+ shift_labels = labels[..., 1:].contiguous()
565
+
566
+ # Flatten for cross-entropy
567
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
568
+ # loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
569
+ loss = loss_fct(
570
+ shift_logits.view(-1, shift_logits.size(-1)),
571
+ shift_labels.view(-1),
572
+ )
573
+
574
+ if not return_dict:
575
+ output = (logits,)
576
+ return ((loss,) + output) if loss is not None else output
577
+
578
+ return CausalLMOutputWithPast(
579
+ loss=loss,
580
+ logits=logits,
581
+ past_key_values=None,
582
+ hidden_states=None,
583
+ attentions=None,
584
+ )
585
+
586
+ @torch.no_grad()
587
+ def generate_move(
588
+ self,
589
+ input_ids: torch.LongTensor,
590
+ temperature: float = 1.0,
591
+ top_k: Optional[int] = None,
592
+ top_p: Optional[float] = None,
593
+ ) -> int:
594
+ """
595
+ Generate the next move given a sequence of moves.
596
+
597
+ Args:
598
+ input_ids: Token IDs of shape (1, seq_len).
599
+ temperature: Sampling temperature (1.0 = no change).
600
+ top_k: If set, only sample from top k tokens.
601
+ top_p: If set, use nucleus sampling with this threshold.
602
+
603
+ Returns:
604
+ The token ID of the predicted next move.
605
+ """
606
+ self.eval()
607
+
608
+ # Get logits for the last position
609
+ outputs = self(input_ids)
610
+ logits = outputs.logits[:, -1, :] / temperature
611
+
612
+ # Apply top-k filtering
613
+ if top_k is not None:
614
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
615
+ logits[indices_to_remove] = float("-inf")
616
+
617
+ # Apply top-p (nucleus) filtering
618
+ if top_p is not None:
619
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
620
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
621
+
622
+ # Remove tokens with cumulative probability above the threshold
623
+ sorted_indices_to_remove = cumulative_probs > top_p
624
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
625
+ sorted_indices_to_remove[..., 0] = 0
626
+
627
+ indices_to_remove = sorted_indices_to_remove.scatter(
628
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
629
+ )
630
+ logits[indices_to_remove] = float("-inf")
631
+
632
+ # Sample from the distribution
633
+ probs = F.softmax(logits, dim=-1)
634
+ next_token = torch.multinomial(probs, num_samples=1)
635
+
636
+ return next_token.item()
637
+
638
+
639
+ # Register the model with Auto classes for easy loading
640
+ from transformers import AutoConfig, AutoModelForCausalLM
641
+
642
+ AutoConfig.register("chess_transformer", ChessConfig)
643
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72437bd478fb1d15478bb2d4079a277d8fdec02823433d900c164e77e5bc19de
3
+ size 3492656
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,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ EOM_TOKEN = "[EOM]" # End of Move - marks boundary between moves
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file: Optional[str] = None,
51
+ vocab: Optional[Dict[str, int]] = None,
52
+ component_mode: bool = False,
53
+ **kwargs,
54
+ ):
55
+ """
56
+ Initialize the chess tokenizer.
57
+
58
+ Args:
59
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
60
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
61
+ component_mode: If True, tokenize moves into components (WP, e2, e4).
62
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
63
+ """
64
+ # Initialize special tokens
65
+ self._pad_token = self.PAD_TOKEN
66
+ self._bos_token = self.BOS_TOKEN
67
+ self._eos_token = self.EOS_TOKEN
68
+ self._unk_token = self.UNK_TOKEN
69
+ self._eom_token = self.EOM_TOKEN
70
+
71
+ # Component mode flag (for splitting moves into parts)
72
+ self._component_mode = component_mode
73
+
74
+ # Remove any duplicate special-token entries passed through kwargs
75
+ # to avoid "multiple values for keyword" errors when loading from disk.
76
+ kwargs.pop("pad_token", None)
77
+ kwargs.pop("bos_token", None)
78
+ kwargs.pop("eos_token", None)
79
+ kwargs.pop("unk_token", None)
80
+ kwargs.pop("eom_token", None)
81
+ kwargs.pop("component_mode", None)
82
+
83
+ # Load or create vocabulary
84
+ if vocab is not None:
85
+ self._vocab = vocab
86
+ elif vocab_file is not None and os.path.exists(vocab_file):
87
+ with open(vocab_file, "r", encoding="utf-8") as f:
88
+ self._vocab = json.load(f)
89
+ else:
90
+ # Create a minimal vocabulary with just special tokens
91
+ # The full vocabulary should be built from the dataset
92
+ self._vocab = self._create_default_vocab()
93
+
94
+ # Create reverse mapping
95
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
96
+
97
+ # Call parent init AFTER setting up vocab
98
+ super().__init__(
99
+ pad_token=self._pad_token,
100
+ bos_token=self._bos_token,
101
+ eos_token=self._eos_token,
102
+ unk_token=self._unk_token,
103
+ component_mode=component_mode, # This gets saved to tokenizer_config.json
104
+ **kwargs,
105
+ )
106
+ # Store EOM token ID for easy access
107
+ self.eom_token_id = self._vocab.get(self.EOM_TOKEN, -1)
108
+
109
+ def _create_default_vocab(self) -> Dict[str, int]:
110
+ """
111
+ Create a minimal default vocabulary with just special tokens.
112
+
113
+ For the full vocabulary, use `build_vocab_from_dataset()`.
114
+ This minimal vocab is just a placeholder - you should build from data.
115
+ """
116
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
117
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
118
+ return vocab
119
+
120
+ @classmethod
121
+ def build_vocab_from_iterator(
122
+ cls,
123
+ iterator,
124
+ min_frequency: int = 1,
125
+ ) -> "ChessTokenizer":
126
+ """
127
+ Build a tokenizer vocabulary from an iterator of game strings.
128
+
129
+ Args:
130
+ iterator: An iterator yielding game strings (space-separated moves).
131
+ min_frequency: Minimum frequency for a token to be included.
132
+
133
+ Returns:
134
+ A ChessTokenizer with the built vocabulary.
135
+ """
136
+ from collections import Counter
137
+
138
+ token_counts = Counter()
139
+
140
+ for game in iterator:
141
+ moves = game.strip().split()
142
+ token_counts.update(moves)
143
+
144
+ # Filter by frequency
145
+ tokens = [
146
+ token for token, count in token_counts.items()
147
+ if count >= min_frequency
148
+ ]
149
+
150
+ # Sort for reproducibility
151
+ tokens = sorted(tokens)
152
+
153
+ # Build vocabulary
154
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
155
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
156
+
157
+ return cls(vocab=vocab)
158
+
159
+ @classmethod
160
+ def build_vocab_from_dataset(
161
+ cls,
162
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
163
+ split: str = "train",
164
+ column: str = "text",
165
+ min_frequency: int = 500,
166
+ max_samples: Optional[int] = 100000,
167
+ ) -> "ChessTokenizer":
168
+ """
169
+ Build a tokenizer vocabulary from a Hugging Face dataset.
170
+
171
+ Args:
172
+ dataset_name: Name of the dataset on Hugging Face Hub.
173
+ split: Dataset split to use.
174
+ column: Column containing the game strings.
175
+ min_frequency: Minimum frequency for a token to be included (default: 500).
176
+ max_samples: Maximum number of samples to process (default: 100k).
177
+
178
+ Returns:
179
+ A ChessTokenizer with the built vocabulary.
180
+ """
181
+ from datasets import load_dataset
182
+
183
+ dataset = load_dataset(dataset_name, split=split)
184
+
185
+ if max_samples is not None:
186
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
187
+
188
+ def game_iterator():
189
+ for example in dataset:
190
+ yield example[column]
191
+
192
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
193
+
194
+ @classmethod
195
+ def build_vocab_more_detailed(
196
+ cls,
197
+ ) -> "ChessTokenizer":
198
+ """
199
+ Build a component-based tokenizer for chess moves.
200
+
201
+ Instead of one token per move (WPe2e4), splits into components:
202
+ WPe2e4 -> [WP, e2, e4]
203
+ BNg8f6(x) -> [BN, g8, f6, (x)]
204
+
205
+ This gives ~90 tokens instead of ~1200, with better generalization.
206
+
207
+ Returns:
208
+ A ChessTokenizer with component vocabulary.
209
+ """
210
+ # Combined color+piece tokens (avoids B collision between Black and Bishop)
211
+ tokens_pieces = [
212
+ "WP", "WN", "WB", "WR", "WQ", "WK", # White pieces
213
+ "BP", "BN", "BB", "BR", "BQ", "BK", # Black pieces
214
+ ]
215
+
216
+ # the positions:
217
+ files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
218
+ ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
219
+ tokens_positions = [f + r for f in files for r in ranks]
220
+
221
+ # the special suffixes:
222
+ tokens_suffixes = [
223
+ "(x)", # capture
224
+ "(+)", # check
225
+ "(x+)", # capture + check
226
+ "(+*)", # checkmate
227
+ "(x+*)", # capture + checkmate
228
+ "(o)", # kingside castling
229
+ "(O)", # queenside castling
230
+ "(xE)", # en passant
231
+ "=Q", # promotion to queen
232
+ "=R", # promotion to rook
233
+ "=B", # promotion to bishop
234
+ "=N", # promotion to knight
235
+ ]
236
+
237
+ # Combine all tokens
238
+ tokens = tokens_pieces + tokens_positions + tokens_suffixes
239
+
240
+ # Build vocabulary with [EOM] for move boundaries
241
+ # [EOM] helps the model understand when a move ends
242
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN, cls.EOM_TOKEN]
243
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
244
+ for ind, token in enumerate(special_tokens+tokens):
245
+ print(f"Token {ind}: {token}")
246
+ # Pass component_mode=True so it gets saved to tokenizer_config.json
247
+ return cls(vocab=vocab, component_mode=True)
248
+
249
+ @property
250
+ def vocab_size(self) -> int:
251
+ """Return the size of the vocabulary."""
252
+ return len(self._vocab)
253
+
254
+ def get_vocab(self) -> Dict[str, int]:
255
+ """Return the vocabulary as a dictionary."""
256
+ return dict(self._vocab)
257
+
258
+ def _tokenize(self, text: str) -> List[str]:
259
+ """
260
+ Tokenize a string of moves into a list of tokens.
261
+
262
+ If component_mode is enabled, splits each move into parts:
263
+ WPe2e4 -> [W, P, e2, e4, " "]
264
+ BNg8f6(x) -> [B, N, g8, f6, (x), " "]
265
+
266
+ Args:
267
+ text: A string of space-separated moves.
268
+
269
+ Returns:
270
+ List of tokens.
271
+ """
272
+ if getattr(self, '_component_mode', False):
273
+ return self._tokenize_components(text)
274
+ return text.strip().split()
275
+
276
+ def _tokenize_components(self, text: str) -> List[str]:
277
+ """
278
+ Tokenize moves into component parts with [EOM] boundaries.
279
+
280
+ Move format: [Color][Piece][from_square][to_square][suffix] [EOM]
281
+ Example:
282
+ WPe2e4 -> [WP, e2, e4, EOM]
283
+ BNg8f6(x) -> [BN, g8, f6, (x), EOM]
284
+ """
285
+ import re
286
+
287
+ tokens = []
288
+ moves = text.strip().split()
289
+
290
+ for i, move in enumerate(moves):
291
+ # Skip special tokens
292
+ if move in [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.EOM_TOKEN]:
293
+ tokens.append(move)
294
+ continue
295
+
296
+ # Parse move: ColorPiece + from_square + to_square + optional suffix
297
+ # Pattern: (W|B)(P|N|B|R|Q|K)([a-h][1-8])([a-h][1-8])(suffix)?
298
+ pattern = r'^([WB])([PNBRQK])([a-h][1-8])([a-h][1-8])(.*)$'
299
+ match = re.match(pattern, move)
300
+
301
+ if match:
302
+ color, piece, from_sq, to_sq, suffix = match.groups()
303
+ # Combined color+piece token (e.g., "WP", "BN", "BB")
304
+ tokens.append(color + piece)
305
+ tokens.extend([from_sq, to_sq])
306
+
307
+ # Handle suffix (could be combination like "(x+)" or "=Q")
308
+ if suffix:
309
+ # Try to match known suffixes
310
+ suffix_pattern = r'(\(x\+\*\)|\(x\+\)|\(\+\*\)|\(xE\)|\(x\)|\(\+\)|\(o\)|\(O\)|=Q|=R|=B|=N)'
311
+ suffix_matches = re.findall(suffix_pattern, suffix)
312
+ tokens.extend(suffix_matches)
313
+
314
+ # Add [EOM] to mark end of this move
315
+ tokens.append(self.EOM_TOKEN)
316
+ else:
317
+ # Fallback: add as unknown + EOM
318
+ tokens.append(self.UNK_TOKEN)
319
+ tokens.append(self.EOM_TOKEN)
320
+
321
+ return tokens
322
+
323
+ def _convert_token_to_id(self, token: str) -> int:
324
+ """Convert a token to its ID."""
325
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
326
+
327
+ def _convert_id_to_token(self, index: int) -> str:
328
+ """Convert an ID to its token."""
329
+ token = self._ids_to_tokens.get(index, self.UNK_TOKEN)
330
+ # Convert [EOM] to whitespace for evaluator compatibility
331
+ # This makes _generate_until_whitespace stop after one move
332
+ if token == self.EOM_TOKEN:
333
+ return " "
334
+ return token
335
+
336
+ # Color+piece tokens that mark the start of a new move
337
+ _MOVE_START_TOKENS = {"WP", "WN", "WB", "WR", "WQ", "WK", "BP", "BN", "BB", "BR", "BQ", "BK"}
338
+
339
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
340
+ """Convert a list of tokens back to a string.
341
+
342
+ In component mode, reconstructs moves by replacing [EOM] with spaces.
343
+ CRITICAL: [EOM] must decode to a non-empty whitespace string so that
344
+ the evaluator's _generate_until_whitespace stops after one move.
345
+ """
346
+ # Filter out special tokens except EOM for cleaner output
347
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
348
+
349
+ if getattr(self, '_component_mode', False):
350
+ # Reconstruct with [EOM] as space delimiter
351
+ result = []
352
+ for token in tokens:
353
+ if token == self.EOM_TOKEN:
354
+ # MUST be non-empty whitespace for evaluator
355
+ result.append(" ")
356
+ elif token not in special:
357
+ result.append(token)
358
+ # Don't strip! We need the trailing space from [EOM]
359
+ return "".join(result)
360
+
361
+ # Non-component mode: just join with spaces
362
+ filtered = [t for t in tokens if t not in special]
363
+ return " ".join(filtered)
364
+
365
+ # =========================================================================
366
+ # Structured Generation Support Methods
367
+ # =========================================================================
368
+
369
+ def get_token_category(self, token: str) -> str:
370
+ """Categorize a token into: piece, square, suffix, eom, or special.
371
+
372
+ Args:
373
+ token: Token string to categorize.
374
+
375
+ Returns:
376
+ Category name: 'piece', 'square', 'suffix', 'eom', or 'special'.
377
+ """
378
+ if token in [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]:
379
+ return 'special'
380
+ if token == self.EOM_TOKEN:
381
+ return 'eom'
382
+ if self.is_piece_token(token):
383
+ return 'piece'
384
+ if self.is_square_token(token):
385
+ return 'square'
386
+ if self.is_suffix_token(token):
387
+ return 'suffix'
388
+ return 'unknown'
389
+
390
+ def is_piece_token(self, token: str) -> bool:
391
+ """Check if token is a piece token (WP, BN, etc.)."""
392
+ return token in ['WP', 'WN', 'WB', 'WR', 'WQ', 'WK', 'BP', 'BN', 'BB', 'BR', 'BQ', 'BK']
393
+
394
+ def is_square_token(self, token: str) -> bool:
395
+ """Check if token is a square token (e2, g8, etc.)."""
396
+ if len(token) != 2:
397
+ return False
398
+ return token[0] in 'abcdefgh' and token[1] in '12345678'
399
+
400
+ def is_suffix_token(self, token: str) -> bool:
401
+ """Check if token is a suffix token ((x), (+), =Q, etc.)."""
402
+ return token in ['(x)', '(+)', '(x+)', '(+*)', '(x+*)', '(o)', '(O)', '(xE)', '=Q', '=R', '=B', '=N']
403
+
404
+ def is_eom_token(self, token: str) -> bool:
405
+ """Check if token is the [EOM] token."""
406
+ return token == self.EOM_TOKEN
407
+
408
+ def get_token_color(self, token: str) -> Optional[str]:
409
+ """Get the color ('W' or 'B') from a piece token, None otherwise."""
410
+ if self.is_piece_token(token) and len(token) >= 2:
411
+ return token[0] # 'W' or 'B'
412
+ return None
413
+
414
+ def build_vocabulary_masks(self) -> dict:
415
+ """Build boolean masks for each token category.
416
+
417
+ Returns:
418
+ Dictionary with keys: 'piece', 'square', 'suffix', 'eom', 'white_piece', 'black_piece'.
419
+ Each value is a boolean list/tensor of length vocab_size.
420
+ """
421
+ import torch
422
+
423
+ vocab_size = len(self._vocab)
424
+ masks = {
425
+ 'piece': [False] * vocab_size,
426
+ 'square': [False] * vocab_size,
427
+ 'suffix': [False] * vocab_size,
428
+ 'eom': [False] * vocab_size,
429
+ 'white_piece': [False] * vocab_size,
430
+ 'black_piece': [False] * vocab_size,
431
+ }
432
+
433
+ for token, token_id in self._vocab.items():
434
+ if self.is_piece_token(token):
435
+ masks['piece'][token_id] = True
436
+ color = self.get_token_color(token)
437
+ if color == 'W':
438
+ masks['white_piece'][token_id] = True
439
+ elif color == 'B':
440
+ masks['black_piece'][token_id] = True
441
+ elif self.is_square_token(token):
442
+ masks['square'][token_id] = True
443
+ elif self.is_suffix_token(token):
444
+ masks['suffix'][token_id] = True
445
+ elif self.is_eom_token(token):
446
+ masks['eom'][token_id] = True
447
+
448
+ # Convert to tensors
449
+ return {k: torch.tensor(v, dtype=torch.bool) for k, v in masks.items()}
450
+
451
+ def analyze_generation_state(self, input_ids: torch.Tensor) -> dict:
452
+ """Analyze the current generation state to determine next expected token.
453
+
454
+ Args:
455
+ input_ids: Tensor of shape (batch_size, seq_len) with token IDs.
456
+
457
+ Returns:
458
+ Dictionary with:
459
+ - 'position': 0 (piece), 1 (from_square), 2 (to_square), 3 (suffix/eom)
460
+ - 'expected_color': 'W' or 'B'
461
+ - 'last_eom_idx': Index of last [EOM] token in sequence
462
+ """
463
+ batch_size = input_ids.shape[0]
464
+ results = []
465
+
466
+ for b in range(batch_size):
467
+ seq = input_ids[b].tolist()
468
+
469
+ # Find last [EOM] or [BOS]
470
+ last_eom_idx = -1
471
+ for i in range(len(seq) - 1, -1, -1):
472
+ token = self._ids_to_tokens.get(seq[i], self.UNK_TOKEN)
473
+ if token in [self.EOM_TOKEN, self.BOS_TOKEN]:
474
+ last_eom_idx = i
475
+ break
476
+
477
+ # Count tokens since last [EOM]/[BOS] (excluding padding)
478
+ tokens_since_boundary = []
479
+ for i in range(last_eom_idx + 1, len(seq)):
480
+ token = self._ids_to_tokens.get(seq[i], self.UNK_TOKEN)
481
+ if token != self.PAD_TOKEN:
482
+ tokens_since_boundary.append(token)
483
+
484
+ # Determine position in move structure: [Piece][Square][Square][Suffix?][EOM]
485
+ num_tokens = len(tokens_since_boundary)
486
+
487
+ if num_tokens == 0:
488
+ position = 0 # Expect piece
489
+ elif num_tokens == 1:
490
+ position = 1 # Expect from_square
491
+ elif num_tokens == 2:
492
+ position = 2 # Expect to_square
493
+ else:
494
+ position = 3 # Expect suffix or [EOM]
495
+
496
+ # Determine expected color by counting complete moves
497
+ # Count [EOM] tokens to get move number
498
+ eom_count = sum(1 for i in seq if self._ids_to_tokens.get(i, '') == self.EOM_TOKEN)
499
+ expected_color = 'W' if eom_count % 2 == 0 else 'B'
500
+
501
+ results.append({
502
+ 'position': position,
503
+ 'expected_color': expected_color,
504
+ 'last_eom_idx': last_eom_idx,
505
+ })
506
+
507
+ # For single batch, return dict directly; for multi-batch, return list
508
+ return results[0] if batch_size == 1 else results
509
+
510
+ def save_vocabulary(
511
+ self,
512
+ save_directory: str,
513
+ filename_prefix: Optional[str] = None,
514
+ ) -> tuple:
515
+ """
516
+ Save the vocabulary to a JSON file.
517
+
518
+ Args:
519
+ save_directory: Directory to save the vocabulary.
520
+ filename_prefix: Optional prefix for the filename.
521
+
522
+ Returns:
523
+ Tuple containing the path to the saved vocabulary file.
524
+ """
525
+ if not os.path.isdir(save_directory):
526
+ os.makedirs(save_directory, exist_ok=True)
527
+
528
+ vocab_file = os.path.join(
529
+ save_directory,
530
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
531
+ )
532
+
533
+ with open(vocab_file, "w", encoding="utf-8") as f:
534
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
535
+
536
+ return (vocab_file,)
537
+
538
+
539
+ def count_vocab_from_dataset(
540
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
541
+ split: str = "train",
542
+ column: str = "text",
543
+ max_samples: Optional[int] = 10000,
544
+ ) -> Dict[str, int]:
545
+ """
546
+ Count token frequencies in a dataset (useful for vocabulary analysis).
547
+
548
+ Args:
549
+ dataset_name: Name of the dataset on Hugging Face Hub.
550
+ split: Dataset split to use.
551
+ column: Column containing the game strings.
552
+ max_samples: Maximum number of samples to process.
553
+
554
+ Returns:
555
+ Dictionary mapping tokens to their frequencies.
556
+ """
557
+ from collections import Counter
558
+ from datasets import load_dataset
559
+
560
+ dataset = load_dataset(dataset_name, split=split)
561
+
562
+ if max_samples is not None:
563
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
564
+
565
+ token_counts = Counter()
566
+
567
+ for example in dataset:
568
+ moves = example[column].strip().split()
569
+ token_counts.update(moves)
570
+
571
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "clean_up_tokenization_spaces": false,
38
+ "component_mode": true,
39
+ "eos_token": "[EOS]",
40
+ "extra_special_tokens": {},
41
+ "model_max_length": 1000000000000000019884624838656,
42
+ "pad_token": "[PAD]",
43
+ "tokenizer_class": "ChessTokenizer",
44
+ "unk_token": "[UNK]",
45
+ "auto_map": {
46
+ "AutoTokenizer": [
47
+ "tokenizer.ChessTokenizer",
48
+ null
49
+ ]
50
+ }
51
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:078339b1e2d26d1eafa619e3e9eaad471f271142e053207e14cd496ff6660728
3
+ size 5713
vocab.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[EOM]": 4,
7
+ "WP": 5,
8
+ "WN": 6,
9
+ "WB": 7,
10
+ "WR": 8,
11
+ "WQ": 9,
12
+ "WK": 10,
13
+ "BP": 11,
14
+ "BN": 12,
15
+ "BB": 13,
16
+ "BR": 14,
17
+ "BQ": 15,
18
+ "BK": 16,
19
+ "a1": 17,
20
+ "a2": 18,
21
+ "a3": 19,
22
+ "a4": 20,
23
+ "a5": 21,
24
+ "a6": 22,
25
+ "a7": 23,
26
+ "a8": 24,
27
+ "b1": 25,
28
+ "b2": 26,
29
+ "b3": 27,
30
+ "b4": 28,
31
+ "b5": 29,
32
+ "b6": 30,
33
+ "b7": 31,
34
+ "b8": 32,
35
+ "c1": 33,
36
+ "c2": 34,
37
+ "c3": 35,
38
+ "c4": 36,
39
+ "c5": 37,
40
+ "c6": 38,
41
+ "c7": 39,
42
+ "c8": 40,
43
+ "d1": 41,
44
+ "d2": 42,
45
+ "d3": 43,
46
+ "d4": 44,
47
+ "d5": 45,
48
+ "d6": 46,
49
+ "d7": 47,
50
+ "d8": 48,
51
+ "e1": 49,
52
+ "e2": 50,
53
+ "e3": 51,
54
+ "e4": 52,
55
+ "e5": 53,
56
+ "e6": 54,
57
+ "e7": 55,
58
+ "e8": 56,
59
+ "f1": 57,
60
+ "f2": 58,
61
+ "f3": 59,
62
+ "f4": 60,
63
+ "f5": 61,
64
+ "f6": 62,
65
+ "f7": 63,
66
+ "f8": 64,
67
+ "g1": 65,
68
+ "g2": 66,
69
+ "g3": 67,
70
+ "g4": 68,
71
+ "g5": 69,
72
+ "g6": 70,
73
+ "g7": 71,
74
+ "g8": 72,
75
+ "h1": 73,
76
+ "h2": 74,
77
+ "h3": 75,
78
+ "h4": 76,
79
+ "h5": 77,
80
+ "h6": 78,
81
+ "h7": 79,
82
+ "h8": 80,
83
+ "(x)": 81,
84
+ "(+)": 82,
85
+ "(x+)": 83,
86
+ "(+*)": 84,
87
+ "(x+*)": 85,
88
+ "(o)": 86,
89
+ "(O)": 87,
90
+ "(xE)": 88,
91
+ "=Q": 89,
92
+ "=R": 90,
93
+ "=B": 91,
94
+ "=N": 92
95
+ }