janisaiad commited on
Commit
2ded2f5
·
verified ·
1 Parent(s): fcc1cf3

Chess Challenge submission by janisaiad

Browse files
Files changed (9) hide show
  1. README.md +25 -0
  2. config.json +25 -0
  3. model.py +447 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +278 -0
  7. tokenizer_config.json +50 -0
  8. tokenizer_decomposed.py +157 -0
  9. vocab.json +150 -0
README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ ## Chess model submitted to the LLM Course Chess Challenge.
11
+
12
+ ### Submission Info
13
+ - **Submitted by**: [janisaiad](https://huggingface.co/janisaiad)
14
+ - **Parameters**: 97,440
15
+ - **Organization**: LLM-course
16
+
17
+ ### Model Details
18
+ - **Architecture**: Tiny Recursive Model (TRM) - looping recurrent transformer (cycle-shared weights)
19
+ - **Vocab size**: 148
20
+ - **Embedding dim**: 80
21
+ - **Layers**: 1
22
+ - **Heads**: 2
23
+ - **Cycles**: 2
24
+
25
+ **TRM note**: this is a *looping* TRM model — at inference/training time we run the same transformer stack for **2** recurrent refinement cycle(s) (weights are shared across cycles), which increases compute/reasoning depth **without increasing parameter count**.
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "model.ChessConfig",
7
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "dropout": 0.1,
11
+ "dtype": "float32",
12
+ "eos_token_id": 2,
13
+ "layer_norm_epsilon": 1e-05,
14
+ "model_type": "chess_transformer",
15
+ "n_ctx": 256,
16
+ "n_cycles": 2,
17
+ "n_embd": 80,
18
+ "n_head": 2,
19
+ "n_inner": 240,
20
+ "n_layer": 1,
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,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ n_cycles: int = 1,
62
+ dropout: float = 0.1,
63
+ layer_norm_epsilon: float = 1e-5,
64
+ tie_weights: bool = True,
65
+ pad_token_id: int = 0,
66
+ bos_token_id: int = 1,
67
+ eos_token_id: int = 2,
68
+ **kwargs,
69
+ ):
70
+ super().__init__(
71
+ pad_token_id=pad_token_id,
72
+ bos_token_id=bos_token_id,
73
+ eos_token_id=eos_token_id,
74
+ **kwargs,
75
+ )
76
+
77
+ self.vocab_size = vocab_size
78
+ self.n_embd = n_embd
79
+ self.n_layer = n_layer
80
+ self.n_head = n_head
81
+ self.n_ctx = n_ctx
82
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
83
+ self.n_cycles = int(n_cycles)
84
+ self.dropout = dropout
85
+ self.layer_norm_epsilon = layer_norm_epsilon
86
+ self.tie_weights = tie_weights
87
+ # Inform HF base class about tying behavior
88
+ self.tie_word_embeddings = bool(tie_weights)
89
+
90
+
91
+ class MultiHeadAttention(nn.Module):
92
+ """
93
+ Multi-head self-attention module.
94
+
95
+ This is a standard scaled dot-product attention implementation
96
+ with causal masking for autoregressive generation.
97
+ """
98
+
99
+ def __init__(self, config: ChessConfig):
100
+ super().__init__()
101
+
102
+ assert config.n_embd % config.n_head == 0, \
103
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
104
+
105
+ self.n_head = config.n_head
106
+ self.n_embd = config.n_embd
107
+ self.head_dim = config.n_embd // config.n_head
108
+
109
+ # Combined QKV projection for efficiency
110
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
111
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
112
+
113
+ self.dropout = nn.Dropout(config.dropout)
114
+
115
+ # Causal mask (will be created on first forward pass)
116
+ self.register_buffer(
117
+ "bias",
118
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
119
+ 1, 1, config.n_ctx, config.n_ctx
120
+ ),
121
+ persistent=False,
122
+ )
123
+
124
+ def forward(
125
+ self,
126
+ x: torch.Tensor,
127
+ attention_mask: Optional[torch.Tensor] = None,
128
+ ) -> torch.Tensor:
129
+ batch_size, seq_len, _ = x.size()
130
+
131
+ # Compute Q, K, V
132
+ qkv = self.c_attn(x)
133
+ q, k, v = qkv.split(self.n_embd, dim=2)
134
+
135
+ # Reshape for multi-head attention
136
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
137
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
138
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
139
+
140
+ # Scaled dot-product attention
141
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
142
+
143
+ # Apply causal mask
144
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
145
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
146
+
147
+ # Apply attention mask (for padding)
148
+ if attention_mask is not None:
149
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
150
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
151
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
152
+
153
+ attn_weights = F.softmax(attn_weights, dim=-1)
154
+ attn_weights = self.dropout(attn_weights)
155
+
156
+ # Apply attention to values
157
+ attn_output = torch.matmul(attn_weights, v)
158
+
159
+ # Reshape back
160
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
161
+ batch_size, seq_len, self.n_embd
162
+ )
163
+
164
+ # Output projection
165
+ attn_output = self.c_proj(attn_output)
166
+
167
+ return attn_output
168
+
169
+
170
+ class FeedForward(nn.Module):
171
+ """
172
+ Feed-forward network (MLP) module.
173
+
174
+ Standard two-layer MLP with GELU activation.
175
+ """
176
+
177
+ def __init__(self, config: ChessConfig):
178
+ super().__init__()
179
+
180
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner)
181
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
182
+ self.dropout = nn.Dropout(config.dropout)
183
+
184
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
185
+ x = self.c_fc(x)
186
+ x = F.gelu(x)
187
+ x = self.c_proj(x)
188
+ x = self.dropout(x)
189
+ return x
190
+
191
+
192
+ class TransformerBlock(nn.Module):
193
+ """
194
+ A single transformer block with attention and feed-forward layers.
195
+
196
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
197
+ training stability.
198
+ """
199
+
200
+ def __init__(self, config: ChessConfig):
201
+ super().__init__()
202
+
203
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
204
+ self.attn = MultiHeadAttention(config)
205
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
206
+ self.mlp = FeedForward(config)
207
+
208
+ def forward(
209
+ self,
210
+ x: torch.Tensor,
211
+ attention_mask: Optional[torch.Tensor] = None,
212
+ ) -> torch.Tensor:
213
+ # Pre-norm attention
214
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
215
+ # Pre-norm FFN
216
+ x = x + self.mlp(self.ln_2(x))
217
+ return x
218
+
219
+
220
+ class ChessForCausalLM(PreTrainedModel):
221
+ """
222
+ Chess Transformer for Causal Language Modeling (next-move prediction).
223
+
224
+ This model is designed to predict the next chess move given a sequence
225
+ of previous moves. It uses a GPT-style architecture with:
226
+ - Token embeddings for chess moves
227
+ - Learned positional embeddings
228
+ - Stacked transformer blocks
229
+ - Linear head for next-token prediction
230
+
231
+ The model supports weight tying between the embedding layer and the
232
+ output projection to save parameters.
233
+
234
+ Example:
235
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
236
+ >>> model = ChessForCausalLM(config)
237
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
238
+ >>> outputs = model(**inputs)
239
+ >>> next_move_logits = outputs.logits[:, -1, :]
240
+ """
241
+
242
+ config_class = ChessConfig
243
+ base_model_prefix = "transformer"
244
+ supports_gradient_checkpointing = True
245
+ # Suppress missing-key warning for tied lm_head when loading
246
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
247
+
248
+ def __init__(self, config: ChessConfig):
249
+ super().__init__(config)
250
+
251
+ # Token and position embeddings
252
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
253
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
254
+
255
+ self.drop = nn.Dropout(config.dropout)
256
+
257
+ # Transformer blocks
258
+ self.h = nn.ModuleList([
259
+ TransformerBlock(config) for _ in range(config.n_layer)
260
+ ])
261
+
262
+ # Final layer norm
263
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
264
+
265
+ # Output head
266
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
267
+
268
+ # Declare tied weights for proper serialization
269
+ if config.tie_weights:
270
+ self._tied_weights_keys = ["lm_head.weight"]
271
+
272
+ # Initialize weights
273
+ self.post_init()
274
+
275
+ # Tie weights if configured
276
+ if config.tie_weights:
277
+ self.tie_weights()
278
+
279
+ def get_input_embeddings(self) -> nn.Module:
280
+ return self.wte
281
+
282
+ def set_input_embeddings(self, new_embeddings: nn.Module):
283
+ self.wte = new_embeddings
284
+ if getattr(self.config, "tie_weights", False):
285
+ self.tie_weights()
286
+
287
+ def get_output_embeddings(self) -> nn.Module:
288
+ return self.lm_head
289
+
290
+ def set_output_embeddings(self, new_embeddings: nn.Module):
291
+ self.lm_head = new_embeddings
292
+
293
+ def tie_weights(self):
294
+ # Use HF helper to tie or clone depending on config
295
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
296
+ self._tie_or_clone_weights(self.lm_head, self.wte)
297
+
298
+ def _init_weights(self, module: nn.Module):
299
+ """Initialize weights following GPT-2 style."""
300
+ if isinstance(module, nn.Linear):
301
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
302
+ if module.bias is not None:
303
+ torch.nn.init.zeros_(module.bias)
304
+ elif isinstance(module, nn.Embedding):
305
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
306
+ elif isinstance(module, nn.LayerNorm):
307
+ torch.nn.init.ones_(module.weight)
308
+ torch.nn.init.zeros_(module.bias)
309
+
310
+ def forward(
311
+ self,
312
+ input_ids: torch.LongTensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ labels: Optional[torch.LongTensor] = None,
316
+ return_dict: Optional[bool] = None,
317
+ **kwargs,
318
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
319
+ """
320
+ Forward pass of the model.
321
+
322
+ Args:
323
+ input_ids: Token IDs of shape (batch_size, seq_len).
324
+ attention_mask: Attention mask of shape (batch_size, seq_len).
325
+ position_ids: Position IDs of shape (batch_size, seq_len).
326
+ labels: Labels for language modeling loss.
327
+ return_dict: Whether to return a ModelOutput object.
328
+
329
+ Returns:
330
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
331
+ """
332
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
333
+
334
+ batch_size, seq_len = input_ids.size()
335
+ device = input_ids.device
336
+
337
+ # Create position IDs if not provided
338
+ if position_ids is None:
339
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
340
+
341
+ if seq_len > self.config.n_ctx:
342
+ raise ValueError(f"seq_len ({seq_len}) exceeds n_ctx ({self.config.n_ctx})")
343
+
344
+ # Get embeddings
345
+ token_embeds = self.wte(input_ids)
346
+ position_embeds = self.wpe(position_ids)
347
+ input_injection = token_embeds + position_embeds
348
+ hidden_states = self.drop(input_injection)
349
+
350
+ # TRM-style refinement cycles (n_cycles=1 matches baseline behavior)
351
+ n_cycles = int(getattr(self.config, "n_cycles", 1))
352
+ for _ in range(max(n_cycles, 1)):
353
+ if n_cycles > 1:
354
+ hidden_states = hidden_states + input_injection
355
+ for block in self.h:
356
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
357
+
358
+ # Final layer norm
359
+ hidden_states = self.ln_f(hidden_states)
360
+
361
+ # Get logits
362
+ logits = self.lm_head(hidden_states)
363
+
364
+ # Compute loss if labels are provided
365
+ loss = None
366
+ if labels is not None:
367
+ # Shift logits and labels for next-token prediction
368
+ shift_logits = logits[..., :-1, :].contiguous()
369
+ shift_labels = labels[..., 1:].contiguous()
370
+
371
+ # Flatten for cross-entropy
372
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
373
+ loss = loss_fct(
374
+ shift_logits.view(-1, shift_logits.size(-1)),
375
+ shift_labels.view(-1),
376
+ )
377
+
378
+ if not return_dict:
379
+ output = (logits,)
380
+ return ((loss,) + output) if loss is not None else output
381
+
382
+ return CausalLMOutputWithPast(
383
+ loss=loss,
384
+ logits=logits,
385
+ past_key_values=None,
386
+ hidden_states=None,
387
+ attentions=None,
388
+ )
389
+
390
+ @torch.no_grad()
391
+ def generate_move(
392
+ self,
393
+ input_ids: torch.LongTensor,
394
+ temperature: float = 1.0,
395
+ top_k: Optional[int] = None,
396
+ top_p: Optional[float] = None,
397
+ ) -> int:
398
+ """
399
+ Generate the next move given a sequence of moves.
400
+
401
+ Args:
402
+ input_ids: Token IDs of shape (1, seq_len).
403
+ temperature: Sampling temperature (1.0 = no change).
404
+ top_k: If set, only sample from top k tokens.
405
+ top_p: If set, use nucleus sampling with this threshold.
406
+
407
+ Returns:
408
+ The token ID of the predicted next move.
409
+ """
410
+ self.eval()
411
+
412
+ # Get logits for the last position
413
+ outputs = self(input_ids)
414
+ logits = outputs.logits[:, -1, :] / temperature
415
+
416
+ # Apply top-k filtering
417
+ if top_k is not None:
418
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
419
+ logits[indices_to_remove] = float("-inf")
420
+
421
+ # Apply top-p (nucleus) filtering
422
+ if top_p is not None:
423
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
424
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
425
+
426
+ # Remove tokens with cumulative probability above the threshold
427
+ sorted_indices_to_remove = cumulative_probs > top_p
428
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
429
+ sorted_indices_to_remove[..., 0] = 0
430
+
431
+ indices_to_remove = sorted_indices_to_remove.scatter(
432
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
433
+ )
434
+ logits[indices_to_remove] = float("-inf")
435
+
436
+ # Sample from the distribution
437
+ probs = F.softmax(logits, dim=-1)
438
+ next_token = torch.multinomial(probs, num_samples=1)
439
+
440
+ return next_token.item()
441
+
442
+
443
+ # Register the model with Auto classes for easy loading
444
+ from transformers import AutoConfig, AutoModelForCausalLM
445
+
446
+ AutoConfig.register("chess_transformer", ChessConfig)
447
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df71cea7e02a25af8b05e271aa3c8c19f716aa0b3eab355927b9c139320c057e
3
+ size 391080
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,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 minimal default vocabulary with just special tokens.
100
+
101
+ For the full vocabulary, use `build_vocab_from_dataset()`.
102
+ This minimal vocab is just a placeholder - you should build from data.
103
+ """
104
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
105
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
106
+ return vocab
107
+
108
+ @classmethod
109
+ def build_vocab_from_iterator(
110
+ cls,
111
+ iterator,
112
+ min_frequency: int = 1,
113
+ ) -> "ChessTokenizer":
114
+ """
115
+ Build a tokenizer vocabulary from an iterator of game strings.
116
+
117
+ Args:
118
+ iterator: An iterator yielding game strings (space-separated moves).
119
+ min_frequency: Minimum frequency for a token to be included.
120
+
121
+ Returns:
122
+ A ChessTokenizer with the built vocabulary.
123
+ """
124
+ from collections import Counter
125
+
126
+ token_counts = Counter()
127
+
128
+ for game in iterator:
129
+ moves = game.strip().split()
130
+ token_counts.update(moves)
131
+
132
+ # Filter by frequency
133
+ tokens = [
134
+ token for token, count in token_counts.items()
135
+ if count >= min_frequency
136
+ ]
137
+
138
+ # Sort for reproducibility
139
+ tokens = sorted(tokens)
140
+
141
+ # Build vocabulary
142
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
143
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
144
+
145
+ return cls(vocab=vocab)
146
+
147
+ @classmethod
148
+ def build_vocab_from_dataset(
149
+ cls,
150
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
151
+ split: str = "train",
152
+ column: str = "text",
153
+ min_frequency: int = 500,
154
+ max_samples: Optional[int] = 100000,
155
+ ) -> "ChessTokenizer":
156
+ """
157
+ Build a tokenizer vocabulary from a Hugging Face dataset.
158
+
159
+ Args:
160
+ dataset_name: Name of the dataset on Hugging Face Hub.
161
+ split: Dataset split to use.
162
+ column: Column containing the game strings.
163
+ min_frequency: Minimum frequency for a token to be included (default: 500).
164
+ max_samples: Maximum number of samples to process (default: 100k).
165
+
166
+ Returns:
167
+ A ChessTokenizer with the built vocabulary.
168
+ """
169
+ from datasets import load_dataset
170
+
171
+ dataset = load_dataset(dataset_name, split=split)
172
+
173
+ if max_samples is not None:
174
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
175
+
176
+ def game_iterator():
177
+ for example in dataset:
178
+ yield example[column]
179
+
180
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
181
+
182
+ @property
183
+ def vocab_size(self) -> int:
184
+ """Return the size of the vocabulary."""
185
+ return len(self._vocab)
186
+
187
+ def get_vocab(self) -> Dict[str, int]:
188
+ """Return the vocabulary as a dictionary."""
189
+ return dict(self._vocab)
190
+
191
+ def _tokenize(self, text: str) -> List[str]:
192
+ """
193
+ Tokenize a string of moves into a list of tokens.
194
+
195
+ Args:
196
+ text: A string of space-separated moves.
197
+
198
+ Returns:
199
+ List of move tokens.
200
+ """
201
+ return text.strip().split()
202
+
203
+ def _convert_token_to_id(self, token: str) -> int:
204
+ """Convert a token to its ID."""
205
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
206
+
207
+ def _convert_id_to_token(self, index: int) -> str:
208
+ """Convert an ID to its token."""
209
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
210
+
211
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
212
+ """Convert a list of tokens back to a string."""
213
+ # Filter out special tokens for cleaner output
214
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
215
+ return " ".join(t for t in tokens if t not in special)
216
+
217
+ def save_vocabulary(
218
+ self,
219
+ save_directory: str,
220
+ filename_prefix: Optional[str] = None,
221
+ ) -> tuple:
222
+ """
223
+ Save the vocabulary to a JSON file.
224
+
225
+ Args:
226
+ save_directory: Directory to save the vocabulary.
227
+ filename_prefix: Optional prefix for the filename.
228
+
229
+ Returns:
230
+ Tuple containing the path to the saved vocabulary file.
231
+ """
232
+ if not os.path.isdir(save_directory):
233
+ os.makedirs(save_directory, exist_ok=True)
234
+
235
+ vocab_file = os.path.join(
236
+ save_directory,
237
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
238
+ )
239
+
240
+ with open(vocab_file, "w", encoding="utf-8") as f:
241
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
242
+
243
+ return (vocab_file,)
244
+
245
+
246
+ def count_vocab_from_dataset(
247
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
248
+ split: str = "train",
249
+ column: str = "text",
250
+ max_samples: Optional[int] = 10000,
251
+ ) -> Dict[str, int]:
252
+ """
253
+ Count token frequencies in a dataset (useful for vocabulary analysis).
254
+
255
+ Args:
256
+ dataset_name: Name of the dataset on Hugging Face Hub.
257
+ split: Dataset split to use.
258
+ column: Column containing the game strings.
259
+ max_samples: Maximum number of samples to process.
260
+
261
+ Returns:
262
+ Dictionary mapping tokens to their frequencies.
263
+ """
264
+ from collections import Counter
265
+ from datasets import load_dataset
266
+
267
+ dataset = load_dataset(dataset_name, split=split)
268
+
269
+ if max_samples is not None:
270
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
271
+
272
+ token_counts = Counter()
273
+
274
+ for example in dataset:
275
+ moves = example[column].strip().split()
276
+ token_counts.update(moves)
277
+
278
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[EOS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "auto_map": {
37
+ "AutoTokenizer": [
38
+ "tokenizer_decomposed.ChessDecomposedTokenizer",
39
+ null
40
+ ]
41
+ },
42
+ "bos_token": "[BOS]",
43
+ "clean_up_tokenization_spaces": false,
44
+ "eos_token": "[EOS]",
45
+ "extra_special_tokens": {},
46
+ "model_max_length": 1000000000000000019884624838656,
47
+ "pad_token": "[PAD]",
48
+ "tokenizer_class": "ChessDecomposedTokenizer",
49
+ "unk_token": "[UNK]"
50
+ }
tokenizer_decomposed.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Decomposed Chess Tokenizer.
3
+
4
+ This tokenizer decomposes each move into 3-4 tokens:
5
+ - color+piece token (e.g., "WP", "BN")
6
+ - from-square token with suffix "_f" (e.g., "e2_f")
7
+ - to-square token with suffix "_t" (e.g., "e4_t")
8
+ - optional promotion token (one of "q", "r", "b", "n")
9
+
10
+ This avoids UNKs for rare moves and makes legality learning easier because the model
11
+ always emits explicit squares.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ from typing import Dict, List, Optional
20
+
21
+ from transformers import PreTrainedTokenizer
22
+
23
+
24
+ class ChessDecomposedTokenizer(PreTrainedTokenizer):
25
+ model_input_names = ["input_ids", "attention_mask"]
26
+ vocab_files_names = {"vocab_file": "vocab.json"}
27
+
28
+ PAD_TOKEN = "[PAD]"
29
+ BOS_TOKEN = "[BOS]"
30
+ EOS_TOKEN = "[EOS]"
31
+ UNK_TOKEN = "[UNK]"
32
+
33
+ _MOVE_RE = re.compile(r"^[WB][PNBRQK][a-h][1-8][a-h][1-8].*$")
34
+
35
+ def __init__(
36
+ self,
37
+ vocab_file: Optional[str] = None,
38
+ vocab: Optional[Dict[str, int]] = None,
39
+ **kwargs,
40
+ ):
41
+ self._pad_token = self.PAD_TOKEN
42
+ self._bos_token = self.BOS_TOKEN
43
+ self._eos_token = self.EOS_TOKEN
44
+ self._unk_token = self.UNK_TOKEN
45
+
46
+ kwargs.pop("pad_token", None)
47
+ kwargs.pop("bos_token", None)
48
+ kwargs.pop("eos_token", None)
49
+ kwargs.pop("unk_token", None)
50
+
51
+ if vocab is not None:
52
+ self._vocab = vocab
53
+ elif vocab_file is not None and os.path.exists(vocab_file):
54
+ with open(vocab_file, "r", encoding="utf-8") as f:
55
+ self._vocab = json.load(f)
56
+ else:
57
+ self._vocab = self._create_full_vocab()
58
+
59
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
60
+
61
+ super().__init__(
62
+ pad_token=self._pad_token,
63
+ bos_token=self._bos_token,
64
+ eos_token=self._eos_token,
65
+ unk_token=self._unk_token,
66
+ **kwargs,
67
+ )
68
+
69
+ @staticmethod
70
+ def _create_full_vocab() -> Dict[str, int]:
71
+ special_tokens = [
72
+ ChessDecomposedTokenizer.PAD_TOKEN,
73
+ ChessDecomposedTokenizer.BOS_TOKEN,
74
+ ChessDecomposedTokenizer.EOS_TOKEN,
75
+ ChessDecomposedTokenizer.UNK_TOKEN,
76
+ ]
77
+
78
+ pieces = ["P", "N", "B", "R", "Q", "K"]
79
+ colors = ["W", "B"]
80
+ piece_tokens = [f"{c}{p}" for c in colors for p in pieces]
81
+
82
+ files = "abcdefgh"
83
+ ranks = "12345678"
84
+ squares = [f"{f}{r}" for f in files for r in ranks]
85
+ from_tokens = [f"{sq}_f" for sq in squares]
86
+ to_tokens = [f"{sq}_t" for sq in squares]
87
+
88
+ promo_tokens = ["q", "r", "b", "n"]
89
+
90
+ tokens = special_tokens + piece_tokens + from_tokens + to_tokens + promo_tokens
91
+ return {tok: idx for idx, tok in enumerate(tokens)}
92
+
93
+ @property
94
+ def vocab_size(self) -> int:
95
+ return len(self._vocab)
96
+
97
+ def get_vocab(self) -> Dict[str, int]:
98
+ return dict(self._vocab)
99
+
100
+ def _tokenize(self, text: str) -> List[str]:
101
+ raw = text.strip()
102
+ if not raw:
103
+ return []
104
+
105
+ parts = raw.split()
106
+ out: List[str] = []
107
+
108
+ for part in parts:
109
+ if part in {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}:
110
+ out.append(part)
111
+ continue
112
+
113
+ if not self._MOVE_RE.match(part):
114
+ out.append(self.UNK_TOKEN)
115
+ continue
116
+
117
+ color = part[0]
118
+ piece = part[1]
119
+ from_sq = part[2:4]
120
+ to_sq = part[4:6]
121
+ out.append(f"{color}{piece}")
122
+ out.append(f"{from_sq}_f")
123
+ out.append(f"{to_sq}_t")
124
+
125
+ if "=" in part:
126
+ promo_idx = part.find("=")
127
+ if promo_idx != -1 and promo_idx + 1 < len(part):
128
+ promo = part[promo_idx + 1].lower()
129
+ if promo in {"q", "r", "b", "n"}:
130
+ out.append(promo)
131
+
132
+ return out
133
+
134
+ def _convert_token_to_id(self, token: str) -> int:
135
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
136
+
137
+ def _convert_id_to_token(self, index: int) -> str:
138
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
139
+
140
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
141
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
142
+ return " ".join(t for t in tokens if t not in special)
143
+
144
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
145
+ if not os.path.isdir(save_directory):
146
+ os.makedirs(save_directory, exist_ok=True)
147
+
148
+ vocab_file = os.path.join(
149
+ save_directory,
150
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
151
+ )
152
+
153
+ with open(vocab_file, "w", encoding="utf-8") as f:
154
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
155
+
156
+ return (vocab_file,)
157
+
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
+ "a2_f": 17,
20
+ "a3_f": 18,
21
+ "a4_f": 19,
22
+ "a5_f": 20,
23
+ "a6_f": 21,
24
+ "a7_f": 22,
25
+ "a8_f": 23,
26
+ "b1_f": 24,
27
+ "b2_f": 25,
28
+ "b3_f": 26,
29
+ "b4_f": 27,
30
+ "b5_f": 28,
31
+ "b6_f": 29,
32
+ "b7_f": 30,
33
+ "b8_f": 31,
34
+ "c1_f": 32,
35
+ "c2_f": 33,
36
+ "c3_f": 34,
37
+ "c4_f": 35,
38
+ "c5_f": 36,
39
+ "c6_f": 37,
40
+ "c7_f": 38,
41
+ "c8_f": 39,
42
+ "d1_f": 40,
43
+ "d2_f": 41,
44
+ "d3_f": 42,
45
+ "d4_f": 43,
46
+ "d5_f": 44,
47
+ "d6_f": 45,
48
+ "d7_f": 46,
49
+ "d8_f": 47,
50
+ "e1_f": 48,
51
+ "e2_f": 49,
52
+ "e3_f": 50,
53
+ "e4_f": 51,
54
+ "e5_f": 52,
55
+ "e6_f": 53,
56
+ "e7_f": 54,
57
+ "e8_f": 55,
58
+ "f1_f": 56,
59
+ "f2_f": 57,
60
+ "f3_f": 58,
61
+ "f4_f": 59,
62
+ "f5_f": 60,
63
+ "f6_f": 61,
64
+ "f7_f": 62,
65
+ "f8_f": 63,
66
+ "g1_f": 64,
67
+ "g2_f": 65,
68
+ "g3_f": 66,
69
+ "g4_f": 67,
70
+ "g5_f": 68,
71
+ "g6_f": 69,
72
+ "g7_f": 70,
73
+ "g8_f": 71,
74
+ "h1_f": 72,
75
+ "h2_f": 73,
76
+ "h3_f": 74,
77
+ "h4_f": 75,
78
+ "h5_f": 76,
79
+ "h6_f": 77,
80
+ "h7_f": 78,
81
+ "h8_f": 79,
82
+ "a1_t": 80,
83
+ "a2_t": 81,
84
+ "a3_t": 82,
85
+ "a4_t": 83,
86
+ "a5_t": 84,
87
+ "a6_t": 85,
88
+ "a7_t": 86,
89
+ "a8_t": 87,
90
+ "b1_t": 88,
91
+ "b2_t": 89,
92
+ "b3_t": 90,
93
+ "b4_t": 91,
94
+ "b5_t": 92,
95
+ "b6_t": 93,
96
+ "b7_t": 94,
97
+ "b8_t": 95,
98
+ "c1_t": 96,
99
+ "c2_t": 97,
100
+ "c3_t": 98,
101
+ "c4_t": 99,
102
+ "c5_t": 100,
103
+ "c6_t": 101,
104
+ "c7_t": 102,
105
+ "c8_t": 103,
106
+ "d1_t": 104,
107
+ "d2_t": 105,
108
+ "d3_t": 106,
109
+ "d4_t": 107,
110
+ "d5_t": 108,
111
+ "d6_t": 109,
112
+ "d7_t": 110,
113
+ "d8_t": 111,
114
+ "e1_t": 112,
115
+ "e2_t": 113,
116
+ "e3_t": 114,
117
+ "e4_t": 115,
118
+ "e5_t": 116,
119
+ "e6_t": 117,
120
+ "e7_t": 118,
121
+ "e8_t": 119,
122
+ "f1_t": 120,
123
+ "f2_t": 121,
124
+ "f3_t": 122,
125
+ "f4_t": 123,
126
+ "f5_t": 124,
127
+ "f6_t": 125,
128
+ "f7_t": 126,
129
+ "f8_t": 127,
130
+ "g1_t": 128,
131
+ "g2_t": 129,
132
+ "g3_t": 130,
133
+ "g4_t": 131,
134
+ "g5_t": 132,
135
+ "g6_t": 133,
136
+ "g7_t": 134,
137
+ "g8_t": 135,
138
+ "h1_t": 136,
139
+ "h2_t": 137,
140
+ "h3_t": 138,
141
+ "h4_t": 139,
142
+ "h5_t": 140,
143
+ "h6_t": 141,
144
+ "h7_t": 142,
145
+ "h8_t": 143,
146
+ "q": 144,
147
+ "r": 145,
148
+ "b": 146,
149
+ "n": 147
150
+ }