younadi commited on
Commit
15c5748
·
verified ·
1 Parent(s): 1607eac

Chess Challenge submission by younadi

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