KshitijAmbilduke commited on
Commit
2f9b818
·
verified ·
1 Parent(s): 824b838

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 +305 -0
  6. tokenizer_config.json +44 -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
+ # tactibear-v1
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,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
107
+ players = ['W', 'B']
108
+ pieces = ['P', 'N', 'B', 'R', 'Q', 'K']
109
+ hor_pos = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
110
+ ver_pos = ['1', '2', '3', '4', '5', '6', '7', '8']
111
+ suffixes = ['(x)', '(+)', '(+*)', '(o)', '(O)']
112
+ move_id = len(special_tokens)
113
+
114
+ for p in players:
115
+ vocab[p] = move_id
116
+ move_id += 1
117
+
118
+ for piece in pieces:
119
+ vocab[piece] = move_id
120
+ move_id += 1
121
+
122
+ for h1 in hor_pos:
123
+ for v1 in ver_pos:
124
+ vocab[h1 + v1] = move_id
125
+ move_id += 1
126
+
127
+ for s in suffixes:
128
+ vocab[s] = move_id
129
+ move_id += 1
130
+
131
+ vocab[" "] = move_id
132
+
133
+ return vocab
134
+
135
+ @classmethod
136
+ def build_vocab_from_iterator(
137
+ cls,
138
+ iterator,
139
+ min_frequency: int = 1,
140
+ ) -> "ChessTokenizer":
141
+ """
142
+ Build a tokenizer vocabulary from an iterator of game strings.
143
+
144
+ Args:
145
+ iterator: An iterator yielding game strings (space-separated moves).
146
+ min_frequency: Minimum frequency for a token to be included.
147
+
148
+ Returns:
149
+ A ChessTokenizer with the built vocabulary.
150
+ """
151
+ from collections import Counter
152
+
153
+ token_counts = Counter()
154
+
155
+ for game in iterator:
156
+ moves = game.strip().split()
157
+ token_counts.update(moves)
158
+
159
+ # Filter by frequency
160
+ tokens = [
161
+ token for token, count in token_counts.items()
162
+ if count >= min_frequency
163
+ ]
164
+
165
+ # Sort for reproducibility
166
+ tokens = sorted(tokens)
167
+
168
+ # Build vocabulary
169
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
170
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
171
+
172
+ return cls(vocab=vocab)
173
+
174
+ @classmethod
175
+ def build_vocab_from_dataset(
176
+ cls,
177
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
178
+ split: str = "train",
179
+ column: str = "text",
180
+ min_frequency: int = 500,
181
+ max_samples: Optional[int] = 100000,
182
+ ) -> "ChessTokenizer":
183
+ """
184
+ Build a tokenizer vocabulary from a Hugging Face dataset.
185
+
186
+ Args:
187
+ dataset_name: Name of the dataset on Hugging Face Hub.
188
+ split: Dataset split to use.
189
+ column: Column containing the game strings.
190
+ min_frequency: Minimum frequency for a token to be included (default: 500).
191
+ max_samples: Maximum number of samples to process (default: 100k).
192
+
193
+ Returns:
194
+ A ChessTokenizer with the built vocabulary.
195
+ """
196
+ from datasets import load_dataset
197
+
198
+ dataset = load_dataset(dataset_name, split=split)
199
+
200
+ if max_samples is not None:
201
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
202
+
203
+ def game_iterator():
204
+ for example in dataset:
205
+ yield example[column]
206
+
207
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
208
+
209
+ @property
210
+ def vocab_size(self) -> int:
211
+ """Return the size of the vocabulary."""
212
+ return len(self._vocab)
213
+
214
+ def get_vocab(self) -> Dict[str, int]:
215
+ """Return the vocabulary as a dictionary."""
216
+ return dict(self._vocab)
217
+
218
+ def _tokenize(self, text: str) -> List[str]:
219
+ """
220
+ Tokenize a string of moves into a list of tokens.
221
+
222
+ Args:
223
+ text: A string of space-separated moves.
224
+
225
+ Returns:
226
+ List of move tokens.
227
+ """
228
+ return text.strip().split()
229
+
230
+ def _convert_token_to_id(self, token: str) -> int:
231
+ """Convert a token to its ID."""
232
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
233
+
234
+ def _convert_id_to_token(self, index: int) -> str:
235
+ """Convert an ID to its token."""
236
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
237
+
238
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
239
+ """Convert a list of tokens back to a string."""
240
+ # Filter out special tokens for cleaner output
241
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
242
+ return " ".join(t for t in tokens if t not in special)
243
+
244
+ def save_vocabulary(
245
+ self,
246
+ save_directory: str,
247
+ filename_prefix: Optional[str] = None,
248
+ ) -> tuple:
249
+ """
250
+ Save the vocabulary to a JSON file.
251
+
252
+ Args:
253
+ save_directory: Directory to save the vocabulary.
254
+ filename_prefix: Optional prefix for the filename.
255
+
256
+ Returns:
257
+ Tuple containing the path to the saved vocabulary file.
258
+ """
259
+ if not os.path.isdir(save_directory):
260
+ os.makedirs(save_directory, exist_ok=True)
261
+
262
+ vocab_file = os.path.join(
263
+ save_directory,
264
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
265
+ )
266
+
267
+ with open(vocab_file, "w", encoding="utf-8") as f:
268
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
269
+
270
+ return (vocab_file,)
271
+
272
+
273
+ def count_vocab_from_dataset(
274
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
275
+ split: str = "train",
276
+ column: str = "text",
277
+ max_samples: Optional[int] = 10000,
278
+ ) -> Dict[str, int]:
279
+ """
280
+ Count token frequencies in a dataset (useful for vocabulary analysis).
281
+
282
+ Args:
283
+ dataset_name: Name of the dataset on Hugging Face Hub.
284
+ split: Dataset split to use.
285
+ column: Column containing the game strings.
286
+ max_samples: Maximum number of samples to process.
287
+
288
+ Returns:
289
+ Dictionary mapping tokens to their frequencies.
290
+ """
291
+ from collections import Counter
292
+ from datasets import load_dataset
293
+
294
+ dataset = load_dataset(dataset_name, split=split)
295
+
296
+ if max_samples is not None:
297
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
298
+
299
+ token_counts = Counter()
300
+
301
+ for example in dataset:
302
+ moves = example[column].strip().split()
303
+ token_counts.update(moves)
304
+
305
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bos_token": "[BOS]",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "[EOS]",
39
+ "extra_special_tokens": {},
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": "[PAD]",
42
+ "tokenizer_class": "ChessTokenizer",
43
+ "unk_token": "[UNK]"
44
+ }
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
+ }