pultch commited on
Commit
ecacb41
·
verified ·
1 Parent(s): afd420e

Chess Challenge submission by pultch

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