Oceane28 commited on
Commit
b7dba90
·
verified ·
1 Parent(s): 2e9b3ab

Chess Challenge submission by Oceane28

Browse files
Files changed (9) hide show
  1. README.md +31 -0
  2. config.json +24 -0
  3. model.py +396 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +154 -0
  7. tokenizer_config.json +50 -0
  8. training_args.bin +3 -0
  9. vocab.json +138 -0
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # chess-6-Oceane28
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Oceane28](https://huggingface.co/Oceane28)
17
+ - **Parameters**: 996,428
18
+ - **Organization**: Oceane28
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ model = AutoModelForCausalLM.from_pretrained("Oceane28/chess-6-Oceane28", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("Oceane28/chess-6-Oceane28", trust_remote_code=True)
27
+ ```
28
+
29
+ ## Evaluation
30
+
31
+ This model is evaluated at the [Chess Challenge Arena](https://huggingface.co/spaces/LLM-course/Chess1MChallenge).
config.json ADDED
@@ -0,0 +1,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": 8,
14
+ "n_inner": 354,
15
+ "n_layer": 6,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.5",
19
+ "vocab_size": 136,
20
+ "auto_map": {
21
+ "AutoConfig": "model.ChessConfig",
22
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
23
+ }
24
+ }
model.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Modèle Transformer pour le Chess Challenge (1M paramètres).
3
+
4
+ Ce module fournit une architecture transformer de style GPT conçue
5
+ pour respecter la contrainte stricte de moins de 1 million de paramètres.
6
+
7
+ Composants clés :
8
+ - ChessConfig : Configuration des hyperparamètres.
9
+ - ChessForCausalLM : Le modèle principal pour la prédiction du prochain coup.
10
+ """
11
+ from __future__ import annotations
12
+ import math
13
+ from dataclasses import dataclass
14
+ from typing import Optional, Tuple, Union
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from transformers import PretrainedConfig, PreTrainedModel, AutoConfig, AutoModelForCausalLM
19
+ from transformers.modeling_outputs import CausalLMOutputWithPast
20
+
21
+ # -----------------------------------------------------------------------------
22
+ # Configuration
23
+ # -----------------------------------------------------------------------------
24
+
25
+ class ChessConfig(PretrainedConfig):
26
+ """
27
+ Classe de configuration pour le modèle Chess Transformer.
28
+
29
+ Conçue pour un budget de paramètres très serré (< 1M).
30
+
31
+ Répartition du budget (avec les valeurs par défaut de ton ami) :
32
+ - Vocabulaire (Embeddings) : 72 * 92 = ~6,6k
33
+ - Embeddings de position : 256 * 92 = ~23,5k
34
+ - Couches Transformer : 11 couches * (~85k par couche) = ~935k
35
+ - Tête LM (liée aux embeddings) : 0 paramètre supplémentaire
36
+ - Total : ~970k paramètres (juste en dessous de 1M).
37
+ """
38
+
39
+ model_type = "chess_transformer"
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_size: int = 1200,
44
+ n_embd: int = 128,
45
+ n_layer: int = 6,
46
+ n_head: int = 4,
47
+ n_ctx: int = 256,
48
+ n_inner: Optional[int] = None,
49
+ dropout: float = 0.1,
50
+ layer_norm_epsilon: float = 1e-5,
51
+ tie_weights: bool = True,
52
+ pad_token_id: int = 0,
53
+ bos_token_id: int = 1,
54
+ eos_token_id: int = 2,
55
+ **kwargs,
56
+ ):
57
+ super().__init__(
58
+ pad_token_id=pad_token_id,
59
+ bos_token_id=bos_token_id,
60
+ eos_token_id=eos_token_id,
61
+ **kwargs,
62
+ )
63
+
64
+ self.vocab_size = vocab_size
65
+ self.n_embd = n_embd
66
+ self.n_layer = n_layer
67
+ self.n_head = n_head
68
+ self.n_ctx = n_ctx
69
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd
70
+ self.dropout = dropout
71
+ self.layer_norm_epsilon = layer_norm_epsilon
72
+ self.tie_weights = tie_weights
73
+ self.tie_word_embeddings = bool(tie_weights)
74
+
75
+
76
+ # -----------------------------------------------------------------------------
77
+ # Modules du Transformer
78
+ # -----------------------------------------------------------------------------
79
+
80
+ class MultiHeadAttention(nn.Module):
81
+ """
82
+ Module d'attention multi-têtes standard.
83
+ Inclut le masquage causal pour empêcher le modèle de "voir le futur".
84
+ """
85
+
86
+ def __init__(self, config: ChessConfig):
87
+ super().__init__()
88
+
89
+ assert config.n_embd % config.n_head == 0, \
90
+ f"n_embd ({config.n_embd}) doit être divisible par n_head ({config.n_head})"
91
+
92
+ self.n_head = config.n_head
93
+ self.n_embd = config.n_embd
94
+ self.head_dim = config.n_embd // config.n_head
95
+
96
+ # Projection combinée Q, K, V pour l'efficacité
97
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
98
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
99
+
100
+ self.dropout = nn.Dropout(config.dropout)
101
+
102
+ # Masque causal (registre persistent=False pour ne pas le sauvegarder dans le checkpoint)
103
+ self.register_buffer(
104
+ "bias",
105
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
106
+ 1, 1, config.n_ctx, config.n_ctx
107
+ ),
108
+ persistent=False,
109
+ )
110
+
111
+ def forward(
112
+ self,
113
+ x: torch.Tensor,
114
+ attention_mask: Optional[torch.Tensor] = None,
115
+ ) -> torch.Tensor:
116
+ batch_size, seq_len, _ = x.size()
117
+
118
+ # Calcul de Q, K, V
119
+ qkv = self.c_attn(x)
120
+ q, k, v = qkv.split(self.n_embd, dim=2)
121
+
122
+ # Remodelage pour l'attention multi-têtes
123
+ # (batch, seq_len, n_head, head_dim) -> (batch, n_head, seq_len, head_dim)
124
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
125
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
126
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
127
+
128
+ # Attention produit scalaire (Scaled Dot-Product Attention)
129
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
130
+
131
+ # Application du masque causal (le futur est masqué avec -inf)
132
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
133
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
134
+
135
+ # Application du masque d'attention (pour le padding)
136
+ if attention_mask is not None:
137
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
138
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
139
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
140
+
141
+ attn_weights = F.softmax(attn_weights, dim=-1)
142
+ attn_weights = self.dropout(attn_weights)
143
+
144
+ # Application de l'attention aux valeurs
145
+ attn_output = torch.matmul(attn_weights, v)
146
+
147
+ # Remise en forme
148
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
149
+ batch_size, seq_len, self.n_embd
150
+ )
151
+
152
+ # Projection de sortie
153
+ attn_output = self.c_proj(attn_output)
154
+
155
+ return attn_output
156
+
157
+
158
+ class FeedForward(nn.Module):
159
+ """
160
+ Réseau de neurones Feed-Forward (MLP).
161
+ Deux couches linéaires avec une activation GELU entre les deux.
162
+ """
163
+
164
+ def __init__(self, config: ChessConfig):
165
+ super().__init__()
166
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner)
167
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
168
+ self.dropout = nn.Dropout(config.dropout)
169
+
170
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
171
+ x = self.c_fc(x)
172
+ x = F.gelu(x)
173
+ x = self.c_proj(x)
174
+ x = self.dropout(x)
175
+ return x
176
+
177
+
178
+ class TransformerBlock(nn.Module):
179
+ """
180
+ Un bloc transformer unique contenant Attention et Feed-Forward.
181
+ Utilise la "Pre-normalization" (LayerNorm avant l'attention/FFN) pour la stabilité.
182
+ """
183
+
184
+ def __init__(self, config: ChessConfig):
185
+ super().__init__()
186
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
187
+ self.attn = MultiHeadAttention(config)
188
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
189
+ self.mlp = FeedForward(config)
190
+
191
+ def forward(
192
+ self,
193
+ x: torch.Tensor,
194
+ attention_mask: Optional[torch.Tensor] = None,
195
+ ) -> torch.Tensor:
196
+ # Connexion résiduelle + Pre-norm Attention
197
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
198
+ # Connexion résiduelle + Pre-norm FFN
199
+ x = x + self.mlp(self.ln_2(x))
200
+ return x
201
+
202
+
203
+ # -----------------------------------------------------------------------------
204
+ # Modèle Principal
205
+ # -----------------------------------------------------------------------------
206
+
207
+ class ChessForCausalLM(PreTrainedModel):
208
+ """
209
+ Modèle final pour la prédiction de coups (Causal Language Modeling).
210
+
211
+ Architecture :
212
+ 1. Embeddings (Tokens + Position)
213
+ 2. Empilement de blocs Transformer
214
+ 3. Tête linéaire finale (Projection vers le vocabulaire)
215
+ """
216
+
217
+ config_class = ChessConfig
218
+ base_model_prefix = "transformer"
219
+ supports_gradient_checkpointing = True
220
+
221
+ # Ignore l'avertissement de clé manquante car lm_head partage les poids avec wte
222
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
223
+
224
+ def __init__(self, config: ChessConfig):
225
+ super().__init__(config)
226
+
227
+ # Embeddings
228
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
229
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
230
+
231
+ self.drop = nn.Dropout(config.dropout)
232
+
233
+ # Blocs Transformer
234
+ self.h = nn.ModuleList([
235
+ TransformerBlock(config) for _ in range(config.n_layer)
236
+ ])
237
+
238
+ # LayerNorm final
239
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
240
+
241
+ # Tête de sortie (sans biais pour économiser des paramètres)
242
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
243
+
244
+ # Gestion du partage de poids (Weight Tying)
245
+ if config.tie_weights:
246
+ self._tied_weights_keys = ["lm_head.weight"]
247
+
248
+ # Initialisation des poids
249
+ self.post_init()
250
+
251
+ # Forcer le lien des poids si configuré
252
+ if config.tie_weights:
253
+ self.tie_weights()
254
+
255
+ def get_input_embeddings(self) -> nn.Module:
256
+ return self.wte
257
+
258
+ def set_input_embeddings(self, new_embeddings: nn.Module):
259
+ self.wte = new_embeddings
260
+ if getattr(self.config, "tie_weights", False):
261
+ self.tie_weights()
262
+
263
+ def get_output_embeddings(self) -> nn.Module:
264
+ return self.lm_head
265
+
266
+ def set_output_embeddings(self, new_embeddings: nn.Module):
267
+ self.lm_head = new_embeddings
268
+
269
+ def tie_weights(self):
270
+ """Lie les poids de l'embedding d'entrée et de la tête de sortie."""
271
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
272
+ self._tie_or_clone_weights(self.lm_head, self.wte)
273
+
274
+ def _init_weights(self, module: nn.Module):
275
+ """Initialisation des poids style GPT-2."""
276
+ if isinstance(module, nn.Linear):
277
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
278
+ if module.bias is not None:
279
+ torch.nn.init.zeros_(module.bias)
280
+ elif isinstance(module, nn.Embedding):
281
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
282
+ elif isinstance(module, nn.LayerNorm):
283
+ torch.nn.init.ones_(module.weight)
284
+ torch.nn.init.zeros_(module.bias)
285
+
286
+ def forward(
287
+ self,
288
+ input_ids: torch.LongTensor,
289
+ attention_mask: Optional[torch.Tensor] = None,
290
+ position_ids: Optional[torch.LongTensor] = None,
291
+ labels: Optional[torch.LongTensor] = None,
292
+ return_dict: Optional[bool] = None,
293
+ **kwargs,
294
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
295
+ """
296
+ Passe avant (Forward pass).
297
+ Calcule les logits et, si des étiquettes (labels) sont fournies, la perte (loss).
298
+ """
299
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
300
+
301
+ batch_size, seq_len = input_ids.size()
302
+ device = input_ids.device
303
+
304
+ # Création des IDs de position s'ils ne sont pas fournis
305
+ if position_ids is None:
306
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
307
+
308
+ # Calcul des embeddings (Token + Position)
309
+ token_embeds = self.wte(input_ids)
310
+ position_embeds = self.wpe(position_ids)
311
+ hidden_states = self.drop(token_embeds + position_embeds)
312
+
313
+ # Passage dans les blocs Transformer
314
+ for block in self.h:
315
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
316
+
317
+ # Normalisation finale
318
+ hidden_states = self.ln_f(hidden_states)
319
+
320
+ # Calcul des logits (prédiction du prochain token)
321
+ logits = self.lm_head(hidden_states)
322
+
323
+ # Calcul de la perte (Training Loss)
324
+ loss = None
325
+ if labels is not None:
326
+ # On décale les logits et les labels d'un cran
327
+ # (le modèle doit prédire le token t+1 à partir du token t)
328
+ shift_logits = logits[..., :-1, :].contiguous()
329
+ shift_labels = labels[..., 1:].contiguous()
330
+
331
+ # Perte CrossEntropy standard
332
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
333
+ loss = loss_fct(
334
+ shift_logits.view(-1, shift_logits.size(-1)),
335
+ shift_labels.view(-1),
336
+ )
337
+
338
+ if not return_dict:
339
+ output = (logits,)
340
+ return ((loss,) + output) if loss is not None else output
341
+
342
+ return CausalLMOutputWithPast(
343
+ loss=loss,
344
+ logits=logits,
345
+ past_key_values=None,
346
+ hidden_states=None,
347
+ attentions=None,
348
+ )
349
+
350
+ @torch.no_grad()
351
+ def generate_move(
352
+ self,
353
+ input_ids: torch.LongTensor,
354
+ temperature: float = 1.0,
355
+ top_k: Optional[int] = None,
356
+ top_p: Optional[float] = None,
357
+ ) -> int:
358
+ """
359
+ Génère le prochain coup pour une séquence donnée.
360
+ Utilisé pour l'inférence en jeu réel.
361
+ """
362
+ self.eval()
363
+
364
+ # Récupère les logits pour la dernière position uniquement
365
+ outputs = self(input_ids)
366
+ logits = outputs.logits[:, -1, :] / temperature
367
+
368
+ # Filtrage Top-K
369
+ if top_k is not None:
370
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
371
+ logits[indices_to_remove] = float("-inf")
372
+
373
+ # Filtrage Top-P (Nucleus Sampling)
374
+ if top_p is not None:
375
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
376
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
377
+
378
+ # On retire les tokens qui sont au-dessus du seuil cumulatif
379
+ sorted_indices_to_remove = cumulative_probs > top_p
380
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
381
+ sorted_indices_to_remove[..., 0] = 0
382
+
383
+ indices_to_remove = sorted_indices_to_remove.scatter(
384
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
385
+ )
386
+ logits[indices_to_remove] = float("-inf")
387
+
388
+ # Échantillonnage final
389
+ probs = F.softmax(logits, dim=-1)
390
+ next_token = torch.multinomial(probs, num_samples=1)
391
+
392
+ return next_token.item()
393
+
394
+ # Enregistrement pour chargement automatique via AutoModel
395
+ AutoConfig.register("chess_transformer", ChessConfig)
396
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50286b26484c3225b11c798752b682a11247037f5c023480787bef0680f51116
3
+ size 3992160
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,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Role-marked square tokenizer for Chess Challenge.
3
+ Each move is represented as: <from_square>_f <to_square>_t [promo?] [EOS]
4
+
5
+ Examples:
6
+ WPe2e4 -> e2_f e4_t [EOS]
7
+ BPe7e8=Q -> e7_f e8_t q [EOS]
8
+ """
9
+ from __future__ import annotations
10
+ import json
11
+ import os
12
+ import re
13
+ from typing import Dict, List, Optional, Tuple, Any
14
+ from transformers import PreTrainedTokenizer
15
+
16
+ _MOVE_RE = re.compile(r"^([WB])([PNBRQK])([a-h][1-8])([a-h][1-8])(.*)$")
17
+ _PROMO_RE = re.compile(r"=([QRBNqrbn])")
18
+
19
+ SQUARES = [f"{f}{r}" for r in "12345678" for f in "abcdefgh"]
20
+ PROMOS = ["q", "r", "b", "n"]
21
+
22
+ class ChessTokenizer(PreTrainedTokenizer):
23
+ model_input_names = ["input_ids", "attention_mask"]
24
+ vocab_files_names = {"vocab_file": "vocab.json"}
25
+
26
+ PAD_TOKEN = "[PAD]"
27
+ BOS_TOKEN = "[BOS]"
28
+ EOS_TOKEN = "[EOS]"
29
+ UNK_TOKEN = "[UNK]"
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_file: Optional[str] = None,
34
+ vocab: Optional[Dict[str, int]] = None,
35
+ **kwargs: Any,
36
+ ):
37
+ self._pad_token = self.PAD_TOKEN
38
+ self._bos_token = self.BOS_TOKEN
39
+ self._eos_token = self.EOS_TOKEN
40
+ self._unk_token = self.UNK_TOKEN
41
+
42
+ for k in ["pad_token", "bos_token", "eos_token", "unk_token"]:
43
+ kwargs.pop(k, None)
44
+
45
+ if vocab is not None:
46
+ self._vocab = vocab
47
+ elif vocab_file is not None and os.path.isfile(vocab_file):
48
+ with open(vocab_file, "r", encoding="utf-8") as f:
49
+ self._vocab = json.load(f)
50
+ else:
51
+ self._vocab = self._build_fixed_vocab()
52
+
53
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
54
+
55
+ super().__init__(
56
+ pad_token=self._pad_token,
57
+ bos_token=self._bos_token,
58
+ eos_token=self._eos_token,
59
+ unk_token=self._unk_token,
60
+ **kwargs,
61
+ )
62
+
63
+ @staticmethod
64
+ def _build_fixed_vocab() -> Dict[str, int]:
65
+ tokens: List[str] = [
66
+ ChessTokenizer.PAD_TOKEN,
67
+ ChessTokenizer.BOS_TOKEN,
68
+ ChessTokenizer.EOS_TOKEN,
69
+ ChessTokenizer.UNK_TOKEN,
70
+ ]
71
+ tokens += [f"{sq}_f" for sq in SQUARES]
72
+ tokens += [f"{sq}_t" for sq in SQUARES]
73
+ tokens += PROMOS
74
+ return {tok: i for i, tok in enumerate(tokens)}
75
+
76
+ @property
77
+ def vocab_size(self) -> int:
78
+ return len(self._vocab)
79
+
80
+ def get_vocab(self) -> Dict[str, int]:
81
+ return dict(self._vocab)
82
+
83
+ @classmethod
84
+ def build_vocab_from_dataset(cls, *args: Any, **kwargs: Any) -> "ChessTokenizer":
85
+ return cls()
86
+
87
+ @classmethod
88
+ def build_vocab_from_iterator(cls, *args: Any, **kwargs: Any) -> "ChessTokenizer":
89
+ return cls()
90
+
91
+ def _tokenize(self, text: str) -> List[str]:
92
+ """Tokenize a space-separated list of dataset moves into role-marked tokens."""
93
+ text = (text or "").strip()
94
+ if not text:
95
+ return []
96
+
97
+ out: List[str] = []
98
+ for move in text.split():
99
+ # Allow already-tokenized text (debugging)
100
+ if move in self._vocab:
101
+ out.append(move)
102
+ continue
103
+
104
+ # Try to match Standard Lichess Format (WPe2e4)
105
+ m = _MOVE_RE.match(move)
106
+ if not m:
107
+ # If it's plain UCI like e2e4 or e7e8q
108
+ if re.fullmatch(r"[a-h][1-8][a-h][1-8][qrbn]?", move):
109
+ src, dst = move[:2], move[2:4]
110
+ out.append(f"{src}_f")
111
+ out.append(f"{dst}_t")
112
+ if len(move) == 5:
113
+ out.append(move[4])
114
+ out.append(self.EOS_TOKEN)
115
+ continue
116
+
117
+ # Unknown token
118
+ out.append(self.UNK_TOKEN)
119
+ out.append(self.EOS_TOKEN)
120
+ continue
121
+
122
+ # Extract parts from WPe2e4...
123
+ _side, _piece, src, dst, suffix = m.groups()
124
+ out.append(f"{src}_f")
125
+ out.append(f"{dst}_t")
126
+
127
+ promo = None
128
+ pm = _PROMO_RE.search(suffix or "")
129
+ if pm:
130
+ promo = pm.group(1).lower()
131
+
132
+ if promo in PROMOS:
133
+ out.append(promo)
134
+
135
+ out.append(self.EOS_TOKEN)
136
+
137
+ return out
138
+
139
+ def _convert_token_to_id(self, token: str) -> int:
140
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
141
+
142
+ def _convert_id_to_token(self, index: int) -> str:
143
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
144
+
145
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
146
+ return " ".join(tokens)
147
+
148
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
149
+ os.makedirs(save_directory, exist_ok=True)
150
+ name = "vocab.json" if not filename_prefix else f"{filename_prefix}-vocab.json"
151
+ path = os.path.join(save_directory, name)
152
+ with open(path, "w", encoding="utf-8") as f:
153
+ json.dump(self._vocab, f, indent=2, ensure_ascii=False)
154
+ return (path,)
tokenizer_config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[EOS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "bos_token": "[BOS]",
37
+ "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": "ChessTokenizer",
43
+ "unk_token": "[UNK]",
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.ChessTokenizer",
47
+ null
48
+ ]
49
+ }
50
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8bf96856bc64ce4893cdd6ee8c82a58af1a49726bbbfb085d0b6a2d7c115ffd
3
+ size 5777
vocab.json ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "a1_f": 4,
7
+ "b1_f": 5,
8
+ "c1_f": 6,
9
+ "d1_f": 7,
10
+ "e1_f": 8,
11
+ "f1_f": 9,
12
+ "g1_f": 10,
13
+ "h1_f": 11,
14
+ "a2_f": 12,
15
+ "b2_f": 13,
16
+ "c2_f": 14,
17
+ "d2_f": 15,
18
+ "e2_f": 16,
19
+ "f2_f": 17,
20
+ "g2_f": 18,
21
+ "h2_f": 19,
22
+ "a3_f": 20,
23
+ "b3_f": 21,
24
+ "c3_f": 22,
25
+ "d3_f": 23,
26
+ "e3_f": 24,
27
+ "f3_f": 25,
28
+ "g3_f": 26,
29
+ "h3_f": 27,
30
+ "a4_f": 28,
31
+ "b4_f": 29,
32
+ "c4_f": 30,
33
+ "d4_f": 31,
34
+ "e4_f": 32,
35
+ "f4_f": 33,
36
+ "g4_f": 34,
37
+ "h4_f": 35,
38
+ "a5_f": 36,
39
+ "b5_f": 37,
40
+ "c5_f": 38,
41
+ "d5_f": 39,
42
+ "e5_f": 40,
43
+ "f5_f": 41,
44
+ "g5_f": 42,
45
+ "h5_f": 43,
46
+ "a6_f": 44,
47
+ "b6_f": 45,
48
+ "c6_f": 46,
49
+ "d6_f": 47,
50
+ "e6_f": 48,
51
+ "f6_f": 49,
52
+ "g6_f": 50,
53
+ "h6_f": 51,
54
+ "a7_f": 52,
55
+ "b7_f": 53,
56
+ "c7_f": 54,
57
+ "d7_f": 55,
58
+ "e7_f": 56,
59
+ "f7_f": 57,
60
+ "g7_f": 58,
61
+ "h7_f": 59,
62
+ "a8_f": 60,
63
+ "b8_f": 61,
64
+ "c8_f": 62,
65
+ "d8_f": 63,
66
+ "e8_f": 64,
67
+ "f8_f": 65,
68
+ "g8_f": 66,
69
+ "h8_f": 67,
70
+ "a1_t": 68,
71
+ "b1_t": 69,
72
+ "c1_t": 70,
73
+ "d1_t": 71,
74
+ "e1_t": 72,
75
+ "f1_t": 73,
76
+ "g1_t": 74,
77
+ "h1_t": 75,
78
+ "a2_t": 76,
79
+ "b2_t": 77,
80
+ "c2_t": 78,
81
+ "d2_t": 79,
82
+ "e2_t": 80,
83
+ "f2_t": 81,
84
+ "g2_t": 82,
85
+ "h2_t": 83,
86
+ "a3_t": 84,
87
+ "b3_t": 85,
88
+ "c3_t": 86,
89
+ "d3_t": 87,
90
+ "e3_t": 88,
91
+ "f3_t": 89,
92
+ "g3_t": 90,
93
+ "h3_t": 91,
94
+ "a4_t": 92,
95
+ "b4_t": 93,
96
+ "c4_t": 94,
97
+ "d4_t": 95,
98
+ "e4_t": 96,
99
+ "f4_t": 97,
100
+ "g4_t": 98,
101
+ "h4_t": 99,
102
+ "a5_t": 100,
103
+ "b5_t": 101,
104
+ "c5_t": 102,
105
+ "d5_t": 103,
106
+ "e5_t": 104,
107
+ "f5_t": 105,
108
+ "g5_t": 106,
109
+ "h5_t": 107,
110
+ "a6_t": 108,
111
+ "b6_t": 109,
112
+ "c6_t": 110,
113
+ "d6_t": 111,
114
+ "e6_t": 112,
115
+ "f6_t": 113,
116
+ "g6_t": 114,
117
+ "h6_t": 115,
118
+ "a7_t": 116,
119
+ "b7_t": 117,
120
+ "c7_t": 118,
121
+ "d7_t": 119,
122
+ "e7_t": 120,
123
+ "f7_t": 121,
124
+ "g7_t": 122,
125
+ "h7_t": 123,
126
+ "a8_t": 124,
127
+ "b8_t": 125,
128
+ "c8_t": 126,
129
+ "d8_t": 127,
130
+ "e8_t": 128,
131
+ "f8_t": 129,
132
+ "g8_t": 130,
133
+ "h8_t": 131,
134
+ "q": 132,
135
+ "r": 133,
136
+ "b": 134,
137
+ "n": 135
138
+ }