Massine10 commited on
Commit
97cabb5
·
verified ·
1 Parent(s): bb6ea00

Chess Challenge submission by Massine10

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