Chiensaucisse67 commited on
Commit
0a626fd
·
verified ·
1 Parent(s): 5360744

Chess Challenge submission by Chiensaucisse67

Browse files
Files changed (8) hide show
  1. README.md +26 -0
  2. config.json +28 -0
  3. model.py +307 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +565 -0
  7. tokenizer_config.json +44 -0
  8. vocab.json +81 -0
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # chess-trm-powerful
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Chiensaucisse67](https://huggingface.co/Chiensaucisse67)
17
+ - **Parameters**: 994,464
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 79
24
+ - **Embedding dim**: 216
25
+ - **Layers**: 2
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.0,
11
+ "dtype": "float32",
12
+ "eos_token_id": 2,
13
+ "h_cycles": 2,
14
+ "l_cycles": 2,
15
+ "layer_norm_epsilon": 1e-05,
16
+ "model_type": "chess_transformer",
17
+ "n_ctx": 256,
18
+ "n_embd": 216,
19
+ "n_head": 4,
20
+ "n_inner": 560,
21
+ "n_layers": null,
22
+ "n_layers_per_block": 2,
23
+ "pad_token_id": 0,
24
+ "rope_theta": 10000.0,
25
+ "tie_weights": true,
26
+ "transformers_version": "4.57.1",
27
+ "vocab_size": 79
28
+ }
model.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TRM (Tiny Recursive Model) adapted for Causal Language Modeling (Chess).
3
+ Based on the official implementation: TinyRecursiveModels/models/recursive_reasoning/trm.py
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from dataclasses import dataclass
10
+ from typing import Optional, Tuple, Union
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from transformers import PretrainedConfig, PreTrainedModel
16
+ from transformers.modeling_outputs import CausalLMOutputWithPast
17
+
18
+ # -----------------------------------------------------------------------------
19
+ # Configuration
20
+ # -----------------------------------------------------------------------------
21
+
22
+ class ChessConfig(PretrainedConfig):
23
+ model_type = "chess_transformer"
24
+
25
+ def __init__(
26
+ self,
27
+ vocab_size: int = 1200,
28
+ n_embd: int = 128,
29
+ n_head: int = 4,
30
+ n_ctx: int = 256,
31
+ h_cycles: int = 2, # Number of High-level reasoning cycles
32
+ l_cycles: int = 2, # Number of Low-level reasoning cycles per H-cycle
33
+ n_layers_per_block: int = 1, # Number of physical layers in the shared block
34
+
35
+ n_inner: Optional[int] = None,
36
+ n_layer: Optional[int] = None, # Not used directly; total layers = h_cycles * l_cycles
37
+ dropout: float = 0.0, # TRM usually uses 0 dropout for reasoning
38
+ layer_norm_epsilon: float = 1e-5,
39
+ tie_weights: bool = True,
40
+ rope_theta: float = 10000.0,
41
+ pad_token_id: int = 0, # Assuming 0 is padding based on your log
42
+ bos_token_id: int = 1,
43
+ eos_token_id: int = 2,
44
+ **kwargs,
45
+ ):
46
+ super().__init__(
47
+ pad_token_id=pad_token_id,
48
+ bos_token_id=bos_token_id,
49
+ eos_token_id=eos_token_id,
50
+ **kwargs,
51
+ )
52
+ self.vocab_size = vocab_size
53
+ self.n_embd = n_embd
54
+ self.n_head = n_head
55
+ self.n_ctx = n_ctx
56
+ self.h_cycles = h_cycles
57
+ self.l_cycles = l_cycles
58
+ self.n_layers_per_block = n_layers_per_block
59
+ self.n_layers = n_layer
60
+ self.n_inner = n_inner if n_inner is not None else int(n_embd * 8/3) # SwiGLU convention
61
+ self.dropout = dropout
62
+ self.layer_norm_epsilon = layer_norm_epsilon
63
+ self.tie_weights = tie_weights
64
+ self.rope_theta = rope_theta
65
+
66
+
67
+ class RMSNorm(nn.Module):
68
+ def __init__(self, dim: int, eps: float = 1e-6):
69
+ super().__init__()
70
+ self.eps = eps
71
+ self.weight = nn.Parameter(torch.ones(dim))
72
+
73
+ def forward(self, x):
74
+ var = torch.mean(x**2, dim=-1, keepdim=True)
75
+ x = x * torch.rsqrt(var + self.eps)
76
+ return self.weight * x
77
+
78
+ class RotaryEmbedding(nn.Module):
79
+ def __init__(self, dim, max_position_embeddings=2048, base=10000.0, device=None):
80
+ super().__init__()
81
+ self.dim = dim
82
+ self.base = base
83
+ self.max_position_embeddings = max_position_embeddings
84
+ self.register_buffer("inv_freq", None, persistent=False)
85
+ self.register_buffer("cos_cached", None, persistent=False)
86
+ self.register_buffer("sin_cached", None, persistent=False)
87
+
88
+ def _update_cos_sin_tables(self, x, seq_len):
89
+ if (self.cos_cached is None or self.cos_cached.shape[0] < seq_len):
90
+ self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=x.device).float() / self.dim))
91
+ t = torch.arange(max(seq_len, self.max_position_embeddings), device=x.device).float()
92
+ freqs = torch.outer(t, self.inv_freq)
93
+ emb = torch.cat((freqs, freqs), dim=-1)
94
+ self.cos_cached = emb.cos()
95
+ self.sin_cached = emb.sin()
96
+
97
+ def forward(self, x, seq_len=None):
98
+ if seq_len is None:
99
+ seq_len = x.shape[1]
100
+ self._update_cos_sin_tables(x, seq_len)
101
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
102
+
103
+ def rotate_half(x):
104
+ x1 = x[..., : x.shape[-1] // 2]
105
+ x2 = x[..., x.shape[-1] // 2 :]
106
+ return torch.cat((-x2, x1), dim=-1)
107
+
108
+ def apply_rotary_pos_emb(q, k, cos, sin):
109
+ # q, k: [batch, seq, head, dim] (after transpose)
110
+ # cos, sin: [seq, dim] -> need broadcast
111
+ cos = cos.unsqueeze(0).unsqueeze(2) # [1, seq, 1, dim]
112
+ sin = sin.unsqueeze(0).unsqueeze(2)
113
+ q_embed = (q * cos) + (rotate_half(q) * sin)
114
+ k_embed = (k * cos) + (rotate_half(k) * sin)
115
+ return q_embed, k_embed
116
+
117
+ class MultiQueryAttention(nn.Module):
118
+ """
119
+ Standard Attention with RoPE support.
120
+ Using Multi-Query (MQA) or standard MHA depending on config.
121
+ Adapted for Causal Masking.
122
+ """
123
+ def __init__(self, config: ChessConfig):
124
+ super().__init__()
125
+ self.n_head = config.n_head
126
+ self.n_embd = config.n_embd
127
+ self.head_dim = config.n_embd // config.n_head
128
+
129
+ self.c_q = nn.Linear(config.n_embd, config.n_embd, bias=False)
130
+ self.c_k = nn.Linear(config.n_embd, self.head_dim, bias=False)
131
+ self.c_v = nn.Linear(config.n_embd, self.head_dim, bias=False)
132
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
133
+
134
+ self.dropout = nn.Dropout(config.dropout)
135
+
136
+ def forward(self, x, cos, sin, attention_mask=None):
137
+ B, T, C = x.size()
138
+
139
+ q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
140
+ k = self.c_k(x).view(B, T, 1, self.head_dim)
141
+ v = self.c_v(x).view(B, T, 1, self.head_dim)
142
+
143
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
144
+
145
+ q = q.transpose(1, 2)
146
+ k = k.transpose(1, 2)
147
+ v = v.transpose(1, 2)
148
+
149
+ k = k.expand(-1, self.n_head, -1, -1)
150
+ v = v.expand(-1, self.n_head, -1, -1)
151
+
152
+ y = F.scaled_dot_product_attention(
153
+ q, k, v,
154
+ attn_mask=None,
155
+ dropout_p=self.dropout.p if self.training else 0.0,
156
+ is_causal=True
157
+ )
158
+
159
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
160
+ y = self.c_proj(y)
161
+ return y
162
+
163
+ class SwiGLU(nn.Module):
164
+ def __init__(self, config: ChessConfig):
165
+ super().__init__()
166
+ self.w1 = nn.Linear(config.n_embd, config.n_inner, bias=False)
167
+ self.w2 = nn.Linear(config.n_embd, config.n_inner, bias=False)
168
+ self.w3 = nn.Linear(config.n_inner, config.n_embd, bias=False)
169
+ self.dropout = nn.Dropout(config.dropout)
170
+
171
+ def forward(self, x):
172
+ x1 = self.w1(x)
173
+ x2 = self.w2(x)
174
+ hidden = F.silu(x1) * x2
175
+ return self.dropout(self.w3(hidden))
176
+
177
+ class TRMBlock(nn.Module):
178
+ def __init__(self, config: ChessConfig):
179
+ super().__init__()
180
+ self.self_attn = MultiQueryAttention(config)
181
+ self.mlp = SwiGLU(config)
182
+ self.ln_1 = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
183
+ self.ln_2 = RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
184
+
185
+ def forward(self, x, cos, sin):
186
+
187
+ attn_out = self.self_attn(x, cos, sin)
188
+ x = self.ln_1(x + attn_out)
189
+
190
+ mlp_out = self.mlp(x)
191
+ x = self.ln_2(x + mlp_out)
192
+ return x
193
+
194
+ class TRMReasoningModule(nn.Module):
195
+ """
196
+ The reusable module containing shared layers.
197
+ Implements Input Injection: hidden_states = hidden_states + injection
198
+ """
199
+ def __init__(self, config: ChessConfig):
200
+ super().__init__()
201
+ self.layers = nn.ModuleList([TRMBlock(config) for _ in range(config.n_layers_per_block)])
202
+
203
+ def forward(self, hidden_states, input_injection, cos, sin):
204
+ hidden_states = hidden_states + input_injection
205
+
206
+ for layer in self.layers:
207
+ hidden_states = layer(hidden_states, cos, sin)
208
+
209
+ return hidden_states
210
+
211
+ class ChessForCausalLM(PreTrainedModel):
212
+ config_class = ChessConfig
213
+
214
+ def __init__(self, config: ChessConfig):
215
+ super().__init__(config)
216
+ self.config = config
217
+
218
+
219
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
220
+ self.rotary = RotaryEmbedding(config.n_embd // config.n_head, max_position_embeddings=config.n_ctx, base=config.rope_theta)
221
+ self.reasoning_module = TRMReasoningModule(config)
222
+
223
+ self.z_H_init = nn.Parameter(torch.randn(1, 1, config.n_embd) * 0.02)
224
+ self.z_L_init = nn.Parameter(torch.randn(1, 1, config.n_embd) * 0.02)
225
+
226
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
227
+
228
+ if config.tie_weights:
229
+ self.lm_head.weight = self.wte.weight
230
+
231
+ self.post_init()
232
+
233
+ def _init_weights(self, module):
234
+ if isinstance(module, nn.Linear):
235
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
236
+ if module.bias is not None:
237
+ torch.nn.init.zeros_(module.bias)
238
+ elif isinstance(module, nn.Embedding):
239
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
240
+
241
+ def forward(
242
+ self,
243
+ input_ids: torch.LongTensor,
244
+ labels: Optional[torch.LongTensor] = None,
245
+ return_dict: Optional[bool] = None,
246
+ **kwargs,
247
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
248
+
249
+ B, T = input_ids.size()
250
+ x_emb = self.wte(input_ids)
251
+
252
+
253
+ cos, sin = self.rotary(x_emb, seq_len=T)
254
+
255
+ z_H = self.z_H_init.expand(B, T, -1).contiguous()
256
+ z_L = self.z_L_init.expand(B, T, -1).contiguous()
257
+
258
+
259
+ with torch.no_grad():
260
+ for _h in range(self.config.h_cycles - 1):
261
+ # L-loop (updates z_L)
262
+ for _l in range(self.config.l_cycles):
263
+ z_L = self.reasoning_module(
264
+ hidden_states=z_L,
265
+ input_injection=(z_H + x_emb),
266
+ cos=cos, sin=sin
267
+ )
268
+ # H-loop step (updates z_H)
269
+ z_H = self.reasoning_module(
270
+ hidden_states=z_H,
271
+ input_injection=z_L,
272
+ cos=cos, sin=sin
273
+ )
274
+
275
+ for _l in range(self.config.l_cycles):
276
+ z_L = self.reasoning_module(
277
+ hidden_states=z_L,
278
+ input_injection=(z_H + x_emb),
279
+ cos=cos, sin=sin
280
+ )
281
+
282
+ z_H = self.reasoning_module(
283
+ hidden_states=z_H,
284
+ input_injection=z_L,
285
+ cos=cos, sin=sin
286
+ )
287
+
288
+ logits = self.lm_head(z_H)
289
+
290
+ loss = None
291
+ if labels is not None:
292
+
293
+ shift_logits = logits[..., :-1, :].contiguous()
294
+ shift_labels = labels[..., 1:].contiguous()
295
+
296
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
297
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
298
+
299
+ return CausalLMOutputWithPast(
300
+ loss=loss,
301
+ logits=logits,
302
+ past_key_values=None
303
+ )
304
+
305
+ from transformers import AutoConfig, AutoModelForCausalLM
306
+ AutoConfig.register("chess_transformer", ChessConfig)
307
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b2a2be23bdc0258e1bc997d35d871cb856d78ea5457ed0594bde2f4830255bf
3
+ size 3980192
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,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 token import OP
20
+ from typing import Dict, List, Optional
21
+
22
+ from transformers import PreTrainedTokenizer
23
+ import re
24
+
25
+ class ChessTokenizer(PreTrainedTokenizer):
26
+ """
27
+ A custom tokenizer for chess moves using extended UCI notation.
28
+
29
+ This tokenizer maps each possible chess move to a unique token ID.
30
+ The vocabulary is built from the training dataset to ensure all moves
31
+ encountered during training have a corresponding token.
32
+
33
+ Example:
34
+ >>> tokenizer = ChessTokenizer()
35
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
36
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
37
+ """
38
+
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+ vocab_files_names = {"vocab_file": "vocab.json"}
41
+
42
+ # Special tokens
43
+ PAD_TOKEN = "[PAD]"
44
+ BOS_TOKEN = "[BOS]"
45
+ EOS_TOKEN = "[EOS]"
46
+ UNK_TOKEN = "[UNK]"
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file: Optional[str] = None,
51
+ vocab: Optional[Dict[str, int]] = None,
52
+ **kwargs,
53
+ ):
54
+ """
55
+ Initialize the chess tokenizer.
56
+
57
+ Args:
58
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
59
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
60
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
61
+ """
62
+ # Initialize special tokens
63
+ self._pad_token = self.PAD_TOKEN
64
+ self._bos_token = self.BOS_TOKEN
65
+ self._eos_token = self.EOS_TOKEN
66
+ self._unk_token = self.UNK_TOKEN
67
+
68
+ # Remove any duplicate special-token entries passed through kwargs
69
+ # to avoid "multiple values for keyword" errors when loading from disk.
70
+ kwargs.pop("pad_token", None)
71
+ kwargs.pop("bos_token", None)
72
+ kwargs.pop("eos_token", None)
73
+ kwargs.pop("unk_token", None)
74
+
75
+ # Load or create vocabulary
76
+ if vocab is not None:
77
+ self._vocab = vocab
78
+ elif vocab_file is not None and os.path.exists(vocab_file):
79
+ with open(vocab_file, "r", encoding="utf-8") as f:
80
+ self._vocab = json.load(f)
81
+ else:
82
+ # Create a minimal vocabulary with just special tokens
83
+ # The full vocabulary should be built from the dataset
84
+ self._vocab = self._create_default_vocab()
85
+
86
+ # Create reverse mapping
87
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
88
+
89
+ # Call parent init AFTER setting up vocab
90
+ super().__init__(
91
+ pad_token=self._pad_token,
92
+ bos_token=self._bos_token,
93
+ eos_token=self._eos_token,
94
+ unk_token=self._unk_token,
95
+ **kwargs,
96
+ )
97
+
98
+ def _create_default_vocab(self) -> Dict[str, int]:
99
+ """
100
+ Create a minimal default vocabulary with just special tokens.
101
+
102
+ For the full vocabulary, use `build_vocab_from_dataset()`.
103
+ This minimal vocab is just a placeholder - you should build from data.
104
+ """
105
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
106
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
107
+ return vocab
108
+
109
+ @classmethod
110
+ def build_vocab_from_iterator(
111
+ cls,
112
+ iterator,
113
+ min_frequency: int = 1,
114
+ ) -> "ChessTokenizer":
115
+ """
116
+ Build a tokenizer vocabulary from an iterator of game strings.
117
+
118
+ Args:
119
+ iterator: An iterator yielding game strings (space-separated moves).
120
+ min_frequency: Minimum frequency for a token to be included.
121
+
122
+ Returns:
123
+ A ChessTokenizer with the built vocabulary.
124
+ """
125
+ from collections import Counter
126
+
127
+ token_counts = Counter()
128
+
129
+ for game in iterator:
130
+ moves = game.strip().split()
131
+ token_counts.update(moves)
132
+
133
+ # Filter by frequency
134
+ tokens = [
135
+ token for token, count in token_counts.items()
136
+ if count >= min_frequency
137
+ ]
138
+
139
+ # Sort for reproducibility
140
+ tokens = sorted(tokens)
141
+
142
+ # Build vocabulary
143
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
144
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
145
+
146
+ return cls(vocab=vocab)
147
+
148
+ @classmethod
149
+ def build_vocab_from_dataset(
150
+ cls,
151
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
152
+ split: str = "train",
153
+ column: str = "text",
154
+ min_frequency: int = 500,
155
+ max_samples: Optional[int] = 100000,
156
+ ) -> "ChessTokenizer":
157
+ """
158
+ Build a tokenizer vocabulary from a Hugging Face dataset.
159
+
160
+ Args:
161
+ dataset_name: Name of the dataset on Hugging Face Hub.
162
+ split: Dataset split to use.
163
+ column: Column containing the game strings.
164
+ min_frequency: Minimum frequency for a token to be included (default: 500).
165
+ max_samples: Maximum number of samples to process (default: 100k).
166
+
167
+ Returns:
168
+ A ChessTokenizer with the built vocabulary.
169
+ """
170
+ from datasets import load_dataset
171
+
172
+ dataset = load_dataset(dataset_name, split=split)
173
+
174
+ if max_samples is not None:
175
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
176
+
177
+ def game_iterator():
178
+ for example in dataset:
179
+ yield example[column]
180
+
181
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
182
+
183
+ @property
184
+ def vocab_size(self) -> int:
185
+ """Return the size of the vocabulary."""
186
+ return len(self._vocab)
187
+
188
+ def get_vocab(self) -> Dict[str, int]:
189
+ """Return the vocabulary as a dictionary."""
190
+ return dict(self._vocab)
191
+
192
+ def _tokenize(self, text: str) -> List[str]:
193
+ """
194
+ Tokenize a string of moves into a list of tokens.
195
+
196
+ Args:
197
+ text: A string of space-separated moves.
198
+
199
+ Returns:
200
+ List of move tokens.
201
+ """
202
+ return text.strip().split()
203
+
204
+ def _convert_token_to_id(self, token: str) -> int:
205
+ """Convert a token to its ID."""
206
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
207
+
208
+ def _convert_id_to_token(self, index: int) -> str:
209
+ """Convert an ID to its token."""
210
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
211
+
212
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
213
+ """Convert a list of tokens back to a string."""
214
+ # Filter out special tokens for cleaner output
215
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
216
+ return " ".join(t for t in tokens if t not in special)
217
+
218
+ def save_vocabulary(
219
+ self,
220
+ save_directory: str,
221
+ filename_prefix: Optional[str] = None,
222
+ ) -> tuple:
223
+ """
224
+ Save the vocabulary to a JSON file.
225
+
226
+ Args:
227
+ save_directory: Directory to save the vocabulary.
228
+ filename_prefix: Optional prefix for the filename.
229
+
230
+ Returns:
231
+ Tuple containing the path to the saved vocabulary file.
232
+ """
233
+ if not os.path.isdir(save_directory):
234
+ os.makedirs(save_directory, exist_ok=True)
235
+
236
+ vocab_file = os.path.join(
237
+ save_directory,
238
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
239
+ )
240
+
241
+ with open(vocab_file, "w", encoding="utf-8") as f:
242
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
243
+
244
+ return (vocab_file,)
245
+
246
+
247
+ def count_vocab_from_dataset(
248
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
249
+ split: str = "train",
250
+ column: str = "text",
251
+ max_samples: Optional[int] = 10000,
252
+ ) -> Dict[str, int]:
253
+ """
254
+ Count token frequencies in a dataset (useful for vocabulary analysis).
255
+
256
+ Args:
257
+ dataset_name: Name of the dataset on Hugging Face Hub.
258
+ split: Dataset split to use.
259
+ column: Column containing the game strings.
260
+ max_samples: Maximum number of samples to process.
261
+
262
+ Returns:
263
+ Dictionary mapping tokens to their frequencies.
264
+ """
265
+ from collections import Counter
266
+ from datasets import load_dataset
267
+
268
+ dataset = load_dataset(dataset_name, split=split)
269
+
270
+ if max_samples is not None:
271
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
272
+
273
+ token_counts = Counter()
274
+
275
+ for example in dataset:
276
+ moves = example[column].strip().split()
277
+ token_counts.update(moves)
278
+
279
+ return dict(token_counts)
280
+
281
+
282
+
283
+ class CoordinateTokenizer(ChessTokenizer):
284
+ def __init__(self, **kwargs):
285
+ squares = [f"{f}{r}" for f in "abcdefgh" for r in "12345678"]
286
+ promotions = ["q", "r", "b", "n"]
287
+ control = ["[PAD]", "[BOS]", "[EOS]", "[UNK]"]
288
+ vocab_list = control + squares + promotions
289
+ self._vocab = {t: i for i, t in enumerate(vocab_list)}
290
+ self._ids_to_token = {i: t for t, i in self._vocab.items()}
291
+
292
+ super().__init__(
293
+ vocab=self._vocab,
294
+ pad_token="[PAD]",
295
+ bos_token="[BOS]",
296
+ eos_token="[EOS]",
297
+ unk_token="[UNK]",
298
+ truncation_side="left",
299
+ **kwargs
300
+ )
301
+
302
+ def _tokenize(self, text: str) -> List[str]:
303
+ raw_moves = text.strip().split()
304
+ tokens = []
305
+ for raw_move in raw_moves:
306
+ squares = re.findall(r'[a-h][1-8]', raw_move)
307
+ tokens.extend(squares)
308
+ if "=" in raw_move:
309
+ idx = raw_move.index("=")
310
+ if idx + 1 < len(raw_move):
311
+ tokens.append(raw_move[idx+1].lower())
312
+ elif "q" in raw_move[-2:].lower():
313
+ tokens.append(raw_move[-1].lower())
314
+ return tokens
315
+
316
+
317
+ class CoordinateChessTokenizer(PreTrainedTokenizer):
318
+ """
319
+ Tokenizer that decomposes chess moves into coordinate components.
320
+
321
+ Example:
322
+ WPe2e4 -> ['e2', 'e4']
323
+ WPa7a8q -> ['a7', 'a8', 'q'] # pawn promotion
324
+
325
+ Vocabulary size: 72 tokens
326
+ - 64 squares (a1-h8)
327
+ - 4 promotions (q, r, b, n)
328
+ - 4 special tokens
329
+ """
330
+
331
+ model_input_names = ["input_ids", "attention_mask"]
332
+ vocab_files_names = {"vocab_file": "vocab.json"}
333
+
334
+ PAD_TOKEN = "[PAD]"
335
+ BOS_TOKEN = "[BOS]"
336
+ EOS_TOKEN = "[EOS]"
337
+ UNK_TOKEN = "[UNK]"
338
+
339
+ # Regex to extract from-square, to-square, and optional promotion
340
+ MOVE_PATTERN = re.compile(r'([a-h][1-8])([a-h][1-8])([qrbn])?')
341
+
342
+ def __init__(self, vocab_file: Optional[str] = None, **kwargs):
343
+ # Remove duplicate special token kwargs
344
+ kwargs.pop("pad_token", None)
345
+ kwargs.pop("bos_token", None)
346
+ kwargs.pop("eos_token", None)
347
+ kwargs.pop("unk_token", None)
348
+
349
+ # Build fixed vocabulary
350
+ if vocab_file is not None and os.path.exists(vocab_file):
351
+ with open(vocab_file, "r", encoding="utf-8") as f:
352
+ self._vocab = json.load(f)
353
+ else:
354
+ self._vocab = self._create_vocab()
355
+
356
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
357
+
358
+ super().__init__(
359
+ pad_token=self.PAD_TOKEN,
360
+ bos_token=self.BOS_TOKEN,
361
+ eos_token=self.EOS_TOKEN,
362
+ unk_token=self.UNK_TOKEN,
363
+ **kwargs,
364
+ )
365
+
366
+ def _create_vocab(self) -> Dict[str, int]:
367
+ """Create fixed vocabulary of 72 tokens."""
368
+ tokens = [
369
+ self.PAD_TOKEN,
370
+ self.BOS_TOKEN,
371
+ self.EOS_TOKEN,
372
+ self.UNK_TOKEN,
373
+ ]
374
+
375
+ # Add all 64 squares
376
+ for file in 'abcdefgh':
377
+ for rank in '12345678':
378
+ tokens.append(f"{file}{rank}")
379
+
380
+ # Add promotion pieces
381
+ tokens.extend(['q', 'r', 'b', 'n'])
382
+
383
+ return {token: idx for idx, token in enumerate(tokens)}
384
+
385
+ @property
386
+ def vocab_size(self) -> int:
387
+ return len(self._vocab)
388
+
389
+ def get_vocab(self) -> Dict[str, int]:
390
+ return dict(self._vocab)
391
+
392
+ def _tokenize(self, text: str) -> List[str]:
393
+ """
394
+ Tokenize move string into coordinate components.
395
+
396
+ Args:
397
+ text: Space-separated moves like "WPe2e4 BNg8f6"
398
+
399
+ Returns:
400
+ List of coordinate tokens: ['e2', 'e4', 'g8', 'f6']
401
+ """
402
+ tokens = []
403
+ raw_moves = text.strip().split()
404
+
405
+ for move in raw_moves:
406
+ match = self.MOVE_PATTERN.search(move)
407
+ if match:
408
+ from_sq, to_sq, promotion = match.groups()
409
+ tokens.append(from_sq)
410
+ tokens.append(to_sq)
411
+ if promotion:
412
+ tokens.append(promotion)
413
+
414
+ return tokens
415
+
416
+ def _convert_token_to_id(self, token: str) -> int:
417
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
418
+
419
+ def _convert_id_to_token(self, index: int) -> str:
420
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
421
+
422
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
423
+ """Reconstruct moves from coordinate tokens."""
424
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
425
+ clean = [t for t in tokens if t not in special]
426
+
427
+ # Group into moves (2 or 3 tokens per move)
428
+ moves = []
429
+ i = 0
430
+ while i < len(clean):
431
+ if i + 1 < len(clean):
432
+ move = clean[i] + clean[i + 1]
433
+ i += 2
434
+ # Check for promotion
435
+ if i < len(clean) and clean[i] in ['q', 'r', 'b', 'n']:
436
+ move += clean[i]
437
+ i += 1
438
+ moves.append(move)
439
+ else:
440
+ i += 1
441
+
442
+ return " ".join(moves)
443
+
444
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
445
+ if not os.path.isdir(save_directory):
446
+ os.makedirs(save_directory, exist_ok=True)
447
+
448
+ vocab_file = os.path.join(
449
+ save_directory,
450
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
451
+ )
452
+
453
+ with open(vocab_file, "w", encoding="utf-8") as f:
454
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
455
+
456
+ return (vocab_file,)
457
+
458
+
459
+ class EnhancedCoordinateTokenizer(CoordinateChessTokenizer):
460
+ """
461
+ Extended version that preserves piece information as optional metadata.
462
+ Vocabulary: 76 tokens (adds W, B, P, N, B, R, Q, K but makes them optional)
463
+
464
+ Use this if you want to preserve color/piece info with minimal vocab growth.
465
+ """
466
+
467
+ def _create_vocab(self) -> Dict[str, int]:
468
+ vocab = super()._create_vocab()
469
+
470
+ # Add optional color and piece tokens
471
+ piece_tokens = ['W', 'B', 'P', 'N', 'R', 'Q', 'K'] # Note: B appears in both contexts
472
+
473
+ next_id = len(vocab)
474
+ for token in piece_tokens:
475
+ if token not in vocab:
476
+ vocab[token] = next_id
477
+ next_id += 1
478
+
479
+ return vocab
480
+
481
+ def _tokenize(self, text: str) -> List[str]:
482
+ """
483
+ Optionally include piece info: WPe2e4 -> ['W', 'P', 'e2', 'e4']
484
+ Or strip it for minimal version: WPe2e4 -> ['e2', 'e4']
485
+ """
486
+ tokens = []
487
+ raw_moves = text.strip().split()
488
+
489
+ for move in raw_moves:
490
+ # Extract color and piece if present
491
+ if len(move) >= 2 and move[0] in 'WB' and move[1] in 'PNBRQK':
492
+ # Uncomment to include piece info (increases sequence length):
493
+ # tokens.extend([move[0], move[1]])
494
+ pass
495
+
496
+ # Extract coordinates
497
+ match = self.MOVE_PATTERN.search(move)
498
+ if match:
499
+ from_sq, to_sq, promotion = match.groups()
500
+ tokens.append(from_sq)
501
+ tokens.append(to_sq)
502
+ if promotion:
503
+ tokens.append(promotion)
504
+
505
+ return tokens
506
+
507
+
508
+
509
+ class SanitizedChessTokenizer(ChessTokenizer):
510
+
511
+ # Strategy:
512
+ # 1. Strip suffixes: (, ), x, +, *, o, O, E
513
+ # 2. Strip prefixes: W or B followed by P, N, B, R, Q, K
514
+ # Regex: ^[WB][PNBRQK] matches the start of the string
515
+
516
+ # We can use a single regex to find the "Pure Move" part.
517
+ # We look for the square-to-square pattern (e.g., e2e4) and optional promotion (q,r,b,n)
518
+ # This is safer than stripping because it ignores all noise around the move.
519
+ MOVE_PATTERN = re.compile(r'([a-h][1-8][a-h][1-8][qrbn]?)')
520
+
521
+ def _sanitize(self, text: str) -> str:
522
+ # Extract just the move part (e.g., "WPe2e4(x)" -> "e2e4")
523
+ match = self.MOVE_PATTERN.search(text)
524
+ if match:
525
+ return match.group(1)
526
+ return self.unk_token # Fallback if no valid move found
527
+
528
+ def _tokenize(self, text: str) -> List[str]:
529
+ # Tokenize by splitting space, then extracting the move
530
+ tokens = []
531
+ for t in text.strip().split():
532
+ clean = self._sanitize(t)
533
+ if clean != self.unk_token:
534
+ tokens.append(clean)
535
+ return tokens
536
+
537
+ @classmethod
538
+ def build_vocab_from_iterator(cls, iterator, min_frequency: int = 1) -> "SanitizedChessTokenizer":
539
+ from collections import Counter
540
+
541
+ token_counts = Counter()
542
+
543
+ for game in iterator:
544
+ moves = game.strip().split()
545
+ # Extract only the Pure UCI part
546
+ clean_moves = []
547
+ for m in moves:
548
+ match = cls.MOVE_PATTERN.search(m)
549
+ if match:
550
+ clean_moves.append(match.group(1))
551
+
552
+ token_counts.update(clean_moves)
553
+
554
+ # Filter by frequency
555
+ tokens = [
556
+ token for token, count in token_counts.items()
557
+ if count >= min_frequency
558
+ ]
559
+ tokens = sorted(tokens)
560
+
561
+ # Build vocabulary
562
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
563
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
564
+
565
+ return cls(vocab=vocab)
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "eos_token": "[EOS]",
39
+ "extra_special_tokens": {},
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": "[PAD]",
42
+ "tokenizer_class": "EnhancedCoordinateTokenizer",
43
+ "unk_token": "[UNK]"
44
+ }
vocab.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "a1": 4,
7
+ "a2": 5,
8
+ "a3": 6,
9
+ "a4": 7,
10
+ "a5": 8,
11
+ "a6": 9,
12
+ "a7": 10,
13
+ "a8": 11,
14
+ "b1": 12,
15
+ "b2": 13,
16
+ "b3": 14,
17
+ "b4": 15,
18
+ "b5": 16,
19
+ "b6": 17,
20
+ "b7": 18,
21
+ "b8": 19,
22
+ "c1": 20,
23
+ "c2": 21,
24
+ "c3": 22,
25
+ "c4": 23,
26
+ "c5": 24,
27
+ "c6": 25,
28
+ "c7": 26,
29
+ "c8": 27,
30
+ "d1": 28,
31
+ "d2": 29,
32
+ "d3": 30,
33
+ "d4": 31,
34
+ "d5": 32,
35
+ "d6": 33,
36
+ "d7": 34,
37
+ "d8": 35,
38
+ "e1": 36,
39
+ "e2": 37,
40
+ "e3": 38,
41
+ "e4": 39,
42
+ "e5": 40,
43
+ "e6": 41,
44
+ "e7": 42,
45
+ "e8": 43,
46
+ "f1": 44,
47
+ "f2": 45,
48
+ "f3": 46,
49
+ "f4": 47,
50
+ "f5": 48,
51
+ "f6": 49,
52
+ "f7": 50,
53
+ "f8": 51,
54
+ "g1": 52,
55
+ "g2": 53,
56
+ "g3": 54,
57
+ "g4": 55,
58
+ "g5": 56,
59
+ "g6": 57,
60
+ "g7": 58,
61
+ "g8": 59,
62
+ "h1": 60,
63
+ "h2": 61,
64
+ "h3": 62,
65
+ "h4": 63,
66
+ "h5": 64,
67
+ "h6": 65,
68
+ "h7": 66,
69
+ "h8": 67,
70
+ "q": 68,
71
+ "r": 69,
72
+ "b": 70,
73
+ "n": 71,
74
+ "W": 72,
75
+ "B": 73,
76
+ "P": 74,
77
+ "N": 75,
78
+ "R": 76,
79
+ "Q": 77,
80
+ "K": 78
81
+ }