Yiwei6534 commited on
Commit
fdceccb
·
verified ·
1 Parent(s): b547437

Chess Challenge submission by Yiwei6534

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 +130 -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_boring
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Yiwei6534](https://huggingface.co/Yiwei6534)
17
+ - **Parameters**: 876,288
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 128
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": 256,
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": 128
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:893082ae900bdf0d7e2e54259b6d4b85d75294afc2208ce31d4b0f313f1859d8
3
+ size 3510576
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
+ # 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
+ return vocab
107
+
108
+ @classmethod
109
+ def build_vocab_from_iterator(
110
+ cls,
111
+ iterator,
112
+ min_frequency: int = 1,
113
+ max_vocab_size: Optional[int] = None,
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
+ max_vocab_size: Maximum vocabulary size (including special tokens).
122
+ If None, no limit is applied.
123
+
124
+ Returns:
125
+ A ChessTokenizer with the built vocabulary.
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
+ # Filter by frequency and sort by count (descending)
136
+ tokens = [
137
+ (token, count) for token, count in token_counts.items()
138
+ if count >= min_frequency
139
+ ]
140
+ tokens = sorted(tokens, key=lambda x: (-x[1], x[0])) # Sort by frequency desc, then alphabetically
141
+
142
+ # Limit vocabulary size if specified
143
+ if max_vocab_size is not None:
144
+ # Reserve space for special tokens
145
+ max_regular_tokens = max_vocab_size - 4 # 4 special tokens
146
+ tokens = tokens[:max_regular_tokens]
147
+
148
+ # Extract just the token strings (sorted by frequency for determinism)
149
+ token_list = [token for token, _ in tokens]
150
+
151
+ # Build vocabulary
152
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
153
+ vocab = {token: idx for idx, token in enumerate(special_tokens + token_list)}
154
+
155
+ return cls(vocab=vocab)
156
+
157
+ @classmethod
158
+ def build_vocab_from_dataset(
159
+ cls,
160
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
161
+ split: str = "train",
162
+ column: str = "text",
163
+ min_frequency: int = 500,
164
+ max_samples: Optional[int] = 100000,
165
+ max_vocab_size: Optional[int] = None,
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
+ max_vocab_size: Maximum vocabulary size (including special tokens).
177
+
178
+ Returns:
179
+ A ChessTokenizer with the built vocabulary.
180
+ """
181
+ from datasets import load_dataset
182
+
183
+ dataset = load_dataset(dataset_name, split=split)
184
+
185
+ if max_samples is not None:
186
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
187
+
188
+ def game_iterator():
189
+ for example in dataset:
190
+ yield example[column]
191
+
192
+ return cls.build_vocab_from_iterator(
193
+ game_iterator(),
194
+ min_frequency=min_frequency,
195
+ max_vocab_size=max_vocab_size,
196
+ )
197
+
198
+ @property
199
+ def vocab_size(self) -> int:
200
+ """Return the size of the vocabulary."""
201
+ return len(self._vocab)
202
+
203
+ def get_vocab(self) -> Dict[str, int]:
204
+ """Return the vocabulary as a dictionary."""
205
+ return dict(self._vocab)
206
+
207
+ def _tokenize(self, text: str) -> List[str]:
208
+ """
209
+ Tokenize a string of moves into a list of tokens.
210
+
211
+ Args:
212
+ text: A string of space-separated moves.
213
+
214
+ Returns:
215
+ List of move tokens.
216
+ """
217
+ return text.strip().split()
218
+
219
+ def _convert_token_to_id(self, token: str) -> int:
220
+ """Convert a token to its ID."""
221
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
222
+
223
+ def _convert_id_to_token(self, index: int) -> str:
224
+ """Convert an ID to its token."""
225
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
226
+
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,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "WNg1f3": 4,
7
+ "BNg8f6": 5,
8
+ "WPe2e4": 6,
9
+ "WPd2d4": 7,
10
+ "WKe1g1(o)": 8,
11
+ "WNb1c3": 9,
12
+ "BNb8c6": 10,
13
+ "BKe8g8(o)": 11,
14
+ "BPd7d5": 12,
15
+ "BPe7e6": 13,
16
+ "BPe7e5": 14,
17
+ "BPd7d6": 15,
18
+ "WPc2c3": 16,
19
+ "WPh2h3": 17,
20
+ "BPg7g6": 18,
21
+ "BPc7c6": 19,
22
+ "BPh7h6": 20,
23
+ "BPc7c5": 21,
24
+ "BPa7a6": 22,
25
+ "WPc2c4": 23,
26
+ "WPa2a3": 24,
27
+ "BBf8e7": 25,
28
+ "WPg2g3": 26,
29
+ "WPe2e3": 27,
30
+ "WPf2f4": 28,
31
+ "WPd2d3": 29,
32
+ "BNb8d7": 30,
33
+ "BPb7b6": 31,
34
+ "WRf1e1": 32,
35
+ "WPe4e5": 33,
36
+ "WNb1d2": 34,
37
+ "BPf7f6": 35,
38
+ "WPb2b3": 36,
39
+ "WBf1d3": 37,
40
+ "WBf1c4": 38,
41
+ "BPb7b5": 39,
42
+ "WPf2f3": 40,
43
+ "WBc1e3": 41,
44
+ "WBc1g5": 42,
45
+ "WPe4d5(x)": 43,
46
+ "BBf8g7": 44,
47
+ "BBc8g4": 45,
48
+ "BRf8e8": 46,
49
+ "BPf7f5": 47,
50
+ "WBf1e2": 48,
51
+ "WPb2b4": 49,
52
+ "BPc5d4(x)": 50,
53
+ "BBc8b7": 51,
54
+ "WPg2g4": 52,
55
+ "WPa2a4": 53,
56
+ "WPh2h4": 54,
57
+ "BPa7a5": 55,
58
+ "BBc8d7": 56,
59
+ "WNf3e5": 57,
60
+ "WBc1f4": 58,
61
+ "WPd4d5": 59,
62
+ "BBf8d6": 60,
63
+ "WPd4e5(x)": 61,
64
+ "BPh7h5": 62,
65
+ "BRa8c8": 63,
66
+ "BNg8e7": 64,
67
+ "BBc8e6": 65,
68
+ "BPe6e5": 66,
69
+ "BPe5d4(x)": 67,
70
+ "WRa1d1": 68,
71
+ "BPd5e4(x)": 69,
72
+ "WNf3d4(x)": 70,
73
+ "WKg1h1": 71,
74
+ "WRa1c1": 72,
75
+ "BPc6c5": 73,
76
+ "WKe1c1(O)": 74,
77
+ "BBf8c5": 75,
78
+ "BPg7g5": 76,
79
+ "BRa8d8": 77,
80
+ "WQd1e2": 78,
81
+ "BNf6e4": 79,
82
+ "WBf1g2": 80,
83
+ "BBc8f5": 81,
84
+ "WBc1d2": 82,
85
+ "BKg8h8": 83,
86
+ "WNf3e5(x)": 84,
87
+ "WPc4d5(x)": 85,
88
+ "WBc1b2": 86,
89
+ "BKe8c8(O)": 87,
90
+ "BPe5e4": 88,
91
+ "WPh4h5": 89,
92
+ "BPe6d5(x)": 90,
93
+ "WQd1d2": 91,
94
+ "BPd6d5": 92,
95
+ "BQd8e7": 93,
96
+ "BRa8b8": 94,
97
+ "BPd5d4": 95,
98
+ "WNf3g5": 96,
99
+ "WPc3c4": 97,
100
+ "BNf6e4(x)": 98,
101
+ "BPb5b4": 99,
102
+ "BQd8c7": 100,
103
+ "WRa1b1": 101,
104
+ "BPd6e5(x)": 102,
105
+ "BPb7c6(x)": 103,
106
+ "BPc6d5(x)": 104,
107
+ "WNc3d5": 105,
108
+ "WPc3d4(x)": 106,
109
+ "WPb2c3(x)": 107,
110
+ "WPe3e4": 108,
111
+ "BPa5a4": 109,
112
+ "WPf4f5": 110,
113
+ "WPg4g5": 111,
114
+ "WPh3h4": 112,
115
+ "WNg1e2": 113,
116
+ "BNc6d4": 114,
117
+ "WPd3d4": 115,
118
+ "BKg8g7": 116,
119
+ "WBf1b5": 117,
120
+ "WKg1h2": 118,
121
+ "BBg4f3(x)": 119,
122
+ "BBf8b4": 120,
123
+ "BPc5c4": 121,
124
+ "BNf6d5": 122,
125
+ "BNf6d5(x)": 123,
126
+ "WKg1g2": 124,
127
+ "BPa6a5": 125,
128
+ "WPa4a5": 126,
129
+ "BQd8d7": 127
130
+ }