gabriellafrds commited on
Commit
41fbda7
·
verified ·
1 Parent(s): 1dde463

Chess Challenge submission by gabriellafrds

Browse files
Files changed (7) hide show
  1. README.md +20 -0
  2. config.json +20 -0
  3. model.safetensors +3 -0
  4. special_tokens_map.json +7 -0
  5. tokenizer.py +351 -0
  6. tokenizer_config.json +59 -0
  7. vocab.json +85 -0
README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+ # chess-gabriellafernandes2
10
+ Chess model submitted to the LLM Course Chess Challenge.
11
+ ## Submission Info
12
+ - **Submitted by**: [gabriellafrds](https://huggingface.co/gabriellafrds)
13
+ - **Parameters**: 870,528
14
+ - **Organization**: LLM-course
15
+ ## Model Details
16
+ - **Architecture**: Chess Transformer (GPT-style)
17
+ - **Vocab size**: 83
18
+ - **Embedding dim**: 128
19
+ - **Layers**: 5
20
+ - **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": 384,
15
+ "n_layer": 5,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.5",
19
+ "vocab_size": 83
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdefb4464c9d58086279bcfdb1ac41d018d3f15a920d942cc9aee4534eb37239
3
+ size 3487536
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[BOS]",
3
+ "eos_token": "[EOS]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #----------------added----------------
47
+ SEP_TOKEN = "[SEP]"
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
+ #------------added-------------
69
+ self._sep_token = self.SEP_TOKEN
70
+
71
+ # Remove any duplicate special-token entries passed through kwargs
72
+ # to avoid "multiple values for keyword" errors when loading from disk.
73
+ kwargs.pop("pad_token", None)
74
+ kwargs.pop("bos_token", None)
75
+ kwargs.pop("eos_token", None)
76
+ kwargs.pop("unk_token", None)
77
+ #--------------added---------
78
+ kwargs.pop("sep_token", None)
79
+
80
+ # Load or create vocabulary
81
+ if vocab is not None:
82
+ self._vocab = vocab
83
+ elif vocab_file is not None and os.path.exists(vocab_file):
84
+ with open(vocab_file, "r", encoding="utf-8") as f:
85
+ self._vocab = json.load(f)
86
+ else:
87
+ # Create a minimal vocabulary with just special tokens
88
+ # The full vocabulary should be built from the dataset
89
+ self._vocab = self._create_default_vocab()
90
+
91
+ # Create reverse mapping
92
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
93
+
94
+ # Call parent init AFTER setting up vocab
95
+ super().__init__(
96
+ pad_token=self._pad_token,
97
+ bos_token=self._bos_token,
98
+ eos_token=self._eos_token,
99
+ unk_token=self._unk_token,
100
+ #--------added----------
101
+ sep_token=self._sep_token,
102
+ **kwargs,
103
+ )
104
+
105
+ def _create_default_vocab(self) -> Dict[str, int]:
106
+ """
107
+ Create a minimal default vocabulary with just special tokens.
108
+
109
+ For the full vocabulary, use `build_vocab_from_dataset()`.
110
+ This minimal vocab is just a placeholder - you should build from data.
111
+ """
112
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.SEP_TOKEN]#---------added-----------
113
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
114
+ return vocab
115
+
116
+ #--------added---------
117
+ @staticmethod
118
+ def split_move_into_subtokens(move: str) -> List[str]:
119
+ """
120
+ Split a move into sub-tokens: [color, piece, from, to, suffix].
121
+ """
122
+ if move in ["o", "O"]:
123
+ return [move]
124
+
125
+ color = move[0] # W/B
126
+ piece = move[1] # P/N/B/R/Q/K
127
+ frm = move[2:4]
128
+ to = move[4:6]
129
+
130
+ suffix = move[6:] if len(move) > 6 else None
131
+ tokens = [color, piece, frm, to]
132
+ if suffix is not None:
133
+ tokens.append(suffix)
134
+ return tokens
135
+
136
+ @classmethod
137
+ def build_vocab_from_iterator(
138
+ cls,
139
+ iterator,
140
+ min_frequency: int = 1,
141
+ ) -> "ChessTokenizer":
142
+ """
143
+ Build a tokenizer vocabulary from an iterator of game strings.
144
+
145
+ Args:
146
+ iterator: An iterator yielding game strings (space-separated moves).
147
+ min_frequency: Minimum frequency for a token to be included.
148
+
149
+ Returns:
150
+ A ChessTokenizer with the built vocabulary.
151
+ """
152
+ from collections import Counter
153
+
154
+ token_counts = Counter()
155
+
156
+ for game in iterator:
157
+ moves = game.strip().split()
158
+ token_counts.update(moves)
159
+
160
+ # Filter by frequency
161
+ tokens = [
162
+ token for token, count in token_counts.items()
163
+ if count >= min_frequency
164
+ ]
165
+
166
+ # Sort for reproducibility
167
+ #-------added-----
168
+ #tokens = sorted(tokens)
169
+ sub_tokens_set = set()
170
+ for move in tokens:
171
+ subtokens = cls.split_move_into_subtokens(move)
172
+ sub_tokens_set.update(subtokens)
173
+
174
+ # Sort for reproducibility
175
+ sorted_subtokens = sorted(sub_tokens_set)
176
+
177
+ # Build vocabulary
178
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN, cls.SEP_TOKEN]#---------added--------
179
+ vocab = {token: idx for idx, token in enumerate(special_tokens + sorted_subtokens)}
180
+
181
+ return cls(vocab=vocab)
182
+
183
+ @classmethod
184
+ def build_vocab_from_dataset(
185
+ cls,
186
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
187
+ split: str = "train",
188
+ column: str = "text",
189
+ min_frequency: int = 500,
190
+ max_samples: Optional[int] = 100000,
191
+ ) -> "ChessTokenizer":
192
+ """
193
+ Build a tokenizer vocabulary from a Hugging Face dataset.
194
+
195
+ Args:
196
+ dataset_name: Name of the dataset on Hugging Face Hub.
197
+ split: Dataset split to use.
198
+ column: Column containing the game strings.
199
+ min_frequency: Minimum frequency for a token to be included (default: 500).
200
+ max_samples: Maximum number of samples to process (default: 100k).
201
+
202
+ Returns:
203
+ A ChessTokenizer with the built vocabulary.
204
+ """
205
+ from datasets import load_dataset
206
+
207
+ dataset = load_dataset(dataset_name, split=split)
208
+
209
+ if max_samples is not None:
210
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
211
+
212
+ def game_iterator():
213
+ for example in dataset:
214
+ yield example[column]
215
+
216
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
217
+
218
+ @property
219
+ def vocab_size(self) -> int:
220
+ """Return the size of the vocabulary."""
221
+ return len(self._vocab)
222
+
223
+ def get_vocab(self) -> Dict[str, int]:
224
+ """Return the vocabulary as a dictionary."""
225
+ return dict(self._vocab)
226
+
227
+ #def _tokenize(self, text: str) -> List[str]:
228
+ """
229
+ Tokenize a string of moves into a list of tokens.
230
+
231
+ Args:
232
+ text: A string of space-separated moves.
233
+
234
+ Returns:
235
+ List of move tokens.
236
+ """
237
+ #return text.strip().split()
238
+
239
+ #-------added-------
240
+ def _tokenize(self, text: str) -> List[str]:
241
+ """
242
+ Tokenize a string of moves into sub-tokens.
243
+ """
244
+ moves = text.strip().split()
245
+ subtokens = []
246
+ for i, move in enumerate(moves):
247
+ subtokens.extend(self.split_move_into_subtokens(move))
248
+ if i != len(moves) - 1:
249
+ subtokens.append(self.SEP_TOKEN)
250
+
251
+ return subtokens
252
+
253
+ def _convert_token_to_id(self, token: str) -> int:
254
+ """Convert a token to its ID."""
255
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
256
+
257
+ def _convert_id_to_token(self, index: int) -> str:
258
+ """Convert an ID to its token."""
259
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
260
+
261
+ #def convert_tokens_to_string(self, tokens: List[str]) -> str:
262
+ """Convert a list of tokens back to a string."""
263
+ # Filter out special tokens for cleaner output
264
+ #special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
265
+ #return " ".join(t for t in tokens if t not in special)
266
+
267
+ #----------added-----------
268
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
269
+ """Convert a list of tokens back to a string."""
270
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
271
+
272
+ game = ""
273
+ sep_before = False # to prevent from having multiple spaces
274
+ for token in tokens:
275
+ if token == self.SEP_TOKEN and not sep_before:
276
+ game += " "
277
+ sep_before = True
278
+ elif token not in special:
279
+ game += token
280
+ sep_before = False
281
+
282
+ return game
283
+
284
+ def save_vocabulary(
285
+ self,
286
+ save_directory: str,
287
+ filename_prefix: Optional[str] = None,
288
+ ) -> tuple:
289
+ """
290
+ Save the vocabulary to a JSON file.
291
+
292
+ Args:
293
+ save_directory: Directory to save the vocabulary.
294
+ filename_prefix: Optional prefix for the filename.
295
+
296
+ Returns:
297
+ Tuple containing the path to the saved vocabulary file.
298
+ """
299
+ if not os.path.isdir(save_directory):
300
+ os.makedirs(save_directory, exist_ok=True)
301
+
302
+ vocab_file = os.path.join(
303
+ save_directory,
304
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
305
+ )
306
+
307
+ with open(vocab_file, "w", encoding="utf-8") as f:
308
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
309
+
310
+ return (vocab_file,)
311
+
312
+
313
+ def count_vocab_from_dataset(
314
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
315
+ split: str = "train",
316
+ column: str = "text",
317
+ max_samples: Optional[int] = 10000,
318
+ ) -> Dict[str, int]:
319
+ """
320
+ Count token frequencies in a dataset (useful for vocabulary analysis).
321
+
322
+ Args:
323
+ dataset_name: Name of the dataset on Hugging Face Hub.
324
+ split: Dataset split to use.
325
+ column: Column containing the game strings.
326
+ max_samples: Maximum number of samples to process.
327
+
328
+ Returns:
329
+ Dictionary mapping tokens to their frequencies.
330
+ """
331
+ from collections import Counter
332
+ from datasets import load_dataset
333
+
334
+ dataset = load_dataset(dataset_name, split=split)
335
+
336
+ if max_samples is not None:
337
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
338
+
339
+ token_counts = Counter()
340
+
341
+ for example in dataset:
342
+ """
343
+ moves = example[column].strip().split()
344
+ token_counts.update(moves)"""
345
+ #--------added--------
346
+ moves = example[column].strip().split()
347
+ for move in moves:
348
+ subtokens = ChessTokenizer.split_move_into_subtokens(move)
349
+ token_counts.update(subtokens)
350
+
351
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "4": {
36
+ "content": "[SEP]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.ChessTokenizer",
47
+ null
48
+ ]
49
+ },
50
+ "bos_token": "[BOS]",
51
+ "clean_up_tokenization_spaces": false,
52
+ "eos_token": "[EOS]",
53
+ "extra_special_tokens": {},
54
+ "model_max_length": 1000000000000000019884624838656,
55
+ "pad_token": "[PAD]",
56
+ "sep_token": "[SEP]",
57
+ "tokenizer_class": "ChessTokenizer",
58
+ "unk_token": "[UNK]"
59
+ }
vocab.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[SEP]": 4,
7
+ "(+)": 5,
8
+ "(O)": 6,
9
+ "(Q)": 7,
10
+ "(o)": 8,
11
+ "(x)": 9,
12
+ "(x+)": 10,
13
+ "(xE)": 11,
14
+ "B": 12,
15
+ "K": 13,
16
+ "N": 14,
17
+ "P": 15,
18
+ "Q": 16,
19
+ "R": 17,
20
+ "W": 18,
21
+ "a1": 19,
22
+ "a2": 20,
23
+ "a3": 21,
24
+ "a4": 22,
25
+ "a5": 23,
26
+ "a6": 24,
27
+ "a7": 25,
28
+ "a8": 26,
29
+ "b1": 27,
30
+ "b2": 28,
31
+ "b3": 29,
32
+ "b4": 30,
33
+ "b5": 31,
34
+ "b6": 32,
35
+ "b7": 33,
36
+ "b8": 34,
37
+ "c1": 35,
38
+ "c2": 36,
39
+ "c3": 37,
40
+ "c4": 38,
41
+ "c5": 39,
42
+ "c6": 40,
43
+ "c7": 41,
44
+ "c8": 42,
45
+ "d1": 43,
46
+ "d2": 44,
47
+ "d3": 45,
48
+ "d4": 46,
49
+ "d5": 47,
50
+ "d6": 48,
51
+ "d7": 49,
52
+ "d8": 50,
53
+ "e1": 51,
54
+ "e2": 52,
55
+ "e3": 53,
56
+ "e4": 54,
57
+ "e5": 55,
58
+ "e6": 56,
59
+ "e7": 57,
60
+ "e8": 58,
61
+ "f1": 59,
62
+ "f2": 60,
63
+ "f3": 61,
64
+ "f4": 62,
65
+ "f5": 63,
66
+ "f6": 64,
67
+ "f7": 65,
68
+ "f8": 66,
69
+ "g1": 67,
70
+ "g2": 68,
71
+ "g3": 69,
72
+ "g4": 70,
73
+ "g5": 71,
74
+ "g6": 72,
75
+ "g7": 73,
76
+ "g8": 74,
77
+ "h1": 75,
78
+ "h2": 76,
79
+ "h3": 77,
80
+ "h4": 78,
81
+ "h5": 79,
82
+ "h6": 80,
83
+ "h7": 81,
84
+ "h8": 82
85
+ }