AMoresc commited on
Commit
657fa75
·
verified ·
1 Parent(s): e998520

Chess Challenge submission by AMoresc

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 +359 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +89 -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_cheating_model
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [AMoresc](https://huggingface.co/AMoresc)
17
+ - **Parameters**: 999,408
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 87
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 6
26
+ - **Heads**: 4
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": 4,
14
+ "n_inner": 360,
15
+ "n_layer": 6,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.3",
19
+ "vocab_size": 87
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e378a53694f51e9aa2033f11163dc724b12dec267f79ff788834c7d5cd301b10
3
+ size 4004080
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,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import re
19
+ from pathlib import Path
20
+ from typing import Dict, List, Optional
21
+
22
+ from transformers import PreTrainedTokenizer
23
+
24
+
25
+ class ChessTokenizer(PreTrainedTokenizer):
26
+ """
27
+ A custom tokenizer for chess moves using extended UCI notation.
28
+
29
+ This tokenizer maps each possible chess move to a unique token ID.
30
+ The vocabulary is built from the training dataset to ensure all moves
31
+ encountered during training have a corresponding token.
32
+
33
+ Example:
34
+ >>> tokenizer = ChessTokenizer()
35
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
36
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
37
+ """
38
+
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+ vocab_files_names = {"vocab_file": "vocab.json"}
41
+
42
+ # Special tokens
43
+ PAD_TOKEN = "[PAD]"
44
+ BOS_TOKEN = "[BOS]"
45
+ EOS_TOKEN = "[EOS]"
46
+ UNK_TOKEN = "[UNK]"
47
+ EOM_TOKEN = "[EOM]" # End of Move
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_file: Optional[str] = None,
52
+ vocab: Optional[Dict[str, int]] = None,
53
+ **kwargs,
54
+ ):
55
+ """
56
+ Initialize the chess tokenizer.
57
+
58
+ Args:
59
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
60
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
61
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
62
+ """
63
+ # Initialize special tokens
64
+ self._pad_token = self.PAD_TOKEN
65
+ self._bos_token = self.BOS_TOKEN
66
+ self._eos_token = self.EOS_TOKEN
67
+ self._unk_token = self.UNK_TOKEN
68
+ self._eom_token = self.EOM_TOKEN
69
+
70
+ # Remove any duplicate special-token entries passed through kwargs
71
+ # to avoid "multiple values for keyword" errors when loading from disk.
72
+ kwargs.pop("pad_token", None)
73
+ kwargs.pop("bos_token", None)
74
+ kwargs.pop("eos_token", None)
75
+ kwargs.pop("unk_token", None)
76
+ kwargs.pop("eom_token", None)
77
+
78
+ # Load or create vocabulary
79
+ if vocab is not None:
80
+ self._vocab = vocab
81
+ elif vocab_file is not None and os.path.exists(vocab_file):
82
+ with open(vocab_file, "r", encoding="utf-8") as f:
83
+ self._vocab = json.load(f)
84
+ else:
85
+ # Create a minimal vocabulary with just special tokens
86
+ # The full vocabulary should be built from the dataset
87
+ self._vocab = self._create_default_vocab()
88
+
89
+ # Create reverse mapping
90
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
91
+ self.is_nlp_basic = True
92
+
93
+ # Call parent init AFTER setting up vocab
94
+ super().__init__(
95
+ pad_token=self._pad_token,
96
+ bos_token=self._bos_token,
97
+ eos_token=self._eos_token,
98
+ unk_token=self._unk_token,
99
+ **kwargs,
100
+ )
101
+
102
+ def _create_default_vocab(self) -> Dict[str, int]:
103
+ """
104
+ Create default vocabulary with all possible tokens.
105
+ Tokens either represent player, piece, square, or special move notation.
106
+ We impose no additional structure to the token set.
107
+ """
108
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.EOM_TOKEN]
109
+ normal_tokens = [ a+b for a in 'BW' for b in 'PNBRQK'] # Player + Piece
110
+ normal_tokens += [a+b for a in 'abcdefgh' for b in '12345678'] # starting or ending square
111
+ normal_tokens += ['(x)', '(+)', '(+*)', '(o)', '(O)', 'EV_NONE'] # special suffixes
112
+
113
+ special_tokens += normal_tokens
114
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
115
+ return vocab
116
+
117
+ @classmethod
118
+ def build_vocab_from_iterator(
119
+ cls,
120
+ iterator,
121
+ min_frequency: int = 1,
122
+ ) -> "ChessTokenizer":
123
+ """
124
+ DOESN'T WORK YET ---
125
+ Build a tokenizer vocabulary from an iterator of game strings.
126
+
127
+ Args:
128
+ iterator: An iterator yielding game strings (space-separated moves).
129
+ min_frequency: Minimum frequency for a token to be included.
130
+
131
+ Returns:
132
+ A ChessTokenizer with the built vocabulary.
133
+ """
134
+ from collections import Counter
135
+
136
+ token_counts = Counter()
137
+ tokenizer = cls()
138
+ for game in iterator:
139
+ moves = game.strip().split()
140
+ tokens = tokenizer._split_move(moves)
141
+ token_counts.update(tokens)
142
+
143
+ # Filter by frequency
144
+ tokens = [
145
+ token for token, count in token_counts.items()
146
+ if count >= min_frequency
147
+ ]
148
+
149
+ # Sort for reproducibility
150
+ tokens = sorted(tokens)
151
+
152
+ # Build vocabulary
153
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
154
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
155
+
156
+ return cls(vocab=vocab)
157
+
158
+ @classmethod
159
+ def build_vocab_from_dataset(
160
+ cls,
161
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
162
+ split: str = "train",
163
+ column: str = "text",
164
+ min_frequency: int = 1,
165
+ max_samples: Optional[int] = 100000,
166
+ ) -> "ChessTokenizer":
167
+ """
168
+ DOESN'T WORK YET ---
169
+ Build a tokenizer vocabulary from a Hugging Face dataset.
170
+
171
+ Args:
172
+ dataset_name: Name of the dataset on Hugging Face Hub.
173
+ split: Dataset split to use.
174
+ column: Column containing the game strings.
175
+ min_frequency: Minimum frequency for a token to be included (default: 1).
176
+ max_samples: Maximum number of samples to process (default: 100k).
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(game_iterator(), min_frequency=min_frequency)
193
+
194
+ @property
195
+ def vocab_size(self) -> int:
196
+ """Return the size of the vocabulary."""
197
+ return len(self._vocab)
198
+
199
+ def get_vocab(self) -> Dict[str, int]:
200
+ """Return the vocabulary as a dictionary."""
201
+ return dict(self._vocab)
202
+
203
+ def _split_move(self, move: str) -> tuple[str, str, str, str]:
204
+ if len(move) < 6:
205
+ return self.UNK_TOKEN, self.UNK_TOKEN, self.UNK_TOKEN, "EV_NONE"
206
+
207
+ color = move[0]
208
+ piece = move[1]
209
+ from_sq = move[2:4]
210
+ to_sq = move[4:6]
211
+ suffix = move[6:]
212
+
213
+ piece_tok = f"P_{color}{piece}"
214
+ from_tok = f"F_{from_sq}"
215
+ to_tok = f"T_{to_sq}"
216
+
217
+ if "(o)" in suffix:
218
+ event_suffix = "(o)"
219
+ elif "(O)" in suffix:
220
+ event_suffix = "(O)"
221
+ else:
222
+ promotion = ""
223
+ promo_match = re.search(r"=([NBRQ])", suffix)
224
+ if promo_match:
225
+ promotion = f"={promo_match.group(1)}"
226
+
227
+ capture = "(x" in suffix
228
+ checkmate = "+*" in suffix
229
+ check = "(+)" in suffix or "(x+)" in suffix
230
+
231
+ if capture and checkmate:
232
+ suffix_event = "(x+*)"
233
+ elif capture and check:
234
+ suffix_event = "(x+)"
235
+ elif capture:
236
+ suffix_event = "(x)"
237
+ elif checkmate:
238
+ suffix_event = "(+*)"
239
+ elif check:
240
+ suffix_event = "(+)"
241
+ else:
242
+ suffix_event = ""
243
+
244
+ event_suffix = promotion + suffix_event
245
+
246
+ event_tok = "EV_NONE" if event_suffix == "" else f"EV_{event_suffix}"
247
+ return piece_tok, from_tok, to_tok, event_tok
248
+ def _tokenize(self, text: str) -> List[str]:
249
+ """
250
+ Tokenize a string of moves into a list of tokens.
251
+
252
+ Args:
253
+ text: A string of space-separated moves.
254
+
255
+ Returns:
256
+ List of move tokens.
257
+ """
258
+ moves_list = text.strip().split()
259
+ tokens = []
260
+
261
+ for move in moves_list:
262
+ if len(move) < 6:
263
+ tokens.append(self.UNK_TOKEN)
264
+ continue
265
+ separation = [ move[0:2], move[2:4], move[4:6], move[6:] ]
266
+ for part in separation:
267
+ if part and part in self._vocab:
268
+ tokens.append(part)
269
+ elif part and part not in self._vocab:
270
+ tokens.append(self.UNK_TOKEN)
271
+ tokens.append(self.EOM_TOKEN)
272
+ return tokens
273
+
274
+ def _convert_token_to_id(self, token: str) -> int:
275
+ """Convert a token to its ID."""
276
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
277
+
278
+ def _convert_id_to_token(self, index: int) -> str:
279
+ """Convert an ID to its token."""
280
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
281
+
282
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
283
+ """Convert a list of tokens back to a string."""
284
+ # Filter out special tokens for cleaner output
285
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
286
+ moves = []
287
+ for token in tokens:
288
+ if token == self.EOM_TOKEN:
289
+ moves.append(" ")
290
+ elif token not in special:
291
+ moves.append(token)
292
+ return "".join(moves)
293
+
294
+
295
+ def save_vocabulary(
296
+ self,
297
+ save_directory: str,
298
+ filename_prefix: Optional[str] = None,
299
+ ) -> tuple:
300
+ """
301
+ Save the vocabulary to a JSON file.
302
+
303
+ Args:
304
+ save_directory: Directory to save the vocabulary.
305
+ filename_prefix: Optional prefix for the filename.
306
+
307
+ Returns:
308
+ Tuple containing the path to the saved vocabulary file.
309
+ """
310
+ if not os.path.isdir(save_directory):
311
+ os.makedirs(save_directory, exist_ok=True)
312
+
313
+ vocab_file = os.path.join(
314
+ save_directory,
315
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
316
+ )
317
+
318
+ with open(vocab_file, "w", encoding="utf-8") as f:
319
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
320
+
321
+ return (vocab_file,)
322
+
323
+
324
+ def count_vocab_from_dataset(
325
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
326
+ chess_tokenizer: ChessTokenizer = ChessTokenizer(),
327
+ split: str = "train",
328
+ column: str = "text",
329
+ max_samples: Optional[int] = 10000,
330
+ ) -> Dict[str, int]:
331
+ """
332
+ Count token frequencies in a dataset (useful for vocabulary analysis).
333
+ ATTENTION: Only counts number of moves, not actual tokens
334
+
335
+ Args:
336
+ dataset_name: Name of the dataset on Hugging Face Hub.
337
+ split: Dataset split to use.
338
+ column: Column containing the game strings.
339
+ max_samples: Maximum number of samples to process.
340
+
341
+ Returns:
342
+ Dictionary mapping tokens to their frequencies.
343
+ """
344
+ from collections import Counter
345
+ from datasets import load_dataset
346
+
347
+ dataset = load_dataset(dataset_name, split=split)
348
+
349
+ if max_samples is not None:
350
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
351
+
352
+ token_counts = Counter()
353
+
354
+ for example in dataset:
355
+ moves = example[column].strip().split()
356
+ moves = chess_tokenizer._tokenize(moves)
357
+ token_counts.update(moves)
358
+
359
+ 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,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[EOM]": 4,
7
+ "BP": 5,
8
+ "BN": 6,
9
+ "BB": 7,
10
+ "BR": 8,
11
+ "BQ": 9,
12
+ "BK": 10,
13
+ "WP": 11,
14
+ "WN": 12,
15
+ "WB": 13,
16
+ "WR": 14,
17
+ "WQ": 15,
18
+ "WK": 16,
19
+ "a1": 17,
20
+ "a2": 18,
21
+ "a3": 19,
22
+ "a4": 20,
23
+ "a5": 21,
24
+ "a6": 22,
25
+ "a7": 23,
26
+ "a8": 24,
27
+ "b1": 25,
28
+ "b2": 26,
29
+ "b3": 27,
30
+ "b4": 28,
31
+ "b5": 29,
32
+ "b6": 30,
33
+ "b7": 31,
34
+ "b8": 32,
35
+ "c1": 33,
36
+ "c2": 34,
37
+ "c3": 35,
38
+ "c4": 36,
39
+ "c5": 37,
40
+ "c6": 38,
41
+ "c7": 39,
42
+ "c8": 40,
43
+ "d1": 41,
44
+ "d2": 42,
45
+ "d3": 43,
46
+ "d4": 44,
47
+ "d5": 45,
48
+ "d6": 46,
49
+ "d7": 47,
50
+ "d8": 48,
51
+ "e1": 49,
52
+ "e2": 50,
53
+ "e3": 51,
54
+ "e4": 52,
55
+ "e5": 53,
56
+ "e6": 54,
57
+ "e7": 55,
58
+ "e8": 56,
59
+ "f1": 57,
60
+ "f2": 58,
61
+ "f3": 59,
62
+ "f4": 60,
63
+ "f5": 61,
64
+ "f6": 62,
65
+ "f7": 63,
66
+ "f8": 64,
67
+ "g1": 65,
68
+ "g2": 66,
69
+ "g3": 67,
70
+ "g4": 68,
71
+ "g5": 69,
72
+ "g6": 70,
73
+ "g7": 71,
74
+ "g8": 72,
75
+ "h1": 73,
76
+ "h2": 74,
77
+ "h3": 75,
78
+ "h4": 76,
79
+ "h5": 77,
80
+ "h6": 78,
81
+ "h7": 79,
82
+ "h8": 80,
83
+ "(x)": 81,
84
+ "(+)": 82,
85
+ "(+*)": 83,
86
+ "(o)": 84,
87
+ "(O)": 85,
88
+ "EV_NONE": 86
89
+ }