alexandreduplessis commited on
Commit
bf76425
·
verified ·
1 Parent(s): 5ddf10f

Chess Challenge submission by alexandreduplessis

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 +355 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +0 -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_minfreq
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [alexandreduplessis](https://huggingface.co/alexandreduplessis)
17
+ - **Parameters**: 4,274,560
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 27969
24
+ - **Embedding dim**: 128
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
+ "eos_token_id": 2,
8
+ "layer_norm_epsilon": 1e-05,
9
+ "model_type": "chess_transformer",
10
+ "n_ctx": 256,
11
+ "n_embd": 128,
12
+ "n_head": 4,
13
+ "n_inner": 384,
14
+ "n_layer": 4,
15
+ "pad_token_id": 0,
16
+ "tie_weights": true,
17
+ "torch_dtype": "float32",
18
+ "transformers_version": "4.55.0",
19
+ "vocab_size": 27969
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f30d3e938a7a78d51b4c284c3a5d834a8f38b971af119519e94afc6dc20de07
3
+ size 17102640
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,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import re
24
+
25
+
26
+
27
+ class ChessTokenizer(PreTrainedTokenizer):
28
+ """
29
+ A custom tokenizer for chess moves using extended UCI notation.
30
+
31
+ This tokenizer maps each possible chess move to a unique token ID.
32
+ The vocabulary is built from the training dataset to ensure all moves
33
+ encountered during training have a corresponding token.
34
+
35
+ Example:
36
+ >>> tokenizer = ChessTokenizer()
37
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
38
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
39
+ """
40
+
41
+ model_input_names = ["input_ids", "attention_mask"]
42
+ vocab_files_names = {"vocab_file": "vocab.json"}
43
+
44
+ # Special tokens
45
+ PAD_TOKEN = "[PAD]"
46
+ BOS_TOKEN = "[BOS]"
47
+ EOS_TOKEN = "[EOS]"
48
+ UNK_TOKEN = "[UNK]"
49
+
50
+ _MOVE_RE = re.compile(
51
+ r'^(?P<color>[WB])(?P<piece>[PNBRQK])(?P<from>[a-h][1-8])(?P<to>[a-h][1-8])(?P<rest>.*)$'
52
+ )
53
+
54
+ _SUFFIX_MAP = {
55
+ "(x)": "cap",
56
+ "(+)": "check",
57
+ "(+*)": "mate",
58
+ "(o)": "castle_k",
59
+ "(O)": "castle_q",
60
+ }
61
+
62
+ _PROMO_RE = re.compile(r'=?([QRBNqrbn])') # accepts "=Q" or "q" style
63
+
64
+
65
+ def __init__(
66
+ self,
67
+ vocab_file: Optional[str] = None,
68
+ vocab: Optional[Dict[str, int]] = None,
69
+ **kwargs,
70
+ ):
71
+ """
72
+ Initialize the chess tokenizer.
73
+
74
+ Args:
75
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
76
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
77
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
78
+ """
79
+ # Initialize special tokens
80
+ self._pad_token = self.PAD_TOKEN
81
+ self._bos_token = self.BOS_TOKEN
82
+ self._eos_token = self.EOS_TOKEN
83
+ self._unk_token = self.UNK_TOKEN
84
+
85
+ # Remove any duplicate special-token entries passed through kwargs
86
+ # to avoid "multiple values for keyword" errors when loading from disk.
87
+ kwargs.pop("pad_token", None)
88
+ kwargs.pop("bos_token", None)
89
+ kwargs.pop("eos_token", None)
90
+ kwargs.pop("unk_token", None)
91
+
92
+ # Load or create vocabulary
93
+ if vocab is not None:
94
+ self._vocab = vocab
95
+ elif vocab_file is not None and os.path.exists(vocab_file):
96
+ with open(vocab_file, "r", encoding="utf-8") as f:
97
+ self._vocab = json.load(f)
98
+ else:
99
+ # Create a minimal vocabulary with just special tokens
100
+ # The full vocabulary should be built from the dataset
101
+ self._vocab = self._create_default_vocab()
102
+
103
+ # Create reverse mapping
104
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
105
+
106
+ # Call parent init AFTER setting up vocab
107
+ super().__init__(
108
+ pad_token=self._pad_token,
109
+ bos_token=self._bos_token,
110
+ eos_token=self._eos_token,
111
+ unk_token=self._unk_token,
112
+ **kwargs,
113
+ )
114
+
115
+ def _decompose_move(self, tok: str) -> List[str]:
116
+ """
117
+ Convert e.g. 'WPe2e4(x)' -> ['WP', 'e2_f', 'e4_t', 'cap']
118
+ """
119
+ m = self._MOVE_RE.match(tok)
120
+ if not m:
121
+ return [self.UNK_TOKEN]
122
+
123
+ color = m.group("color")
124
+ piece = m.group("piece")
125
+ from_sq = m.group("from")
126
+ to_sq = m.group("to")
127
+ rest = m.group("rest") or ""
128
+
129
+ out = [f"{color}{piece}", f"{from_sq}_f", f"{to_sq}_t"]
130
+
131
+ for raw, mapped in self._SUFFIX_MAP.items():
132
+ if raw in rest:
133
+ out.append(mapped)
134
+
135
+ pm = self._PROMO_RE.search(rest)
136
+ if pm:
137
+ p = pm.group(1).lower()
138
+ if p in ("q", "r", "b", "n"):
139
+ out.append(f"promo_{p}")
140
+
141
+ return out
142
+ def _create_default_vocab(self) -> Dict[str, int]:
143
+ """
144
+ Create a minimal default vocabulary with just special tokens.
145
+
146
+ For the full vocabulary, use `build_vocab_from_dataset()`.
147
+ This minimal vocab is just a placeholder - you should build from data.
148
+ """
149
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
150
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
151
+ return vocab
152
+
153
+ @classmethod
154
+ def build_vocab_from_iterator(
155
+ cls,
156
+ iterator,
157
+ min_frequency: int = 1,
158
+ ) -> "ChessTokenizer":
159
+ """
160
+ Build a tokenizer vocabulary from an iterator of game strings.
161
+
162
+ Args:
163
+ iterator: An iterator yielding game strings (space-separated moves).
164
+ min_frequency: Minimum frequency for a token to be included.
165
+
166
+ Returns:
167
+ A ChessTokenizer with the built vocabulary.
168
+ """
169
+ from collections import Counter
170
+
171
+ token_counts = Counter()
172
+
173
+ for game in iterator:
174
+ moves = game.strip().split()
175
+ token_counts.update(moves)
176
+
177
+ # Filter by frequency
178
+ tokens = [
179
+ token for token, count in token_counts.items()
180
+ if count >= min_frequency
181
+ ]
182
+
183
+ # Sort for reproducibility
184
+ tokens = sorted(tokens)
185
+
186
+ # Build vocabulary
187
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
188
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
189
+
190
+ return cls(vocab=vocab)
191
+
192
+ @classmethod
193
+ def build_vocab_from_dataset(
194
+ cls,
195
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
196
+ split: str = "train",
197
+ column: str = "text",
198
+ min_frequency: int = 500,
199
+ max_samples: Optional[int] = 100000,
200
+ ) -> "ChessTokenizer":
201
+ """
202
+ Build a tokenizer vocabulary from a Hugging Face dataset.
203
+
204
+ Args:
205
+ dataset_name: Name of the dataset on Hugging Face Hub.
206
+ split: Dataset split to use.
207
+ column: Column containing the game strings.
208
+ min_frequency: Minimum frequency for a token to be included (default: 500).
209
+ max_samples: Maximum number of samples to process (default: 100k).
210
+
211
+ Returns:
212
+ A ChessTokenizer with the built vocabulary.
213
+ """
214
+ from datasets import load_dataset
215
+
216
+ dataset = load_dataset(dataset_name, split=split)
217
+
218
+ if max_samples is not None:
219
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
220
+
221
+ def game_iterator():
222
+ for example in dataset:
223
+ yield example[column]
224
+
225
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
226
+
227
+ @property
228
+ def vocab_size(self) -> int:
229
+ """Return the size of the vocabulary."""
230
+ return len(self._vocab)
231
+
232
+ def get_vocab(self) -> Dict[str, int]:
233
+ """Return the vocabulary as a dictionary."""
234
+ return dict(self._vocab)
235
+
236
+ def _tokenize(self, text: str) -> List[str]:
237
+ """
238
+ Tokenize a string of moves into a list of tokens.
239
+
240
+ Args:
241
+ text: A string of space-separated moves.
242
+
243
+ Returns:
244
+ List of move tokens.
245
+ """
246
+ return text.strip().split()
247
+ # def _tokenize(self, text: str) -> List[str]:
248
+ # parts = text.strip().split()
249
+ # out: List[str] = []
250
+ # special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
251
+
252
+ # for p in parts:
253
+ # if p in special:
254
+ # out.append(p)
255
+ # else:
256
+ # out.extend(self._decompose_move(p))
257
+ # return out
258
+
259
+
260
+ @classmethod
261
+ def build_structured_vocab(cls) -> "ChessTokenizer":
262
+ special = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
263
+
264
+ # 12 color+piece tokens
265
+ cp = [f"{c}{p}" for c in ("W", "B") for p in ("P", "N", "B", "R", "Q", "K")]
266
+
267
+ files = "abcdefgh"
268
+ ranks = "12345678"
269
+
270
+ from_tokens = [f"{f}{r}_f" for f in files for r in ranks] # 64
271
+ to_tokens = [f"{f}{r}_t" for f in files for r in ranks] # 64
272
+
273
+ suffix = ["cap", "check", "mate", "castle_k", "castle_q"]
274
+ promo = [f"promo_{p}" for p in ("q", "r", "b", "n")]
275
+
276
+ tokens = special + cp + from_tokens + to_tokens + suffix + promo
277
+ vocab = {t: i for i, t in enumerate(tokens)}
278
+ return cls(vocab=vocab)
279
+
280
+ def _convert_token_to_id(self, token: str) -> int:
281
+ """Convert a token to its ID."""
282
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
283
+
284
+ def _convert_id_to_token(self, index: int) -> str:
285
+ """Convert an ID to its token."""
286
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
287
+
288
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
289
+ """Convert a list of tokens back to a string."""
290
+ # Filter out special tokens for cleaner output
291
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
292
+ return " ".join(t for t in tokens if t not in special)
293
+
294
+ def save_vocabulary(
295
+ self,
296
+ save_directory: str,
297
+ filename_prefix: Optional[str] = None,
298
+ ) -> tuple:
299
+ """
300
+ Save the vocabulary to a JSON file.
301
+
302
+ Args:
303
+ save_directory: Directory to save the vocabulary.
304
+ filename_prefix: Optional prefix for the filename.
305
+
306
+ Returns:
307
+ Tuple containing the path to the saved vocabulary file.
308
+ """
309
+ if not os.path.isdir(save_directory):
310
+ os.makedirs(save_directory, exist_ok=True)
311
+
312
+ vocab_file = os.path.join(
313
+ save_directory,
314
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
315
+ )
316
+
317
+ with open(vocab_file, "w", encoding="utf-8") as f:
318
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
319
+
320
+ return (vocab_file,)
321
+
322
+
323
+ def count_vocab_from_dataset(
324
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
325
+ split: str = "train",
326
+ column: str = "text",
327
+ max_samples: Optional[int] = 10000,
328
+ ) -> Dict[str, int]:
329
+ """
330
+ Count token frequencies in a dataset (useful for vocabulary analysis).
331
+
332
+ Args:
333
+ dataset_name: Name of the dataset on Hugging Face Hub.
334
+ split: Dataset split to use.
335
+ column: Column containing the game strings.
336
+ max_samples: Maximum number of samples to process.
337
+
338
+ Returns:
339
+ Dictionary mapping tokens to their frequencies.
340
+ """
341
+ from collections import Counter
342
+ from datasets import load_dataset
343
+
344
+ dataset = load_dataset(dataset_name, split=split)
345
+
346
+ if max_samples is not None:
347
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
348
+
349
+ token_counts = Counter()
350
+
351
+ for example in dataset:
352
+ moves = example[column].strip().split()
353
+ token_counts.update(moves)
354
+
355
+ 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.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
The diff for this file is too large to render. See raw diff