Valbad commited on
Commit
7a31b53
·
verified ·
1 Parent(s): 2e4923c

Chess Challenge submission by Valbad

Browse files
Files changed (7) hide show
  1. README.md +26 -0
  2. config.json +20 -0
  3. model.safetensors +3 -0
  4. special_tokens_map.json +6 -0
  5. tokenizer.py +615 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +99 -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-better-valbad
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Valbad](https://huggingface.co/Valbad)
17
+ - **Parameters**: 440,300
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 97
24
+ - **Embedding dim**: 100
25
+ - **Layers**: 4
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 100,
13
+ "n_head": 4,
14
+ "n_inner": 300,
15
+ "n_layer": 4,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.3",
19
+ "vocab_size": 97
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cd361c3d20274e1cd1458bebd874f6e7a6898e7592857e17d2015bbe40baa05
3
+ size 1765576
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,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_iterator(
149
+ # cls,
150
+ # iterator,
151
+ # vocab_size: int = 1200,
152
+ # min_frequency: int = 1,
153
+ # ) -> "ChessTokenizer":
154
+ # """
155
+ # Build a tokenizer vocabulary from an iterator of game strings.
156
+
157
+ # - Controls final vocab size explicitly via vocab_size.
158
+ # - Keeps the most frequent move tokens (best coverage).
159
+ # - Uses min_frequency as a floor, but vocab_size is the main control.
160
+ # """
161
+ # from collections import Counter
162
+
163
+ # token_counts = Counter()
164
+ # for game in iterator:
165
+ # moves = game.strip().split()
166
+ # token_counts.update(moves)
167
+
168
+ # # Filter by min_frequency first
169
+ # items = [(tok, cnt) for tok, cnt in token_counts.items() if cnt >= min_frequency]
170
+
171
+ # # Sort by frequency desc, then token for determinism
172
+ # items.sort(key=lambda x: (-x[1], x[0]))
173
+
174
+ # special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
175
+ # max_move_tokens = max(0, vocab_size - len(special_tokens))
176
+
177
+ # move_tokens = [tok for tok, _ in items[:max_move_tokens]]
178
+ # vocab = {token: idx for idx, token in enumerate(special_tokens + move_tokens)}
179
+
180
+ # return cls(vocab=vocab)
181
+
182
+
183
+ # # @classmethod
184
+ # # def build_vocab_from_dataset(
185
+ # # cls,
186
+ # # dataset_name: str = "dlouapre/lichess_2025-01_1M",
187
+ # # split: str = "train",
188
+ # # column: str = "text",
189
+ # # min_frequency: int = 500,
190
+ # # max_samples: Optional[int] = 100000,
191
+ # # ) -> "ChessTokenizer":
192
+ # # """
193
+ # # Build a tokenizer vocabulary from a Hugging Face dataset.
194
+
195
+ # # Args:
196
+ # # dataset_name: Name of the dataset on Hugging Face Hub.
197
+ # # split: Dataset split to use.
198
+ # # column: Column containing the game strings.
199
+ # # min_frequency: Minimum frequency for a token to be included (default: 500).
200
+ # # max_samples: Maximum number of samples to process (default: 100k).
201
+
202
+ # # Returns:
203
+ # # A ChessTokenizer with the built vocabulary.
204
+ # # """
205
+ # # from datasets import load_dataset
206
+
207
+ # # dataset = load_dataset(dataset_name, split=split)
208
+
209
+ # # if max_samples is not None:
210
+ # # dataset = dataset.select(range(min(max_samples, len(dataset))))
211
+
212
+ # # def game_iterator():
213
+ # # for example in dataset:
214
+ # # yield example[column]
215
+
216
+ # # return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
217
+ # @classmethod
218
+ # def build_vocab_from_dataset(
219
+ # cls,
220
+ # dataset_name: str = "dlouapre/lichess_2025-01_1M",
221
+ # split: str = "train",
222
+ # column: str = "text",
223
+ # vocab_size: int = 1200,
224
+ # min_frequency: int = 1,
225
+ # max_samples: Optional[int] = 200000,
226
+ # ) -> "ChessTokenizer":
227
+ # """
228
+ # Build a tokenizer vocabulary from a Hugging Face dataset.
229
+
230
+ # Args:
231
+ # vocab_size: Final vocab size INCLUDING special tokens.
232
+ # min_frequency: Minimum count to consider a move (usually 1 is fine).
233
+ # max_samples: How many games to scan to build vocab.
234
+ # """
235
+ # from datasets import load_dataset
236
+
237
+ # dataset = load_dataset(dataset_name, split=split)
238
+
239
+ # # if max_samples is not None: # v0&1
240
+ # # dataset = dataset.select(range(min(max_samples, len(dataset))))
241
+
242
+ # if max_samples is not None: # v2
243
+ # n = min(max_samples, len(dataset))
244
+ # dataset = dataset.shuffle(seed=42).select(range(n))
245
+
246
+ # def game_iterator():
247
+ # for example in dataset:
248
+ # yield example[column]
249
+
250
+ # return cls.build_vocab_from_iterator(
251
+ # game_iterator(),
252
+ # vocab_size=vocab_size,
253
+ # min_frequency=min_frequency,
254
+ # )
255
+
256
+ # @property
257
+ # def vocab_size(self) -> int:
258
+ # """Return the size of the vocabulary."""
259
+ # return len(self._vocab)
260
+
261
+ # def get_vocab(self) -> Dict[str, int]:
262
+ # """Return the vocabulary as a dictionary."""
263
+ # return dict(self._vocab)
264
+
265
+ # def _tokenize(self, text: str) -> List[str]:
266
+ # """
267
+ # Tokenize a string of moves into a list of tokens.
268
+
269
+ # Args:
270
+ # text: A string of space-separated moves.
271
+
272
+ # Returns:
273
+ # List of move tokens.
274
+ # """
275
+ # return text.strip().split()
276
+
277
+ # def _convert_token_to_id(self, token: str) -> int:
278
+ # """Convert a token to its ID."""
279
+ # return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
280
+
281
+ # def _convert_id_to_token(self, index: int) -> str:
282
+ # """Convert an ID to its token."""
283
+ # return self._ids_to_tokens.get(index, self.UNK_TOKEN)
284
+
285
+ # def convert_tokens_to_string(self, tokens: List[str]) -> str:
286
+ # """Convert a list of tokens back to a string."""
287
+ # # Filter out special tokens for cleaner output
288
+ # special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
289
+ # return " ".join(t for t in tokens if t not in special)
290
+
291
+ # def save_vocabulary(
292
+ # self,
293
+ # save_directory: str,
294
+ # filename_prefix: Optional[str] = None,
295
+ # ) -> tuple:
296
+ # """
297
+ # Save the vocabulary to a JSON file.
298
+
299
+ # Args:
300
+ # save_directory: Directory to save the vocabulary.
301
+ # filename_prefix: Optional prefix for the filename.
302
+
303
+ # Returns:
304
+ # Tuple containing the path to the saved vocabulary file.
305
+ # """
306
+ # if not os.path.isdir(save_directory):
307
+ # os.makedirs(save_directory, exist_ok=True)
308
+
309
+ # vocab_file = os.path.join(
310
+ # save_directory,
311
+ # (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
312
+ # )
313
+
314
+ # with open(vocab_file, "w", encoding="utf-8") as f:
315
+ # json.dump(self._vocab, f, ensure_ascii=False, indent=2)
316
+
317
+ # return (vocab_file,)
318
+
319
+ # # def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
320
+ # # if token_ids_1 is not None:
321
+ # # # Not expected here, but handle gracefully
322
+ # # token_ids = token_ids_0 + token_ids_1
323
+ # # else:
324
+ # # token_ids = token_ids_0
325
+ # # return [self.bos_token_id] + token_ids + [self.eos_token_id]
326
+
327
+ # # def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
328
+ # # if already_has_special_tokens:
329
+ # # return [1 if t in (self.pad_token_id, self.bos_token_id, self.eos_token_id, self.unk_token_id) else 0 for t in token_ids_0]
330
+ # # if token_ids_1 is not None:
331
+ # # token_ids = token_ids_0 + token_ids_1
332
+ # # else:
333
+ # # token_ids = token_ids_0
334
+ # # return [1] + [0] * len(token_ids) + [1]
335
+
336
+ # def count_vocab_from_dataset(
337
+ # dataset_name: str = "dlouapre/lichess_2025-01_1M",
338
+ # split: str = "train",
339
+ # column: str = "text",
340
+ # max_samples: Optional[int] = 10000,
341
+ # ) -> Dict[str, int]:
342
+ # """
343
+ # Count token frequencies in a dataset (useful for vocabulary analysis).
344
+
345
+ # Args:
346
+ # dataset_name: Name of the dataset on Hugging Face Hub.
347
+ # split: Dataset split to use.
348
+ # column: Column containing the game strings.
349
+ # max_samples: Maximum number of samples to process.
350
+
351
+ # Returns:
352
+ # Dictionary mapping tokens to their frequencies.
353
+ # """
354
+ # from collections import Counter
355
+ # from datasets import load_dataset
356
+
357
+ # dataset = load_dataset(dataset_name, split=split)
358
+
359
+ # if max_samples is not None:
360
+ # dataset = dataset.select(range(min(max_samples, len(dataset))))
361
+
362
+ # token_counts = Counter()
363
+
364
+ # for example in dataset:
365
+ # moves = example[column].strip().split()
366
+ # token_counts.update(moves)
367
+
368
+ # return dict(token_counts)
369
+
370
+ """
371
+ Grammar-aware Chess Tokenizer for the Chess Challenge.
372
+
373
+ Goal: maximize legal move extraction in evaluate.py which searches for
374
+ two square patterns ([a-h][1-8]) in the generated text and takes the first two.
375
+
376
+ Strategy:
377
+ - Decompose each move into structured tokens:
378
+ - CP_<color><piece> (e.g., CP_WP, CP_BN)
379
+ - SQ_<square> (e.g., SQ_e2, SQ_e4)
380
+ - EV_<event> (e.g., EV_NONE, EV_X, EV_PLUS, EV_MATE, EV_PROMO_Q, ...)
381
+ - SEP (end-of-move marker, decoded as a space)
382
+ - Deterministic vocab: no dataset-dependent OOV -> UNK for rare full moves disappears.
383
+ """
384
+
385
+ from __future__ import annotations
386
+
387
+ import json
388
+ import os
389
+ import re
390
+ from typing import Dict, List, Optional
391
+
392
+ from transformers import PreTrainedTokenizer
393
+
394
+
395
+ class ChessTokenizer(PreTrainedTokenizer):
396
+ model_input_names = ["input_ids", "attention_mask"]
397
+ vocab_files_names = {"vocab_file": "vocab.json"}
398
+
399
+ PAD_TOKEN = "[PAD]"
400
+ BOS_TOKEN = "[BOS]"
401
+ EOS_TOKEN = "[EOS]"
402
+ UNK_TOKEN = "[UNK]"
403
+ SEP_TOKEN = "[SEP]" # end-of-move marker (decoded as a space)
404
+
405
+ _SQUARE_RE = re.compile(r"^[a-h][1-8]$") # positions are in the format xY where x is in [a-h], y in [1-8]
406
+
407
+ def __init__(
408
+ self,
409
+ vocab_file: Optional[str] = None,
410
+ vocab: Optional[Dict[str, int]] = None,
411
+ **kwargs,
412
+ ):
413
+ self._pad_token = self.PAD_TOKEN
414
+ self._bos_token = self.BOS_TOKEN
415
+ self._eos_token = self.EOS_TOKEN
416
+ self._unk_token = self.UNK_TOKEN
417
+ self._sep_token = self.SEP_TOKEN
418
+
419
+ kwargs.pop("pad_token", None)
420
+ kwargs.pop("bos_token", None)
421
+ kwargs.pop("eos_token", None)
422
+ kwargs.pop("unk_token", None)
423
+
424
+ if vocab is not None:
425
+ self._vocab = vocab
426
+ elif vocab_file is not None and os.path.exists(vocab_file):
427
+ with open(vocab_file, "r", encoding="utf-8") as f:
428
+ self._vocab = json.load(f)
429
+ else:
430
+ self._vocab = self._create_default_vocab()
431
+
432
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
433
+
434
+ super().__init__(
435
+ pad_token=self._pad_token,
436
+ bos_token=self._bos_token,
437
+ eos_token=self._eos_token,
438
+ unk_token=self._unk_token,
439
+ **kwargs,
440
+ )
441
+
442
+ #### Vocab
443
+ def _create_default_vocab(self) -> Dict[str, int]:
444
+ special = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.SEP_TOKEN]
445
+
446
+ # Color+piece (12 tokens)
447
+ cp = [f"CP_{c}{p}" for c in "WB" for p in "PNBRQK"]
448
+
449
+ # Squares (64 tokens)
450
+ squares = [f"SQ_{f}{r}" for f in "abcdefgh" for r in "12345678"]
451
+
452
+ # Events: keep small & canonical (you can extend later)
453
+ events = [
454
+ "EV_NONE",
455
+ "EV_X",
456
+ "EV_PLUS",
457
+ "EV_MATE",
458
+ "EV_XPLUS",
459
+ "EV_XMATE",
460
+ "EV_O", # kingside castle
461
+ "EV_OO", # queenside castle
462
+ "EV_PROMO_N",
463
+ "EV_PROMO_B",
464
+ "EV_PROMO_R",
465
+ "EV_PROMO_Q",
466
+ "EV_XPROMO_N",
467
+ "EV_XPROMO_B",
468
+ "EV_XPROMO_R",
469
+ "EV_XPROMO_Q",
470
+ ]
471
+
472
+ vocab_list = special + cp + squares + events # this vocabulary has size 12 + 64 + 16 + 5 = 97 tokens
473
+ return {tok: i for i, tok in enumerate(vocab_list)}
474
+
475
+ @property
476
+ def vocab_size(self) -> int:
477
+ return len(self._vocab)
478
+
479
+ def get_vocab(self) -> Dict[str, int]:
480
+ return dict(self._vocab)
481
+
482
+ #### Core tokenization
483
+ def _tokenize(self, text: str) -> List[str]:
484
+ """
485
+ Input is a space-separated list of moves in extended UCI, e.g.
486
+ "WPe2e4 BPe7e5 ..."
487
+
488
+ Output is a sequence of structured tokens:
489
+ CP_WP SQ_e2 SQ_e4 EV_NONE [SEP] ...
490
+ """
491
+ moves = text.strip().split()
492
+ tokens: List[str] = []
493
+
494
+ for mv in moves:
495
+ toks = self._tokenize_one_move(mv)
496
+ tokens.extend(toks)
497
+ tokens.append(self.SEP_TOKEN)
498
+
499
+ return tokens
500
+
501
+ def _tokenize_one_move(self, mv: str) -> List[str]:
502
+ # Minimal sanity: needs at least "WPe2e4" length 6
503
+ if len(mv) < 6:
504
+ return [self.UNK_TOKEN]
505
+
506
+ color = mv[0] # W/B
507
+ piece = mv[1] # P/N/B/R/Q/K
508
+ from_sq = mv[2:4]
509
+ to_sq = mv[4:6]
510
+ suffix = mv[6:] # can include capture/check/mate/castle/promo etc. => cf events tokens
511
+
512
+ cp_tok = f"CP_{color}{piece}"
513
+ from_tok = f"SQ_{from_sq}"
514
+ to_tok = f"SQ_{to_sq}"
515
+
516
+ if cp_tok not in self._vocab or from_tok not in self._vocab or to_tok not in self._vocab:
517
+ return [self.UNK_TOKEN]
518
+
519
+ ev_tok = self._event_token(piece, from_sq, to_sq, suffix)
520
+
521
+ return [cp_tok, from_tok, to_tok, ev_tok]
522
+
523
+ def _event_token(self, piece: str, from_sq: str, to_sq: str, suffix: str) -> str:
524
+ """
525
+ Canonicalize suffix into one of EV_* tokens.
526
+ Keep it simple: evaluator does not need these, but they help learning.
527
+ """
528
+ # Castling (dataset uses (o)/(O))
529
+ if "(o)" in suffix: # kingside
530
+ return "EV_O"
531
+ if "(O)" in suffix: # queenside
532
+ return "EV_OO"
533
+
534
+ capture = "(x" in suffix # covers (x), (x+), (x+*), (x+) etc.
535
+ mate = "+*" in suffix
536
+ check = "(+)" in suffix or "(x+)" in suffix or "(+)" in suffix # tolerant
537
+
538
+ promo = None
539
+ m = re.search(r"=([NBRQ])", suffix)
540
+ if m:
541
+ promo = m.group(1)
542
+
543
+ if promo is not None:
544
+ base = f"EV_PROMO_{promo}"
545
+ if capture:
546
+ base = f"EV_XPROMO_{promo}"
547
+ return base if base in self._vocab else "EV_NONE"
548
+
549
+ if capture and mate:
550
+ return "EV_XMATE"
551
+ if capture and check:
552
+ return "EV_XPLUS"
553
+ if capture:
554
+ return "EV_X"
555
+ if mate:
556
+ return "EV_MATE"
557
+ if check:
558
+ return "EV_PLUS"
559
+ return "EV_NONE"
560
+
561
+ #### Conversions
562
+ def _convert_token_to_id(self, token: str) -> int:
563
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
564
+
565
+ def _convert_id_to_token(self, index: int) -> str:
566
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
567
+
568
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
569
+ """
570
+ Decode to a string that contains squares early and clearly.
571
+ We intentionally emit raw squares like "e2" "e4" separated by spaces,
572
+ so evaluate.py will reliably extract them.
573
+ """
574
+ out: List[str] = []
575
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
576
+
577
+ for tok in tokens:
578
+ if tok in special:
579
+ continue
580
+ if tok == self.SEP_TOKEN:
581
+ out.append(" ")
582
+ continue
583
+ if tok.startswith("SQ_"):
584
+ out.append(tok[3:]) # "SQ_e2" -> "e2"
585
+ out.append(" ")
586
+ continue
587
+ if tok.startswith("CP_"):
588
+ # Optional: keep CP to help model conditioning; does not hurt extraction
589
+ out.append(tok[3:]) # "CP_WP" -> "WP"
590
+ out.append(" ")
591
+ continue
592
+ if tok.startswith("EV_"):
593
+ # Optional: keep events; ensure no squares are embedded here
594
+ out.append(tok[3:]) # "EV_X" -> "X"
595
+ out.append(" ")
596
+ continue
597
+ # fallback
598
+ out.append(tok)
599
+ out.append(" ")
600
+
601
+ return "".join(out).strip()
602
+
603
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
604
+ if not os.path.isdir(save_directory):
605
+ os.makedirs(save_directory, exist_ok=True)
606
+
607
+ vocab_file = os.path.join(
608
+ save_directory,
609
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
610
+ )
611
+ with open(vocab_file, "w", encoding="utf-8") as f:
612
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
613
+ return (vocab_file,)
614
+
615
+
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.ChessTokenizer",
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": "ChessTokenizer",
49
+ "unk_token": "[UNK]"
50
+ }
vocab.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[SEP]": 4,
7
+ "CP_WP": 5,
8
+ "CP_WN": 6,
9
+ "CP_WB": 7,
10
+ "CP_WR": 8,
11
+ "CP_WQ": 9,
12
+ "CP_WK": 10,
13
+ "CP_BP": 11,
14
+ "CP_BN": 12,
15
+ "CP_BB": 13,
16
+ "CP_BR": 14,
17
+ "CP_BQ": 15,
18
+ "CP_BK": 16,
19
+ "SQ_a1": 17,
20
+ "SQ_a2": 18,
21
+ "SQ_a3": 19,
22
+ "SQ_a4": 20,
23
+ "SQ_a5": 21,
24
+ "SQ_a6": 22,
25
+ "SQ_a7": 23,
26
+ "SQ_a8": 24,
27
+ "SQ_b1": 25,
28
+ "SQ_b2": 26,
29
+ "SQ_b3": 27,
30
+ "SQ_b4": 28,
31
+ "SQ_b5": 29,
32
+ "SQ_b6": 30,
33
+ "SQ_b7": 31,
34
+ "SQ_b8": 32,
35
+ "SQ_c1": 33,
36
+ "SQ_c2": 34,
37
+ "SQ_c3": 35,
38
+ "SQ_c4": 36,
39
+ "SQ_c5": 37,
40
+ "SQ_c6": 38,
41
+ "SQ_c7": 39,
42
+ "SQ_c8": 40,
43
+ "SQ_d1": 41,
44
+ "SQ_d2": 42,
45
+ "SQ_d3": 43,
46
+ "SQ_d4": 44,
47
+ "SQ_d5": 45,
48
+ "SQ_d6": 46,
49
+ "SQ_d7": 47,
50
+ "SQ_d8": 48,
51
+ "SQ_e1": 49,
52
+ "SQ_e2": 50,
53
+ "SQ_e3": 51,
54
+ "SQ_e4": 52,
55
+ "SQ_e5": 53,
56
+ "SQ_e6": 54,
57
+ "SQ_e7": 55,
58
+ "SQ_e8": 56,
59
+ "SQ_f1": 57,
60
+ "SQ_f2": 58,
61
+ "SQ_f3": 59,
62
+ "SQ_f4": 60,
63
+ "SQ_f5": 61,
64
+ "SQ_f6": 62,
65
+ "SQ_f7": 63,
66
+ "SQ_f8": 64,
67
+ "SQ_g1": 65,
68
+ "SQ_g2": 66,
69
+ "SQ_g3": 67,
70
+ "SQ_g4": 68,
71
+ "SQ_g5": 69,
72
+ "SQ_g6": 70,
73
+ "SQ_g7": 71,
74
+ "SQ_g8": 72,
75
+ "SQ_h1": 73,
76
+ "SQ_h2": 74,
77
+ "SQ_h3": 75,
78
+ "SQ_h4": 76,
79
+ "SQ_h5": 77,
80
+ "SQ_h6": 78,
81
+ "SQ_h7": 79,
82
+ "SQ_h8": 80,
83
+ "EV_NONE": 81,
84
+ "EV_X": 82,
85
+ "EV_PLUS": 83,
86
+ "EV_MATE": 84,
87
+ "EV_XPLUS": 85,
88
+ "EV_XMATE": 86,
89
+ "EV_O": 87,
90
+ "EV_OO": 88,
91
+ "EV_PROMO_N": 89,
92
+ "EV_PROMO_B": 90,
93
+ "EV_PROMO_R": 91,
94
+ "EV_PROMO_Q": 92,
95
+ "EV_XPROMO_N": 93,
96
+ "EV_XPROMO_B": 94,
97
+ "EV_XPROMO_R": 95,
98
+ "EV_XPROMO_Q": 96
99
+ }