Valbad commited on
Commit
ba438e3
·
verified ·
1 Parent(s): b8165ad

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 +370 -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-baseline-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**: 930,600
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 5000
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": 5000
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7ff1be405662ed91f0c3feba04fa9ca40ce87f870891a8a787e838f9a25e420
3
+ size 3726776
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,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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