OussamaleZ commited on
Commit
0d80a62
·
verified ·
1 Parent(s): 282817d

Chess Challenge submission by OussamaleZ

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