barthcharlirr commited on
Commit
103d01d
·
verified ·
1 Parent(s): 2900ad1

Chess Challenge submission by barthcharlirr

Browse files
Files changed (7) hide show
  1. README.md +20 -0
  2. config.json +20 -0
  3. model.safetensors +3 -0
  4. special_tokens_map.json +6 -0
  5. tokenizer.py +347 -0
  6. tokenizer_config.json +44 -0
  7. vocab.json +79 -0
README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+ # sacllmchess
10
+ Chess model submitted to the LLM Course Chess Challenge.
11
+ ## Submission Info
12
+ - **Submitted by**: [barthcharlirr](https://huggingface.co/barthcharlirr)
13
+ - **Parameters**: 704,384
14
+ - **Organization**: LLM-course
15
+ ## Model Details
16
+ - **Architecture**: Chess Transformer (GPT-style)
17
+ - **Vocab size**: 77
18
+ - **Embedding dim**: 128
19
+ - **Layers**: 4
20
+ - **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": 128,
13
+ "n_head": 4,
14
+ "n_inner": 384,
15
+ "n_layer": 4,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.6",
19
+ "vocab_size": 77
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaf299245939dab02a5c9c91272340276121d9f819e8bd51524074825774ab47
3
+ size 2821936
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,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Report removed tokens
133
+ report_removed_tokens(token_counts, min_frequency)
134
+
135
+ # Filter by frequency
136
+ tokens = [
137
+ token for token, count in token_counts.items()
138
+ if count >= min_frequency
139
+ ]
140
+
141
+ # Sort for reproducibility
142
+ tokens = sorted(tokens)
143
+
144
+ # Build vocabulary
145
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
146
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
147
+
148
+ return cls(vocab=vocab)
149
+
150
+ @classmethod
151
+ def build_vocab_from_dataset(
152
+ cls,
153
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
154
+ split: str = "train",
155
+ column: str = "text",
156
+ min_frequency: int = 500,
157
+ max_samples: Optional[int] = 100000,
158
+ ) -> "ChessTokenizer":
159
+ """
160
+ Build a tokenizer vocabulary from a Hugging Face dataset.
161
+
162
+ Args:
163
+ dataset_name: Name of the dataset on Hugging Face Hub.
164
+ split: Dataset split to use.
165
+ column: Column containing the game strings.
166
+ min_frequency: Minimum frequency for a token to be included (default: 500).
167
+ max_samples: Maximum number of samples to process (default: 100k).
168
+
169
+ Returns:
170
+ A ChessTokenizer with the built vocabulary.
171
+ """
172
+ from datasets import load_dataset
173
+
174
+ dataset = load_dataset(dataset_name, split=split)
175
+
176
+ if max_samples is not None:
177
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
178
+
179
+ def game_iterator():
180
+ for example in dataset:
181
+ yield example[column]
182
+
183
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
184
+
185
+ @property
186
+ def vocab_size(self) -> int:
187
+ """Return the size of the vocabulary."""
188
+ return len(self._vocab)
189
+
190
+ def get_vocab(self) -> Dict[str, int]:
191
+ """Return the vocabulary as a dictionary."""
192
+ return dict(self._vocab)
193
+
194
+ # def _tokenize(self, text: str) -> List[str]:
195
+ # """
196
+ # Tokenize a string of moves into a list of tokens.
197
+
198
+ # Args:
199
+ # text: A string of space-separated moves.
200
+
201
+ # Returns:
202
+ # List of move tokens.
203
+ # """
204
+ # return text.strip().split()
205
+
206
+ def _tokenize(self, text: str) -> List[str]:
207
+ tokens = []
208
+
209
+ for move in text.strip().split():
210
+ # strip color + piece (first 2 chars)
211
+ core = move[2:]
212
+
213
+ # squares
214
+ from_sq = core[0:2]
215
+ to_sq = core[2:4]
216
+ tokens.extend([from_sq, to_sq])
217
+
218
+ # modifiers
219
+ if "(" in core:
220
+ suffix = core[4:]
221
+ if "x" in suffix:
222
+ tokens.append("x")
223
+ if "+*" in suffix:
224
+ tokens.append("+*")
225
+ elif "+" in suffix:
226
+ tokens.append("+")
227
+ for promo in ["Q", "R", "B", "N"]:
228
+ if f"({promo})" in suffix:
229
+ tokens.append(promo)
230
+
231
+ # castling
232
+ if "O" in move or "o" in move:
233
+ tokens.append("O")
234
+
235
+ return tokens
236
+
237
+
238
+ def _convert_token_to_id(self, token: str) -> int:
239
+ """Convert a token to its ID."""
240
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
241
+
242
+ def _convert_id_to_token(self, index: int) -> str:
243
+ """Convert an ID to its token."""
244
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
245
+
246
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
247
+ """Convert a list of tokens back to a string."""
248
+ # Filter out special tokens for cleaner output
249
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
250
+ return " ".join(t for t in tokens if t not in special)
251
+
252
+ def save_vocabulary(
253
+ self,
254
+ save_directory: str,
255
+ filename_prefix: Optional[str] = None,
256
+ ) -> tuple:
257
+ """
258
+ Save the vocabulary to a JSON file.
259
+
260
+ Args:
261
+ save_directory: Directory to save the vocabulary.
262
+ filename_prefix: Optional prefix for the filename.
263
+
264
+ Returns:
265
+ Tuple containing the path to the saved vocabulary file.
266
+ """
267
+ if not os.path.isdir(save_directory):
268
+ os.makedirs(save_directory, exist_ok=True)
269
+
270
+ vocab_file = os.path.join(
271
+ save_directory,
272
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
273
+ )
274
+
275
+ with open(vocab_file, "w", encoding="utf-8") as f:
276
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
277
+
278
+ return (vocab_file,)
279
+ @classmethod
280
+ def build_square_pair_vocab(cls) -> "ChessTokenizer":
281
+ files = "abcdefgh"
282
+ ranks = "12345678"
283
+
284
+ squares = [f + r for f in files for r in ranks]
285
+ modifiers = ["x", "+", "+*", "Q", "R", "B", "N", "O", "o"]
286
+
287
+ special_tokens = [
288
+ cls.PAD_TOKEN,
289
+ cls.BOS_TOKEN,
290
+ cls.EOS_TOKEN,
291
+ cls.UNK_TOKEN,
292
+ ]
293
+
294
+ vocab_tokens = special_tokens + squares + modifiers
295
+ vocab = {tok: i for i, tok in enumerate(vocab_tokens)}
296
+
297
+ return cls(vocab=vocab)
298
+
299
+
300
+
301
+ def count_vocab_from_dataset(
302
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
303
+ split: str = "train",
304
+ column: str = "text",
305
+ max_samples: Optional[int] = 10000,
306
+ ) -> Dict[str, int]:
307
+ """
308
+ Count token frequencies in a dataset (useful for vocabulary analysis).
309
+
310
+ Args:
311
+ dataset_name: Name of the dataset on Hugging Face Hub.
312
+ split: Dataset split to use.
313
+ column: Column containing the game strings.
314
+ max_samples: Maximum number of samples to process.
315
+
316
+ Returns:
317
+ Dictionary mapping tokens to their frequencies.
318
+ """
319
+ from collections import Counter
320
+ from datasets import load_dataset
321
+
322
+ dataset = load_dataset(dataset_name, split=split)
323
+
324
+ if max_samples is not None:
325
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
326
+
327
+ token_counts = Counter()
328
+
329
+ for example in dataset:
330
+ moves = example[column].strip().split()
331
+ token_counts.update(moves)
332
+
333
+ return dict(token_counts)
334
+
335
+
336
+ def report_removed_tokens(token_counts, min_frequency: int) -> None:
337
+ """
338
+ Print how many tokens were removed by the min_frequency filter.
339
+ """
340
+ total_unique = len(token_counts)
341
+ kept = sum(1 for c in token_counts.values() if c >= min_frequency)
342
+ removed = total_unique - kept
343
+
344
+ print(
345
+ f"[Tokenizer] Vocab filtering: "
346
+ f"kept={kept}, removed={removed}, min_frequency={min_frequency}"
347
+ )
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": "ChessTokenizer",
43
+ "unk_token": "[UNK]"
44
+ }
vocab.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "x": 68,
71
+ "+": 69,
72
+ "+*": 70,
73
+ "Q": 71,
74
+ "R": 72,
75
+ "B": 73,
76
+ "N": 74,
77
+ "O": 75,
78
+ "o": 76
79
+ }