agroudiev commited on
Commit
01a54ef
·
verified ·
1 Parent(s): f9f20eb

Chess Challenge submission by agroudiev

Browse files
Files changed (6) hide show
  1. README.md +3 -3
  2. config.json +3 -3
  3. model.safetensors +2 -2
  4. tokenizer.py +278 -0
  5. tokenizer_config.json +6 -0
  6. vocab.json +75 -80
README.md CHANGED
@@ -14,13 +14,13 @@ Chess model submitted to the LLM Course Chess Challenge.
14
  ## Submission Info
15
 
16
  - **Submitted by**: [agroudiev](https://huggingface.co/agroudiev)
17
- - **Parameters**: 999,896
18
  - **Organization**: LLM-course
19
 
20
  ## Model Details
21
 
22
  - **Architecture**: Chess Transformer (GPT-style)
23
- - **Vocab size**: 139
24
  - **Embedding dim**: 128
25
  - **Layers**: 6
26
- - **Heads**: 8
 
14
  ## Submission Info
15
 
16
  - **Submitted by**: [agroudiev](https://huggingface.co/agroudiev)
17
+ - **Parameters**: 990,004
18
  - **Organization**: LLM-course
19
 
20
  ## Model Details
21
 
22
  - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 134
24
  - **Embedding dim**: 128
25
  - **Layers**: 6
26
+ - **Heads**: 4
config.json CHANGED
@@ -10,11 +10,11 @@
10
  "model_type": "chess_transformer",
11
  "n_ctx": 256,
12
  "n_embd": 128,
13
- "n_head": 8,
14
- "n_inner": 356,
15
  "n_layer": 6,
16
  "pad_token_id": 0,
17
  "tie_weights": true,
18
  "transformers_version": "4.57.4",
19
- "vocab_size": 139
20
  }
 
10
  "model_type": "chess_transformer",
11
  "n_ctx": 256,
12
  "n_embd": 128,
13
+ "n_head": 4,
14
+ "n_inner": 350,
15
  "n_layer": 6,
16
  "pad_token_id": 0,
17
  "tie_weights": true,
18
  "transformers_version": "4.57.4",
19
+ "vocab_size": 134
20
  }
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b7c76abb2502ca91c2fb9acfb939e55e6015ef8e30bd347133665ab0838cf33e
3
- size 4006032
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24c1decf60ef24cda76b5d1e328823253e4d38bdc08dfae6ad569aed71570aa5
3
+ size 3966464
tokenizer.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ) -> "ChessTokenizer":
114
+ """
115
+ Build a tokenizer vocabulary from an iterator of game strings.
116
+
117
+ Args:
118
+ iterator: An iterator yielding game strings (space-separated moves).
119
+ min_frequency: Minimum frequency for a token to be included.
120
+
121
+ Returns:
122
+ A ChessTokenizer with the built vocabulary.
123
+ """
124
+ from collections import Counter
125
+
126
+ token_counts = Counter()
127
+
128
+ for game in iterator:
129
+ moves = game.strip().split()
130
+ token_counts.update(moves)
131
+
132
+ # Filter by frequency
133
+ tokens = [
134
+ token for token, count in token_counts.items()
135
+ if count >= min_frequency
136
+ ]
137
+
138
+ # Sort for reproducibility
139
+ tokens = sorted(tokens)
140
+
141
+ # Build vocabulary
142
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
143
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
144
+
145
+ return cls(vocab=vocab)
146
+
147
+ @classmethod
148
+ def build_vocab_from_dataset(
149
+ cls,
150
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
151
+ split: str = "train",
152
+ column: str = "text",
153
+ min_frequency: int = 500,
154
+ max_samples: Optional[int] = 100000,
155
+ ) -> "ChessTokenizer":
156
+ """
157
+ Build a tokenizer vocabulary from a Hugging Face dataset.
158
+
159
+ Args:
160
+ dataset_name: Name of the dataset on Hugging Face Hub.
161
+ split: Dataset split to use.
162
+ column: Column containing the game strings.
163
+ min_frequency: Minimum frequency for a token to be included (default: 500).
164
+ max_samples: Maximum number of samples to process (default: 100k).
165
+
166
+ Returns:
167
+ A ChessTokenizer with the built vocabulary.
168
+ """
169
+ from datasets import load_dataset
170
+
171
+ dataset = load_dataset(dataset_name, split=split)
172
+
173
+ if max_samples is not None:
174
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
175
+
176
+ def game_iterator():
177
+ for example in dataset:
178
+ yield example[column]
179
+
180
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
181
+
182
+ @property
183
+ def vocab_size(self) -> int:
184
+ """Return the size of the vocabulary."""
185
+ return len(self._vocab)
186
+
187
+ def get_vocab(self) -> Dict[str, int]:
188
+ """Return the vocabulary as a dictionary."""
189
+ return dict(self._vocab)
190
+
191
+ def _tokenize(self, text: str) -> List[str]:
192
+ """
193
+ Tokenize a string of moves into a list of tokens.
194
+
195
+ Args:
196
+ text: A string of space-separated moves.
197
+
198
+ Returns:
199
+ List of move tokens.
200
+ """
201
+ return text.strip().split()
202
+
203
+ def _convert_token_to_id(self, token: str) -> int:
204
+ """Convert a token to its ID."""
205
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
206
+
207
+ def _convert_id_to_token(self, index: int) -> str:
208
+ """Convert an ID to its token."""
209
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
210
+
211
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
212
+ """Convert a list of tokens back to a string."""
213
+ # Filter out special tokens for cleaner output
214
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
215
+ return " ".join(t for t in tokens if t not in special)
216
+
217
+ def save_vocabulary(
218
+ self,
219
+ save_directory: str,
220
+ filename_prefix: Optional[str] = None,
221
+ ) -> tuple:
222
+ """
223
+ Save the vocabulary to a JSON file.
224
+
225
+ Args:
226
+ save_directory: Directory to save the vocabulary.
227
+ filename_prefix: Optional prefix for the filename.
228
+
229
+ Returns:
230
+ Tuple containing the path to the saved vocabulary file.
231
+ """
232
+ if not os.path.isdir(save_directory):
233
+ os.makedirs(save_directory, exist_ok=True)
234
+
235
+ vocab_file = os.path.join(
236
+ save_directory,
237
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
238
+ )
239
+
240
+ with open(vocab_file, "w", encoding="utf-8") as f:
241
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
242
+
243
+ return (vocab_file,)
244
+
245
+
246
+ def count_vocab_from_dataset(
247
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
248
+ split: str = "train",
249
+ column: str = "text",
250
+ max_samples: Optional[int] = 10000,
251
+ ) -> Dict[str, int]:
252
+ """
253
+ Count token frequencies in a dataset (useful for vocabulary analysis).
254
+
255
+ Args:
256
+ dataset_name: Name of the dataset on Hugging Face Hub.
257
+ split: Dataset split to use.
258
+ column: Column containing the game strings.
259
+ max_samples: Maximum number of samples to process.
260
+
261
+ Returns:
262
+ Dictionary mapping tokens to their frequencies.
263
+ """
264
+ from collections import Counter
265
+ from datasets import load_dataset
266
+
267
+ dataset = load_dataset(dataset_name, split=split)
268
+
269
+ if max_samples is not None:
270
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
271
+
272
+ token_counts = Counter()
273
+
274
+ for example in dataset:
275
+ moves = example[column].strip().split()
276
+ token_counts.update(moves)
277
+
278
+ return dict(token_counts)
tokenizer_config.json CHANGED
@@ -33,6 +33,12 @@
33
  "special": true
34
  }
35
  },
 
 
 
 
 
 
36
  "bos_token": "[BOS]",
37
  "clean_up_tokenization_spaces": false,
38
  "eos_token": "[EOS]",
 
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]",
vocab.json CHANGED
@@ -58,84 +58,79 @@
58
  "BPg6g5": 56,
59
  "BPg7g5": 57,
60
  "BPg7g6": 58,
61
- "BPh5h4": 59,
62
- "BPh7h5": 60,
63
- "BPh7h6": 61,
64
- "BQd8b6": 62,
65
- "BQd8c7": 63,
66
- "BQd8d7": 64,
67
- "BQd8e7": 65,
68
- "BRa8b8": 66,
69
- "BRa8c8": 67,
70
- "BRa8d8": 68,
71
- "BRf8d8": 69,
72
- "BRf8e8": 70,
73
- "WBc1b2": 71,
74
- "WBc1d2": 72,
75
- "WBc1e3": 73,
76
- "WBc1f4": 74,
77
- "WBc1g5": 75,
78
- "WBf1b5": 76,
79
- "WBf1c4": 77,
80
- "WBf1d3": 78,
81
- "WBf1e2": 79,
82
- "WBf1g2": 80,
83
- "WBg5f6(x)": 81,
84
- "WKe1c1(O)": 82,
85
- "WKe1g1(o)": 83,
86
- "WKg1g2": 84,
87
- "WKg1h1": 85,
88
- "WKg1h2": 86,
89
- "WNb1c3": 87,
90
- "WNb1d2": 88,
91
- "WNc3d5": 89,
92
- "WNf3d4(x)": 90,
93
- "WNf3e5": 91,
94
- "WNf3e5(x)": 92,
95
- "WNf3g5": 93,
96
- "WNg1e2": 94,
97
- "WNg1f3": 95,
98
- "WPa2a3": 96,
99
- "WPa2a4": 97,
100
- "WPa4a5": 98,
101
- "WPb2b3": 99,
102
- "WPb2b4": 100,
103
- "WPb2c3(x)": 101,
104
- "WPb4b5": 102,
105
- "WPc2c3": 103,
106
- "WPc2c4": 104,
107
- "WPc3c4": 105,
108
- "WPc3d4(x)": 106,
109
- "WPc4c5": 107,
110
- "WPc4d5(x)": 108,
111
- "WPd2d3": 109,
112
- "WPd2d4": 110,
113
- "WPd3d4": 111,
114
- "WPd4d5": 112,
115
- "WPd4e5(x)": 113,
116
- "WPe2e3": 114,
117
- "WPe2e4": 115,
118
- "WPe3e4": 116,
119
- "WPe4d5(x)": 117,
120
- "WPe4e5": 118,
121
- "WPf2f3": 119,
122
- "WPf2f4": 120,
123
- "WPf4f5": 121,
124
- "WPg2g3": 122,
125
- "WPg2g4": 123,
126
- "WPg4g5": 124,
127
- "WPh2h3": 125,
128
- "WPh2h4": 126,
129
- "WPh3h4": 127,
130
- "WPh4h5": 128,
131
- "WQd1c2": 129,
132
- "WQd1d2": 130,
133
- "WQd1e2": 131,
134
- "WQd1f3": 132,
135
- "WRa1b1": 133,
136
- "WRa1c1": 134,
137
- "WRa1d1": 135,
138
- "WRa1e1": 136,
139
- "WRf1d1": 137,
140
- "WRf1e1": 138
141
  }
 
58
  "BPg6g5": 56,
59
  "BPg7g5": 57,
60
  "BPg7g6": 58,
61
+ "BPh7h5": 59,
62
+ "BPh7h6": 60,
63
+ "BQd8b6": 61,
64
+ "BQd8c7": 62,
65
+ "BQd8d7": 63,
66
+ "BQd8e7": 64,
67
+ "BRa8b8": 65,
68
+ "BRa8c8": 66,
69
+ "BRa8d8": 67,
70
+ "BRf8e8": 68,
71
+ "WBc1b2": 69,
72
+ "WBc1d2": 70,
73
+ "WBc1e3": 71,
74
+ "WBc1f4": 72,
75
+ "WBc1g5": 73,
76
+ "WBf1b5": 74,
77
+ "WBf1c4": 75,
78
+ "WBf1d3": 76,
79
+ "WBf1e2": 77,
80
+ "WBf1g2": 78,
81
+ "WKe1c1(O)": 79,
82
+ "WKe1g1(o)": 80,
83
+ "WKg1g2": 81,
84
+ "WKg1h1": 82,
85
+ "WKg1h2": 83,
86
+ "WNb1c3": 84,
87
+ "WNb1d2": 85,
88
+ "WNc3d5": 86,
89
+ "WNf3d4(x)": 87,
90
+ "WNf3e5": 88,
91
+ "WNf3e5(x)": 89,
92
+ "WNf3g5": 90,
93
+ "WNg1e2": 91,
94
+ "WNg1f3": 92,
95
+ "WPa2a3": 93,
96
+ "WPa2a4": 94,
97
+ "WPa4a5": 95,
98
+ "WPb2b3": 96,
99
+ "WPb2b4": 97,
100
+ "WPb2c3(x)": 98,
101
+ "WPb4b5": 99,
102
+ "WPc2c3": 100,
103
+ "WPc2c4": 101,
104
+ "WPc3c4": 102,
105
+ "WPc3d4(x)": 103,
106
+ "WPc4c5": 104,
107
+ "WPc4d5(x)": 105,
108
+ "WPd2d3": 106,
109
+ "WPd2d4": 107,
110
+ "WPd3d4": 108,
111
+ "WPd4d5": 109,
112
+ "WPd4e5(x)": 110,
113
+ "WPe2e3": 111,
114
+ "WPe2e4": 112,
115
+ "WPe3e4": 113,
116
+ "WPe4d5(x)": 114,
117
+ "WPe4e5": 115,
118
+ "WPf2f3": 116,
119
+ "WPf2f4": 117,
120
+ "WPf4f5": 118,
121
+ "WPg2g3": 119,
122
+ "WPg2g4": 120,
123
+ "WPg4g5": 121,
124
+ "WPh2h3": 122,
125
+ "WPh2h4": 123,
126
+ "WPh3h4": 124,
127
+ "WPh4h5": 125,
128
+ "WQd1c2": 126,
129
+ "WQd1d2": 127,
130
+ "WQd1e2": 128,
131
+ "WRa1b1": 129,
132
+ "WRa1c1": 130,
133
+ "WRa1d1": 131,
134
+ "WRa1e1": 132,
135
+ "WRf1e1": 133
 
 
 
 
 
136
  }