iliasslasri commited on
Commit
273c42d
·
verified ·
1 Parent(s): cc2be2c

Chess Challenge submission by iliasslasri

Browse files
Files changed (7) hide show
  1. README.md +26 -0
  2. config.json +22 -0
  3. model.safetensors +3 -0
  4. special_tokens_map.json +6 -0
  5. tokenizer.py +300 -0
  6. tokenizer_config.json +49 -0
  7. vocab.json +77 -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-player
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [iliasslasri](https://huggingface.co/iliasslasri)
17
+ - **Parameters**: 980,720
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 75
24
+ - **Embedding dim**: 92
25
+ - **Layers**: 11
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./11_4_92/checkpoint-100197/",
3
+ "architectures": [
4
+ "ChessForCausalLM"
5
+ ],
6
+ "bos_token_id": 1,
7
+ "dropout": 0.1,
8
+ "eos_token_id": 2,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "model_type": "chess_transformer",
11
+ "n_ctx": 256,
12
+ "n_embd": 92,
13
+ "n_head": 4,
14
+ "n_inner": 276,
15
+ "n_layer": 11,
16
+ "pad_token_id": 0,
17
+ "tie_weights": false,
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "transformers_version": "4.40.0",
21
+ "vocab_size": 75
22
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b949bf10b181977fa25e45d6d1a03712c6b4651e5cb0c6f6a591166cfb17de4f
3
+ size 3934384
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,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ processed_tokens = []
128
+ for game in iterator:
129
+ moves = game.strip().split()
130
+ for move in moves:
131
+ if '(' in move:
132
+ split_index = move.find('(')
133
+ # Split into Base Move "BQb8c7" and Effect "(x+)"
134
+ base_move = move[:split_index]
135
+
136
+ processed_tokens.extend([base_move[:1], base_move[1:2], base_move[2:4], base_move[4:]])
137
+ else:
138
+ # If no effect, keep the move as is
139
+ processed_tokens.extend([move[0:1], move[1:2], move[2:4], move[4:]])
140
+ token_counts.update(processed_tokens)
141
+
142
+ # Filter by frequency
143
+ tokens = [
144
+ token for token, count in token_counts.items()
145
+ if count >= min_frequency
146
+ ]
147
+
148
+ # Sort for reproducibility
149
+ tokens = sorted(tokens)
150
+
151
+ # Build vocabulary
152
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
153
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
154
+
155
+ return cls(vocab=vocab)
156
+
157
+ @classmethod
158
+ def build_vocab_from_dataset(
159
+ cls,
160
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
161
+ split: str = "train",
162
+ column: str = "text",
163
+ min_frequency: int = 500,
164
+ max_samples: Optional[int] = 100000,
165
+ ) -> "ChessTokenizer":
166
+ """
167
+ Build a tokenizer vocabulary from a Hugging Face dataset.
168
+
169
+ Args:
170
+ dataset_name: Name of the dataset on Hugging Face Hub.
171
+ split: Dataset split to use.
172
+ column: Column containing the game strings.
173
+ min_frequency: Minimum frequency for a token to be included (default: 500).
174
+ max_samples: Maximum number of samples to process (default: 100k).
175
+
176
+ Returns:
177
+ A ChessTokenizer with the built vocabulary.
178
+ """
179
+ from datasets import load_dataset
180
+
181
+ dataset = load_dataset(dataset_name, split=split)
182
+
183
+ if max_samples is not None:
184
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
185
+
186
+ def game_iterator():
187
+ for example in dataset:
188
+ yield example[column]
189
+
190
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
191
+
192
+ @property
193
+ def vocab_size(self) -> int:
194
+ """Return the size of the vocabulary."""
195
+ return len(self._vocab)
196
+
197
+ def get_vocab(self) -> Dict[str, int]:
198
+ """Return the vocabulary as a dictionary."""
199
+ return dict(self._vocab)
200
+
201
+ def _tokenize(self, text: str) -> List[str]:
202
+ """
203
+ Tokenize a string of moves into a list of tokens.
204
+
205
+ Args:
206
+ text: A string of space-separated moves.
207
+
208
+ Returns:
209
+ List of move tokens.
210
+ """
211
+ moves = text.strip().split()
212
+ tokens = []
213
+ for move in moves:
214
+ if '(' in move:
215
+ split_index = move.find('(')
216
+ # Split into Base Move "BQb8c7" and Effect "(x+)"
217
+ base_move = move[:split_index]
218
+
219
+ tokens.extend([base_move[:1], base_move[1:2], base_move[2:4], base_move[4:]])
220
+ else:
221
+ # If no effect, keep the move as is
222
+ tokens.extend([move[:1], move[1:2], move[2:4], move[4:]])
223
+ return tokens
224
+
225
+ def _convert_token_to_id(self, token: str) -> int:
226
+ """Convert a token to its ID."""
227
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
228
+
229
+ def _convert_id_to_token(self, index: int) -> str:
230
+ """Convert an ID to its token."""
231
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
232
+
233
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
234
+ """Convert a list of tokens back to a string."""
235
+ # Filter out special tokens for cleaner output
236
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
237
+ return " ".join(t for t in tokens if t not in special)
238
+
239
+ def save_vocabulary(
240
+ self,
241
+ save_directory: str,
242
+ filename_prefix: Optional[str] = None,
243
+ ) -> tuple:
244
+ """
245
+ Save the vocabulary to a JSON file.
246
+
247
+ Args:
248
+ save_directory: Directory to save the vocabulary.
249
+ filename_prefix: Optional prefix for the filename.
250
+
251
+ Returns:
252
+ Tuple containing the path to the saved vocabulary file.
253
+ """
254
+ if not os.path.isdir(save_directory):
255
+ os.makedirs(save_directory, exist_ok=True)
256
+
257
+ vocab_file = os.path.join(
258
+ save_directory,
259
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
260
+ )
261
+
262
+ with open(vocab_file, "w", encoding="utf-8") as f:
263
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
264
+
265
+ return (vocab_file,)
266
+
267
+
268
+ def count_vocab_from_dataset(
269
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
270
+ split: str = "train",
271
+ column: str = "text",
272
+ max_samples: Optional[int] = 10000,
273
+ ) -> Dict[str, int]:
274
+ """
275
+ Count token frequencies in a dataset (useful for vocabulary analysis).
276
+
277
+ Args:
278
+ dataset_name: Name of the dataset on Hugging Face Hub.
279
+ split: Dataset split to use.
280
+ column: Column containing the game strings.
281
+ max_samples: Maximum number of samples to process.
282
+
283
+ Returns:
284
+ Dictionary mapping tokens to their frequencies.
285
+ """
286
+ from collections import Counter
287
+ from datasets import load_dataset
288
+
289
+ dataset = load_dataset(dataset_name, split=split)
290
+
291
+ if max_samples is not None:
292
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
293
+
294
+ token_counts = Counter()
295
+
296
+ for example in dataset:
297
+ moves = example[column].strip().split()
298
+ token_counts.update(moves)
299
+
300
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": true,
44
+ "eos_token": "[EOS]",
45
+ "model_max_length": 1000000000000000019884624838656,
46
+ "pad_token": "[PAD]",
47
+ "tokenizer_class": "ChessTokenizer",
48
+ "unk_token": "[UNK]"
49
+ }
vocab.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "B": 4,
7
+ "K": 5,
8
+ "N": 6,
9
+ "P": 7,
10
+ "Q": 8,
11
+ "R": 9,
12
+ "W": 10,
13
+ "a1": 11,
14
+ "a2": 12,
15
+ "a3": 13,
16
+ "a4": 14,
17
+ "a5": 15,
18
+ "a6": 16,
19
+ "a7": 17,
20
+ "a8": 18,
21
+ "b1": 19,
22
+ "b2": 20,
23
+ "b3": 21,
24
+ "b4": 22,
25
+ "b5": 23,
26
+ "b6": 24,
27
+ "b7": 25,
28
+ "b8": 26,
29
+ "c1": 27,
30
+ "c2": 28,
31
+ "c3": 29,
32
+ "c4": 30,
33
+ "c5": 31,
34
+ "c6": 32,
35
+ "c7": 33,
36
+ "c8": 34,
37
+ "d1": 35,
38
+ "d2": 36,
39
+ "d3": 37,
40
+ "d4": 38,
41
+ "d5": 39,
42
+ "d6": 40,
43
+ "d7": 41,
44
+ "d8": 42,
45
+ "e1": 43,
46
+ "e2": 44,
47
+ "e3": 45,
48
+ "e4": 46,
49
+ "e5": 47,
50
+ "e6": 48,
51
+ "e7": 49,
52
+ "e8": 50,
53
+ "f1": 51,
54
+ "f2": 52,
55
+ "f3": 53,
56
+ "f4": 54,
57
+ "f5": 55,
58
+ "f6": 56,
59
+ "f7": 57,
60
+ "f8": 58,
61
+ "g1": 59,
62
+ "g2": 60,
63
+ "g3": 61,
64
+ "g4": 62,
65
+ "g5": 63,
66
+ "g6": 64,
67
+ "g7": 65,
68
+ "g8": 66,
69
+ "h1": 67,
70
+ "h2": 68,
71
+ "h3": 69,
72
+ "h4": 70,
73
+ "h5": 71,
74
+ "h6": 72,
75
+ "h7": 73,
76
+ "h8": 74
77
+ }