KshitijAmbilduke commited on
Commit
bf6cd10
·
verified ·
1 Parent(s): 6731f8c

Chess Challenge submission by KshitijAmbilduke

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